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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5480cf37c862356fddc85c0016b98b33aefe0e55 | 367134ba5a65885e863bdc4507601606690974c1 | /test/general_recursion.lean | 5a1d17b148397181aeb4d77306a09c1efefc9d74 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 10,707 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Simon Hudon
-/
import tactic.norm_num
import tactic.linarith
import tactic.omega
import control.lawful_fix
import order.category.omega_complete_partial_order
import data.nat.basic
universes u_1 u_2
namespace roption.examples
open function has_fix omega_complete_partial_order
/-! `easy` is a trivial, non-recursive example -/
def easy.intl (easy : ℕ → ℕ → roption ℕ) : ℕ → ℕ → roption ℕ
| x y := pure x
def easy :=
fix easy.intl
-- automation coming soon
theorem easy.cont : continuous' easy.intl :=
pi.omega_complete_partial_order.flip₂_continuous' easy.intl
(λ x, pi.omega_complete_partial_order.flip₂_continuous' _ (λ x_1, const_continuous' (pure x)))
-- automation coming soon
theorem easy.equations.eqn_1 (x y : ℕ) : easy x y = pure x :=
by rw [easy, lawful_fix.fix_eq' easy.cont]; refl
/-! division on natural numbers -/
def div.intl (div : ℕ → ℕ → roption ℕ) : ℕ → ℕ → roption ℕ
| x y :=
if y ≤ x ∧ y > 0
then div (x - y) y
else pure x
def div : ℕ → ℕ → roption ℕ :=
fix div.intl
-- automation coming soon
theorem div.cont : continuous' div.intl :=
pi.omega_complete_partial_order.flip₂_continuous' div.intl
(λ (x : ℕ),
pi.omega_complete_partial_order.flip₂_continuous' (λ (g : ℕ → ℕ → roption ℕ), div.intl g x)
(λ (x_1 : ℕ),
(continuous_hom.ite_continuous' (λ (x_2 : ℕ → ℕ → roption ℕ), x_2 (x - x_1) x_1)
(λ (x_1 : ℕ → ℕ → roption ℕ), pure x)
(pi.omega_complete_partial_order.flip₁_continuous'
(λ (v_1 : ℕ) (x_2 : ℕ → ℕ → roption ℕ), x_2 (x - x_1) v_1) _ $
pi.omega_complete_partial_order.flip₁_continuous'
(λ (v : ℕ) (g : ℕ → ℕ → roption ℕ) (x : ℕ), g v x) _ id_continuous')
(const_continuous' (pure x)))))
-- automation coming soon
theorem div.equations.eqn_1 (x y : ℕ) : div x y = if y ≤ x ∧ y > 0 then div (x - y) y else pure x :=
by conv_lhs { rw [div, lawful_fix.fix_eq' div.cont] }; refl
inductive tree (α : Type*)
| nil {} : tree
| node (x : α) : tree → tree → tree
open roption.examples.tree
/-! `map` on a `tree` using monadic notation -/
def tree_map.intl {α β : Type*} (f : α → β) (tree_map : tree α → roption (tree β)) :
tree α → roption (tree β)
| nil := pure nil
| (node x t₀ t₁) :=
do tt₀ ← tree_map t₀,
tt₁ ← tree_map t₁,
pure $ node (f x) tt₀ tt₁
-- automation coming soon
def tree_map {α : Type u_1} {β : Type u_2} (f : α → β) : tree α → roption (tree β) :=
fix (tree_map.intl f)
-- automation coming soon
theorem tree_map.cont :
∀ {α : Type u_1} {β : Type u_2} (f : α → β), continuous' (tree_map.intl f) :=
λ {α : Type u_1} {β : Type u_2} (f : α → β),
pi.omega_complete_partial_order.flip₂_continuous' (tree_map.intl f)
(λ (x : tree α),
tree.cases_on x (id (const_continuous' (pure nil)))
(λ (x_x : α) (x_a x_a_1 : tree α),
(continuous_hom.bind_continuous' (λ (x : tree α → roption (tree β)), x x_a)
(λ (x : tree α → roption (tree β)) (tt₀ : tree β),
x x_a_1 >>= λ (tt₁ : tree β), pure (node (f x_x) tt₀ tt₁))
(pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → roption (tree β)), x v) x_a id_continuous')
(pi.omega_complete_partial_order.flip₂_continuous'
(λ (x : tree α → roption (tree β)) (tt₀ : tree β),
x x_a_1 >>= λ (tt₁ : tree β), pure (node (f x_x) tt₀ tt₁))
(λ (x : tree β),
continuous_hom.bind_continuous' (λ (x : tree α → roption (tree β)), x x_a_1)
(λ (x_1 : tree α → roption (tree β)) (tt₁ : tree β), pure (node (f x_x) x tt₁))
(pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → roption (tree β)), x v) x_a_1
id_continuous')
(pi.omega_complete_partial_order.flip₂_continuous'
(λ (x_1 : tree α → roption (tree β)) (tt₁ : tree β), pure (node (f x_x) x tt₁))
(λ (x_1 : tree β), const_continuous' (pure (node (f x_x) x x_1)))))))))
-- automation coming soon
theorem tree_map.equations.eqn_1 {α : Type u_1} {β : Type u_2} (f : α → β) :
tree_map f nil = pure nil :=
by rw [tree_map,lawful_fix.fix_eq' (tree_map.cont f)]; refl
-- automation coming soon
theorem tree_map.equations.eqn_2 {α : Type u_1} {β : Type u_2} (f : α → β) (x : α)
(t₀ t₁ : tree α) :
tree_map f (node x t₀ t₁) = tree_map f t₀ >>= λ (tt₀ : tree β), tree_map f t₁ >>=
λ (tt₁ : tree β), pure (node (f x) tt₀ tt₁) :=
by conv_lhs { rw [tree_map,lawful_fix.fix_eq' (tree_map.cont f)] }; refl
/-! `map` on a `tree` using applicative notation -/
def tree_map'.intl {α β} (f : α → β) (tree_map : tree α → roption (tree β)) :
tree α → roption (tree β)
| nil := pure nil
| (node x t₀ t₁) :=
node (f x) <$> tree_map t₀ <*> tree_map t₁
-- automation coming soon
def tree_map' {α : Type u_1} {β : Type u_2} (f : α → β) : tree α → roption (tree β) :=
fix (tree_map'.intl f)
-- automation coming soon
theorem tree_map'.cont :
∀ {α : Type u_1} {β : Type u_2} (f : α → β), continuous' (tree_map'.intl f) :=
λ {α : Type u_1} {β : Type u_2} (f : α → β),
pi.omega_complete_partial_order.flip₂_continuous' (tree_map'.intl f)
(λ (x : tree α),
tree.cases_on x (id (const_continuous' (pure nil)))
(λ (x_x : α) (x_a x_a_1 : tree α),
(continuous_hom.seq_continuous' (λ (x : tree α → roption (tree β)), node (f x_x) <$> x x_a)
(λ (x : tree α → roption (tree β)), x x_a_1)
(continuous_hom.map_continuous' (node (f x_x)) (λ (x : tree α → roption (tree β)), x x_a)
(pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → roption (tree β)), x v) x_a id_continuous'))
(pi.omega_complete_partial_order.flip₁_continuous' (λ (v : tree α) (x : tree α → roption (tree β)), x v) x_a_1 id_continuous'))))
-- automation coming soon
theorem tree_map'.equations.eqn_1 {α : Type u_1} {β : Type u_2} (f : α → β) :
tree_map' f nil = pure nil :=
by rw [tree_map',lawful_fix.fix_eq' (tree_map'.cont f)]; refl
-- automation coming soon
theorem tree_map'.equations.eqn_2 {α : Type u_1} {β : Type u_2} (f : α → β) (x : α) (t₀ t₁ : tree α) :
tree_map' f (node x t₀ t₁) = node (f x) <$> tree_map' f t₀ <*> tree_map' f t₁ :=
by conv_lhs { rw [tree_map',lawful_fix.fix_eq' (tree_map'.cont f)] }; refl
/-! f91 is a function whose proof of termination cannot rely on the structural
ordering of its arguments and does not use the usual well-founded order
on natural numbers. It is an interesting candidate to show that `fix` lets us disentangle
the issue of termination from the definition of the function. -/
def f91.intl (f91 : ℕ → roption ℕ) (n : ℕ) : roption ℕ :=
if n > 100
then pure $ n - 10
else f91 (n + 11) >>= f91
-- automation coming soon
def f91 : ℕ → roption ℕ := fix f91.intl
-- automation coming soon
lemma f91.cont : continuous' f91.intl :=
pi.omega_complete_partial_order.flip₂_continuous' f91.intl
(λ (x : ℕ),
id
(continuous_hom.ite_continuous' (λ (x_1 : ℕ → roption ℕ), pure (x - 10)) (λ (x_1 : ℕ → roption ℕ), x_1 (x + 11) >>= x_1)
(const_continuous' (pure (x - 10)))
(continuous_hom.bind_continuous' (λ (x_1 : ℕ → roption ℕ), x_1 (x + 11)) (λ (x : ℕ → roption ℕ), x)
(pi.omega_complete_partial_order.flip₁_continuous' (λ (v : ℕ) (x : ℕ → roption ℕ), x v) (x + 11) id_continuous')
(pi.omega_complete_partial_order.flip₂_continuous' (λ (x : ℕ → roption ℕ), x)
(λ (x_1 : ℕ), pi.omega_complete_partial_order.flip₁_continuous' (λ (v : ℕ) (g : ℕ → roption ℕ), g v) x_1 id_continuous')))))
.
-- automation coming soon
theorem f91.equations.eqn_1 (n : ℕ) : f91 n = ite (n > 100) (pure (n - 10)) (f91 (n + 11) >>= f91) :=
by conv_lhs { rw [f91, lawful_fix.fix_eq' f91.cont] }; refl
lemma f91_spec (n : ℕ) : (∃ n', n < n' + 11 ∧ n' ∈ f91 n) :=
begin
apply well_founded.induction (measure_wf $ λ n, 101 - n) n,
clear n, dsimp [measure,inv_image], intros n ih,
by_cases h' : n > 100,
{ rw [roption.examples.f91.equations.eqn_1,if_pos h'],
existsi n - 10, rw nat.sub_add_eq_add_sub, norm_num [pure],
apply le_of_lt, transitivity 100, norm_num, exact h' },
{ rw [roption.examples.f91.equations.eqn_1,if_neg h'],
simp, rcases ih (n + 11) _ with ⟨n',hn₀,hn₁⟩,
rcases ih (n') _ with ⟨n'',hn'₀,hn'₁⟩,
refine ⟨n'',_,_,hn₁,hn'₁⟩,
{ clear ih hn₁ hn'₁, omega },
{ clear ih hn₁, omega },
{ clear ih, omega } },
end
lemma f91_dom (n : ℕ) : (f91 n).dom :=
by rw roption.dom_iff_mem; apply exists_imp_exists _ (f91_spec n); simp
def f91' (n : ℕ) : ℕ := (f91 n).get (f91_dom n)
run_cmd guard (f91' 109 = 99)
lemma f91_spec' (n : ℕ) : f91' n = if n > 100 then n - 10 else 91 :=
begin
suffices : (∃ n', n' ∈ f91 n ∧ n' = if n > 100 then n - 10 else 91),
{ dsimp [f91'], rw roption.get_eq_of_mem,
rcases this with ⟨n,_,_⟩, subst n, assumption },
apply well_founded.induction (measure_wf $ λ n, 101 - n) n,
clear n, dsimp [measure,inv_image], intros n ih,
by_cases h' : n > 100,
{ rw [roption.examples.f91.equations.eqn_1,if_pos h',if_pos h'],
simp [pure] },
{ rw [roption.examples.f91.equations.eqn_1,if_neg h',if_neg h'],
simp, rcases ih (n + 11) _ with ⟨n',hn'₀,hn'₁⟩,
split_ifs at hn'₁,
{ subst hn'₁, norm_num at hn'₀, refine ⟨_,hn'₀,_⟩,
rcases ih (n+1) _ with ⟨n',hn'₀,hn'₁⟩,
split_ifs at hn'₁,
{ subst n', convert hn'₀, clear hn'₀ hn'₀ ih, omega },
{ subst n', exact hn'₀ },
{ clear ih hn'₀, omega } },
{ refine ⟨_,hn'₀,_⟩, subst n',
rcases ih 91 _ with ⟨n',hn'₀,hn'₁⟩,
rw if_neg at hn'₁, subst n', exact hn'₀,
{ clear ih hn'₀ hn'₀, omega, },
{ clear ih hn'₀, omega, } },
{ clear ih, omega } }
end
end roption.examples
|
23d0272f27435b64c5e7facd1eaa088895ab8a9c | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/category_theory/equivalence.lean | 28be1b6de041fa4eb3d4099d85712cc9d1d57a7d | [
"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 | 24,308 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn
-/
import category_theory.fully_faithful
import category_theory.full_subcategory
import category_theory.whiskering
import category_theory.essential_image
import tactic.slice
/-!
# Equivalence of categories
An equivalence of categories `C` and `D` is a pair of functors `F : C ⥤ D` and `G : D ⥤ C` such
that `η : 𝟭 C ≅ F ⋙ G` and `ε : G ⋙ F ≅ 𝟭 D`. In many situations, equivalences are a better
notion of "sameness" of categories than the stricter isomorphims of categories.
Recall that one way to express that two functors `F : C ⥤ D` and `G : D ⥤ C` are adjoint is using
two natural transformations `η : 𝟭 C ⟶ F ⋙ G` and `ε : G ⋙ F ⟶ 𝟭 D`, called the unit and the
counit, such that the compositions `F ⟶ FGF ⟶ F` and `G ⟶ GFG ⟶ G` are the identity. Unfortunately,
it is not the case that the natural isomorphisms `η` and `ε` in the definition of an equivalence
automatically give an adjunction. However, it is true that
* if one of the two compositions is the identity, then so is the other, and
* given an equivalence of categories, it is always possible to refine `η` in such a way that the
identities are satisfied.
For this reason, in mathlib we define an equivalence to be a "half-adjoint equivalence", which is
a tuple `(F, G, η, ε)` as in the first paragraph such that the composite `F ⟶ FGF ⟶ F` is the
identity. By the remark above, this already implies that the tuple is an "adjoint equivalence",
i.e., that the composite `G ⟶ GFG ⟶ G` is also the identity.
We also define essentially surjective functors and show that a functor is an equivalence if and only
if it is full, faithful and essentially surjective.
## Main definitions
* `equivalence`: bundled (half-)adjoint equivalences of categories
* `is_equivalence`: type class on a functor `F` containing the data of the inverse `G` as well as
the natural isomorphisms `η` and `ε`.
* `ess_surj`: type class on a functor `F` containing the data of the preimages and the isomorphisms
`F.obj (preimage d) ≅ d`.
## Main results
* `equivalence.mk`: upgrade an equivalence to a (half-)adjoint equivalence
* `equivalence.of_fully_faithfully_ess_surj`: a fully faithful essentially surjective functor is an
equivalence.
## Notations
We write `C ≌ D` (`\backcong`, not to be confused with `≅`/`\cong`) for a bundled equivalence.
-/
namespace category_theory
open category_theory.functor nat_iso category
-- declare the `v`'s first; see `category_theory.category` for an explanation
universes v₁ v₂ v₃ u₁ u₂ u₃
/-- We define an equivalence as a (half)-adjoint equivalence, a pair of functors with
a unit and counit which are natural isomorphisms and the triangle law `Fη ≫ εF = 1`, or in other
words the composite `F ⟶ FGF ⟶ F` is the identity.
In `unit_inverse_comp`, we show that this is actually an adjoint equivalence, i.e., that the
composite `G ⟶ GFG ⟶ G` is also the identity.
The triangle equation is written as a family of equalities between morphisms, it is more
complicated if we write it as an equality of natural transformations, because then we would have
to insert natural transformations like `F ⟶ F1`.
See https://stacks.math.columbia.edu/tag/001J
-/
structure equivalence (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] :=
mk' ::
(functor : C ⥤ D)
(inverse : D ⥤ C)
(unit_iso : 𝟭 C ≅ functor ⋙ inverse)
(counit_iso : inverse ⋙ functor ≅ 𝟭 D)
(functor_unit_iso_comp' : ∀(X : C), functor.map ((unit_iso.hom : 𝟭 C ⟶ functor ⋙ inverse).app X) ≫
counit_iso.hom.app (functor.obj X) = 𝟙 (functor.obj X) . obviously)
restate_axiom equivalence.functor_unit_iso_comp'
infixr ` ≌ `:10 := equivalence
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
namespace equivalence
/-- The unit of an equivalence of categories. -/
abbreviation unit (e : C ≌ D) : 𝟭 C ⟶ e.functor ⋙ e.inverse := e.unit_iso.hom
/-- The counit of an equivalence of categories. -/
abbreviation counit (e : C ≌ D) : e.inverse ⋙ e.functor ⟶ 𝟭 D := e.counit_iso.hom
/-- The inverse of the unit of an equivalence of categories. -/
abbreviation unit_inv (e : C ≌ D) : e.functor ⋙ e.inverse ⟶ 𝟭 C := e.unit_iso.inv
/-- The inverse of the counit of an equivalence of categories. -/
abbreviation counit_inv (e : C ≌ D) : 𝟭 D ⟶ e.inverse ⋙ e.functor := e.counit_iso.inv
/- While these abbreviations are convenient, they also cause some trouble,
preventing structure projections from unfolding. -/
@[simp] lemma equivalence_mk'_unit (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit = unit_iso.hom := rfl
@[simp] lemma equivalence_mk'_counit (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit = counit_iso.hom := rfl
@[simp] lemma equivalence_mk'_unit_inv (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit_inv = unit_iso.inv := rfl
@[simp] lemma equivalence_mk'_counit_inv (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit_inv = counit_iso.inv := rfl
@[simp] lemma functor_unit_comp (e : C ≌ D) (X : C) :
e.functor.map (e.unit.app X) ≫ e.counit.app (e.functor.obj X) = 𝟙 (e.functor.obj X) :=
e.functor_unit_iso_comp X
@[simp] lemma counit_inv_functor_comp (e : C ≌ D) (X : C) :
e.counit_inv.app (e.functor.obj X) ≫ e.functor.map (e.unit_inv.app X) = 𝟙 (e.functor.obj X) :=
begin
erw [iso.inv_eq_inv
(e.functor.map_iso (e.unit_iso.app X) ≪≫ e.counit_iso.app (e.functor.obj X)) (iso.refl _)],
exact e.functor_unit_comp X
end
lemma counit_inv_app_functor (e : C ≌ D) (X : C) :
e.counit_inv.app (e.functor.obj X) = e.functor.map (e.unit.app X) :=
by { symmetry, erw [←iso.comp_hom_eq_id (e.counit_iso.app _), functor_unit_comp], refl }
lemma counit_app_functor (e : C ≌ D) (X : C) :
e.counit.app (e.functor.obj X) = e.functor.map (e.unit_inv.app X) :=
by { erw [←iso.hom_comp_eq_id (e.functor.map_iso (e.unit_iso.app X)), functor_unit_comp], refl }
/-- The other triangle equality. The proof follows the following proof in Globular:
http://globular.science/1905.001 -/
@[simp] lemma unit_inverse_comp (e : C ≌ D) (Y : D) :
e.unit.app (e.inverse.obj Y) ≫ e.inverse.map (e.counit.app Y) = 𝟙 (e.inverse.obj Y) :=
begin
rw [←id_comp (e.inverse.map _), ←map_id e.inverse, ←counit_inv_functor_comp, map_comp,
←iso.hom_inv_id_assoc (e.unit_iso.app _) (e.inverse.map (e.functor.map _)),
app_hom, app_inv],
slice_lhs 2 3 { erw [e.unit.naturality] },
slice_lhs 1 2 { erw [e.unit.naturality] },
slice_lhs 4 4
{ rw [←iso.hom_inv_id_assoc (e.inverse.map_iso (e.counit_iso.app _)) (e.unit_inv.app _)] },
slice_lhs 3 4 { erw [←map_comp e.inverse, e.counit.naturality],
erw [(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp],
slice_lhs 2 3 { erw [←map_comp e.inverse, e.counit_iso.inv.naturality, map_comp] },
slice_lhs 3 4 { erw [e.unit_inv.naturality] },
slice_lhs 4 5 { erw [←map_comp (e.functor ⋙ e.inverse), (e.unit_iso.app _).hom_inv_id, map_id] },
erw [id_comp],
slice_lhs 3 4 { erw [←e.unit_inv.naturality] },
slice_lhs 2 3 { erw [←map_comp e.inverse, ←e.counit_iso.inv.naturality,
(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp, (e.unit_iso.app _).hom_inv_id], refl
end
@[simp] lemma inverse_counit_inv_comp (e : C ≌ D) (Y : D) :
e.inverse.map (e.counit_inv.app Y) ≫ e.unit_inv.app (e.inverse.obj Y) = 𝟙 (e.inverse.obj Y) :=
begin
erw [iso.inv_eq_inv
(e.unit_iso.app (e.inverse.obj Y) ≪≫ e.inverse.map_iso (e.counit_iso.app Y)) (iso.refl _)],
exact e.unit_inverse_comp Y
end
lemma unit_app_inverse (e : C ≌ D) (Y : D) :
e.unit.app (e.inverse.obj Y) = e.inverse.map (e.counit_inv.app Y) :=
by { erw [←iso.comp_hom_eq_id (e.inverse.map_iso (e.counit_iso.app Y)), unit_inverse_comp], refl }
lemma unit_inv_app_inverse (e : C ≌ D) (Y : D) :
e.unit_inv.app (e.inverse.obj Y) = e.inverse.map (e.counit.app Y) :=
by { symmetry, erw [←iso.hom_comp_eq_id (e.unit_iso.app _), unit_inverse_comp], refl }
@[simp] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) :
e.functor.map (e.inverse.map f) = e.counit.app X ≫ f ≫ e.counit_inv.app Y :=
(nat_iso.naturality_2 (e.counit_iso) f).symm
@[simp] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) :
e.inverse.map (e.functor.map f) = e.unit_inv.app X ≫ f ≫ e.unit.app Y :=
(nat_iso.naturality_1 (e.unit_iso) f).symm
section
-- In this section we convert an arbitrary equivalence to a half-adjoint equivalence.
variables {F : C ⥤ D} {G : D ⥤ C} (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D)
/-- If `η : 𝟭 C ≅ F ⋙ G` is part of a (not necessarily half-adjoint) equivalence, we can upgrade it
to a refined natural isomorphism `adjointify_η η : 𝟭 C ≅ F ⋙ G` which exhibits the properties
required for a half-adjoint equivalence. See `equivalence.mk`. -/
def adjointify_η : 𝟭 C ≅ F ⋙ G :=
calc
𝟭 C ≅ F ⋙ G : η
... ≅ F ⋙ (𝟭 D ⋙ G) : iso_whisker_left F (left_unitor G).symm
... ≅ F ⋙ ((G ⋙ F) ⋙ G) : iso_whisker_left F (iso_whisker_right ε.symm G)
... ≅ F ⋙ (G ⋙ (F ⋙ G)) : iso_whisker_left F (associator G F G)
... ≅ (F ⋙ G) ⋙ (F ⋙ G) : (associator F G (F ⋙ G)).symm
... ≅ 𝟭 C ⋙ (F ⋙ G) : iso_whisker_right η.symm (F ⋙ G)
... ≅ F ⋙ G : left_unitor (F ⋙ G)
lemma adjointify_η_ε (X : C) :
F.map ((adjointify_η η ε).hom.app X) ≫ ε.hom.app (F.obj X) = 𝟙 (F.obj X) :=
begin
dsimp [adjointify_η], simp,
have := ε.hom.naturality (F.map (η.inv.app X)), dsimp at this, rw [this], clear this,
rw [←assoc _ _ (F.map _)],
have := ε.hom.naturality (ε.inv.app $ F.obj X), dsimp at this, rw [this], clear this,
have := (ε.app $ F.obj X).hom_inv_id, dsimp at this, rw [this], clear this,
rw [id_comp], have := (F.map_iso $ η.app X).hom_inv_id, dsimp at this, rw [this]
end
end
/-- Every equivalence of categories consisting of functors `F` and `G` such that `F ⋙ G` and
`G ⋙ F` are naturally isomorphic to identity functors can be transformed into a half-adjoint
equivalence without changing `F` or `G`. -/
protected definition mk (F : C ⥤ D) (G : D ⥤ C)
(η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : C ≌ D :=
⟨F, G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩
/-- Equivalence of categories is reflexive. -/
@[refl, simps] def refl : C ≌ C :=
⟨𝟭 C, 𝟭 C, iso.refl _, iso.refl _, λ X, category.id_comp _⟩
instance : inhabited (C ≌ C) :=
⟨refl⟩
/-- Equivalence of categories is symmetric. -/
@[symm, simps] def symm (e : C ≌ D) : D ≌ C :=
⟨e.inverse, e.functor, e.counit_iso.symm, e.unit_iso.symm, e.inverse_counit_inv_comp⟩
variables {E : Type u₃} [category.{v₃} E]
/-- Equivalence of categories is transitive. -/
@[trans, simps] def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E :=
{ functor := e.functor ⋙ f.functor,
inverse := f.inverse ⋙ e.inverse,
unit_iso :=
begin
refine iso.trans e.unit_iso _,
exact iso_whisker_left e.functor (iso_whisker_right f.unit_iso e.inverse) ,
end,
counit_iso :=
begin
refine iso.trans _ f.counit_iso,
exact iso_whisker_left f.inverse (iso_whisker_right e.counit_iso f.functor)
end,
-- We wouldn't have needed to give this proof if we'd used `equivalence.mk`,
-- but we choose to avoid using that here, for the sake of good structure projection `simp`
-- lemmas.
functor_unit_iso_comp' := λ X,
begin
dsimp,
rw [← f.functor.map_comp_assoc, e.functor.map_comp, ←counit_inv_app_functor, fun_inv_map,
iso.inv_hom_id_app_assoc, assoc, iso.inv_hom_id_app, counit_app_functor,
← functor.map_comp],
erw [comp_id, iso.hom_inv_id_app, functor.map_id],
end }
/-- Composing a functor with both functors of an equivalence yields a naturally isomorphic
functor. -/
def fun_inv_id_assoc (e : C ≌ D) (F : C ⥤ E) : e.functor ⋙ e.inverse ⋙ F ≅ F :=
(functor.associator _ _ _).symm ≪≫ iso_whisker_right e.unit_iso.symm F ≪≫ F.left_unitor
@[simp] lemma fun_inv_id_assoc_hom_app (e : C ≌ D) (F : C ⥤ E) (X : C) :
(fun_inv_id_assoc e F).hom.app X = F.map (e.unit_inv.app X) :=
by { dsimp [fun_inv_id_assoc], tidy }
@[simp] lemma fun_inv_id_assoc_inv_app (e : C ≌ D) (F : C ⥤ E) (X : C) :
(fun_inv_id_assoc e F).inv.app X = F.map (e.unit.app X) :=
by { dsimp [fun_inv_id_assoc], tidy }
/-- Composing a functor with both functors of an equivalence yields a naturally isomorphic
functor. -/
def inv_fun_id_assoc (e : C ≌ D) (F : D ⥤ E) : e.inverse ⋙ e.functor ⋙ F ≅ F :=
(functor.associator _ _ _).symm ≪≫ iso_whisker_right e.counit_iso F ≪≫ F.left_unitor
@[simp] lemma inv_fun_id_assoc_hom_app (e : C ≌ D) (F : D ⥤ E) (X : D) :
(inv_fun_id_assoc e F).hom.app X = F.map (e.counit.app X) :=
by { dsimp [inv_fun_id_assoc], tidy }
@[simp] lemma inv_fun_id_assoc_inv_app (e : C ≌ D) (F : D ⥤ E) (X : D) :
(inv_fun_id_assoc e F).inv.app X = F.map (e.counit_inv.app X) :=
by { dsimp [inv_fun_id_assoc], tidy }
/-- If `C` is equivalent to `D`, then `C ⥤ E` is equivalent to `D ⥤ E`. -/
@[simps functor inverse unit_iso counit_iso]
def congr_left (e : C ≌ D) : (C ⥤ E) ≌ (D ⥤ E) :=
equivalence.mk
((whiskering_left _ _ _).obj e.inverse)
((whiskering_left _ _ _).obj e.functor)
(nat_iso.of_components (λ F, (e.fun_inv_id_assoc F).symm) (by tidy))
(nat_iso.of_components (λ F, e.inv_fun_id_assoc F) (by tidy))
/-- If `C` is equivalent to `D`, then `E ⥤ C` is equivalent to `E ⥤ D`. -/
@[simps functor inverse unit_iso counit_iso]
def congr_right (e : C ≌ D) : (E ⥤ C) ≌ (E ⥤ D) :=
equivalence.mk
((whiskering_right _ _ _).obj e.functor)
((whiskering_right _ _ _).obj e.inverse)
(nat_iso.of_components
(λ F, F.right_unitor.symm ≪≫ iso_whisker_left F e.unit_iso ≪≫ functor.associator _ _ _)
(by tidy))
(nat_iso.of_components
(λ F, functor.associator _ _ _ ≪≫ iso_whisker_left F e.counit_iso ≪≫ F.right_unitor)
(by tidy))
section cancellation_lemmas
variables (e : C ≌ D)
/- We need special forms of `cancel_nat_iso_hom_right(_assoc)` and
`cancel_nat_iso_inv_right(_assoc)` for units and counits, because neither `simp` or `rw` will apply
those lemmas in this setting without providing `e.unit_iso` (or similar) as an explicit argument.
We also provide the lemmas for length four compositions, since they're occasionally useful.
(e.g. in proving that equivalences take monos to monos) -/
@[simp] lemma cancel_unit_right {X Y : C}
(f f' : X ⟶ Y) :
f ≫ e.unit.app Y = f' ≫ e.unit.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_unit_inv_right {X Y : C}
(f f' : X ⟶ e.inverse.obj (e.functor.obj Y)) :
f ≫ e.unit_inv.app Y = f' ≫ e.unit_inv.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_counit_right {X Y : D}
(f f' : X ⟶ e.functor.obj (e.inverse.obj Y)) :
f ≫ e.counit.app Y = f' ≫ e.counit.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_counit_inv_right {X Y : D}
(f f' : X ⟶ Y) :
f ≫ e.counit_inv.app Y = f' ≫ e.counit_inv.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_unit_right_assoc {W X X' Y : C}
(f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) :
f ≫ g ≫ e.unit.app Y = f' ≫ g' ≫ e.unit.app Y ↔ f ≫ g = f' ≫ g' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_counit_inv_right_assoc {W X X' Y : D}
(f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) :
f ≫ g ≫ e.counit_inv.app Y = f' ≫ g' ≫ e.counit_inv.app Y ↔ f ≫ g = f' ≫ g' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_unit_right_assoc' {W X X' Y Y' Z : C}
(f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) :
f ≫ g ≫ h ≫ e.unit.app Z = f' ≫ g' ≫ h' ≫ e.unit.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_counit_inv_right_assoc' {W X X' Y Y' Z : D}
(f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) :
f ≫ g ≫ h ≫ e.counit_inv.app Z = f' ≫ g' ≫ h' ≫ e.counit_inv.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' :=
by simp only [←category.assoc, cancel_mono]
end cancellation_lemmas
section
-- There's of course a monoid structure on `C ≌ C`,
-- but let's not encourage using it.
-- The power structure is nevertheless useful.
/-- Natural number powers of an auto-equivalence. Use `(^)` instead. -/
def pow_nat (e : C ≌ C) : ℕ → (C ≌ C)
| 0 := equivalence.refl
| 1 := e
| (n+2) := e.trans (pow_nat (n+1))
/-- Powers of an auto-equivalence. Use `(^)` instead. -/
def pow (e : C ≌ C) : ℤ → (C ≌ C)
| (int.of_nat n) := e.pow_nat n
| (int.neg_succ_of_nat n) := e.symm.pow_nat (n+1)
instance : has_pow (C ≌ C) ℤ := ⟨pow⟩
@[simp] lemma pow_zero (e : C ≌ C) : e^(0 : ℤ) = equivalence.refl := rfl
@[simp] lemma pow_one (e : C ≌ C) : e^(1 : ℤ) = e := rfl
@[simp] lemma pow_neg_one (e : C ≌ C) : e^(-1 : ℤ) = e.symm := rfl
-- TODO as necessary, add the natural isomorphisms `(e^a).trans e^b ≅ e^(a+b)`.
-- At this point, we haven't even defined the category of equivalences.
end
end equivalence
/-- A functor that is part of a (half) adjoint equivalence -/
class is_equivalence (F : C ⥤ D) :=
mk' ::
(inverse : D ⥤ C)
(unit_iso : 𝟭 C ≅ F ⋙ inverse)
(counit_iso : inverse ⋙ F ≅ 𝟭 D)
(functor_unit_iso_comp' : ∀ (X : C), F.map ((unit_iso.hom : 𝟭 C ⟶ F ⋙ inverse).app X) ≫
counit_iso.hom.app (F.obj X) = 𝟙 (F.obj X) . obviously)
restate_axiom is_equivalence.functor_unit_iso_comp'
attribute [simp, reassoc] is_equivalence.functor_unit_iso_comp
namespace is_equivalence
instance of_equivalence (F : C ≌ D) : is_equivalence F.functor :=
{ ..F }
instance of_equivalence_inverse (F : C ≌ D) : is_equivalence F.inverse :=
is_equivalence.of_equivalence F.symm
open equivalence
/-- To see that a functor is an equivalence, it suffices to provide an inverse functor `G` such that
`F ⋙ G` and `G ⋙ F` are naturally isomorphic to identity functors. -/
protected definition mk {F : C ⥤ D} (G : D ⥤ C)
(η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : is_equivalence F :=
⟨G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩
end is_equivalence
namespace functor
/-- Interpret a functor that is an equivalence as an equivalence. -/
def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D :=
⟨F, is_equivalence.inverse F, is_equivalence.unit_iso, is_equivalence.counit_iso,
is_equivalence.functor_unit_iso_comp⟩
instance is_equivalence_refl : is_equivalence (𝟭 C) :=
is_equivalence.of_equivalence equivalence.refl
/-- The inverse functor of a functor that is an equivalence. -/
def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C :=
is_equivalence.inverse F
instance is_equivalence_inv (F : C ⥤ D) [is_equivalence F] : is_equivalence F.inv :=
is_equivalence.of_equivalence F.as_equivalence.symm
@[simp] lemma as_equivalence_functor (F : C ⥤ D) [is_equivalence F] :
F.as_equivalence.functor = F := rfl
@[simp] lemma as_equivalence_inverse (F : C ⥤ D) [is_equivalence F] :
F.as_equivalence.inverse = inv F := rfl
@[simp] lemma as_equivalence_unit {F : C ⥤ D} [h : is_equivalence F] :
F.as_equivalence.unit_iso = @@is_equivalence.unit_iso _ _ h := rfl
@[simp] lemma as_equivalence_counit {F : C ⥤ D} [is_equivalence F] :
F.as_equivalence.counit_iso = is_equivalence.counit_iso := rfl
@[simp] lemma inv_inv (F : C ⥤ D) [is_equivalence F] :
inv (inv F) = F := rfl
variables {E : Type u₃} [category.{v₃} E]
instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] :
is_equivalence (F ⋙ G) :=
is_equivalence.of_equivalence (equivalence.trans (as_equivalence F) (as_equivalence G))
end functor
namespace equivalence
@[simp]
lemma functor_inv (E : C ≌ D) : E.functor.inv = E.inverse := rfl
@[simp]
lemma inverse_inv (E : C ≌ D) : E.inverse.inv = E.functor := rfl
@[simp]
lemma functor_as_equivalence (E : C ≌ D) : E.functor.as_equivalence = E :=
by { cases E, congr, }
@[simp]
lemma inverse_as_equivalence (E : C ≌ D) : E.inverse.as_equivalence = E.symm :=
by { cases E, congr, }
end equivalence
namespace is_equivalence
@[simp] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) :
F.map (F.inv.map f) = F.as_equivalence.counit.app X ≫ f ≫ F.as_equivalence.counit_inv.app Y :=
begin
erw [nat_iso.naturality_2],
refl
end
@[simp] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) :
F.inv.map (F.map f) = F.as_equivalence.unit_inv.app X ≫ f ≫ F.as_equivalence.unit.app Y :=
begin
erw [nat_iso.naturality_1],
refl
end
end is_equivalence
namespace equivalence
/--
An equivalence is essentially surjective.
See https://stacks.math.columbia.edu/tag/02C3.
-/
lemma ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F :=
⟨λ Y, ⟨F.inv.obj Y, ⟨F.as_equivalence.counit_iso.app Y⟩⟩⟩
/--
An equivalence is faithful.
See https://stacks.math.columbia.edu/tag/02C3.
-/
@[priority 100] -- see Note [lower instance priority]
instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F :=
{ map_injective' := λ X Y f g w,
begin
have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w,
simpa only [cancel_epi, cancel_mono, is_equivalence.inv_fun_map] using p
end }.
/--
An equivalence is full.
See https://stacks.math.columbia.edu/tag/02C3.
-/
@[priority 100] -- see Note [lower instance priority]
instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F :=
{ preimage := λ X Y f, F.as_equivalence.unit.app X ≫ F.inv.map f ≫ F.as_equivalence.unit_inv.app Y,
witness' := λ X Y f, F.inv.map_injective $
by simpa only [is_equivalence.inv_fun_map, assoc, iso.inv_hom_id_app_assoc, iso.inv_hom_id_app]
using comp_id _ }
@[simps] private noncomputable def equivalence_inverse (F : C ⥤ D) [full F] [faithful F]
[ess_surj F] : D ⥤ C :=
{ obj := λ X, F.obj_preimage X,
map := λ X Y f, F.preimage ((F.obj_obj_preimage_iso X).hom ≫ f ≫ (F.obj_obj_preimage_iso Y).inv),
map_id' := λ X, begin apply F.map_injective, tidy end,
map_comp' := λ X Y Z f g, by apply F.map_injective; simp }
/--
A functor which is full, faithful, and essentially surjective is an equivalence.
See https://stacks.math.columbia.edu/tag/02C3.
-/
noncomputable def of_fully_faithfully_ess_surj
(F : C ⥤ D) [full F] [faithful F] [ess_surj F] : is_equivalence F :=
is_equivalence.mk (equivalence_inverse F)
(nat_iso.of_components
(λ X, (preimage_iso $ F.obj_obj_preimage_iso $ F.obj X).symm)
(λ X Y f, by { apply F.map_injective, obviously }))
(nat_iso.of_components F.obj_obj_preimage_iso (by tidy))
@[simp] lemma functor_map_inj_iff (e : C ≌ D) {X Y : C} (f g : X ⟶ Y) :
e.functor.map f = e.functor.map g ↔ f = g :=
⟨λ h, e.functor.map_injective h, λ h, h ▸ rfl⟩
@[simp] lemma inverse_map_inj_iff (e : C ≌ D) {X Y : D} (f g : X ⟶ Y) :
e.inverse.map f = e.inverse.map g ↔ f = g :=
functor_map_inj_iff e.symm f g
instance ess_surj_induced_functor {C' : Type*} (e : C' ≃ D) : ess_surj (induced_functor e) :=
{ mem_ess_image := λ Y, ⟨e.symm Y, by simp⟩, }
noncomputable
instance induced_functor_of_equiv {C' : Type*} (e : C' ≃ D) : is_equivalence (induced_functor e) :=
equivalence.of_fully_faithfully_ess_surj _
noncomputable
instance fully_faithful_to_ess_image (F : C ⥤ D) [full F] [faithful F] :
is_equivalence F.to_ess_image :=
of_fully_faithfully_ess_surj F.to_ess_image
end equivalence
end category_theory
|
4b369c2819ed347f27b4f2f4dd3863f99d7646f1 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /library/init/native/procedure.lean | 45c0b5184fb2f3dc21881a3679c964fb57e936f1 | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 525 | lean | /-
Copyright (c) 2016 Jared Roesch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jared Roesch
-/
prelude
import init.meta.name
import init.meta.expr
meta def procedure :=
name × expr
meta def procedure.to_string : procedure → string
| (n, e) := "def " ++ to_string n ++ " := \n" ++ to_string e
meta def procedure.map_body (f : expr → expr) : procedure → procedure
| (n, e) := (n, f e)
meta instance : has_to_string procedure :=
⟨ procedure.to_string ⟩
|
e24014597f58e45b43bbe76a3aef5ac9a26acbfb | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/UnaryDistributes.lean | 4b0cc1a962654ee410ea4c2526c8d04c574c346e | [] | no_license | ysharoda/Deriving-Definitions | 3e149e6641fae440badd35ac110a0bd705a49ad2 | dfecb27572022de3d4aa702cae8db19957523a59 | refs/heads/master | 1,679,127,857,700 | 1,615,939,007,000 | 1,615,939,007,000 | 229,785,731 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,416 | lean | import init.data.nat.basic
import init.data.fin.basic
import data.vector
import .Prelude
open Staged
open nat
open fin
open vector
section UnaryDistributes
structure UnaryDistributes (A : Type) : Type :=
(prim : (A → A))
(op : (A → (A → A)))
(distribute_prim_op : (∀ {x y : A} , (prim (op x y)) = (op (prim x) (prim y))))
open UnaryDistributes
structure Sig (AS : Type) : Type :=
(primS : (AS → AS))
(opS : (AS → (AS → AS)))
structure Product (A : Type) : Type :=
(primP : ((Prod A A) → (Prod A A)))
(opP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(distribute_prim_opP : (∀ {xP yP : (Prod A A)} , (primP (opP xP yP)) = (opP (primP xP) (primP yP))))
structure Hom {A1 : Type} {A2 : Type} (Un1 : (UnaryDistributes A1)) (Un2 : (UnaryDistributes A2)) : Type :=
(hom : (A1 → A2))
(pres_prim : (∀ {x1 : A1} , (hom ((prim Un1) x1)) = ((prim Un2) (hom x1))))
(pres_op : (∀ {x1 x2 : A1} , (hom ((op Un1) x1 x2)) = ((op Un2) (hom x1) (hom x2))))
structure RelInterp {A1 : Type} {A2 : Type} (Un1 : (UnaryDistributes A1)) (Un2 : (UnaryDistributes A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_prim : (∀ {x1 : A1} {y1 : A2} , ((interp x1 y1) → (interp ((prim Un1) x1) ((prim Un2) y1)))))
(interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Un1) x1 x2) ((op Un2) y1 y2))))))
inductive UnaryDistributesTerm : Type
| primL : (UnaryDistributesTerm → UnaryDistributesTerm)
| opL : (UnaryDistributesTerm → (UnaryDistributesTerm → UnaryDistributesTerm))
open UnaryDistributesTerm
inductive ClUnaryDistributesTerm (A : Type) : Type
| sing : (A → ClUnaryDistributesTerm)
| primCl : (ClUnaryDistributesTerm → ClUnaryDistributesTerm)
| opCl : (ClUnaryDistributesTerm → (ClUnaryDistributesTerm → ClUnaryDistributesTerm))
open ClUnaryDistributesTerm
inductive OpUnaryDistributesTerm (n : ℕ) : Type
| v : ((fin n) → OpUnaryDistributesTerm)
| primOL : (OpUnaryDistributesTerm → OpUnaryDistributesTerm)
| opOL : (OpUnaryDistributesTerm → (OpUnaryDistributesTerm → OpUnaryDistributesTerm))
open OpUnaryDistributesTerm
inductive OpUnaryDistributesTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpUnaryDistributesTerm2)
| sing2 : (A → OpUnaryDistributesTerm2)
| primOL2 : (OpUnaryDistributesTerm2 → OpUnaryDistributesTerm2)
| opOL2 : (OpUnaryDistributesTerm2 → (OpUnaryDistributesTerm2 → OpUnaryDistributesTerm2))
open OpUnaryDistributesTerm2
def simplifyCl {A : Type} : ((ClUnaryDistributesTerm A) → (ClUnaryDistributesTerm A))
| (opCl (primCl x) (primCl y)) := (primCl (opCl x y))
| (primCl x1) := (primCl (simplifyCl x1))
| (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2))
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpUnaryDistributesTerm n) → (OpUnaryDistributesTerm n))
| (opOL (primOL x) (primOL y)) := (primOL (opOL x y))
| (primOL x1) := (primOL (simplifyOpB x1))
| (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2))
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpUnaryDistributesTerm2 n A) → (OpUnaryDistributesTerm2 n A))
| (opOL2 (primOL2 x) (primOL2 y)) := (primOL2 (opOL2 x y))
| (primOL2 x1) := (primOL2 (simplifyOp x1))
| (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2))
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((UnaryDistributes A) → (UnaryDistributesTerm → A))
| Un (primL x1) := ((prim Un) (evalB Un x1))
| Un (opL x1 x2) := ((op Un) (evalB Un x1) (evalB Un x2))
def evalCl {A : Type} : ((UnaryDistributes A) → ((ClUnaryDistributesTerm A) → A))
| Un (sing x1) := x1
| Un (primCl x1) := ((prim Un) (evalCl Un x1))
| Un (opCl x1 x2) := ((op Un) (evalCl Un x1) (evalCl Un x2))
def evalOpB {A : Type} {n : ℕ} : ((UnaryDistributes A) → ((vector A n) → ((OpUnaryDistributesTerm n) → A)))
| Un vars (v x1) := (nth vars x1)
| Un vars (primOL x1) := ((prim Un) (evalOpB Un vars x1))
| Un vars (opOL x1 x2) := ((op Un) (evalOpB Un vars x1) (evalOpB Un vars x2))
def evalOp {A : Type} {n : ℕ} : ((UnaryDistributes A) → ((vector A n) → ((OpUnaryDistributesTerm2 n A) → A)))
| Un vars (v2 x1) := (nth vars x1)
| Un vars (sing2 x1) := x1
| Un vars (primOL2 x1) := ((prim Un) (evalOp Un vars x1))
| Un vars (opOL2 x1 x2) := ((op Un) (evalOp Un vars x1) (evalOp Un vars x2))
def inductionB {P : (UnaryDistributesTerm → Type)} : ((∀ (x1 : UnaryDistributesTerm) , ((P x1) → (P (primL x1)))) → ((∀ (x1 x2 : UnaryDistributesTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : UnaryDistributesTerm) , (P x))))
| ppriml popl (primL x1) := (ppriml _ (inductionB ppriml popl x1))
| ppriml popl (opL x1 x2) := (popl _ _ (inductionB ppriml popl x1) (inductionB ppriml popl x2))
def inductionCl {A : Type} {P : ((ClUnaryDistributesTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 : (ClUnaryDistributesTerm A)) , ((P x1) → (P (primCl x1)))) → ((∀ (x1 x2 : (ClUnaryDistributesTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClUnaryDistributesTerm A)) , (P x)))))
| psing pprimcl popcl (sing x1) := (psing x1)
| psing pprimcl popcl (primCl x1) := (pprimcl _ (inductionCl psing pprimcl popcl x1))
| psing pprimcl popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing pprimcl popcl x1) (inductionCl psing pprimcl popcl x2))
def inductionOpB {n : ℕ} {P : ((OpUnaryDistributesTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 : (OpUnaryDistributesTerm n)) , ((P x1) → (P (primOL x1)))) → ((∀ (x1 x2 : (OpUnaryDistributesTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpUnaryDistributesTerm n)) , (P x)))))
| pv pprimol popol (v x1) := (pv x1)
| pv pprimol popol (primOL x1) := (pprimol _ (inductionOpB pv pprimol popol x1))
| pv pprimol popol (opOL x1 x2) := (popol _ _ (inductionOpB pv pprimol popol x1) (inductionOpB pv pprimol popol x2))
def inductionOp {n : ℕ} {A : Type} {P : ((OpUnaryDistributesTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 : (OpUnaryDistributesTerm2 n A)) , ((P x1) → (P (primOL2 x1)))) → ((∀ (x1 x2 : (OpUnaryDistributesTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpUnaryDistributesTerm2 n A)) , (P x))))))
| pv2 psing2 pprimol2 popol2 (v2 x1) := (pv2 x1)
| pv2 psing2 pprimol2 popol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 pprimol2 popol2 (primOL2 x1) := (pprimol2 _ (inductionOp pv2 psing2 pprimol2 popol2 x1))
| pv2 psing2 pprimol2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 pprimol2 popol2 x1) (inductionOp pv2 psing2 pprimol2 popol2 x2))
def stageB : (UnaryDistributesTerm → (Staged UnaryDistributesTerm))
| (primL x1) := (stage1 primL (codeLift1 primL) (stageB x1))
| (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2))
def stageCl {A : Type} : ((ClUnaryDistributesTerm A) → (Staged (ClUnaryDistributesTerm A)))
| (sing x1) := (Now (sing x1))
| (primCl x1) := (stage1 primCl (codeLift1 primCl) (stageCl x1))
| (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2))
def stageOpB {n : ℕ} : ((OpUnaryDistributesTerm n) → (Staged (OpUnaryDistributesTerm n)))
| (v x1) := (const (code (v x1)))
| (primOL x1) := (stage1 primOL (codeLift1 primOL) (stageOpB x1))
| (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2))
def stageOp {n : ℕ} {A : Type} : ((OpUnaryDistributesTerm2 n A) → (Staged (OpUnaryDistributesTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| (primOL2 x1) := (stage1 primOL2 (codeLift1 primOL2) (stageOp x1))
| (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2))
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(primT : ((Repr A) → (Repr A)))
(opT : ((Repr A) → ((Repr A) → (Repr A))))
end UnaryDistributes |
0f2c4cc74bb2e0a2bc9cbc2788b151ded9123f04 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/int/cast.lean | 92721d3fc512b030e55c33476ef5d058170820c7 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 8,258 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.int.basic
import data.nat.cast
open nat
namespace int
/- cast (injection into groups with one) -/
@[simp, push_cast] theorem nat_cast_eq_coe_nat : ∀ n,
@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n =
@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n
| 0 := rfl
| (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n)
/-- Coercion `ℕ → ℤ` as a `ring_hom`. -/
def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩
section cast
variables {α : Type*}
section
variables [has_zero α] [has_one α] [has_add α] [has_neg α]
/-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/
protected def cast : ℤ → α
| (n : ℕ) := n
| -[1+ n] := -(n+1)
-- see Note [coercion into rings]
@[priority 900] instance cast_coe : has_coe_t ℤ α := ⟨int.cast⟩
@[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl
theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl
@[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl
theorem cast_coe_nat' (n : ℕ) :
(@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n : α) = n :=
by simp
@[simp, norm_cast] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl
end
@[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] [has_neg α] :
((1 : ℤ) : α) = 1 := nat.cast_one
@[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) :
((int.sub_nat_nat m n : ℤ) : α) = m - n :=
begin
unfold sub_nat_nat, cases e : n - m,
{ simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] },
{ rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e,
nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] },
end
@[simp, norm_cast] theorem cast_neg_of_nat [add_group α] [has_one α] :
∀ n, ((neg_of_nat n : ℤ) : α) = -n
| 0 := neg_zero.symm
| (n+1) := rfl
@[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n
| (m : ℕ) (n : ℕ) := nat.cast_add _ _
| (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _
| -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $
show (n:α) = -(m+1) + n + (m+1),
by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm,
nat.cast_add, cast_succ, neg_add_cancel_left]
| -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1),
begin
rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add],
apply congr_arg (λ x:ℕ, -(x:α)),
ac_refl
end
@[simp, norm_cast] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n
| (n : ℕ) := cast_neg_of_nat _
| -[1+ n] := (neg_neg _).symm
@[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n :=
by simp [sub_eq_add_neg]
@[simp, norm_cast] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n
| (m : ℕ) (n : ℕ) := nat.cast_mul _ _
| (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $
show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg]
| -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $
show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n,
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul]
| -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg]
/-- `coe : ℤ → α` as an `add_monoid_hom`. -/
def cast_add_hom (α : Type*) [add_group α] [has_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩
@[simp] lemma coe_cast_add_hom [add_group α] [has_one α] : ⇑(cast_add_hom α) = coe := rfl
/-- `coe : ℤ → α` as a `ring_hom`. -/
def cast_ring_hom (α : Type*) [ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩
@[simp] lemma coe_cast_ring_hom [ring α] : ⇑(cast_ring_hom α) = coe := rfl
lemma cast_commute [ring α] (m : ℤ) (x : α) : commute ↑m x :=
int.cases_on m (λ n, n.cast_commute x) (λ n, ((n+1).cast_commute x).neg_left)
lemma commute_cast [ring α] (x : α) (m : ℤ) : commute x m :=
(m.cast_commute x).symm
@[simp, norm_cast]
theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp}
@[simp, norm_cast]
theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp}
@[simp, norm_cast] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _
@[simp, norm_cast] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp
theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n
| (n : ℕ) := by simp
| -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using
show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one
@[simp, norm_cast] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
@[simp, norm_cast] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n :=
by simpa [-cast_le] using not_congr (@cast_le α _ n m)
@[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
@[simp, norm_cast] theorem cast_min [linear_ordered_comm_ring α] {a b : ℤ} :
(↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [h, min]
@[simp, norm_cast] theorem cast_max [linear_ordered_comm_ring α] {a b : ℤ} :
(↑(max a b) : α) = max a b :=
by by_cases b ≤ a; simp [h, max]
@[simp, norm_cast] theorem cast_abs [linear_ordered_comm_ring α] {q : ℤ} :
((abs q : ℤ) : α) = abs q :=
by simp [abs]
lemma coe_int_dvd [comm_ring α] (m n : ℤ) (h : m ∣ n) :
(m : α) ∣ (n : α) :=
ring_hom.map_dvd (int.cast_ring_hom α) h
end cast
end int
open int
namespace add_monoid_hom
variables {A : Type*}
/-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal
if `f 1 = g 1`. -/
@[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g :=
have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat h1,
have ∀ n : ℕ, f n = g n := ext_iff.1 this,
ext $ λ n, int.cases_on n this $ λ n, eq_on_neg (this $ n + 1)
variables [add_group A] [has_one A]
theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A :=
ext_int $ by simp [h1]
theorem eq_int_cast (f : ℤ →+ A) (h1 : f 1 = 1) : ∀ n : ℤ, f n = n :=
ext_iff.1 (f.eq_int_cast_hom h1)
end add_monoid_hom
namespace monoid_hom
variables {M : Type*} [monoid M]
open multiplicative
theorem ext_int {f g : multiplicative ℤ →* M}
(h1 : f (of_add 1) = g (of_add 1)) : f = g :=
begin
ext,
exact add_monoid_hom.ext_iff.1
(@add_monoid_hom.ext_int _ _ f.to_additive g.to_additive h1) _,
end
end monoid_hom
namespace ring_hom
variables {α : Type*} {β : Type*} [ring α] [ring β]
@[simp] lemma eq_int_cast (f : ℤ →+* α) (n : ℤ) : f n = n :=
f.to_add_monoid_hom.eq_int_cast f.map_one n
lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α :=
ring_hom.ext f.eq_int_cast
@[simp] lemma map_int_cast (f : α →+* β) (n : ℤ) : f n = n :=
(f.comp (int.cast_ring_hom α)).eq_int_cast n
lemma ext_int {R : Type*} [semiring R] (f g : ℤ →+* R) : f = g :=
coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm
instance int.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℤ →+* R) :=
⟨ring_hom.ext_int⟩
end ring_hom
@[simp, norm_cast] theorem int.cast_id (n : ℤ) : ↑n = n :=
((ring_hom.id ℤ).eq_int_cast n).symm
|
5b82dbc7036538309a30bfea826734bdb992fb76 | e21db629d2e37a833531fdcb0b37ce4d71825408 | /src/mcl/syncablep.lean | d0d049b1decaf2ad59e55f8e881b44f7827b4132 | [] | no_license | fischerman/GPU-transformation-verifier | 614a28cb4606a05a0eb27e8d4eab999f4f5ea60c | 75a5016f05382738ff93ce5859c4cfa47ccb63c1 | refs/heads/master | 1,586,985,789,300 | 1,579,290,514,000 | 1,579,290,514,000 | 165,031,073 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,048 | lean | import mcl.defs
import mcl.rhl
import mcl.lemmas
import mcl.compute_list
import mcl.ts_updates
import syncablep
open parlang
open parlang.thread_state
open parlang.state
open mcl
open mcl.rhl
/-- Copies *var* from tlocal of the nth thread into index n of *m* (forall n). Generally used as an assertion language for Hoare proofs -/
def from_tlocal {sig : signature} {n} (var) (s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) (m : memory (parlang_mcl_shared sig)) (h : (((sig.val var).type).dim) = 1) :=
((list.range_fin n).foldl (λ (m : parlang.memory (parlang_mcl_shared sig)) tid,
m.update ⟨var, eq.mpr (by rw h) v[tid.val]⟩ ((s.threads.nth tid).tlocal.get ⟨var, eq.mpr (by rw h) v[tid.val]⟩))) m
lemma from_tlocal_comm_update {sig : signature} {n} (var₁ var₂) (s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig))
(m : memory (parlang_mcl_shared sig)) {h₁} {idx val} :
from_tlocal var₁ s (m.update ⟨var₂, idx⟩ val) h₁ = memory.update (from_tlocal var₁ s m h₁) ⟨var₂, idx⟩ val := begin
unfold from_tlocal,
induction n,
{ refl, },
{
rw [list.foldl_range_fin_succ],
sorry, -- complicated with dependent type fin
}
end
lemma from_tlocal_comm {sig : signature} {n} (var₁ var₂) (s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig))
(s' : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) (m : memory (parlang_mcl_shared sig)) {h₁ h₂} :
from_tlocal var₁ s (from_tlocal var₂ s' m h₂) h₁ = from_tlocal var₂ s' (from_tlocal var₁ s m h₁) h₂ := begin
unfold from_tlocal,
induction n,
{
refl,
}, {
rw [list.foldl_range_fin_succ],
rw [list.foldl_range_fin_succ],
repeat { rw ← from_tlocal },
sorry,
}
end
--lemma : from_tlocal "b" (map_active_threads ac (ts_updates [op.compute_list (... :: coms)]) s = from_tlocal "b" (map_active_threads ac (ts_updates [op.compute_list (... :: coms)]) s
lemma from_tlocal_eq {sig : signature} {n}
{s s' : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)}
{m m' : memory (parlang_mcl_shared sig)} {var} {h : ((sig.val var).type).dim = 1} :
(∀ tid, (s.threads.nth tid).tlocal.get ⟨var, begin rw h, exact v[tid] end⟩ = (s'.threads.nth tid).tlocal.get ⟨var, begin rw h, exact v[tid] end⟩) →
m = m' →
from_tlocal var s m h = from_tlocal var s' m' h := begin
intros hveq hmeq,
subst hmeq,
unfold from_tlocal,
induction n,
{ refl, },
{
rw list.foldl_range_fin_succ,
sorry,
}
end
lemma syncable'_compute_list_syncable {sig : signature} {n} {ac : vector bool n} {computes} {shole lhole : set $ mcl_address sig}
{s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)}
{m : memory (parlang_mcl_shared sig)} :
s.syncable m →
(∀ tid : fin n, (s.threads.nth tid).stores = ∅) →
(∀ tid : fin n, (s.threads.nth tid).loads = ∅) →
syncable' shole lhole (map_active_threads ac (ts_updates [op.compute_list computes]) s) m := begin
intros syncable no_stores no_loads,
unfold syncable' state.syncable,
split,
{
simp only [accesses, compute_list_stores', compute_list_loads', compute_list_shared'],
exact syncable,
}, {
intros i tid,
simp [no_stores tid, no_loads tid],
}
end
instance deciable_exists_nat (p) : decidable (@Exists ℕ p) := sorry
instance deciable_exists_fin (n p) : decidable (@Exists (fin n) p) := sorry
/-- Processes a store
Which thread accesses which index doesn't matter
-/
lemma syncable'_store {sig : signature} {n} {ac : vector bool n} {computes} {shole lhole : set $ mcl_address sig}
{dim} {idx : vector (expression sig type.int) dim} {var t} {h₁ : type_of (sig.val var) = t} {h₂}
{updates : list $ op sig}
{s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)}
{m : memory (parlang_mcl_shared sig)}
(idx_1 : (((sig.val var).type).dim) = 1) :
(∀ idx, (⟨var, idx⟩ : mcl_address sig) ∉ shole) →
(∀ idx, (⟨var, idx⟩ : mcl_address sig) ∉ lhole) →
(∀ tid₁ tid₂, tid₁ ≠ tid₂ → idx.map (λ ind, eval (s.threads.nth tid₁).tlocal ind) ≠ idx.map (λ ind, eval (s.threads.nth tid₂).tlocal ind)) →
syncable' (shole ∪ array_address_range var) (lhole ∪ array_address_range var) (map_active_threads ac (ts_updates $ op.compute_list computes :: updates) s) m →
syncable' shole lhole (map_active_threads ac (ts_updates $ op.compute_list computes :: op.store var idx h₁ h₂ :: updates) s) (from_tlocal var (map_active_threads ac (ts_updates [op.compute_list computes]) s) m idx_1)
| var_not_in_shole var_not_in_lhole distinct_idx (and.intro syncable holes_constraint) := begin
clear syncable'_store,
unfold syncable',
-- proof: syncable
split, {
intros i,
by_cases i_is_var : i.fst = var,
{
subst i_is_var,
specialize var_not_in_shole i.snd,
specialize var_not_in_lhole i.snd,
-- cases distinct out-of-bound
-- by_cases i_is_oob : (∃ (tid : fin n), i.snd = eq.mpr _ (idx.map (λ ind, eval (s.threads.nth tid).tlocal ind))),
sorry,
},
sorry,
}, {
-- proof: store hole
intros i tid,
have : i ∈ shole ∪ array_address_range var := sorry, --trivial
by_cases i_is_var : i.fst = var,
{
-- if i is var we store into hole -> contradiction
subst i_is_var,
specialize var_not_in_shole i.snd,
specialize var_not_in_lhole i.snd,
cases i,
split,
{
intros i_in_store,
contradiction,
}, {
intros i_in_loads,
contradiction,
}
}, {
by_cases tid_activeness : ac.nth tid = tt,
{
rw map_active_threads_nth_ac tid_activeness,
specialize holes_constraint i tid,
rw map_active_threads_nth_ac tid_activeness at holes_constraint,
rw [ts_updates] at holes_constraint,
/- LARGE PROOF STARTS HERE -/
clear syncable,
rw [ts_updates, ts_updates],
revert holes_constraint,
generalize eq : compute_list computes (vector.nth (s.threads) tid) = s',
rw ← list.reverse_reverse updates,
generalize eq' : list.reverse updates = ups,
intro holes_constraint,
-- we do induction on the reverse of the list, such that we "append" elements to the end of updates (i.e. later)
-- afterwards cases on the update (either store or compute)
induction ups generalizing updates,
{
simp [ts_updates, thread_state.tlocal_to_shared, store],
simp [ts_updates, thread_state.tlocal_to_shared, store] at holes_constraint,
cases holes_constraint with shole_constraint lhole_constraint,
split, {
intros i_in_shole i_in_stores,
cases i_in_stores, {
subst i_in_stores,
apply i_is_var,
refl,
}, {
specialize shole_constraint (or.inl i_in_shole),
contradiction,
},
}, {
intro i_in_lhole,
apply lhole_constraint (or.inl i_in_lhole),
}
}, {
rw [ts_update_split],
simp,
cases ups_hd,
{
simp only [ts_updates],
simp only [ts_update_split] at holes_constraint,
simp [ts_updates, -set.mem_union_eq] at holes_constraint,
specialize @ups_ih _ (list.reverse ups_tl),
swap,
{
split, {
intro,
apply store_stores,
apply holes_constraint.left a,
}, {
intro,
apply store_loads,
apply holes_constraint.right a,
},
},
simp [thread_state.tlocal_to_shared, store],
simp [thread_state.tlocal_to_shared, store] at ups_ih,
split,
{
intros i_in_shole,
rw not_or_distrib,
split, {
-- proof that the new store doesn't store in i
cases holes_constraint with shole_constraint lhole_constraint,
simp [thread_state.tlocal_to_shared, store] at shole_constraint,
rw not_or_distrib at shole_constraint,
cases shole_constraint (or.inl i_in_shole),
rw ts_updates_tlocal s'.shared s'.loads s'.stores,
simp,
have : s' = {tlocal := s'.tlocal, shared := s'.shared, loads := s'.loads, stores := s'.stores} := begin
cases s',
simp,
end,
rw ← this,
assumption,
}, {
apply ups_ih.left i_in_shole,
}
}, {
intros i_in_lhole,
apply ups_ih.right i_in_lhole,
}
}, {
-- the head element is compute_list
simp [ts_updates],
apply ups_ih,
swap 3,
exact list.reverse ups_tl,
rw [ts_update_split] at holes_constraint,
simp [ts_updates] at holes_constraint,
simp,
exact holes_constraint,
simp,
}
},
}, {
specialize holes_constraint i tid,
rw ← map_active_threads_nth_inac tid_activeness,
rw ← map_active_threads_nth_inac tid_activeness at holes_constraint,
simp *,
intro a,
apply holes_constraint.right (or.inl a),
}
}
},
end |
e4501a97fa0693abe1963eda8c472c2738ed3108 | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/data/finset/basic.lean | b0cf6b3d4cb19a1ec749f127d5fe92c5c268b617 | [
"Apache-2.0"
] | permissive | spolu/mathlib | bacf18c3d2a561d00ecdc9413187729dd1f705ed | 480c92cdfe1cf3c2d083abded87e82162e8814f4 | refs/heads/master | 1,671,684,094,325 | 1,600,736,045,000 | 1,600,736,045,000 | 297,564,749 | 1 | 0 | null | 1,600,758,368,000 | 1,600,758,367,000 | null | UTF-8 | Lean | false | false | 90,446 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro
-/
import data.multiset.finset_ops
import tactic.monotonicity
import tactic.apply
/-!
# Finite sets
mathlib has several different models for finite sets,
and it can be confusing when you're first getting used to them!
This file builds the basic theory of `finset α`,
modelled as a `multiset α` without duplicates.
It's "constructive" in the since that there is an underlying list of elements,
although this is wrapped in a quotient by permutations,
so anytime you actually use this list you're obligated to show you didn't depend on the ordering.
There's also the typeclass `fintype α`
(which asserts that there is some `finset α` containing every term of type `α`)
as well as the predicate `finite` on `s : set α` (which asserts `nonempty (fintype s)`).
-/
open multiset subtype nat
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `finset α` is the type of finite sets of elements of `α`. It is implemented
as a multiset (a list up to permutation) which has no duplicate elements. -/
structure finset (α : Type*) :=
(val : multiset α)
(nodup : nodup val)
namespace finset
theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t
| ⟨s, _⟩ ⟨t, _⟩ rfl := rfl
@[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t :=
⟨eq_of_veq, congr_arg _⟩
@[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 :=
erase_dup_eq_self.2 s.2
instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α)
| s₁ s₂ := decidable_of_iff _ val_inj
/- membership -/
instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩
theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl
@[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl
instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) :=
multiset.decidable_mem _ _
/-! ### set coercion -/
/-- Convert a finset to a set in the natural way. -/
instance : has_lift (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩
@[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl
@[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = ↑s := rfl
@[simp] lemma coe_mem {s : finset α} (x : (↑s : set α)) : ↑x ∈ s := x.2
@[simp] lemma mk_coe {s : finset α} (x : (↑s : set α)) {h} :
(⟨↑x, h⟩ : (↑s : set α)) = x :=
by { apply subtype.eq, refl, }
instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) :
decidable (a ∈ (↑s : set α)) := s.decidable_mem _
/-! ### extensionality -/
theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ :=
val_inj.symm.trans $ nodup_ext s₁.2 s₂.2
@[ext]
theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ :=
ext_iff.2
@[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ :=
set.ext_iff.trans ext_iff.symm
lemma coe_injective {α} : function.injective (coe : finset α → set α) :=
λ s t, coe_inj.1
/-! ### subset -/
instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩
theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl
@[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _
theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans
theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ :=
λ h' h, subset.trans h h'
-- TODO: these should be global attributes, but this will require fixing other files
local attribute [trans] subset.trans superset.trans
theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset
theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ :=
ext $ λ a, ⟨@H₁ a, @H₂ a⟩
theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl
@[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} :
(↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2
instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩
instance : partial_order (finset α) :=
{ le := (⊆),
lt := (⊂),
le_refl := subset.refl,
le_trans := @subset.trans _,
le_antisymm := @subset.antisymm _ }
theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ :=
le_antisymm_iff
@[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl
@[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊂ s₂ :=
show (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁,
by simp only [set.ssubset_def, finset.coe_subset]
@[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ :=
and_congr val_le_iff $ not_congr val_le_iff
theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ :=
set.ssubset_iff_of_subset h
/-! ### Nonempty -/
/-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used
in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks
to the dot notation. -/
protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s
@[simp, norm_cast] lemma coe_nonempty {s : finset α} : (↑s:set α).nonempty ↔ s.nonempty := iff.rfl
lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h
lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty :=
set.nonempty.mono hst hs
/-! ### empty -/
/-- The empty finset -/
protected def empty : finset α := ⟨0, nodup_zero⟩
instance : has_emptyc (finset α) := ⟨finset.empty⟩
instance : inhabited (finset α) := ⟨∅⟩
@[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl
@[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id
@[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ :=
λ e, not_mem_empty a $ e ▸ h
theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ :=
exists.elim h $ λ a, ne_empty_of_mem
@[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _
theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ :=
eq_of_veq (eq_zero_of_forall_not_mem H)
lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s :=
⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩
@[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅
theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero
theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty :=
exists_mem_of_ne_zero (mt val_eq_zero.1 h)
theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ :=
⟨nonempty.ne_empty, nonempty_of_ne_empty⟩
theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty :=
classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h))
@[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl
/-- A `finset` for an empty type is empty. -/
lemma eq_empty_of_not_nonempty (h : ¬ nonempty α) (s : finset α) : s = ∅ :=
finset.eq_empty_of_forall_not_mem $ λ x, false.elim $ not_nonempty_iff_imp_false.1 h x
/-! ### singleton -/
/--
`{a} : finset a` is the set `{a}` containing `a` and nothing else.
This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`.
-/
instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩
@[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = a :: 0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton
theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton
theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl
theorem singleton_inj {a b : α} : ({a} : finset α) = {b} ↔ a = b :=
⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩
theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩
@[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty
@[simp] lemma coe_singleton (a : α) : ↑({a} : finset α) = ({a} : set α) := by { ext, simp }
lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} :
s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a :=
begin
split; intro t,
rw t,
refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩,
ext, rw finset.mem_singleton,
refine ⟨t.right _, λ r, r.symm ▸ t.left⟩
end
lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s :=
by simp only [eq_singleton_iff_unique_mem, exists_unique]
lemma singleton_subset_set_iff {s : set α} {a : α} :
↑({a} : finset α) ⊆ s ↔ a ∈ s :=
by rw [coe_singleton, set.singleton_subset_iff]
@[simp] lemma singleton_subset_iff {s : finset α} {a : α} :
{a} ⊆ s ↔ a ∈ s :=
singleton_subset_set_iff
/-! ### cons -/
/-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as
`insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`,
and the union is guaranteed to be disjoint. -/
def cons {α} (a : α) (s : finset α) (h : a ∉ s) : finset α :=
⟨a :: s.1, multiset.nodup_cons.2 ⟨h, s.2⟩⟩
@[simp] theorem mem_cons {α a s h b} : b ∈ @cons α a s h ↔ b = a ∨ b ∈ s :=
by rcases s with ⟨⟨s⟩⟩; apply list.mem_cons_iff
@[simp] theorem cons_val {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).1 = a :: s.1 := rfl
/-! ### disjoint union -/
/-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`.
It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis
ensures that the sets are disjoint. -/
def disj_union {α} (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : finset α :=
⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, h⟩⟩
@[simp] theorem mem_disj_union {α s t h a} :
a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t :=
by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append
/-! ### insert -/
section decidable_eq
variables [decidable_eq α]
/-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/
instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩
theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl
@[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl
theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) :=
by rw [erase_dup_cons, erase_dup_eq_self]; refl
theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 :=
by rw [insert_val, ndinsert_of_not_mem h]
@[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert
theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1
theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s :=
mem_ndinsert_of_mem h
theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s :=
(mem_insert.1 h).resolve_left
@[simp] theorem cons_eq_insert {α} [decidable_eq α] (a s h) : @cons α a s h = insert a s :=
ext $ λ a, by simp
@[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) :
↑(insert a s) = (insert a ↑s : set α) :=
set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff]
instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩
@[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s :=
eq_of_veq $ ndinsert_of_mem h
@[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = {a} :=
insert_eq_of_mem $ mem_singleton_self _
theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) :=
ext $ λ x, by simp only [mem_insert, or.left_comm]
theorem insert_singleton_comm (a b : α) : ({a, b} : finset α) = {b, a} :=
begin
ext,
simp [or.comm]
end
@[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s :=
ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self]
@[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ :=
ne_empty_of_mem (mem_insert_self a s)
lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) :
s ≠ insert a t :=
by { contrapose! h, simp [h] }
theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib]
theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s :=
λ b, mem_insert_of_mem
theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t :=
insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩
lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a ∉ s, insert a s ⊆ t) :=
by exact_mod_cast @set.ssubset_iff_insert α ↑s ↑t
lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff.mpr ⟨a, h, subset.refl _⟩
@[elab_as_eliminator]
protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α]
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s
| ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin
cases nodup_cons.1 nd with m nd',
rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)],
{ exact h₂ (by exact m) (IH nd') },
{ rw [insert_val, ndinsert_of_not_mem m] }
end) nd
/--
To prove a proposition about an arbitrary `finset α`,
it suffices to prove it for the empty `finset`,
and to show that if it holds for some `finset α`,
then it holds for the `finset` obtained by inserting a new element.
-/
@[elab_as_eliminator]
protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α]
(s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s :=
finset.induction h₁ h₂ s
/-- Inserting an element to a finite set is equivalent to the option type. -/
def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) :
{i // i ∈ insert x t} ≃ option {i // i ∈ t} :=
begin
refine
{ to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩,
inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩,
.. },
{ intro y, by_cases h : ↑y = x,
simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk],
simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] },
{ rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk],
have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 },
simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta,
subtype.coe_mk] },
end
/-! ### union -/
/-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/
instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩
theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl
@[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 :=
ndunion_eq_union s₁.2
@[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion
@[simp] theorem disj_union_eq_union {α} [decidable_eq α] (s t h) : @disj_union α s t h = s ∪ t :=
ext $ λ a, by simp
theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ :=
mem_union.2 $ or.inl h
theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ :=
mem_union.2 $ or.inr h
theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ :=
by rw [mem_union, not_or_distrib]
@[simp, norm_cast]
lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := set.ext $ λ x, mem_union
theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ :=
val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩)
theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _
theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _
lemma union_subset_union {s1 t1 s2 t2 : finset α} (h1 : s1 ⊆ t1) (h2 : s2 ⊆ t2) :
s1 ∪ s2 ⊆ t1 ∪ t2 :=
by { intros x hx, rw finset.mem_union at hx ⊢, tauto }
theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ :=
ext $ λ x, by simp only [mem_union, or_comm]
instance : is_commutative (finset α) (∪) := ⟨union_comm⟩
@[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) :=
ext $ λ x, by simp only [mem_union, or_assoc]
instance : is_associative (finset α) (∪) := ⟨union_assoc⟩
@[simp] theorem union_idempotent (s : finset α) : s ∪ s = s :=
ext $ λ _, mem_union.trans $ or_self _
instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩
theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
ext $ λ _, by simp only [mem_union, or.left_comm]
theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ :=
ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)]
theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s
@[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s :=
ext $ λ x, mem_union.trans $ or_false _
@[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s :=
ext $ λ x, mem_union.trans $ false_or _
theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl
@[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) :=
by simp only [insert_eq, union_assoc]
@[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) :=
by simp only [insert_eq, union_left_comm]
theorem insert_union_distrib (a : α) (s t : finset α) :
insert a (s ∪ t) = insert a s ∪ insert a t :=
by simp only [insert_union, union_insert, insert_idem]
@[simp] lemma union_eq_left_iff_subset {s t : finset α} :
s ∪ t = s ↔ t ⊆ s :=
begin
split,
{ assume h,
have : t ⊆ s ∪ t := subset_union_right _ _,
rwa h at this },
{ assume h,
exact subset.antisymm (union_subset (subset.refl _) h) (subset_union_left _ _) }
end
@[simp] lemma left_eq_union_iff_subset {s t : finset α} :
s = s ∪ t ↔ t ⊆ s :=
by rw [← union_eq_left_iff_subset, eq_comm]
@[simp] lemma union_eq_right_iff_subset {s t : finset α} :
t ∪ s = s ↔ t ⊆ s :=
by rw [union_comm, union_eq_left_iff_subset]
@[simp] lemma right_eq_union_iff_subset {s t : finset α} :
s = t ∪ s ↔ t ⊆ s :=
by rw [← union_eq_right_iff_subset, eq_comm]
/-! ### inter -/
/-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/
instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩
theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl
@[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 :=
ndinter_eq_inter s₁.2
@[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter
theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) :
a ∈ s₁ := (mem_inter.1 h).1
theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) :
a ∈ s₂ := (mem_inter.1 h).2
theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ :=
and_imp.1 mem_inter.2
theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left
theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right
theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ :=
by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial
@[simp, norm_cast]
lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := set.ext $ λ _, mem_inter
@[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s :=
by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left]
@[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t :=
by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right]
theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ :=
ext $ λ _, by simp only [mem_inter, and_comm]
@[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) :=
ext $ λ _, by simp only [mem_inter, and_assoc]
theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
ext $ λ _, by simp only [mem_inter, and.left_comm]
theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ :=
ext $ λ _, by simp only [mem_inter, and.right_comm]
@[simp] theorem inter_self (s : finset α) : s ∩ s = s :=
ext $ λ _, mem_inter.trans $ and_self _
@[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ :=
ext $ λ _, mem_inter.trans $ and_false _
@[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ :=
ext $ λ _, mem_inter.trans $ false_and _
@[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s :=
by rw [inter_comm, union_inter_cancel_right]
@[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) :
insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) :=
ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h,
by simp only [mem_inter, mem_insert, or_and_distrib_left, this]
@[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) :
s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) :=
by rw [inter_comm, insert_inter_of_mem h, inter_comm]
@[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) :
insert a s₁ ∩ s₂ = s₁ ∩ s₂ :=
ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H,
by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or]
@[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) :
s₁ ∩ insert a s₂ = s₁ ∩ s₂ :=
by rw [inter_comm, insert_inter_of_not_mem h, inter_comm]
@[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} :=
show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter]
@[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ :=
eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h
@[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} :=
by rw [inter_comm, singleton_inter_of_mem h]
@[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ :=
by rw [inter_comm, singleton_inter_of_not_mem h]
@[mono]
lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t :=
begin
intros a a_in,
rw finset.mem_inter at a_in ⊢,
exact ⟨h a_in.1, h' a_in.2⟩
end
lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s :=
finset.inter_subset_inter h (finset.subset.refl _)
lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y :=
finset.inter_subset_inter (finset.subset.refl _) h
/-! ### lattice laws -/
instance : lattice (finset α) :=
{ sup := (∪),
sup_le := assume a b c, union_subset,
le_sup_left := subset_union_left,
le_sup_right := subset_union_right,
inf := (∩),
le_inf := assume a b c, subset_inter,
inf_le_left := inter_subset_left,
inf_le_right := inter_subset_right,
..finset.partial_order }
@[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl
instance : semilattice_inf_bot (finset α) :=
{ bot := ∅, bot_le := empty_subset, ..finset.lattice }
instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) :=
{ ..finset.semilattice_inf_bot, ..finset.lattice }
instance : distrib_lattice (finset α) :=
{ le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c,
by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt};
simp only [true_or, imp_true_iff, true_and, or_true],
..finset.lattice }
theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left
theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right
theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left
theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right
lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff
/-! ### erase -/
/-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are
not equal to `a`. -/
def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩
@[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl
@[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s :=
mem_erase_iff_of_nodup s.2
theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2
@[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl
theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a :=
by simp only [mem_erase]; exact and.left
theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase
theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b :=
by simp only [mem_erase]; exact and.intro
/-- An element of `s` that is not an element of `erase s a` must be
`a`. -/
lemma eq_of_mem_of_not_mem_erase {a b : α} {s : finset α} (hs : b ∈ s)
(hsa : b ∉ s.erase a) : b = a :=
begin
rw [mem_erase, not_and] at hsa,
exact not_imp_not.mp hsa hs
end
theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s :=
ext $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or];
apply and_iff_right_of_imp; rintro H rfl; exact h H
theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s :=
ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and];
apply or_iff_right_of_imp; rintro rfl; exact h
theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a :=
val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h
theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _
@[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) :=
set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl
lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s :=
calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _
... = _ : insert_erase h
theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s :=
eq_of_veq $ erase_of_not_mem h
theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t :=
by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp];
exact forall_congr (λ x, forall_swap)
theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s :=
subset_insert_iff.1 $ subset.refl _
theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) :=
subset_insert_iff.2 $ subset.refl _
/-! ### sdiff -/
/-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/
instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩
@[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} :
a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2
lemma not_mem_sdiff_of_mem_right {a : α} {s t : finset α} (h : a ∈ t) : a ∉ s \ t :=
by simp only [mem_sdiff, h, not_true, not_false_iff, and_false]
theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ :=
ext $ λ a, by simpa only [mem_sdiff, mem_union, or_comm,
or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a)
theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ :=
(union_comm _ _).trans (sdiff_union_of_subset h)
theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u :=
by { ext x, simp [and_assoc] }
@[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ :=
eq_empty_of_forall_not_mem $
by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h
@[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ :=
(inter_comm _ _).trans (inter_sdiff_self _ _)
@[simp] theorem sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ :=
by ext; simp
theorem sdiff_inter_distrib_right (s₁ s₂ s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = (s₁ \ s₂) ∪ (s₁ \ s₃) :=
by ext; simp only [and_or_distrib_left, mem_union, not_and_distrib, mem_sdiff, mem_inter]
@[simp] theorem sdiff_inter_self_left (s₁ s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ :=
by simp only [sdiff_inter_distrib_right, sdiff_self, empty_union]
@[simp] theorem sdiff_inter_self_right (s₁ s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ :=
by simp only [sdiff_inter_distrib_right, sdiff_self, union_empty]
@[simp] theorem sdiff_empty {s₁ : finset α} : s₁ \ ∅ = s₁ :=
ext (by simp)
@[mono]
theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) :
t₁ \ s₁ ⊆ t₂ \ s₂ :=
by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂)
theorem sdiff_subset_self {s₁ s₂ : finset α} : s₁ \ s₂ ⊆ s₁ :=
suffices s₁ \ s₂ ⊆ s₁ \ ∅, by simpa [sdiff_empty] using this,
sdiff_subset_sdiff (subset.refl _) (empty_subset _)
@[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) :=
set.ext $ λ _, mem_sdiff
@[simp] theorem union_sdiff_self_eq_union {s t : finset α} : s ∪ (t \ s) = s ∪ t :=
ext $ λ a, by simp only [mem_union, mem_sdiff, or_iff_not_imp_left,
imp_and_distrib, and_iff_left id]
@[simp] theorem sdiff_union_self_eq_union {s t : finset α} : (s \ t) ∪ t = s ∪ t :=
by rw [union_comm, union_sdiff_self_eq_union, union_comm]
lemma union_sdiff_symm {s t : finset α} : s ∪ (t \ s) = t ∪ (s \ t) :=
by rw [union_sdiff_self_eq_union, union_sdiff_self_eq_union, union_comm]
lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s :=
by { simp only [ext_iff, mem_union, mem_sdiff, mem_inter], tauto }
@[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t :=
by { simp only [ext_iff, mem_sdiff], tauto }
lemma sdiff_eq_empty_iff_subset {s t : finset α} : s \ t = ∅ ↔ s ⊆ t :=
by { rw [subset_iff, ext_iff], simp }
@[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ :=
by { rw sdiff_eq_empty_iff_subset, exact empty_subset _ }
lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) :
(insert x s) \ t = insert x (s \ t) :=
begin
rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert],
exact set.insert_diff_of_not_mem ↑s h
end
lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) :
(insert x s) \ t = s \ t :=
begin
rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert],
exact set.insert_diff_of_mem ↑s h
end
@[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s :=
by simp [subset_iff, mem_sdiff] {contextual := tt}
lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t :=
by { simp only [ext_iff, mem_sdiff, mem_union], tauto }
lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) :=
by { simp only [ext_iff, mem_union, mem_sdiff, mem_inter], tauto }
lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t :=
by rw [union_sdiff_distrib, sdiff_self, union_empty]
lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a :=
by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto }
lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t :=
by { simp only [ext_iff, mem_sdiff, mem_inter], tauto }
lemma inter_eq_inter_of_sdiff_eq_sdiff {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ → s ∩ t₁ = s ∩ t₂ :=
by { simp only [ext_iff, mem_sdiff, mem_inter], intros b c, replace b := b c, split; tauto }
end decidable_eq
/-! ### attach -/
/-- `attach s` takes the elements of `s` and forms a new set of elements of the
subtype `{x // x ∈ s}`. -/
def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) :
sizeof x < sizeof s := by
{ cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof],
apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx }
@[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl
@[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _
@[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl
/-! ### piecewise -/
section piecewise
/-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its
complement. -/
def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] :
Πi, δ i :=
λi, if i ∈ s then f i else g i
variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i)
@[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g j = f j :=
by simp [piecewise]
@[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g :=
by { ext i, simp [piecewise] }
variable [∀j, decidable (j ∈ s)]
@[norm_cast] lemma piecewise_coe [∀j, decidable (j ∈ (↑s : set α))] :
(↑s : set α).piecewise f g = s.piecewise f g :=
by { ext, congr }
@[simp, priority 980]
lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i :=
by simp [piecewise, hi]
@[simp, priority 980]
lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i :=
by simp [piecewise, hi]
@[simp, priority 990]
lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)]
(h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i :=
by simp [piecewise, h]
lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) :=
begin
classical,
rw [← piecewise_coe, ← piecewise_coe, ← set.piecewise_insert, ← coe_insert j s],
congr
end
lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) :
function.update f i v = piecewise (singleton i) (λj, v) f :=
begin
ext j,
by_cases h : j = i,
{ rw [h], simp },
{ simp [h] }
end
end piecewise
section decidable_pi_exists
variables {s : finset α}
instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∀a (h : a ∈ s), p a h) :=
multiset.decidable_dforall_multiset
/-- decidable equality for functions whose domain is bounded by finsets -/
instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈s, β a) :=
multiset.decidable_eq_pi_multiset
instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∃a (h : a ∈ s), p a h) :=
multiset.decidable_dexists_multiset
end decidable_pi_exists
/-! ### filter -/
section filter
variables {p q : α → Prop} [decidable_pred p] [decidable_pred q]
/-- `filter p s` is the set of elements of `s` that satisfy `p`. -/
def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α :=
⟨_, nodup_filter p s.2⟩
@[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl
@[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter
@[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _
theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x :=
⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩,
λ ⟨x, hs, hp⟩, ⟨s.filter_subset, λ h, hp (mem_filter.1 (h hs)).2⟩⟩
theorem filter_filter (s : finset α) :
(s.filter p).filter q = s.filter (λa, p a ∧ q a) :=
ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm]
lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] :
@finset.filter α (λ _, true) h s = s :=
by ext; simp
@[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ :=
ext $ assume a, by simp only [mem_filter, and_false]; refl
/-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/
@[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s :=
ext $ λ x, ⟨λ h, (mem_filter.1 h).1, λ hx, mem_filter.2 ⟨hx, h x hx⟩⟩
/-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/
lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ :=
eq_empty_of_forall_not_mem (by simpa)
lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s :=
eq_of_veq $ filter_congr H
lemma filter_empty : filter p ∅ = ∅ :=
subset_empty.1 $ filter_subset _
lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p :=
assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩
@[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) :=
set.ext $ λ _, mem_filter
theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ :=
by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] }
variable [decidable_eq α]
theorem filter_union (s₁ s₂ : finset α) :
(s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p :=
ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right]
theorem filter_union_right (p q : α → Prop) [decidable_pred p] [decidable_pred q] (s : finset α) :
s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) :=
ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm]
lemma filter_mem_eq_inter {s t : finset α} : s.filter (λ i, i ∈ t) = s ∩ t :=
ext $ λ i, by rw [mem_filter, mem_inter]
theorem filter_inter {s t : finset α} : filter p s ∩ t = filter p (s ∩ t) :=
by { ext, simp only [mem_inter, mem_filter, and.right_comm] }
theorem inter_filter {s t : finset α} : s ∩ filter p t = filter p (s ∩ t) :=
by rw [inter_comm, filter_inter, inter_comm]
theorem filter_insert (a : α) (s : finset α) :
filter p (insert a s) = if p a then insert a (filter p s) else (filter p s) :=
by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] }
theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) :
s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q :=
ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left]
theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) :
s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q :=
ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self]
theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) :
s.filter (λ a, ¬ p a) = s \ s.filter p :=
ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $
λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm
theorem sdiff_eq_filter (s₁ s₂ : finset α) :
s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter]
theorem sdiff_eq_self (s₁ s₂ : finset α) :
s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ :=
by { simp [subset.antisymm_iff,sdiff_subset_self],
split; intro h,
{ transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp },
{ calc s₁ \ s₂
⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)]
... ⊇ s₁ \ ∅ : by mono using [(⊇)]
... ⊇ s₁ : by simp [(⊇)] } }
theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)]
(s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s :=
by simp only [filter_not, union_sdiff_of_subset (filter_subset s)]
theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ :=
by simp only [filter_not, inter_sdiff_self]
lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) :
∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ :=
begin
classical,
refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩,
{ simp [filter_union_right, em] },
{ intro x, simp },
{ intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ }
end
/- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/
@[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p)
[decidable_pred p] : @filter α p h s = s.filter p :=
by congr
section classical
open_locale classical
/-- The following instance allows us to write `{ x ∈ s | p x }` for `finset.filter s p`.
Since the former notation requires us to define this for all propositions `p`, and `finset.filter`
only works for decidable propositions, the notation `{ x ∈ s | p x }` is only compatible with
classical logic because it uses `classical.prop_decidable`.
We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp`
unfolds the notation `{ x ∈ s | p x }` to `finset.filter s p`. If `p` happens to be decidable, the
simp-lemma `filter_congr_decidable` will make sure that `finset.filter` uses the right instance
for decidability.
-/
noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩
@[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl
end classical
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq'` with the equality the other way.
-/
-- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing
-- on, e.g. `x ∈ s.filter(eq b)`.
lemma filter_eq [decidable_eq β] (s : finset β) (b : β) :
s.filter(eq b) = ite (b ∈ s) {b} ∅ :=
begin
split_ifs,
{ ext,
simp only [mem_filter, mem_singleton],
exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ },
{ ext,
simp only [mem_filter, not_and, iff_false, not_mem_empty],
rintros m ⟨e⟩, exact h m, }
end
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq` with the equality the other way.
-/
lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) :
s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ :=
trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b)
lemma filter_ne [decidable_eq β] (s : finset β) (b : β) :
s.filter (λ a, b ≠ a) = s.erase b :=
by { ext, simp only [mem_filter, mem_erase, ne.def], cc, }
lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) :
s.filter (λ a, a ≠ b) = s.erase b :=
trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b)
end filter
/-! ### range -/
section range
variables {n m l : ℕ}
/-- `range n` is the set of natural numbers less than `n`. -/
def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩
@[simp] theorem range_coe (n : ℕ) : (range n).1 = multiset.range n := rfl
@[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range
@[simp] theorem range_zero : range 0 = ∅ := rfl
@[simp] theorem range_one : range 1 = {0} := rfl
theorem range_succ : range (succ n) = insert n (range n) :=
eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm
theorem range_add_one : range (n + 1) = insert n (range n) :=
range_succ
@[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self
@[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n
@[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset
theorem range_mono : monotone range := λ _ _, range_subset.2
end range
/- useful rules for calculations with quantifiers -/
theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false :=
by simp only [not_mem_empty, false_and, exists_false]
theorem exists_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) :=
by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left]
theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true :=
iff_true_intro $ λ _, false.elim
theorem forall_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) :=
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
end finset
/-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/
def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ :=
{ to_fun := λ i, i.1 - k,
inv_fun := λ j, ⟨j + k, by simp⟩,
left_inv :=
begin
assume j,
rw subtype.ext_iff_val,
apply nat.sub_add_cancel,
simpa using j.2
end,
right_inv := λ j, nat.add_sub_cancel _ _ }
@[simp] lemma coe_not_mem_range_equiv (k : ℕ) :
(not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl
@[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) :
((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl
namespace option
/-- Construct an empty or singleton finset from an `option` -/
def to_finset (o : option α) : finset α :=
match o with
| none := ∅
| some a := {a}
end
@[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl
@[simp] theorem to_finset_some {a : α} : (some a).to_finset = {a} := rfl
@[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o :=
by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl
end option
/-! ### erase_dup on list and multiset -/
namespace multiset
variable [decidable_eq α]
/-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/
def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩
@[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl
theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset :=
finset.val_inj.1 (erase_dup_eq_self.2 n).symm
@[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s :=
mem_erase_dup
@[simp] lemma to_finset_zero :
to_finset (0 : multiset α) = ∅ :=
rfl
@[simp] lemma to_finset_cons (a : α) (s : multiset α) :
to_finset (a :: s) = insert a (to_finset s) :=
finset.eq_of_veq erase_dup_cons
@[simp] lemma to_finset_add (s t : multiset α) :
to_finset (s + t) = to_finset s ∪ to_finset t :=
finset.ext $ by simp
@[simp] lemma to_finset_nsmul (s : multiset α) :
∀(n : ℕ) (hn : n ≠ 0), (n •ℕ s).to_finset = s.to_finset
| 0 h := by contradiction
| (n+1) h :=
begin
by_cases n = 0,
{ rw [h, zero_add, one_nsmul] },
{ rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] }
end
@[simp] lemma to_finset_inter (s t : multiset α) :
to_finset (s ∩ t) = to_finset s ∩ to_finset t :=
finset.ext $ by simp
@[simp] lemma to_finset_union (s t : multiset α) :
(s ∪ t).to_finset = s.to_finset ∪ t.to_finset :=
by ext; simp
theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 :=
finset.val_inj.symm.trans multiset.erase_dup_eq_zero
@[simp] lemma to_finset_subset (m1 m2 : multiset α) :
m1.to_finset ⊆ m2.to_finset ↔ m1 ⊆ m2 :=
by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset]
end multiset
namespace list
variable [decidable_eq α]
/-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/
def to_finset (l : list α) : finset α := multiset.to_finset l
@[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl
theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset :=
multiset.to_finset_eq n
@[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l :=
mem_erase_dup
@[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ :=
rfl
@[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) :=
finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h]
theorem to_finset_surjective : function.surjective (to_finset : list α → finset α) :=
begin
refine λ s, ⟨quotient.out' s.val, finset.ext $ λ x, _⟩,
obtain ⟨l, hl⟩ := quot.exists_rep s.val,
rw [list.mem_to_finset, finset.mem_def, ←hl],
exact list.perm.mem_iff (quotient.mk_out l)
end
end list
namespace finset
/-! ### map -/
section map
open function
/-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image
finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/
def map (f : α ↪ β) (s : finset α) : finset β :=
⟨s.1.map f, nodup_map f.2 s.2⟩
@[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl
@[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl
variables {f : α ↪ β} {s : finset α}
@[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b :=
mem_map.trans $ by simp only [exists_prop]; refl
theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s :=
mem_map_of_injective f.2
theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f :=
(mem_map' _).2
@[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : finset α) : (↑(s.map f) : set β) = f '' ↑s :=
set.ext $ λ x, mem_map.trans set.mem_image_iff_bex.symm
theorem coe_map_subset_range (f : α ↪ β) (s : finset α) : (↑(s.map f) : set β) ⊆ set.range f :=
calc ↑(s.map f) = f '' ↑s : coe_map f s
... ⊆ set.range f : set.image_subset_range f ↑s
theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} :
s.to_finset.map f = (s.map f).to_finset :=
ext $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset]
@[simp] theorem map_refl : s.map (embedding.refl _) = s :=
ext $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right
theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) :=
eq_of_veq $ by simp only [map_val, multiset.map_map]; refl
theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ :=
⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs,
λ h, by simp [subset_def, map_subset_map h]⟩
theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ :=
by simp only [subset.antisymm_iff, map_subset_map]
/-- Associate to an embedding `f` from `α` to `β` the embedding that maps a finset to its image
under `f`. -/
def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩
@[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl
theorem map_filter {p : β → Prop} [decidable_pred p] :
(s.map f).filter p = (s.filter (p ∘ f)).map f :=
ext $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact
⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩,
by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩
theorem map_union [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f :=
ext $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib]
theorem map_inter [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f :=
ext $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact
⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩,
by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩
@[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} :=
ext $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm
@[simp] theorem map_insert [decidable_eq α] [decidable_eq β]
(f : α ↪ β) (a : α) (s : finset α) :
(insert a s).map f = insert (f a) (s.map f) :=
by simp only [insert_eq, map_union, map_singleton]
@[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s :=
eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _
end map
lemma range_add_one' (n : ℕ) :
range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ.inj⟩) :=
by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n]
/-! ### image -/
section image
variables [decidable_eq β]
/-- `image f s` is the forward image of `s` under `f`. -/
def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset
@[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl
@[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl
variables {f : α → β} {s : finset α}
@[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b :=
by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop]
theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f :=
mem_image.2 ⟨_, h, rfl⟩
@[simp, norm_cast] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s :=
set.ext $ λ _, mem_image.trans set.mem_image_iff_bex.symm
lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty :=
let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩
theorem image_to_finset [decidable_eq α] {s : multiset α} :
s.to_finset.image f = (s.map f).to_finset :=
ext $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map]
theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f :=
multiset.erase_dup_eq_self.2 (nodup_map_on H s.2)
theorem image_id [decidable_eq α] : s.image id = s :=
ext $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right]
theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) :=
eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map]
theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f :=
by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset',
multiset.map_subset_map h]
theorem image_subset_iff {s : finset α} {t : finset β} {f : α → β} :
s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t :=
calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t : by norm_cast
... ↔ _ : set.image_subset_iff
theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image
theorem coe_image_subset_range : ↑(s.image f) ⊆ set.range f :=
calc ↑(s.image f) = f '' ↑s : coe_image
... ⊆ set.range f : set.image_subset_range f ↑s
theorem image_filter {p : β → Prop} [decidable_pred p] :
(s.image f).filter p = (s.filter (p ∘ f)).image f :=
ext $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact
⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩,
by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩
theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) :
(s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f :=
ext $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right,
exists_or_distrib]
theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) :
(s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f :=
ext $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b,
⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩,
λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩.
@[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} :=
ext $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm
@[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) :
(insert a s).image f = insert (f a) (s.image f) :=
by simp only [insert_eq, image_singleton, image_union]
@[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s :=
eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self]
@[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} :
attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s})
((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) :=
ext $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx)
(λ h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h)
(λ h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩),
λ _, finset.mem_attach _ _⟩
theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f :=
eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm
lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b :=
ext $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right,
h.bex, true_and, mem_singleton, eq_comm]
/--
Because `finset.image` requires a `decidable_eq` instances for the target type,
we can only construct a `functor finset` when working classically.
-/
instance [Π P, decidable P] : functor finset :=
{ map := λ α β f s, s.image f, }
instance [Π P, decidable P] : is_lawful_functor finset :=
{ id_map := λ α x, image_id,
comp_map := λ α β γ f g s, image_image.symm, }
/-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose
elements belong to `s`. -/
protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) :=
(s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩,
λ x y H, subtype.eq $ subtype.mk.inj H⟩
@[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} :
∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s
| ⟨a, ha⟩ := by simp [finset.subtype, ha]
/-- `s.subtype p` converts back to `s.filter p` with
`embedding.subtype`. -/
@[simp] lemma subtype_map (p : α → Prop) [decidable_pred p] :
(s.subtype p).map (function.embedding.subtype _) = s.filter p :=
begin
ext x,
rw mem_map,
change (∃ a : {x // p x}, ∃ H, a.val = x) ↔ _,
split,
{ rintros ⟨y, hy, hyval⟩,
rw [mem_subtype, hyval] at hy,
rw mem_filter,
use hy,
rw ← hyval,
use y.property },
{ intro hx,
rw mem_filter at hx,
use ⟨⟨x, hx.2⟩, mem_subtype.2 hx.1, rfl⟩ }
end
/-- If all elements of a `finset` satisfy the predicate `p`,
`s.subtype p` converts back to `s` with `embedding.subtype`. -/
lemma subtype_map_of_mem {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) :
(s.subtype p).map (function.embedding.subtype _) = s :=
by rw [subtype_map, filter_true_of_mem h]
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, all elements of the result have the property of
the subtype. -/
lemma property_of_mem_map_subtype {p : α → Prop} (s : finset {x // p x}) {a : α}
(h : a ∈ s.map (function.embedding.subtype _)) : p a :=
begin
rcases mem_map.1 h with ⟨x, hx, rfl⟩,
exact x.2
end
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, the result does not contain any value that does
not satisfy the property of the subtype. -/
lemma not_mem_map_subtype_of_not_property {p : α → Prop} (s : finset {x // p x})
{a : α} (h : ¬ p a) : a ∉ (s.map (function.embedding.subtype _)) :=
mt s.property_of_mem_map_subtype h
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, the result is a subset of the set giving the
subtype. -/
lemma map_subtype_subset {t : set α} (s : finset t) :
↑(s.map (function.embedding.subtype _)) ⊆ t :=
begin
intros a ha,
rw mem_coe at ha,
convert property_of_mem_map_subtype s ha
end
lemma subset_image_iff {f : α → β}
{s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s :=
begin
classical,
split, swap,
{ rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs },
intro h, induction s using finset.induction with a s has ih h,
{ refine ⟨∅, set.empty_subset _, _⟩,
convert finset.image_empty _ },
rw [finset.coe_insert, set.insert_subset] at h,
rcases ih h.2 with ⟨s', hst, hsi⟩,
rcases h.1 with ⟨x, hxt, rfl⟩,
refine ⟨insert x s', _, _⟩,
{ rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ },
rw [finset.image_insert, hsi],
congr
end
end image
end finset
theorem multiset.to_finset_map [decidable_eq α] [decidable_eq β] (f : α → β) (m : multiset α) :
(m.map f).to_finset = m.to_finset.image f :=
finset.val_inj.1 (multiset.erase_dup_map_erase_dup_eq _ _).symm
namespace finset
/-! ### card -/
section card
/-- `card s` is the cardinality (number of elements) of `s`. -/
def card (s : finset α) : nat := s.1.card
theorem card_def (s : finset α) : s.card = s.1.card := rfl
@[simp] lemma card_mk {m nodup} : (⟨m, nodup⟩ : finset α).card = m.card := rfl
@[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl
@[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ :=
card_eq_zero.trans val_eq_zero
theorem card_pos {s : finset α} : 0 < card s ↔ s.nonempty :=
pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm
theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 :=
(not_congr card_eq_zero).2 (ne_empty_of_mem h)
theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = {a} :=
by cases s; simp only [multiset.card_eq_one, finset.card, ← val_inj, singleton_val]
@[simp] theorem card_insert_of_not_mem [decidable_eq α]
{a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 :=
by simpa only [card_cons, card, insert_val] using
congr_arg multiset.card (ndinsert_of_not_mem h)
theorem card_insert_of_mem [decidable_eq α] {a : α} {s : finset α}
(h : a ∈ s) : card (insert a s) = card s := by rw insert_eq_of_mem h
theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 :=
by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right},
rw [card_insert_of_not_mem h]]
@[simp] theorem card_singleton (a : α) : card ({a} : finset α) = 1 := card_singleton _
lemma card_singleton_inter [decidable_eq α] {x : α} {s : finset α} : ({x} ∩ s).card ≤ 1 :=
begin
cases (finset.decidable_mem x s),
{ simp [finset.singleton_inter_of_not_mem h] },
{ simp [finset.singleton_inter_of_mem h] },
end
theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} :
a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem
theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} :
a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem
theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} :
card (erase s a) ≤ card s := card_erase_le
@[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n
@[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach
end card
end finset
theorem multiset.to_finset_card_le [decidable_eq α] (m : multiset α) : m.to_finset.card ≤ m.card :=
card_le_of_le (erase_dup_le _)
theorem list.to_finset_card_le [decidable_eq α] (l : list α) : l.to_finset.card ≤ l.length :=
multiset.to_finset_card_le ⟦l⟧
namespace finset
section card
theorem card_image_le [decidable_eq β] {f : α → β} {s : finset α} : card (image f s) ≤ card s :=
by simpa only [card_map] using (s.1.map f).to_finset_card_le
theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α}
(H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s :=
by simp only [card, image_val_of_inj_on H, card_map]
theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α)
(H : function.injective f) : card (image f s) = card s :=
card_image_of_inj_on $ λ x _ y _ h, H h
@[simp] lemma card_map {α β} (f : α ↪ β) {s : finset α} : (s.map f).card = s.card :=
multiset.card_map _ _
lemma card_eq_of_bijective {s : finset α} {n : ℕ}
(f : ∀i, i < n → α)
(hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s)
(f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) :
card s = n :=
begin
classical,
have : ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a,
from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩,
assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩,
have : s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)),
by simpa only [ext_iff, mem_image, exists_prop, subtype.exists, mem_attach, true_and],
calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) :
by rw [this]
... = card ((range n).attach) :
card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq,
subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq
... = card (range n) : card_attach
... = n : card_range n
end
lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} :
s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) :=
iff.intro
(assume eq,
have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _,
let ⟨a, has⟩ := card_pos.mp this in
⟨a, s.erase a, s.not_mem_erase a, insert_erase has,
by simp only [eq, card_erase_of_mem has, pred_succ]⟩)
(assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat)
theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t :=
multiset.card_le_of_le ∘ val_le_iff.mpr
theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t :=
eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂
lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card :=
card_lt_of_lt (val_lt_iff.2 h)
lemma card_le_card_of_inj_on {s : finset α} {t : finset β}
(f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) :
card s ≤ card t :=
begin
classical,
calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj]
... ≤ card t : card_le_of_subset $
assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end
end
lemma card_le_of_inj_on {n} {s : finset α}
(f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s :=
calc n = card (range n) : (card_range n).symm
... ≤ card s : card_le_card_of_inj_on f
(by simpa only [mem_range])
(by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂)
/-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to
define an object on `s`. Then one can inductively define an object on all finsets, starting from
the empty set and iterating. This can be used either to define data, or to prove properties. -/
@[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} :
∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s
| ⟨s, nd⟩ ih := multiset.strong_induction_on s
(λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd
@[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop}
(s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s :=
finset.strong_induction_on s $ λ s,
finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $
λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _)
lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β)
(h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b)
(h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card :=
by haveI := classical.prop_decidable; exact
calc s.card = s.attach.card : card_attach.symm
... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card :
eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h)))
... = t.card : congr_arg card (finset.ext $ λ b,
⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _,
λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩)
lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) :
(s ∪ t).card + (s ∩ t).card = s.card + t.card :=
finset.induction_on t (by simp) $ λ a r har, by by_cases a ∈ s; simp *; cc
lemma card_union_le [decidable_eq α] (s t : finset α) :
(s ∪ t).card ≤ s.card + t.card :=
card_union_add_card_inter s t ▸ le_add_right _ _
lemma card_union_eq [decidable_eq α] {s t : finset α} (h : disjoint s t) :
(s ∪ t).card = s.card + t.card :=
begin
rw [← card_union_add_card_inter],
convert (add_zero _).symm, rw [card_eq_zero], rwa [disjoint_iff] at h
end
lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β}
(f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂)
(hst : card t ≤ card s) :
(∀ b ∈ t, ∃ a ha, b = f a ha) :=
by haveI := classical.dec_eq β; exact
λ b hb,
have h : card (image (λ (a : {a // a ∈ s}), f a a.prop) (attach s)) = card s,
from @card_attach _ s ▸ card_image_of_injective _
(λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h),
have h₁ : image (λ a : {a // a ∈ s}, f a a.prop) s.attach = t :=
eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in
ha₂ ▸ hf _ _) (by simp [hst, h]),
begin
rw ← h₁ at hb,
rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩,
exact ⟨a, a.2, ha₂.symm⟩,
end
open function
lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β}
(f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha)
(hst : card s ≤ card t)
⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s)
(ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ :=
by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact
let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in
let g : {x // x ∈ t} → {x // x ∈ s} :=
@surj_inv _ _ f'
(λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in
have hg : injective g, from function.injective_surj_inv _,
have hsg : surjective g, from λ x,
let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x)
(λ x _, show (g x) ∈ s.attach, from mem_attach _ _)
(λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in
⟨y, hy.snd.symm⟩,
have hif : injective f',
from (left_inverse_of_surjective_of_right_inverse hsg
(right_inverse_surj_inv _)).injective,
subtype.ext_iff_val.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂))
end card
/-! ### bind -/
section bind
variables [decidable_eq β] {s : finset α} {t : α → finset β}
/-- `bind s t` is the union of `t x` over `x ∈ s` -/
protected def bind (s : finset α) (t : α → finset β) : finset β :=
(s.1.bind (λ a, (t a).1)).to_finset
@[simp] theorem bind_val (s : finset α) (t : α → finset β) :
(s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl
@[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl
@[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a :=
by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop]
@[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t :=
ext $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert,
or_and_distrib_right, exists_or_distrib, exists_eq_left]
-- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib]
@[simp] lemma singleton_bind {a : α} : finset.bind {a} t = t a :=
begin
classical,
rw [← insert_emptyc_eq, bind_insert, bind_empty, union_empty]
end
theorem bind_inter (s : finset α) (f : α → finset β) (t : finset β) :
s.bind f ∩ t = s.bind (λ x, f x ∩ t) :=
begin
ext x,
simp only [mem_bind, mem_inter],
tauto
end
theorem inter_bind (t : finset β) (s : finset α) (f : α → finset β) :
t ∩ s.bind f = s.bind (λ x, t ∩ f x) :=
by rw [inter_comm, bind_inter]; simp [inter_comm]
theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} :
(s.image f).bind t = s.bind (λa, t (f a)) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [image_insert, bind_insert, ih])
theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} :
(s.bind t).image f = s.bind (λa, (t a).image f) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [bind_insert, image_union, ih])
theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) :
(s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) :=
ext $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop]
lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ :=
have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a),
from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩,
by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop]
lemma bind_subset_bind_of_subset_left {α : Type*} {s₁ s₂ : finset α}
(t : α → finset β) (h : s₁ ⊆ s₂) : s₁.bind t ⊆ s₂.bind t :=
begin
intro x,
simp only [and_imp, mem_bind, exists_prop],
exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩)
end
lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f :=
ext $ λ x, by simp only [mem_bind, mem_image, mem_singleton, eq_comm]
@[simp] lemma bind_singleton_eq_self [decidable_eq α] :
s.bind (singleton : α → finset α) = s :=
by { rw bind_singleton, exact image_id }
lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) :
(s.image g).bind (λa, s.filter $ (λc, g c = a)) = s :=
begin
ext b,
suffices : (∃ a, a ∈ s ∧ b ∈ s ∧ g b = g a) ↔ b ∈ s, by simpa,
exact ⟨λ ⟨a, ha, hb, hab⟩, hb, λ hb, ⟨b, hb, hb, rfl⟩⟩
end
end bind
/-! ### prod-/
section prod
variables {s : finset α} {t : finset β}
/-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩
@[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl
@[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product
theorem subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} :
s ⊆ (s.image prod.fst).product (s.image prod.snd) :=
λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩
theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
s.product t = s.bind (λa, t.image $ λb, (a, b)) :=
ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff,
and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left]
@[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t :=
multiset.card_product _ _
end prod
/-! ### sigma -/
section sigma
variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)}
/-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/
protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) :=
⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩
@[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma
theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)}
(H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ :=
λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩
theorem sigma_eq_bind [decidable_eq (Σ a, σ a)] (s : finset α)
(t : Πa, finset (σ a)) :
s.sigma t = s.bind (λa, (t a).map $ function.embedding.sigma_mk a) :=
by { ext ⟨x, y⟩, simp [and.left_comm] }
end sigma
/-! ### disjoint -/
section disjoint
variable [decidable_eq α]
theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t :=
by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and,
and_imp]; refl
theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 :=
disjoint_left
theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) :=
decidable_of_decidable_of_iff (by apply_instance) eq_bot_iff
theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
by rw [disjoint.comm, disjoint_left]
theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁))
theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁))
@[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left
@[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right
@[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s :=
by simp only [disjoint_left, mem_singleton, forall_eq]
@[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s :=
disjoint.comm.trans singleton_disjoint
@[simp] theorem disjoint_insert_left {a : α} {s t : finset α} :
disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t :=
by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
@[simp] theorem disjoint_insert_right {a : α} {s t : finset α} :
disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t :=
disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm]
@[simp] theorem disjoint_union_left {s t u : finset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right {s t u : finset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib]
lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s :=
disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2
lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) :=
sdiff_disjoint.symm
lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) :=
disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint
lemma sdiff_eq_self_iff_disjoint {s t : finset α} : s \ t = s ↔ disjoint s t :=
by rw [sdiff_eq_self, subset_empty, disjoint_iff_inter_eq_empty]
lemma sdiff_eq_self_of_disjoint {s t : finset α} (h : disjoint s t) : s \ t = s :=
sdiff_eq_self_iff_disjoint.2 h
lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ :=
disjoint_self
lemma disjoint_bind_left {ι : Type*}
(s : finset ι) (f : ι → finset α) (t : finset α) :
disjoint (s.bind f) t ↔ (∀i∈s, disjoint (f i) t) :=
begin
classical,
refine s.induction _ _,
{ simp only [forall_mem_empty_iff, bind_empty, disjoint_empty_left] },
{ assume i s his ih,
simp only [disjoint_union_left, bind_insert, his, forall_mem_insert, ih] }
end
lemma disjoint_bind_right {ι : Type*}
(s : finset α) (t : finset ι) (f : ι → finset α) :
disjoint s (t.bind f) ↔ (∀i∈t, disjoint s (f i)) :=
by simpa only [disjoint.comm] using disjoint_bind_left t f s
@[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) :
card (s ∪ t) = card s + card t :=
by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero]
theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s :=
suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this,
by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel]
lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] :
disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) :=
by split; simp [disjoint_left] {contextual := tt}
lemma disjoint_filter_filter {s t : finset α} {p q : α → Prop} [decidable_pred p]
[decidable_pred q] :
(disjoint s t) → disjoint (s.filter p) (t.filter q) :=
disjoint.mono (filter_subset _) (filter_subset _)
lemma disjoint_iff_disjoint_coe {α : Type*} {a b : finset α} [decidable_eq α] :
disjoint a b ↔ disjoint (↑a : set α) (↑b : set α) :=
by { rw [finset.disjoint_left, set.disjoint_left], refl }
end disjoint
/--
Given a set A and a set B inside it, we can shrink A to any appropriate size, and keep B
inside it.
-/
lemma exists_intermediate_set {A B : finset α} (i : ℕ)
(h₁ : i + card B ≤ card A) (h₂ : B ⊆ A) :
∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B :=
begin
classical,
rcases nat.le.dest h₁ with ⟨k, _⟩,
clear h₁,
induction k with k ih generalizing A,
{ exact ⟨A, h₂, subset.refl _, h.symm⟩ },
{ have : (A \ B).nonempty,
{ rw [← card_pos, card_sdiff h₂, ← h, nat.add_right_comm,
nat.add_sub_cancel, nat.add_succ],
apply nat.succ_pos },
rcases this with ⟨a, ha⟩,
have z : i + card B + k = card (erase A a),
{ rw [card_erase_of_mem, ← h, nat.add_succ, nat.pred_succ],
rw mem_sdiff at ha,
exact ha.1 },
rcases ih _ z with ⟨B', hB', B'subA', cards⟩,
{ exact ⟨B', hB', trans B'subA' (erase_subset _ _), cards⟩ },
{ rintros t th,
apply mem_erase_of_ne_of_mem _ (h₂ th),
rintro rfl,
exact not_mem_sdiff_of_mem_right th ha } }
end
/-- We can shrink A to any smaller size. -/
lemma exists_smaller_set (A : finset α) (i : ℕ) (h₁ : i ≤ card A) :
∃ (B : finset α), B ⊆ A ∧ card B = i :=
let ⟨B, _, x₁, x₂⟩ := exists_intermediate_set i (by simpa) (empty_subset A) in ⟨B, x₁, x₂⟩
/-- `finset.fin_range k` is the finset `{0, 1, ..., k-1}`, as a `finset (fin k)`. -/
def fin_range (k : ℕ) : finset (fin k) :=
⟨list.fin_range k, list.nodup_fin_range k⟩
@[simp]
lemma fin_range_card {k : ℕ} : (fin_range k).card = k :=
by simp [fin_range]
@[simp]
lemma mem_fin_range {k : ℕ} (m : fin k) : m ∈ fin_range k :=
list.mem_fin_range m
/-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n`
is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/
def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) :=
⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.veq_of_eq) s.2⟩
@[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} :
a ∈ s.attach_fin h ↔ (a : ℕ) ∈ s :=
⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁,
λ h, multiset.mem_pmap.2 ⟨a, h, fin.eta _ _⟩⟩
@[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) :
(s.attach_fin h).card = s.card := multiset.card_pmap _ _ _
/-! ### choose -/
section choose
variables (p : α → Prop) [decidable_pred p] (l : finset α)
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the corresponding subtype. -/
def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } :=
multiset.choose_x p l.val hp
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the ambient type. -/
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
theorem lt_wf {α} : well_founded (@has_lt.lt (finset α) _) :=
have H : subrelation (@has_lt.lt (finset α) _)
(inv_image (<) card),
from λ x y hxy, card_lt_card hxy,
subrelation.wf H $ inv_image.wf _ $ nat.lt_wf
end finset
namespace list
variable [decidable_eq α]
theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length :=
congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h
end list
namespace multiset
lemma disjoint_to_finset [decidable_eq α] (m1 m2 : multiset α) :
_root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 :=
begin
rw finset.disjoint_iff_ne,
split,
{ intro h,
intros a ha1 ha2,
rw ← multiset.mem_to_finset at ha1 ha2,
exact h _ ha1 _ ha2 rfl },
{ rintros h a ha b hb rfl,
rw multiset.mem_to_finset at ha hb,
exact h ha hb }
end
end multiset
|
29bf03c7c08b7d7c730565119ead638aab214247 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/category_theory/sites/sheaf.lean | aec549949d1001282f47617b9010c2da788faf47 | [
"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 | 10,617 | lean | /-
Copyright (c) 2020 Kevin Buzzard, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Bhavik Mehta
-/
import category_theory.sites.sheaf_of_types
import category_theory.limits.yoneda
import category_theory.limits.preserves.shapes.equalizers
import category_theory.limits.preserves.shapes.products
import category_theory.concrete_category
/-!
# Sheaves taking values in a category
If C is a category with a Grothendieck topology, we define the notion of a sheaf taking values in
an arbitrary category `A`. We follow the definition in https://stacks.math.columbia.edu/tag/00VR,
noting that the presheaf of sets "defined above" can be seen in the comments between tags 00VQ and
00VR on the page https://stacks.math.columbia.edu/tag/00VL. The advantage of this definition is
that we need no assumptions whatsoever on `A` other than the assumption that the morphisms in `C`
and `A` live in the same universe.
* An `A`-valued presheaf `P : Cᵒᵖ ⥤ A` is defined to be a sheaf (for the topology `J`) iff for
every `X : A`, the type-valued presheaves of sets given by sending `U : Cᵒᵖ` to `Hom_{A}(X, P U)`
are all sheaves of sets, see `category_theory.presheaf.is_sheaf`.
* When `A = Type`, this recovers the basic definition of sheaves of sets, see
`category_theory.is_sheaf_iff_is_sheaf_of_type`.
* An alternate definition when `C` is small, has pullbacks and `A` has products is given by an
equalizer condition `category_theory.presheaf.is_sheaf'`. This is equivalent to the earlier
definition, shown in `category_theory.presheaf.is_sheaf_iff_is_sheaf'`.
* When `A = Type`, this is *definitionally* equal to the equalizer condition for presieves in
`category_theory.sites.sheaf_of_types`.
* When `A` has limits and there is a functor `s : A ⥤ Type` which is faithful, reflects isomorphisms
and preserves limits, then `P : C^op ⥤ A` is a sheaf iff the underlying presheaf of types
`P ⋙ s : C^op ⥤ Type` is a sheaf (`category_theory.presheaf.is_sheaf_iff_is_sheaf_forget`).
Cf https://stacks.math.columbia.edu/tag/0073, which is a weaker version of this statement (it's
only over spaces, not sites) and https://stacks.math.columbia.edu/tag/00YR (a), which
additionally assumes filtered colimits.
-/
universes v v' u' u
noncomputable theory
namespace category_theory
open opposite category_theory category limits sieve classical
namespace presheaf
variables {C : Type u} [category.{v} C]
variables {A : Type u'} [category.{v} A]
variables (J : grothendieck_topology C)
-- We follow https://stacks.math.columbia.edu/tag/00VL definition 00VR
/--
A sheaf of A is a presheaf P : C^op => A such that for every X : A, the
presheaf of types given by sending U : C to Hom_{A}(X, P U) is a sheaf of types.
https://stacks.math.columbia.edu/tag/00VR
-/
def is_sheaf (P : Cᵒᵖ ⥤ A) : Prop :=
∀ X : A, presieve.is_sheaf J (P ⋙ coyoneda.obj (op X))
end presheaf
variables {C : Type u} [category.{v} C]
variables (J : grothendieck_topology C)
variables (A : Type u') [category.{v} A]
/-- The category of sheaves taking values in `A` on a grothendieck topology. -/
@[derive category]
def Sheaf : Type* :=
{P : Cᵒᵖ ⥤ A // presheaf.is_sheaf J P}
/-- The inclusion functor from sheaves to presheaves. -/
@[simps {rhs_md := semireducible}, derive [full, faithful]]
def Sheaf_to_presheaf : Sheaf J A ⥤ (Cᵒᵖ ⥤ A) :=
full_subcategory_inclusion (presheaf.is_sheaf J)
lemma is_sheaf_iff_is_sheaf_of_type (P : Cᵒᵖ ⥤ Type v) :
presheaf.is_sheaf J P ↔ presieve.is_sheaf J P :=
begin
split,
{ intros hP,
exact presieve.is_sheaf_iso J (coyoneda.iso_comp_punit _) (hP punit) },
{ intros hP X Y S hS z hz,
refine ⟨λ x, (hP S hS).amalgamate (λ Z f hf, z f hf x) _, _, _⟩,
{ intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ h,
exact congr_fun (hz g₁ g₂ hf₁ hf₂ h) x },
{ intros Z f hf,
ext x,
apply presieve.is_sheaf_for.valid_glue },
{ intros y hy,
ext x,
apply (hP S hS).is_separated_for.ext,
intros Y' f hf,
rw [presieve.is_sheaf_for.valid_glue _ _ _ hf, ← hy _ hf],
refl } }
end
/--
The category of sheaves taking values in Type is the same as the category of set-valued sheaves.
-/
@[simps]
def Sheaf_equiv_SheafOfTypes : Sheaf J (Type v) ≌ SheafOfTypes J :=
{ functor :=
{ obj := λ S, ⟨S.1, (is_sheaf_iff_is_sheaf_of_type _ _).1 S.2⟩,
map := λ S₁ S₂ f, f },
inverse :=
{ obj := λ S, ⟨S.1, (is_sheaf_iff_is_sheaf_of_type _ _).2 S.2⟩,
map := λ S₁ S₂ f, f },
unit_iso := nat_iso.of_components (λ X, ⟨𝟙 _, 𝟙 _, by tidy, by tidy⟩) (by tidy),
counit_iso := nat_iso.of_components (λ X, ⟨𝟙 _, 𝟙 _, by tidy, by tidy⟩) (by tidy) }
instance : inhabited (Sheaf (⊥ : grothendieck_topology C) (Type v)) :=
⟨(Sheaf_equiv_SheafOfTypes _).inverse.obj (default _)⟩
end category_theory
namespace category_theory
open opposite category_theory category limits sieve classical
namespace presheaf
-- Under here is the equalizer story, which is equivalent if A has products (and doesn't
-- make sense otherwise). It's described in https://stacks.math.columbia.edu/tag/00VL,
-- between 00VQ and 00VR.
variables {C : Type v} [small_category C]
variables {A : Type u} [category.{v} A]
variables (J : grothendieck_topology C)
variables {U : C} (R : presieve U)
variables (P : Cᵒᵖ ⥤ A)
section
variables [has_products A]
/--
The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of https://stacks.math.columbia.edu/tag/00VM.
-/
def first_obj : A :=
∏ (λ (f : Σ V, {f : V ⟶ U // R f}), P.obj (op f.1))
/--
The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of https://stacks.math.columbia.edu/tag/00VM.
-/
def fork_map : P.obj (op U) ⟶ first_obj R P :=
pi.lift (λ f, P.map f.2.1.op)
variables [has_pullbacks C]
/--
The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which
contains the data used to check a family of elements for a presieve is compatible.
-/
def second_obj : A :=
∏ (λ (fg : (Σ V, {f : V ⟶ U // R f}) × (Σ W, {g : W ⟶ U // R g})),
P.obj (op (pullback fg.1.2.1 fg.2.2.1)))
/-- The map `pr₀*` of https://stacks.math.columbia.edu/tag/00VM. -/
def first_map : first_obj R P ⟶ second_obj R P :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op)
/-- The map `pr₁*` of https://stacks.math.columbia.edu/tag/00VM. -/
def second_map : first_obj R P ⟶ second_obj R P :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op)
lemma w : fork_map R P ≫ first_map R P = fork_map R P ≫ second_map R P :=
begin
apply limit.hom_ext,
rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩,
simp only [first_map, second_map, fork_map, limit.lift_π, limit.lift_π_assoc, assoc,
fan.mk_π_app, subtype.coe_mk, subtype.val_eq_coe],
rw [← P.map_comp, ← op_comp, pullback.condition],
simp,
end
/--
An alternative definition of the sheaf condition in terms of equalizers. This is shown to be
equivalent in `category_theory.presheaf.is_sheaf_iff_is_sheaf'`.
-/
def is_sheaf' (P : Cᵒᵖ ⥤ A) : Prop := ∀ (U : C) (R : presieve U) (hR : generate R ∈ J U),
nonempty (is_limit (fork.of_ι _ (w R P)))
/-- (Implementation). An auxiliary lemma to convert between sheaf conditions. -/
def is_sheaf_for_is_sheaf_for' (P : Cᵒᵖ ⥤ A) (s : A ⥤ Type v)
[Π J, preserves_limits_of_shape (discrete J) s] (U : C) (R : presieve U) :
is_limit (s.map_cone (fork.of_ι _ (w R P))) ≃
is_limit (fork.of_ι _ (equalizer.presieve.w (P ⋙ s) R)) :=
begin
apply equiv.trans (is_limit_map_cone_fork_equiv _ _) _,
apply (is_limit.postcompose_hom_equiv _ _).symm.trans (is_limit.equiv_iso_limit _),
{ apply nat_iso.of_components _ _,
{ rintro (_ | _),
{ apply preserves_product.iso s },
{ apply preserves_product.iso s } },
{ rintro _ _ (_ | _),
{ ext : 1,
dsimp [equalizer.presieve.first_map, first_map],
simp only [limit.lift_π, map_lift_pi_comparison, assoc, fan.mk_π_app, functor.map_comp],
erw pi_comparison_comp_π_assoc },
{ ext : 1,
dsimp [equalizer.presieve.second_map, second_map],
simp only [limit.lift_π, map_lift_pi_comparison, assoc, fan.mk_π_app, functor.map_comp],
erw pi_comparison_comp_π_assoc },
{ dsimp,
simp } } },
{ refine fork.ext (iso.refl _) _,
dsimp [equalizer.fork_map, fork_map],
simp }
end
/-- The equalizer definition of a sheaf given by `is_sheaf'` is equivalent to `is_sheaf`. -/
theorem is_sheaf_iff_is_sheaf' :
is_sheaf J P ↔ is_sheaf' J P :=
begin
split,
{ intros h U R hR,
refine ⟨_⟩,
apply coyoneda_jointly_reflects_limits,
intro X,
have q : presieve.is_sheaf_for (P ⋙ coyoneda.obj X) _ := h X.unop _ hR,
rw ←presieve.is_sheaf_for_iff_generate at q,
rw equalizer.presieve.sheaf_condition at q,
replace q := classical.choice q,
apply (is_sheaf_for_is_sheaf_for' _ _ _ _).symm q },
{ intros h U X S hS,
rw equalizer.presieve.sheaf_condition,
refine ⟨_⟩,
refine is_sheaf_for_is_sheaf_for' _ _ _ _ _,
apply is_limit_of_preserves,
apply classical.choice (h _ S _),
simpa }
end
end
section concrete
variables [has_pullbacks C]
/--
For a concrete category `(A, s)` where the forgetful functor `s : A ⥤ Type v` preserves limits and
reflects isomorphisms, and `A` has limits, an `A`-valued presheaf `P : Cᵒᵖ ⥤ A` is a sheaf iff its
underlying `Type`-valued presheaf `P ⋙ s : Cᵒᵖ ⥤ Type` is a sheaf.
Note this lemma applies for "algebraic" categories, eg groups, abelian groups and rings, but not
for the category of topological spaces, topological rings, etc since reflecting isomorphisms doesn't
hold.
-/
lemma is_sheaf_iff_is_sheaf_forget (s : A ⥤ Type v)
[has_limits A] [preserves_limits s] [reflects_isomorphisms s] :
is_sheaf J P ↔ is_sheaf J (P ⋙ s) :=
begin
rw [is_sheaf_iff_is_sheaf', is_sheaf_iff_is_sheaf'],
apply forall_congr (λ U, _),
apply ball_congr (λ R hR, _),
letI : reflects_limits s := reflects_limits_of_reflects_isomorphisms,
have : is_limit (s.map_cone (fork.of_ι _ (w R P))) ≃ is_limit (fork.of_ι _ (w R (P ⋙ s))) :=
is_sheaf_for_is_sheaf_for' P s U R,
rw ←equiv.nonempty_iff_nonempty this,
split,
{ exact nonempty.map (λ t, is_limit_of_preserves s t) },
{ exact nonempty.map (λ t, is_limit_of_reflects s t) }
end
end concrete
end presheaf
end category_theory
|
a706352ccfeca0c91b4fffb8dc9ef4df76095236 | 4727251e0cd73359b15b664c3170e5d754078599 | /test/push_neg.lean | 887ab382dd27659547e8058cdff67711921c5d42 | [
"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 | 2,317 | lean | import tactic.push_neg
import data.int.basic
example (h : ∃ p: ℕ, ¬ ∀ n : ℕ, n > p) (h' : ∃ p: ℕ, ¬ ∃ n : ℕ, n < p) : ¬ ∀ n : ℕ, n = 0 :=
begin
push_neg at *,
guard_target_strict ∃ (n : ℕ), n ≠ 0,
guard_hyp_strict h : ∃ (p n : ℕ), n ≤ p,
guard_hyp_strict h' : ∃ (p : ℕ), ∀ (n : ℕ), p ≤ n,
use 1,
end
-- In the next example, ℤ should be ℝ in maths, but I don't want to import real numbers
-- for testing only
example (a : ℕ → ℤ) (l : ℤ) (h : ¬ ∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε) : true :=
begin
push_neg at h,
guard_hyp_strict h : ∃ (ε : ℤ), ε > 0 ∧ ∀ (N : ℕ), ∃ (n : ℕ), n ≥ N ∧ ε ≤ |a n - l|,
trivial
end
example (f : ℤ → ℤ) (x₀ y₀) (h : ¬ ∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - y₀| ≤ ε) : true :=
begin
push_neg at h,
guard_hyp_strict h : ∃ (ε : ℤ), ε > 0 ∧ ∀ δ > 0, (∃ (x : ℤ), |x - x₀| ≤ δ ∧ ε < |f x - y₀| ),
trivial
end
example (n) : n*n ≠ 1 → n ≠ 1 :=
begin
contrapose,
rw [not_not, not_not],
intro h,
rw [h, one_mul]
end
example (n) : n*n ≠ 1 → n ≠ 1 :=
begin
contrapose!,
intro h,
rw [h, one_mul]
end
example (n) (h : n*n ≠ 1) : n ≠ 1 :=
begin
contrapose h,
rw not_not at *,
rw [h, one_mul]
end
example (n) (h : n*n ≠ 1) : n ≠ 1 :=
begin
contrapose! h,
rw [h, one_mul]
end
example (n) (h : n*n ≠ 1) : n ≠ 1 :=
begin
contrapose! h with newh,
rw [newh, one_mul]
end
example : 0 = 0 :=
begin
success_if_fail_with_msg { contrapose }
"The goal is not an implication, and you didn't specify an assumption",
refl
end
-- Remember that ∀ is the same as Π which is a generalization of → so we need to make sure
-- `contrapose` fails with a helpful error message in the next example.
example : ∀ x : ℕ, x = x :=
begin
success_if_fail_with_msg { contrapose }
"contrapose only applies to nondependent arrows between props",
intro, refl
end
open tactic
example (X : Type) (f : X → ℕ) (h : ¬∀ x, f x = 0) (hf : false) : false :=
begin
have h1 := h,
-- h h1: ¬∀ (x : X), f x = 0
push_neg at h,
push_neg at h1,
(do ht ← get_local `h >>= infer_type,
h1t ← get_local `h1 >>= infer_type,
guard (ht = h1t) ),
exact hf
end
|
32b59e3de4e309b400c6a391e134bce6339ed803 | ea4aee6b11f86433e69bb5e50d0259e056d0ae61 | /src/tidy/force.lean | c19775b167a6993441333b95df191fd52f3680df | [] | no_license | timjb/lean-tidy | e18feff0b7f0aad08c614fb4d34aaf527bf21e20 | e767e259bf76c69edfd4ab8af1b76e6f1ed67f48 | refs/heads/master | 1,624,861,693,182 | 1,504,411,006,000 | 1,504,411,006,000 | 103,740,824 | 0 | 0 | null | 1,505,553,968,000 | 1,505,553,968,000 | null | UTF-8 | Lean | false | false | 505 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
open tactic
meta def force { α : Type } (t : tactic α) : tactic α :=
do
goals ← get_goals,
result ← t,
goals' ← get_goals,
guard (goals ≠ goals') <|> fail "force tactic failed",
return result
namespace tactic.interactive
meta def force (t : itactic) : tactic unit := _root_.force t
end tactic.interactive |
83fe1d0e0a1eefea8dd016114e3c0654b6221594 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/ring_theory/trace.lean | 69e9dae1053c11e98a65ab007f61ddd97241ce2a | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,246 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import linear_algebra.bilinear_form
import linear_algebra.matrix.charpoly.coeff
import linear_algebra.determinant
import linear_algebra.vandermonde
import linear_algebra.trace
import field_theory.is_alg_closed.algebraic_closure
import field_theory.primitive_element
import ring_theory.power_basis
/-!
# Trace for (finite) ring extensions.
Suppose we have an `R`-algebra `S` with a finite basis. For each `s : S`,
the trace of the linear map given by multiplying by `s` gives information about
the roots of the minimal polynomial of `s` over `R`.
## Implementation notes
Typically, the trace is defined specifically for finite field extensions.
The definition is as general as possible and the assumption that we have
fields or that the extension is finite is added to the lemmas as needed.
We only define the trace for left multiplication (`algebra.left_mul_matrix`,
i.e. `algebra.lmul_left`).
For now, the definitions assume `S` is commutative, so the choice doesn't matter anyway.
## References
* https://en.wikipedia.org/wiki/Field_trace
-/
universes u v w
variables {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T]
variables [algebra R S] [algebra R T]
variables {K L : Type*} [field K] [field L] [algebra K L]
variables {ι : Type w} [fintype ι]
open finite_dimensional
open linear_map
open matrix
open_locale big_operators
open_locale matrix
namespace algebra
variables (b : basis ι R S)
variables (R S)
/-- The trace of an element `s` of an `R`-algebra is the trace of `(*) s`,
as an `R`-linear map. -/
noncomputable def trace : S →ₗ[R] R :=
(linear_map.trace R S).comp (lmul R S).to_linear_map
variables {S}
-- Not a `simp` lemma since there are more interesting ways to rewrite `trace R S x`,
-- for example `trace_trace`
lemma trace_apply (x) : trace R S x = linear_map.trace R S (lmul R S x) := rfl
lemma trace_eq_zero_of_not_exists_basis
(h : ¬ ∃ (s : finset S), nonempty (basis s R S)) : trace R S = 0 :=
by { ext s, simp [trace_apply, linear_map.trace, h] }
include b
variables {R}
-- Can't be a `simp` lemma because it depends on a choice of basis
lemma trace_eq_matrix_trace [decidable_eq ι] (b : basis ι R S) (s : S) :
trace R S s = matrix.trace _ R _ (algebra.left_mul_matrix b s) :=
by rw [trace_apply, linear_map.trace_eq_matrix_trace _ b, to_matrix_lmul_eq]
/-- If `x` is in the base field `K`, then the trace is `[L : K] * x`. -/
lemma trace_algebra_map_of_basis (x : R) :
trace R S (algebra_map R S x) = fintype.card ι • x :=
begin
haveI := classical.dec_eq ι,
rw [trace_apply, linear_map.trace_eq_matrix_trace R b, trace_diag],
convert finset.sum_const _,
ext i,
simp,
end
omit b
/-- If `x` is in the base field `K`, then the trace is `[L : K] * x`.
(If `L` is not finite-dimensional over `K`, then `trace` and `finrank` return `0`.)
-/
@[simp]
lemma trace_algebra_map (x : K) : trace K L (algebra_map K L x) = finrank K L • x :=
begin
by_cases H : ∃ (s : finset L), nonempty (basis s K L),
{ rw [trace_algebra_map_of_basis H.some_spec.some, finrank_eq_card_basis H.some_spec.some] },
{ simp [trace_eq_zero_of_not_exists_basis K H, finrank_eq_zero_of_not_exists_basis_finset H] }
end
lemma trace_trace_of_basis [algebra S T] [is_scalar_tower R S T]
{ι κ : Type*} [fintype ι] [fintype κ]
(b : basis ι R S) (c : basis κ S T) (x : T) :
trace R S (trace S T x) = trace R T x :=
begin
haveI := classical.dec_eq ι,
haveI := classical.dec_eq κ,
rw [trace_eq_matrix_trace (b.smul c), trace_eq_matrix_trace b, trace_eq_matrix_trace c,
matrix.trace_apply, matrix.trace_apply, matrix.trace_apply,
← finset.univ_product_univ, finset.sum_product],
refine finset.sum_congr rfl (λ i _, _),
simp only [alg_hom.map_sum, smul_left_mul_matrix, finset.sum_apply,
-- The unifier is not smart enough to apply this one by itself:
finset.sum_apply i _ (λ y, left_mul_matrix b (left_mul_matrix c x y y))]
end
lemma trace_comp_trace_of_basis [algebra S T] [is_scalar_tower R S T]
{ι κ : Type*} [fintype ι] [fintype κ]
(b : basis ι R S) (c : basis κ S T) :
(trace R S).comp ((trace S T).restrict_scalars R) = trace R T :=
by { ext, rw [linear_map.comp_apply, linear_map.restrict_scalars_apply, trace_trace_of_basis b c] }
@[simp]
lemma trace_trace [algebra K T] [algebra L T] [is_scalar_tower K L T]
[finite_dimensional K L] [finite_dimensional L T] (x : T) :
trace K L (trace L T x) = trace K T x :=
trace_trace_of_basis (basis.of_vector_space K L) (basis.of_vector_space L T) x
@[simp]
lemma trace_comp_trace [algebra K T] [algebra L T] [is_scalar_tower K L T]
[finite_dimensional K L] [finite_dimensional L T] :
(trace K L).comp ((trace L T).restrict_scalars K) = trace K T :=
by { ext, rw [linear_map.comp_apply, linear_map.restrict_scalars_apply, trace_trace] }
section trace_form
variables (R S)
/-- The `trace_form` maps `x y : S` to the trace of `x * y`.
It is a symmetric bilinear form and is nondegenerate if the extension is separable. -/
noncomputable def trace_form : bilin_form R S :=
(linear_map.compr₂ (lmul R S).to_linear_map (trace R S)).to_bilin
variables {S}
-- This is a nicer lemma than the one produced by `@[simps] def trace_form`.
@[simp] lemma trace_form_apply (x y : S) : trace_form R S x y = trace R S (x * y) := rfl
lemma trace_form_is_sym : sym_bilin_form.is_sym (trace_form R S) :=
λ x y, congr_arg (trace R S) (mul_comm _ _)
lemma trace_form_to_matrix [decidable_eq ι] (i j) :
bilin_form.to_matrix b (trace_form R S) i j = trace R S (b i * b j) :=
by rw [bilin_form.to_matrix_apply, trace_form_apply]
lemma trace_form_to_matrix_power_basis (h : power_basis R S) :
bilin_form.to_matrix h.basis (trace_form R S) = λ i j, (trace R S (h.gen ^ (i + j : ℕ))) :=
by { ext, rw [trace_form_to_matrix, pow_add, h.basis_eq_pow, h.basis_eq_pow] }
end trace_form
end algebra
section eq_sum_roots
open algebra polynomial
variables {F : Type*} [field F]
variables [algebra K S] [algebra K F]
lemma power_basis.trace_gen_eq_sum_roots [nontrivial S] (pb : power_basis K S)
(hf : (minpoly K pb.gen).splits (algebra_map K F)) :
algebra_map K F (trace K S pb.gen) =
((minpoly K pb.gen).map (algebra_map K F)).roots.sum :=
begin
have d_pos : 0 < pb.dim := power_basis.dim_pos pb,
have d_pos' : 0 < (minpoly K pb.gen).nat_degree, { simpa },
haveI : nonempty (fin pb.dim) := ⟨⟨0, d_pos⟩⟩,
-- Write the LHS as the `d-1`'th coefficient of `minpoly K pb.gen`
rw [trace_eq_matrix_trace pb.basis, trace_eq_neg_charpoly_coeff, charpoly_left_mul_matrix,
ring_hom.map_neg, ← pb.nat_degree_minpoly, fintype.card_fin,
← next_coeff_of_pos_nat_degree _ d_pos',
← next_coeff_map (algebra_map K F).injective],
-- Rewrite `minpoly K pb.gen` as a product over the roots.
conv_lhs { rw eq_prod_roots_of_splits hf },
rw [monic.next_coeff_mul, next_coeff_C_eq_zero, zero_add, monic.next_coeff_multiset_prod],
-- And conclude both sides are the same.
simp_rw [next_coeff_X_sub_C, multiset.sum_map_neg, neg_neg],
-- Now we deal with the side conditions.
{ intros, apply monic_X_sub_C },
{ convert monic_one, simp [(minpoly.monic pb.is_integral_gen).leading_coeff] },
{ apply monic_multiset_prod_of_monic,
intros, apply monic_X_sub_C },
end
namespace intermediate_field.adjoin_simple
open intermediate_field
lemma trace_gen_eq_zero {x : L} (hx : ¬ is_integral K x) :
algebra.trace K K⟮x⟯ (adjoin_simple.gen K x) = 0 :=
begin
rw [trace_eq_zero_of_not_exists_basis, linear_map.zero_apply],
contrapose! hx,
obtain ⟨s, ⟨b⟩⟩ := hx,
refine is_integral_of_mem_of_fg (K⟮x⟯).to_subalgebra _ x _,
{ exact (submodule.fg_iff_finite_dimensional _).mpr (finite_dimensional.of_finset_basis b) },
{ exact subset_adjoin K _ (set.mem_singleton x) }
end
lemma trace_gen_eq_sum_roots (x : L)
(hf : (minpoly K x).splits (algebra_map K F)) :
algebra_map K F (trace K K⟮x⟯ (adjoin_simple.gen K x)) =
((minpoly K x).map (algebra_map K F)).roots.sum :=
begin
have injKKx : function.injective (algebra_map K K⟮x⟯) := ring_hom.injective _,
have injKxL : function.injective (algebra_map K⟮x⟯ L) := ring_hom.injective _,
by_cases hx : is_integral K x, swap,
{ simp [minpoly.eq_zero hx, trace_gen_eq_zero hx], },
have hx' : is_integral K (adjoin_simple.gen K x),
{ rwa [← is_integral_algebra_map_iff injKxL, adjoin_simple.algebra_map_gen],
apply_instance },
rw [← adjoin.power_basis_gen hx, (adjoin.power_basis hx).trace_gen_eq_sum_roots];
rw [adjoin.power_basis_gen hx, minpoly.eq_of_algebra_map_eq injKxL hx'];
try { simp only [adjoin_simple.algebra_map_gen _ _] },
exact hf
end
end intermediate_field.adjoin_simple
open intermediate_field
variables (K)
lemma trace_eq_trace_adjoin [finite_dimensional K L] (x : L) :
algebra.trace K L x = finrank K⟮x⟯ L • trace K K⟮x⟯ (adjoin_simple.gen K x) :=
begin
rw ← @trace_trace _ _ K K⟮x⟯ _ _ _ _ _ _ _ _ x,
conv in x { rw ← intermediate_field.adjoin_simple.algebra_map_gen K x },
rw [trace_algebra_map, ← is_scalar_tower.algebra_map_smul K, (algebra.trace K K⟮x⟯).map_smul,
smul_eq_mul, algebra.smul_def],
apply_instance
end
variables {K}
lemma trace_eq_sum_roots [finite_dimensional K L]
{x : L} (hF : (minpoly K x).splits (algebra_map K F)) :
algebra_map K F (algebra.trace K L x) =
finrank K⟮x⟯ L • ((minpoly K x).map (algebra_map K _)).roots.sum :=
by rw [trace_eq_trace_adjoin K x, algebra.smul_def, ring_hom.map_mul, ← algebra.smul_def,
intermediate_field.adjoin_simple.trace_gen_eq_sum_roots _ hF, is_scalar_tower.algebra_map_smul]
end eq_sum_roots
variables {F : Type*} [field F]
variables [algebra R L] [algebra L F] [algebra R F] [is_scalar_tower R L F]
open polynomial
lemma algebra.is_integral_trace [finite_dimensional L F] {x : F} (hx : _root_.is_integral R x) :
_root_.is_integral R (algebra.trace L F x) :=
begin
have hx' : _root_.is_integral L x := is_integral_of_is_scalar_tower _ hx,
rw [← is_integral_algebra_map_iff (algebra_map L (algebraic_closure F)).injective,
trace_eq_sum_roots],
{ refine (is_integral.multiset_sum _).nsmul _,
intros y hy,
rw mem_roots_map (minpoly.ne_zero hx') at hy,
use [minpoly R x, minpoly.monic hx],
rw ← aeval_def at ⊢ hy,
exact minpoly.aeval_of_is_scalar_tower R x y hy },
{ apply is_alg_closed.splits_codomain },
{ apply_instance }
end
section eq_sum_embeddings
variables [algebra K F] [is_scalar_tower K L F]
open algebra intermediate_field
variables (F) (E : Type*) [field E] [algebra K E]
lemma trace_eq_sum_embeddings_gen
(pb : power_basis K L)
(hE : (minpoly K pb.gen).splits (algebra_map K E)) (hfx : (minpoly K pb.gen).separable) :
algebra_map K E (algebra.trace K L pb.gen) =
(@@finset.univ (power_basis.alg_hom.fintype pb)).sum (λ σ, σ pb.gen) :=
begin
letI := classical.dec_eq E,
rw [pb.trace_gen_eq_sum_roots hE, fintype.sum_equiv pb.lift_equiv', finset.sum_mem_multiset,
finset.sum_eq_multiset_sum, multiset.to_finset_val,
multiset.erase_dup_eq_self.mpr (nodup_roots ((separable_map _).mpr hfx)), multiset.map_id],
{ intro x, refl },
{ intro σ, rw [power_basis.lift_equiv'_apply_coe, id.def] }
end
variables [is_alg_closed E]
lemma sum_embeddings_eq_finrank_mul [finite_dimensional K F] [is_separable K F]
(pb : power_basis K L) :
∑ σ : F →ₐ[K] E, σ (algebra_map L F pb.gen) =
finrank L F • (@@finset.univ (power_basis.alg_hom.fintype pb)).sum
(λ σ : L →ₐ[K] E, σ pb.gen) :=
begin
haveI : finite_dimensional L F := finite_dimensional.right K L F,
haveI : is_separable L F := is_separable_tower_top_of_is_separable K L F,
letI : fintype (L →ₐ[K] E) := power_basis.alg_hom.fintype pb,
letI : ∀ (f : L →ₐ[K] E), fintype (@@alg_hom L F E _ _ _ _ f.to_ring_hom.to_algebra) :=
_, -- will be solved by unification
rw [fintype.sum_equiv alg_hom_equiv_sigma (λ (σ : F →ₐ[K] E), _) (λ σ, σ.1 pb.gen),
← finset.univ_sigma_univ, finset.sum_sigma, ← finset.sum_nsmul],
refine finset.sum_congr rfl (λ σ _, _),
{ letI : algebra L E := σ.to_ring_hom.to_algebra,
simp only [finset.sum_const, finset.card_univ],
rw alg_hom.card L F E },
{ intros σ,
simp only [alg_hom_equiv_sigma, equiv.coe_fn_mk, alg_hom.restrict_domain, alg_hom.comp_apply,
is_scalar_tower.coe_to_alg_hom'] }
end
lemma trace_eq_sum_embeddings [finite_dimensional K L] [is_separable K L]
{x : L} (hx : is_integral K x) :
algebra_map K E (algebra.trace K L x) = ∑ σ : L →ₐ[K] E, σ x :=
begin
rw [trace_eq_trace_adjoin K x, algebra.smul_def, ring_hom.map_mul, ← adjoin.power_basis_gen hx,
trace_eq_sum_embeddings_gen E (adjoin.power_basis hx) (is_alg_closed.splits_codomain _),
← algebra.smul_def, algebra_map_smul],
{ exact (sum_embeddings_eq_finrank_mul L E (adjoin.power_basis hx)).symm },
{ haveI := is_separable_tower_bot_of_is_separable K K⟮x⟯ L,
exact is_separable.separable K _ }
end
end eq_sum_embeddings
section det_ne_zero
open algebra
variables (pb : power_basis K L)
lemma det_trace_form_ne_zero' [is_separable K L] :
det (bilin_form.to_matrix pb.basis (trace_form K L)) ≠ 0 :=
begin
suffices : algebra_map K (algebraic_closure L)
(det (bilin_form.to_matrix pb.basis (trace_form K L))) ≠ 0,
{ refine mt (λ ht, _) this,
rw [ht, ring_hom.map_zero] },
haveI : finite_dimensional K L := pb.finite_dimensional,
let e : (L →ₐ[K] algebraic_closure L) ≃ fin pb.dim := fintype.equiv_fin_of_card_eq _,
let M : matrix (fin pb.dim) (fin pb.dim) (algebraic_closure L) :=
vandermonde (λ i, e.symm i pb.gen),
calc algebra_map K (algebraic_closure _) (bilin_form.to_matrix pb.basis (trace_form K L)).det
= det ((algebra_map K _).map_matrix $
bilin_form.to_matrix pb.basis (trace_form K L)) : ring_hom.map_det _ _
... = det (Mᵀ ⬝ M) : _
... = det M * det M : by rw [det_mul, det_transpose]
... ≠ 0 : mt mul_self_eq_zero.mp _,
{ refine congr_arg det _, ext i j,
rw [vandermonde_transpose_mul_vandermonde, ring_hom.map_matrix_apply, matrix.map_apply,
bilin_form.to_matrix_apply, pb.basis_eq_pow, pb.basis_eq_pow, trace_form_apply,
← pow_add, trace_eq_sum_embeddings (algebraic_closure L) (pb.is_integral_gen.pow _),
fintype.sum_equiv e],
intros σ,
rw [e.symm_apply_apply, σ.map_pow] },
{ simp only [det_vandermonde, finset.prod_eq_zero_iff, not_exists, sub_eq_zero],
intros i _ j hij h,
exact (finset.mem_filter.mp hij).2.ne' (e.symm.injective $ pb.alg_hom_ext h) },
{ rw [alg_hom.card, pb.finrank] }
end
lemma det_trace_form_ne_zero [is_separable K L] [decidable_eq ι] (b : basis ι K L) :
det (bilin_form.to_matrix b (trace_form K L)) ≠ 0 :=
begin
haveI : finite_dimensional K L := finite_dimensional.of_fintype_basis b,
let pb : power_basis K L := field.power_basis_of_finite_of_separable _ _,
rw [← bilin_form.to_matrix_mul_basis_to_matrix pb.basis b,
← det_comm' (pb.basis.to_matrix_mul_to_matrix_flip b) _,
← matrix.mul_assoc, det_mul],
swap, { apply basis.to_matrix_mul_to_matrix_flip },
refine mul_ne_zero
(is_unit_of_mul_eq_one _ ((b.to_matrix pb.basis)ᵀ ⬝ b.to_matrix pb.basis).det _).ne_zero
(det_trace_form_ne_zero' pb),
calc (pb.basis.to_matrix b ⬝ (pb.basis.to_matrix b)ᵀ).det *
((b.to_matrix pb.basis)ᵀ ⬝ b.to_matrix pb.basis).det
= (pb.basis.to_matrix b ⬝ (b.to_matrix pb.basis ⬝ pb.basis.to_matrix b)ᵀ ⬝
b.to_matrix pb.basis).det
: by simp only [← det_mul, matrix.mul_assoc, matrix.transpose_mul]
... = 1 : by simp only [basis.to_matrix_mul_to_matrix_flip, matrix.transpose_one,
matrix.mul_one, matrix.det_one]
end
variables (K L)
theorem trace_form_nondegenerate [finite_dimensional K L] [is_separable K L] :
(trace_form K L).nondegenerate :=
bilin_form.nondegenerate_of_det_ne_zero (trace_form K L) _
(det_trace_form_ne_zero (finite_dimensional.fin_basis K L))
end det_ne_zero
|
14fa93d9d3576368167791065a55691b7de96939 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/topology/algebra/monoid.lean | a529e063d121080192abb3f6cbe9d3a24cfb5f8a | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 6,136 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
Theory of topological monoids.
-/
import topology.continuous_on
import group_theory.submonoid.basic
import deprecated.submonoid
open classical set filter topological_space
open_locale classical topological_space big_operators
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Basic hypothesis to talk about a topological additive monoid or a topological additive
semigroup. A topological additive monoid over `α`, for example, is obtained by requiring both the
instances `add_monoid α` and `has_continuous_add α`. -/
class has_continuous_add (α : Type*) [topological_space α] [has_add α] : Prop :=
(continuous_add : continuous (λp:α×α, p.1 + p.2))
/-- Basic hypothesis to talk about a topological monoid or a topological semigroup.
A topological monoid over `α`, for example, is obtained by requiring both the instances `monoid α` and
`has_continuous_mul α`. -/
@[to_additive]
class has_continuous_mul (α : Type*) [topological_space α] [has_mul α] : Prop :=
(continuous_mul : continuous (λp:α×α, p.1 * p.2))
section has_continuous_mul
variables [topological_space α] [has_mul α] [has_continuous_mul α]
@[to_additive]
lemma continuous_mul : continuous (λp:α×α, p.1 * p.2) :=
has_continuous_mul.continuous_mul
@[to_additive, continuity]
lemma continuous.mul [topological_space β] {f : β → α} {g : β → α}
(hf : continuous f) (hg : continuous g) :
continuous (λx, f x * g x) :=
continuous_mul.comp (hf.prod_mk hg)
attribute [continuity] continuous.add
@[to_additive]
lemma continuous_mul_left (a : α) : continuous (λ b:α, a * b) :=
continuous_const.mul continuous_id
@[to_additive]
lemma continuous_mul_right (a : α) : continuous (λ b:α, b * a) :=
continuous_id.mul continuous_const
@[to_additive]
lemma continuous_on.mul [topological_space β] {f : β → α} {g : β → α} {s : set β}
(hf : continuous_on f s) (hg : continuous_on g s) :
continuous_on (λx, f x * g x) s :=
(continuous_mul.comp_continuous_on (hf.prod hg) : _)
@[to_additive]
lemma tendsto_mul {a b : α} : tendsto (λp:α×α, p.fst * p.snd) (𝓝 (a, b)) (𝓝 (a * b)) :=
continuous_iff_continuous_at.mp has_continuous_mul.continuous_mul (a, b)
@[to_additive]
lemma filter.tendsto.mul {f : β → α} {g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, f x * g x) x (𝓝 (a * b)) :=
tendsto_mul.comp (hf.prod_mk_nhds hg)
@[to_additive]
lemma continuous_at.mul [topological_space β] {f : β → α} {g : β → α} {x : β}
(hf : continuous_at f x) (hg : continuous_at g x) :
continuous_at (λx, f x * g x) x :=
hf.mul hg
@[to_additive]
lemma continuous_within_at.mul [topological_space β] {f : β → α} {g : β → α} {s : set β} {x : β}
(hf : continuous_within_at f s x) (hg : continuous_within_at g s x) :
continuous_within_at (λx, f x * g x) s x :=
hf.mul hg
@[to_additive]
instance [topological_space β] [has_mul β] [has_continuous_mul β] : has_continuous_mul (α × β) :=
⟨((continuous_fst.comp continuous_fst).mul (continuous_fst.comp continuous_snd)).prod_mk
((continuous_snd.comp continuous_fst).mul (continuous_snd.comp continuous_snd))⟩
end has_continuous_mul
section has_continuous_mul
variables [topological_space α] [monoid α] [has_continuous_mul α]
@[to_additive]
lemma tendsto_list_prod {f : γ → β → α} {x : filter β} {a : γ → α} :
∀l:list γ, (∀c∈l, tendsto (f c) x (𝓝 (a c))) →
tendsto (λb, (l.map (λc, f c b)).prod) x (𝓝 ((l.map a).prod))
| [] _ := by simp [tendsto_const_nhds]
| (f :: l) h :=
begin
simp only [list.map_cons, list.prod_cons],
exact (h f (list.mem_cons_self _ _)).mul
(tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc)))
end
@[to_additive]
lemma continuous_list_prod [topological_space β] {f : γ → β → α} (l : list γ)
(h : ∀c∈l, continuous (f c)) :
continuous (λa, (l.map (λc, f c a)).prod) :=
continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc,
continuous_iff_continuous_at.1 (h c hc) x
-- @[to_additive continuous_smul]
@[continuity]
lemma continuous_pow : ∀ n : ℕ, continuous (λ a : α, a ^ n)
| 0 := by simpa using continuous_const
| (k+1) := show continuous (λ (a : α), a * a ^ k), from continuous_id.mul (continuous_pow _)
@[continuity]
lemma continuous.pow {f : β → α} [topological_space β] (h : continuous f) (n : ℕ) :
continuous (λ b, (f b) ^ n) :=
continuous.comp (continuous_pow n) h
end has_continuous_mul
section
variables [topological_space α] [comm_monoid α]
@[to_additive]
lemma is_submonoid.mem_nhds_one (β : set α) [is_submonoid β] (oβ : is_open β) :
β ∈ 𝓝 (1 : α) :=
mem_nhds_sets_iff.2 ⟨β, (by refl), oβ, is_submonoid.one_mem⟩
variable [has_continuous_mul α]
@[to_additive]
lemma tendsto_multiset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : multiset γ) :
(∀c∈s, tendsto (f c) x (𝓝 (a c))) →
tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) :=
by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l }
@[to_additive]
lemma tendsto_finset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : finset γ) :
(∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) :=
tendsto_multiset_prod _
@[to_additive, continuity]
lemma continuous_multiset_prod [topological_space β] {f : γ → β → α} (s : multiset γ) :
(∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) :=
by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l }
attribute [continuity] continuous_multiset_sum
@[to_additive, continuity]
lemma continuous_finset_prod [topological_space β] {f : γ → β → α} (s : finset γ) :
(∀c∈s, continuous (f c)) → continuous (λa, ∏ c in s, f c a) :=
continuous_multiset_prod _
attribute [continuity] continuous_finset_sum
end
|
94f47d2fac3c27d8a30eeb5a10f6290b053416f2 | f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58 | /analysis/topology/topological_space.lean | 9cc51f7533984ed28bbffbeebddeb0732609f415 | [
"Apache-2.0"
] | permissive | semorrison/mathlib | 1be6f11086e0d24180fec4b9696d3ec58b439d10 | 20b4143976dad48e664c4847b75a85237dca0a89 | refs/heads/master | 1,583,799,212,170 | 1,535,634,130,000 | 1,535,730,505,000 | 129,076,205 | 0 | 0 | Apache-2.0 | 1,551,697,998,000 | 1,523,442,265,000 | Lean | UTF-8 | Lean | false | false | 58,054 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
Theory of topological spaces.
Parts of the formalization is based on the books:
N. Bourbaki: General Topology
I. M. James: Topologies and Uniformities
A major difference is that this formalization is heavily based on the filter library.
-/
import order.filter data.set.countable tactic
open set filter lattice classical
local attribute [instance] prop_decidable
universes u v w
structure topological_space (α : Type u) :=
(is_open : set α → Prop)
(is_open_univ : is_open univ)
(is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t))
(is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s))
attribute [class] topological_space
section topological_space
variables {α : Type u} {β : Type v} {ι : Sort w} {a a₁ a₂ : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop}
lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g
| ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl
section
variables [t : topological_space α]
include t
/-- `is_open s` means that `s` is open in the ambient topological space on `α` -/
def is_open (s : set α) : Prop := topological_space.is_open t s
@[simp]
lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t
lemma is_open_inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) :=
topological_space.is_open_inter t s₁ s₂ h₁ h₂
lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) :=
topological_space.is_open_sUnion t s h
end
lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s :=
rfl
variables [topological_space α]
lemma is_open_union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) :=
have (⋃₀ {s₁, s₂}) = (s₁ ∪ s₂), by simp [union_comm],
this ▸ is_open_sUnion $ show ∀(t : set α), t ∈ ({s₁, s₂} : set (set α)) → is_open t,
by finish
lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) :=
is_open_sUnion $ assume t ⟨i, (heq : t = f i)⟩, heq.symm ▸ h i
lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) :
is_open (⋃i∈s, f i) :=
is_open_Union $ assume i, is_open_Union $ assume hi, h i hi
@[simp] lemma is_open_empty : is_open (∅ : set α) :=
have is_open (⋃₀ ∅ : set α), from is_open_sUnion (assume a, false.elim),
by simp at this; assumption
lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) :=
finite.induction_on hs (by simp) $ λ a s has hs ih h, begin
suffices : is_open (a ∩ ⋂₀ s), { simpa },
exact is_open_inter (h _ $ mem_insert _ _) (ih $ assume t ht, h _ $ mem_insert_of_mem _ ht)
end
lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) :=
finite.induction_on hs
(by simp)
(by simp [or_imp_distrib, _root_.is_open_inter, forall_and_distrib] {contextual := tt})
lemma is_open_const {p : Prop} : is_open {a : α | p} :=
by_cases
(assume : p, begin simp [*]; exact is_open_univ end)
(assume : ¬ p, begin simp [*]; exact is_open_empty end)
lemma is_open_and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} :=
is_open_inter
/-- A set is closed if its complement is open -/
def is_closed (s : set α) : Prop := is_open (-s)
@[simp] lemma is_closed_empty : is_closed (∅ : set α) := by simp [is_closed]
@[simp] lemma is_closed_univ : is_closed (univ : set α) := by simp [is_closed]
lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) :=
by simp [is_closed]; exact is_open_inter
lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) :=
by simp [is_closed, compl_sInter]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht
lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) :=
is_closed_sInter $ assume t ⟨i, (heq : t = f i)⟩, heq.symm ▸ h i
@[simp] lemma is_open_compl_iff {s : set α} : is_open (-s) ↔ is_closed s := iff.rfl
@[simp] lemma is_closed_compl_iff {s : set α} : is_closed (-s) ↔ is_open s :=
by rw [←is_open_compl_iff, compl_compl]
lemma is_open_diff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) :=
is_open_inter h₁ $ is_open_compl_iff.mpr h₂
lemma is_closed_inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) :=
by rw [is_closed, compl_inter]; exact is_open_union h₁ h₂
lemma is_closed_Union {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) :=
finite.induction_on hs
(by simp)
(by simp [or_imp_distrib, is_closed_union, forall_and_distrib] {contextual := tt})
lemma is_closed_imp [topological_space α] {p q : α → Prop}
(hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} :=
have {x | p x → q x} = (- {x | p x}) ∪ {x | q x}, from set.ext $ by finish,
by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq
lemma is_open_neg : is_closed {a | p a} → is_open {a | ¬ p a} :=
is_open_compl_iff.mpr
/-- The interior of a set `s` is the largest open subset of `s`. -/
def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s}
lemma mem_interior {s : set α} {x : α} :
x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by simp [interior, and_comm, and.left_comm]
@[simp] lemma is_open_interior {s : set α} : is_open (interior s) :=
is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁
lemma interior_subset {s : set α} : interior s ⊆ s :=
sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂
lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s :=
subset_sUnion_of_mem ⟨h₂, h₁⟩
lemma interior_eq_of_open {s : set α} (h : is_open s) : interior s = s :=
subset.antisymm interior_subset (interior_maximal (subset.refl s) h)
lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s :=
⟨assume h, h ▸ is_open_interior, interior_eq_of_open⟩
lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s :=
by simp [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset]
lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) :
s ⊆ interior t ↔ s ⊆ t :=
⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩
lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t :=
interior_maximal (subset.trans interior_subset h) is_open_interior
@[simp] lemma interior_empty : interior (∅ : set α) = ∅ :=
interior_eq_of_open is_open_empty
@[simp] lemma interior_univ : interior (univ : set α) = univ :=
interior_eq_of_open is_open_univ
@[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s :=
interior_eq_of_open is_open_interior
@[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t :=
subset.antisymm
(subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t))
(interior_maximal (inter_subset_inter interior_subset interior_subset) $ by simp [is_open_inter])
lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) :
interior (s ∪ t) = interior s :=
have interior (s ∪ t) ⊆ s, from
assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩,
classical.by_contradiction $ assume hx₂ : x ∉ s,
have u \ s ⊆ t,
from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂,
have u \ s ⊆ interior t,
by simp [subset_interior_iff_subset_of_open, this, is_open_diff hu₁ h₁],
have u \ s ⊆ ∅,
by rw [h₂] at this; assumption,
this ⟨hx₁, hx₂⟩,
subset.antisymm
(interior_maximal this is_open_interior)
(interior_mono $ subset_union_left _ _)
lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by rw ← subset_interior_iff_open; simp [subset_def, mem_interior]
/-- The closure of `s` is the smallest closed set containing `s`. -/
def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t}
@[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) :=
is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁
lemma subset_closure {s : set α} : s ⊆ closure s :=
subset_sInter $ assume t ⟨h₁, h₂⟩, h₂
lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t :=
sInter_subset_of_mem ⟨h₂, h₁⟩
lemma closure_eq_of_is_closed {s : set α} (h : is_closed s) : closure s = s :=
subset.antisymm (closure_minimal (subset.refl s) h) subset_closure
lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s :=
⟨assume h, h ▸ is_closed_closure, closure_eq_of_is_closed⟩
lemma closure_subset_iff_subset_of_is_closed {s t : set α} (h₁ : is_closed t) :
closure s ⊆ t ↔ s ⊆ t :=
⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩
lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_minimal (subset.trans h subset_closure) is_closed_closure
@[simp] lemma closure_empty : closure (∅ : set α) = ∅ :=
closure_eq_of_is_closed is_closed_empty
lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ :=
begin
split ; intro h,
{ rw set.eq_empty_iff_forall_not_mem,
intros x H,
simpa [h] using subset_closure H },
{ exact (eq.symm h) ▸ closure_empty },
end
@[simp] lemma closure_univ : closure (univ : set α) = univ :=
closure_eq_of_is_closed is_closed_univ
@[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s :=
closure_eq_of_is_closed is_closed_closure
@[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t :=
subset.antisymm
(closure_minimal (union_subset_union subset_closure subset_closure) $ by simp [is_closed_union])
(union_subset (closure_mono $ subset_union_left _ _) (closure_mono $ subset_union_right _ _))
lemma interior_subset_closure {s : set α} : interior s ⊆ closure s :=
subset.trans interior_subset subset_closure
lemma closure_eq_compl_interior_compl {s : set α} : closure s = - interior (- s) :=
begin
simp [interior, closure],
rw [compl_sUnion, compl_image_set_of],
simp [compl_subset_compl]
end
@[simp] lemma interior_compl_eq {s : set α} : interior (- s) = - closure s :=
by simp [closure_eq_compl_interior_compl]
@[simp] lemma closure_compl_eq {s : set α} : closure (- s) = - interior s :=
by simp [closure_eq_compl_interior_compl]
lemma closure_compl {s : set α} : closure (-s) = - interior s :=
subset.antisymm
(by simp [closure_subset_iff_subset_of_is_closed, compl_subset_compl, subset.refl])
begin
rw [compl_subset_comm, subset_interior_iff_subset_of_open, compl_subset_comm],
exact subset_closure,
exact is_open_compl_iff.mpr is_closed_closure
end
lemma interior_compl {s : set α} : interior (-s) = - closure s :=
calc interior (- s) = - - interior (- s) : by simp
... = - closure (- (- s)) : by rw [closure_compl]
... = - closure s : by simp
theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → o ∩ s ≠ ∅ :=
⟨λ h o oo ao os,
have s ⊆ -o, from λ x xs xo, @ne_empty_of_mem α (o∩s) x ⟨xo, xs⟩ os,
closure_minimal this (is_closed_compl_iff.2 oo) h ao,
λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc,
let ⟨x, hc, hs⟩ := exists_mem_of_ne_empty (H _ h₁ nc) in hc (h₂ hs)⟩
lemma dense_iff_inter_open {s : set α} : closure s = univ ↔ ∀ U, is_open U → U ≠ ∅ → U ∩ s ≠ ∅ :=
begin
split ; intro h,
{ intros U U_op U_ne,
cases exists_mem_of_ne_empty U_ne with x x_in,
exact mem_closure_iff.1 (by simp[h]) U U_op x_in },
{ ext x,
suffices : x ∈ closure s, by simp [this],
rw mem_closure_iff,
intros U U_op x_in,
exact h U U_op (ne_empty_of_mem x_in) },
end
/-- The frontier of a set is the set of points between the closure and interior. -/
def frontier (s : set α) : set α := closure s \ interior s
lemma frontier_eq_closure_inter_closure {s : set α} :
frontier s = closure s ∩ closure (- s) :=
by rw [closure_compl, frontier, diff_eq]
@[simp] lemma frontier_compl (s : set α) : frontier (-s) = frontier s :=
by simp [frontier_eq_closure_inter_closure, inter_comm]
/-- neighbourhood filter -/
def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s)
lemma tendsto_nhds {m : β → α} {f : filter β} (h : ∀s, a ∈ s → is_open s → m ⁻¹' s ∈ f.sets) :
tendsto m f (nhds a) :=
show map m f ≤ (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s),
from le_infi $ assume s, le_infi $ assume ⟨ha, hs⟩, le_principal_iff.mpr $ h s ha hs
lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (nhds a) :=
tendsto_nhds $ assume s ha hs, univ_mem_sets' $ assume _, ha
lemma nhds_sets {a : α} : (nhds a).sets = {s | ∃t⊆s, is_open t ∧ a ∈ t} :=
calc (nhds a).sets = (⋃s∈{s : set α| a ∈ s ∧ is_open s}, (principal s).sets) : infi_sets_eq'
(assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩,
⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩, by simp⟩)
⟨univ, by simp⟩
... = {s | ∃t⊆s, is_open t ∧ a ∈ t} :
le_antisymm
(supr_le $ assume i, supr_le $ assume ⟨hi₁, hi₂⟩ t ht, ⟨i, ht, hi₂, hi₁⟩)
(assume t ⟨i, hi₁, hi₂, hi₃⟩, by simp; exact ⟨i, ⟨hi₃, hi₂⟩, hi₁⟩)
lemma map_nhds {a : α} {f : α → β} :
map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal (image f s)) :=
calc map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, map f (principal s)) :
map_binfi_eq
(assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩,
⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩, by simp⟩)
⟨univ, by simp⟩
... = _ : by simp
lemma mem_nhds_sets_iff {a : α} {s : set α} :
s ∈ (nhds a).sets ↔ ∃t⊆s, is_open t ∧ a ∈ t :=
by simp [nhds_sets]
lemma mem_of_nhds {a : α} {s : set α} : s ∈ (nhds a).sets → a ∈ s :=
by simp [mem_nhds_sets_iff]; exact assume t ht _ hs, ht hs
lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) :
s ∈ (nhds a).sets :=
by simp [nhds_sets]; exact ⟨s, subset.refl _, hs, ha⟩
lemma pure_le_nhds : pure ≤ (nhds : α → filter α) :=
assume a, le_infi $ assume s, le_infi $ assume ⟨h₁, _⟩, principal_mono.mpr $ by simp [h₁]
@[simp] lemma nhds_neq_bot {a : α} : nhds a ≠ ⊥ :=
assume : nhds a = ⊥,
have return a = (⊥ : filter α),
from lattice.bot_unique $ this ▸ pure_le_nhds a,
pure_neq_bot this
lemma interior_eq_nhds {s : set α} : interior s = {a | nhds a ≤ principal s} :=
set.ext $ by simp [mem_interior, nhds_sets]
lemma mem_interior_iff_mem_nhds {s : set α} {a : α} :
a ∈ interior s ↔ s ∈ (nhds a).sets :=
by simp [interior_eq_nhds]
lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, nhds a ≤ principal s :=
calc is_open s ↔ interior s = s : by rw [interior_eq_iff_open]
... ↔ s ⊆ interior s : ⟨assume h, by simp [*, subset.refl], subset.antisymm interior_subset⟩
... ↔ (∀a∈s, nhds a ≤ principal s) : by rw [interior_eq_nhds]; refl
lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ (nhds a).sets :=
by simpa using @is_open_iff_nhds α _ _
lemma closure_eq_nhds {s : set α} : closure s = {a | nhds a ⊓ principal s ≠ ⊥} :=
calc closure s = - interior (- s) : closure_eq_compl_interior_compl
... = {a | ¬ nhds a ≤ principal (-s)} : by rw [interior_eq_nhds]; refl
... = {a | nhds a ⊓ principal s ≠ ⊥} : set.ext $ assume a, not_congr
(inf_eq_bot_iff_le_compl
(show principal s ⊔ principal (-s) = ⊤, by simp [principal_univ])
(by simp)).symm
theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ (nhds a).sets, t ∩ s ≠ ∅ :=
mem_closure_iff.trans
⟨λ H t ht, subset_ne_empty
(inter_subset_inter_left _ interior_subset)
(H _ is_open_interior (mem_interior_iff_mem_nhds.2 ht)),
λ H o oo ao, H _ (mem_nhds_sets oo ao)⟩
lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s :=
calc is_closed s ↔ closure s = s : by rw [closure_eq_iff_is_closed]
... ↔ closure s ⊆ s : ⟨assume h, by simp [*, subset.refl], assume h, subset.antisymm h subset_closure⟩
... ↔ (∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s) : by rw [closure_eq_nhds]; refl
lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) :=
assume a ⟨hs, ht⟩,
have s ∈ (nhds a).sets, from mem_nhds_sets h hs,
have nhds a ⊓ principal s = nhds a, from inf_of_le_left $ by simp [this],
have nhds a ⊓ principal (s ∩ t) ≠ ⊥,
from calc nhds a ⊓ principal (s ∩ t) = nhds a ⊓ (principal s ⊓ principal t) : by simp
... = nhds a ⊓ principal t : by rw [←inf_assoc, this]
... ≠ ⊥ : by rw [closure_eq_nhds] at ht; assumption,
by rw [closure_eq_nhds]; assumption
lemma closure_diff {s t : set α} : closure s - closure t ⊆ closure (s - t) :=
calc closure s \ closure t = (- closure t) ∩ closure s : by simp [diff_eq, inter_comm]
... ⊆ closure (- closure t ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure
... = closure (s \ closure t) : by simp [diff_eq, inter_comm]
... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure
lemma mem_of_closed_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
(hb : b ≠ ⊥) (hf : tendsto f b (nhds a)) (hs : is_closed s) (h : f ⁻¹' s ∈ b.sets) : a ∈ s :=
have b.map f ≤ nhds a ⊓ principal s,
from le_trans (le_inf (le_refl _) (le_principal_iff.mpr h)) (inf_le_inf hf (le_refl _)),
is_closed_iff_nhds.mp hs a $ neq_bot_of_le_neq_bot (map_ne_bot hb) this
lemma mem_closure_of_tendsto {f : β → α} {x : filter β} {a : α} {s : set α}
(hf : tendsto f x (nhds a)) (hs : is_closed s) (h : x ⊓ principal (f ⁻¹' s) ≠ ⊥) : a ∈ s :=
is_closed_iff_nhds.mp hs _ $ neq_bot_of_le_neq_bot (@map_ne_bot _ _ _ f h) $
le_inf (le_trans (map_mono $ inf_le_left) hf) $
le_trans (map_mono $ inf_le_right_of_le $ by simp; exact subset.refl _) (@map_vmap_le _ _ _ f)
/- locally finite family [General Topology (Bourbaki, 1995)] -/
section locally_finite
/-- A family of sets in `set α` is locally finite if at every point `x:α`,
there is a neighborhood of `x` which meets only finitely many sets in the family -/
def locally_finite (f : β → set α) :=
∀x:α, ∃t∈(nhds x).sets, finite {i | f i ∩ t ≠ ∅ }
lemma locally_finite_of_finite {f : β → set α} (h : finite (univ : set β)) : locally_finite f :=
assume x, ⟨univ, univ_mem_sets, finite_subset h $ by simp⟩
lemma locally_finite_subset
{f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ :=
assume a,
let ⟨t, ht₁, ht₂⟩ := hf₂ a in
⟨t, ht₁, finite_subset ht₂ $ assume i hi,
neq_bot_of_le_neq_bot hi $ inter_subset_inter (hf i) $ subset.refl _⟩
lemma is_closed_Union_of_locally_finite {f : β → set α}
(h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) :=
is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i),
have ∀i, a ∈ -f i,
from assume i hi, by simp at h; exact h i hi,
have ∀i, - f i ∈ (nhds a).sets,
by rw [nhds_sets]; exact assume i, ⟨- f i, subset.refl _, h₂ i, this i⟩,
let ⟨t, h_sets, (h_fin : finite {i | f i ∩ t ≠ ∅ })⟩ := h₁ a in
calc nhds a ≤ principal (t ∩ (⋂ i∈{i | f i ∩ t ≠ ∅ }, - f i)) :
begin
rw [le_principal_iff],
apply @filter.inter_mem_sets _ (nhds a) _ _ h_sets,
apply @filter.Inter_mem_sets _ (nhds a) _ _ _ h_fin,
exact assume i h, this i
end
... ≤ principal (- ⋃i, f i) :
begin
simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq,
mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists,
not_eq_empty_iff_exists, exists_imp_distrib, (≠)],
exact assume x xt ht i xfi, ht i x xfi xt xfi
end
end locally_finite
/- compact sets -/
section compact
/-- A set `s` is compact if every filter that contains `s` also meets every
neighborhood of some `a ∈ s`. -/
def compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ nhds a ≠ ⊥
lemma compact_of_is_closed_subset {s t : set α}
(hs : compact s) (ht : is_closed t) (h : t ⊆ s) : compact t :=
assume f hnf hsf,
let ⟨a, hsa, (ha : f ⊓ nhds a ≠ ⊥)⟩ := hs f hnf (le_trans hsf $ by simp [h]) in
have ∀a, principal t ⊓ nhds a ≠ ⊥ → a ∈ t,
by intro a; rw [inf_comm]; rw [is_closed_iff_nhds] at ht; exact ht a,
have a ∈ t,
from this a $ neq_bot_of_le_neq_bot ha $ inf_le_inf hsf (le_refl _),
⟨a, this, ha⟩
lemma compact_adherence_nhdset {s t : set α} {f : filter α}
(hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : is_open t) (ht₂ : ∀a∈s, nhds a ⊓ f ≠ ⊥ → a ∈ t) :
t ∈ f.sets :=
classical.by_cases mem_sets_of_neq_bot $
assume : f ⊓ principal (- t) ≠ ⊥,
let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ nhds a ≠ ⊥)⟩ := hs _ this $ inf_le_left_of_le hf₂ in
have a ∈ t,
from ht₂ a ha $ neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left,
have nhds a ⊓ principal (-t) ≠ ⊥,
from neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right,
have ∀s∈(nhds a ⊓ principal (-t)).sets, s ≠ ∅,
from forall_sets_neq_empty_iff_neq_bot.mpr this,
have false,
from this _ ⟨t, mem_nhds_sets ht₁ ‹a ∈ t›, -t, subset.refl _, subset.refl _⟩ (by simp),
by contradiction
lemma compact_iff_ultrafilter_le_nhds {s : set α} :
compact s ↔ (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a) :=
⟨assume hs : compact s, assume f hf hfs,
let ⟨a, ha, h⟩ := hs _ hf.left hfs in
⟨a, ha, le_of_ultrafilter hf h⟩,
assume hs : (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a),
assume f hf hfs,
let ⟨a, ha, (h : ultrafilter_of f ≤ nhds a)⟩ :=
hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in
have ultrafilter_of f ⊓ nhds a ≠ ⊥,
by simp [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left,
⟨a, ha, neq_bot_of_le_neq_bot this (inf_le_inf ultrafilter_of_le (le_refl _))⟩⟩
lemma compact_elim_finite_subcover {s : set α} {c : set (set α)}
(hs : compact s) (hc₁ : ∀t∈c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c' :=
classical.by_contradiction $ assume h,
have h : ∀{c'}, c' ⊆ c → finite c' → ¬ s ⊆ ⋃₀ c',
from assume c' h₁ h₂ h₃, h ⟨c', h₁, h₂, h₃⟩,
let
f : filter α := (⨅c':{c' : set (set α) // c' ⊆ c ∧ finite c'}, principal (s - ⋃₀ c')),
⟨a, ha⟩ := @exists_mem_of_ne_empty α s
(assume h', h (empty_subset _) finite_empty $ h'.symm ▸ empty_subset _)
in
have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩
(assume ⟨c₁, hc₁, hc'₁⟩ ⟨c₂, hc₂, hc'₂⟩, ⟨⟨c₁ ∪ c₂, union_subset hc₁ hc₂, finite_union hc'₁ hc'₂⟩,
principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_left _ _,
principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_right _ _⟩)
(assume ⟨c', hc'₁, hc'₂⟩, show principal (s \ _) ≠ ⊥, by simp [diff_eq_empty]; exact h hc'₁ hc'₂),
have f ≤ principal s, from infi_le_of_le ⟨∅, empty_subset _, finite_empty⟩ $
show principal (s \ ⋃₀∅) ≤ principal s, by simp; exact subset.refl s,
let
⟨a, ha, (h : f ⊓ nhds a ≠ ⊥)⟩ := hs f ‹f ≠ ⊥› this,
⟨t, ht₁, (ht₂ : a ∈ t)⟩ := hc₂ ha
in
have f ≤ principal (-t),
from infi_le_of_le ⟨{t}, by simp [ht₁], finite_insert _ finite_empty⟩ $
principal_mono.mpr $
show s - ⋃₀{t} ⊆ - t, begin simp; exact assume x ⟨_, hnt⟩, hnt end,
have is_closed (- t), from is_open_compl_iff.mp $ by simp; exact hc₁ t ht₁,
have a ∈ - t, from is_closed_iff_nhds.mp this _ $ neq_bot_of_le_neq_bot h $
le_inf inf_le_right (inf_le_left_of_le ‹f ≤ principal (- t)›),
this ‹a ∈ t›
lemma compact_elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α}
(hs : compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) :
∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i :=
if h : b = ∅ then ⟨∅, by simp, by simp, h ▸ hc₂⟩ else
let ⟨i, hi⟩ := exists_mem_of_ne_empty h in
have hc'₁ : ∀i∈c '' b, is_open i, from assume i ⟨j, hj, h⟩, h ▸ hc₁ _ hj,
have hc'₂ : s ⊆ ⋃₀ (c '' b), by simpa,
let ⟨d, hd₁, hd₂, hd₃⟩ := compact_elim_finite_subcover hs hc'₁ hc'₂ in
have ∀x : d, ∃i, i ∈ b ∧ c i = x, from assume ⟨x, hx⟩, hd₁ hx,
let ⟨f', hf⟩ := axiom_of_choice this,
f := λx:set α, (if h : x ∈ d then f' ⟨x, h⟩ else i : β) in
have ∀(x : α) (i : set α), i ∈ d → x ∈ i → (∃ (i : β), i ∈ f '' d ∧ x ∈ c i),
from assume x i hid hxi, ⟨f i, mem_image_of_mem f hid,
by simpa [f, hid, (hf ⟨_, hid⟩).2] using hxi⟩,
⟨f '' d,
assume i ⟨j, hj, h⟩,
h ▸ by simpa [f, hj] using (hf ⟨_, hj⟩).1,
finite_image f hd₂,
subset.trans hd₃ $ by simpa [subset_def]⟩
lemma compact_of_finite_subcover {s : set α}
(h : ∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') : compact s :=
assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, f ⊓ nhds x ≠ ⊥),
have hf : ∀x∈s, nhds x ⊓ f = ⊥,
by simpa [not_and, inf_comm],
have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t,
from assume ⟨x, hxs, hx⟩,
have ∅ ∈ (nhds x ⊓ f).sets, by rw [empty_in_sets_eq_bot, hf x hxs],
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in
have ∅ ∈ (nhds x ⊓ principal t₂).sets,
from (nhds x ⊓ principal t₂).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht,
have nhds x ⊓ principal t₂ = ⊥,
by rwa [empty_in_sets_eq_bot] at this,
by simp [closure_eq_nhds] at hx; exact hx t₂ ht₂ this,
have ∀x∈s, ∃t∈f.sets, x ∉ closure t, by simpa [_root_.not_forall],
let c := (λt, - closure t) '' f.sets, ⟨c', hcc', hcf, hsc'⟩ := h c
(assume t ⟨s, hs, h⟩, h ▸ is_closed_closure) (by simpa [subset_def]) in
let ⟨b, hb⟩ := axiom_of_choice $
show ∀s:c', ∃t, t ∈ f.sets ∧ - closure t = s,
from assume ⟨x, hx⟩, hcc' hx in
have (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets,
from Inter_mem_sets hcf $ assume t ht, by rw [dif_pos ht]; exact (hb ⟨t, ht⟩).left,
have s ∩ (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets,
from inter_mem_sets (by simp at hfs; assumption) this,
have ∅ ∈ f.sets,
from mem_sets_of_superset this $ assume x ⟨hxs, hxi⟩,
let ⟨t, htc', hxt⟩ := (show ∃t ∈ c', x ∈ t, by simpa using hsc' hxs) in
have -closure (b ⟨t, htc'⟩) = t, from (hb _).right,
have x ∈ - t,
from this ▸ (calc x ∈ b ⟨t, htc'⟩ : by simp at hxi; have h := hxi t htc'; rwa [dif_pos htc'] at h
... ⊆ closure (b ⟨t, htc'⟩) : subset_closure
... ⊆ - - closure (b ⟨t, htc'⟩) : by simp; exact subset.refl _),
show false, from this hxt,
hfn $ by rwa [empty_in_sets_eq_bot] at this
lemma compact_iff_finite_subcover {s : set α} :
compact s ↔ (∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') :=
⟨assume hc c, compact_elim_finite_subcover hc, compact_of_finite_subcover⟩
lemma compact_empty : compact (∅ : set α) :=
assume f hnf hsf, not.elim hnf $
by simpa [empty_in_sets_eq_bot] using hsf
lemma compact_singleton {a : α} : compact ({a} : set α) :=
compact_of_finite_subcover $ assume c hc₁ hc₂,
let ⟨i, hic, hai⟩ := (show ∃i ∈ c, a ∈ i, by simpa using hc₂) in
⟨{i}, by simp [hic], finite_singleton _, by simp [hai]⟩
lemma compact_bUnion_of_compact {s : set β} {f : β → set α} (hs : finite s) :
(∀i ∈ s, compact (f i)) → compact (⋃i ∈ s, f i) :=
assume hf, compact_of_finite_subcover $ assume c c_open c_cover,
have ∀i : subtype s, ∃c' ⊆ c, finite c' ∧ f i ⊆ ⋃₀ c', from
assume ⟨i, hi⟩, compact_elim_finite_subcover (hf i hi) c_open
(calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi
... ⊆ ⋃₀ c : c_cover),
let ⟨finite_subcovers, h⟩ := axiom_of_choice this in
let c' := ⋃i, finite_subcovers i in
have c' ⊆ c, from Union_subset (λi, (h i).fst),
have finite c', from @finite_Union _ _ hs.fintype _ (λi, (h i).snd.1),
have (⋃i ∈ s, f i) ⊆ ⋃₀ c', from bUnion_subset $ λi hi, calc
f i ⊆ ⋃₀ finite_subcovers ⟨i,hi⟩ : (h ⟨i,hi⟩).snd.2
... ⊆ ⋃₀ c' : sUnion_mono (subset_Union _ _),
⟨c', ‹c' ⊆ c›, ‹finite c'›, this⟩
lemma compact_of_finite {s : set α} (hs : finite s) : compact s :=
let s' : set α := ⋃i ∈ s, {i} in
have e : s' = s, from ext $ λi, by simp,
have compact s', from compact_bUnion_of_compact hs (λ_ _, compact_singleton),
e ▸ this
end compact
/- separation axioms -/
section separation
/-- A T₁ space, also known as a Fréchet space, is a topological space
where for every pair `x ≠ y`, there is an open set containing `x` and not `y`.
Equivalently, every singleton set is closed. -/
class t1_space (α : Type u) [topological_space α] :=
(t1 : ∀x, is_closed ({x} : set α))
lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) :=
t1_space.t1 x
lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ (nhds y).sets :=
mem_nhds_sets is_closed_singleton $ by simp; exact h
@[simp] lemma closure_singleton [topological_space α] [t1_space α] {a : α} :
closure ({a} : set α) = {a} :=
closure_eq_of_is_closed is_closed_singleton
/-- A T₂ space, also known as a Hausdorff space, is one in which for every
`x ≠ y` there exists disjoint open sets around `x` and `y`. This is
the most widely used of the separation axioms. -/
class t2_space (α : Type u) [topological_space α] :=
(t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅)
lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) :
∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ :=
t2_space.t2 x y h
instance t2_space.t1_space [topological_space α] [t2_space α] : t1_space α :=
⟨assume x,
have ∀y, y ≠ x ↔ ∃ (i : set α), (x ∉ i ∧ is_open i) ∧ y ∈ i,
from assume y, ⟨assume h',
let ⟨u, v, hu, hv, hy, hx, h⟩ := t2_separation h' in
have x ∉ u,
from assume : x ∈ u,
have x ∈ u ∩ v, from ⟨this, hx⟩,
by rwa [h] at this,
⟨u, ⟨this, hu⟩, hy⟩,
assume ⟨s, ⟨hx, hs⟩, hy⟩ h, hx $ h ▸ hy⟩,
have (-{x} : set α) = (⋃s∈{s : set α | x ∉ s ∧ is_open s}, s),
by apply set.ext; simpa,
show is_open (- {x}),
by rw [this]; exact (is_open_Union $ assume s, is_open_Union $ assume ⟨_, hs⟩, hs)⟩
lemma eq_of_nhds_neq_bot [ht : t2_space α] {x y : α} (h : nhds x ⊓ nhds y ≠ ⊥) : x = y :=
classical.by_contradiction $ assume : x ≠ y,
let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in
have u ∩ v ∈ (nhds x ⊓ nhds y).sets,
from inter_mem_inf_sets (mem_nhds_sets hu hx) (mem_nhds_sets hv hy),
h $ empty_in_sets_eq_bot.mp $ huv ▸ this
@[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : nhds a = nhds b ↔ a = b :=
⟨assume h, eq_of_nhds_neq_bot $ by simp [h], assume h, h ▸ rfl⟩
@[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : nhds a ≤ nhds b ↔ a = b :=
⟨assume h, eq_of_nhds_neq_bot $ by simp [inf_of_le_left h], assume h, h ▸ le_refl _⟩
lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α}
(hl : l ≠ ⊥) (ha : tendsto f l (nhds a)) (hb : tendsto f l (nhds b)) : a = b :=
eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot (map_ne_bot hl) $ le_inf ha hb
end separation
section regularity
/-- A T₃ space, also known as a regular space (although this condition sometimes
omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist
disjoint open sets containing `x` and `C` respectively. -/
class regular_space (α : Type u) [topological_space α] extends t2_space α :=
(regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ nhds a ⊓ principal t = ⊥)
lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ (nhds a).sets) :
∃t∈(nhds a).sets, t ⊆ s ∧ is_closed t :=
let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in
have ∃t, is_open t ∧ -s' ⊆ t ∧ nhds a ⊓ principal t = ⊥,
from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃),
let ⟨t, ht₁, ht₂, ht₃⟩ := this in
⟨-t,
mem_sets_of_neq_bot $ by simp; exact ht₃,
subset.trans (compl_subset_comm.1 ht₂) h₁,
is_closed_compl_iff.mpr ht₁⟩
end regularity
/- generating sets -/
end topological_space
namespace topological_space
variables {α : Type u}
/-- The least topology containing a collection of basic sets. -/
inductive generate_open (g : set (set α)) : set α → Prop
| basic : ∀s∈g, generate_open s
| univ : generate_open univ
| inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t)
| sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k)
/-- The smallest topological space containing the collection `g` of basic sets -/
def generate_from (g : set (set α)) : topological_space α :=
{ is_open := generate_open g,
is_open_univ := generate_open.univ g,
is_open_inter := generate_open.inter,
is_open_sUnion := generate_open.sUnion }
lemma nhds_generate_from {g : set (set α)} {a : α} :
@nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) :=
le_antisymm
(infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩)
(le_infi $ assume s, le_infi $ assume ⟨as, hs⟩,
have ∀s, generate_open g s → a ∈ s → (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) ≤ principal s,
begin
intros s hs,
induction hs,
case generate_open.basic : s hs
{ exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ },
case generate_open.univ
{ rw [principal_univ],
exact assume _, le_top },
case generate_open.inter : s t hs' ht' hs ht
{ exact assume ⟨has, hat⟩, calc _ ≤ principal s ⊓ principal t : le_inf (hs has) (ht hat)
... = _ : by simp },
case generate_open.sUnion : k hk' hk
{ exact λ ⟨t, htk, hat⟩, calc _ ≤ principal t : hk t htk hat
... ≤ _ : begin simp; exact subset_sUnion_of_mem htk end }
end,
this s hs as)
lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β}
(h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f.sets) : tendsto m f (@nhds β (generate_from g) b) :=
by rw [nhds_generate_from]; exact
(tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs)
end topological_space
section lattice
variables {α : Type u} {β : Type v}
instance : partial_order (topological_space α) :=
{ le := λt s, t.is_open ≤ s.is_open,
le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂,
le_refl := assume t, le_refl t.is_open,
le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ }
lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} :
topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} :=
iff.intro
(assume ht s hs, ht _ $ topological_space.generate_open.basic s hs)
(assume hg s hs, hs.rec_on (assume v hv, hg hv)
t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k))
protected def mk_of_closure (s : set (set α))
(hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α :=
{ is_open := λu, u ∈ s,
is_open_univ := hs ▸ topological_space.generate_open.univ _,
is_open_inter := hs ▸ topological_space.generate_open.inter,
is_open_sUnion := hs ▸ topological_space.generate_open.sUnion }
lemma mk_of_closure_sets {s : set (set α)}
{hs : {u | (topological_space.generate_from s).is_open u} = s} :
mk_of_closure s hs = topological_space.generate_from s :=
topological_space_eq hs.symm
def gi_generate_from (α : Type*) :
galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) :=
{ gc := assume g t, generate_from_le_iff_subset_is_open,
le_l_u := assume ts s hs, topological_space.generate_open.basic s hs,
choice := λg hg, mk_of_closure g
(subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _),
choice_eq := assume s hs, mk_of_closure_sets }
instance {α : Type u} : complete_lattice (topological_space α) :=
(gi_generate_from α).lift_complete_lattice
@[simp] lemma is_open_top {s : set α} : @is_open α ⊤ s := trivial
lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x ≤ @nhds α t₁ x) :
t₁ ≤ t₂ :=
assume s, show @is_open α t₁ s → @is_open α t₂ s,
begin simp [is_open_iff_nhds]; exact assume hs a ha, h _ $ hs _ ha end
lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x = @nhds α t₁ x) :
t₁ = t₂ :=
le_antisymm
(le_of_nhds_le_nhds $ assume x, le_of_eq $ h x)
(le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm)
end lattice
section galois_connection
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of
sets that are preimages of some open set in `β`. This is the coarsest topology that
makes `f` continuous. -/
def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) :
topological_space α :=
{ is_open := λs, ∃s', t.is_open s' ∧ s = f ⁻¹' s',
is_open_univ := ⟨univ, by simp; exact t.is_open_univ⟩,
is_open_inter := assume s₁ s₂ ⟨s'₁, hs₁, eq₁⟩ ⟨s'₂, hs₂, eq₂⟩,
⟨s'₁ ∩ s'₂, by simp [eq₁, eq₂]; exact t.is_open_inter _ _ hs₁ hs₂⟩,
is_open_sUnion := assume s h,
begin
simp [classical.skolem] at h,
cases h with f hf,
apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h),
simp [sUnion_eq_bUnion, (λx h, (hf x h).right.symm)],
exact (@is_open_Union β _ t _ $ assume i,
show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left)
end }
lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} :
@is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ s = f ⁻¹' t) :=
⟨assume ⟨t, ht, heq⟩, ⟨-t, by simp; assumption, by simp [preimage_compl, heq.symm]⟩,
assume ⟨t, ht, heq⟩, ⟨-t, ht, by simp [preimage_compl, heq.symm]⟩⟩
/-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined
such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that
makes `f` continuous. -/
def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) :
topological_space β :=
{ is_open := λs, t.is_open (f ⁻¹' s),
is_open_univ := by simp; exact t.is_open_univ,
is_open_inter := assume s₁ s₂ h₁ h₂, by simp; exact t.is_open_inter _ _ h₁ h₂,
is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i,
show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from
@is_open_Union _ _ t _ $ assume hi, h i hi) }
variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α}
lemma induced_le_iff_le_coinduced {f : α → β } {tα : topological_space α} {tβ : topological_space β} :
tβ.induced f ≤ tα ↔ tβ ≤ tα.coinduced f :=
iff.intro
(assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩)
(assume h s ⟨t, ht, hst⟩, hst.symm ▸ h _ ht)
lemma gc_induced_coinduced (f : α → β) :
galois_connection (topological_space.induced f) (topological_space.coinduced f) :=
assume f g, induced_le_iff_le_coinduced
lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g :=
(gc_induced_coinduced g).monotone_l h
lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f :=
(gc_induced_coinduced f).monotone_u h
@[simp] lemma induced_bot : (⊥ : topological_space α).induced g = ⊥ :=
(gc_induced_coinduced g).l_bot
@[simp] lemma induced_sup : (t₁ ⊔ t₂).induced g = t₁.induced g ⊔ t₂.induced g :=
(gc_induced_coinduced g).l_sup
@[simp] lemma induced_supr {ι : Sort w} {t : ι → topological_space α} :
(⨆i, t i).induced g = (⨆i, (t i).induced g) :=
(gc_induced_coinduced g).l_supr
@[simp] lemma coinduced_top : (⊤ : topological_space α).coinduced f = ⊤ :=
(gc_induced_coinduced f).u_top
@[simp] lemma coinduced_inf : (t₁ ⊓ t₂).coinduced f = t₁.coinduced f ⊓ t₂.coinduced f :=
(gc_induced_coinduced f).u_inf
@[simp] lemma coinduced_infi {ι : Sort w} {t : ι → topological_space α} :
(⨅i, t i).coinduced f = (⨅i, (t i).coinduced f) :=
(gc_induced_coinduced f).u_infi
lemma induced_id [t : topological_space α] : t.induced id = t :=
topological_space_eq $ funext $ assume s, propext $
⟨assume ⟨s', hs, h⟩, h.symm ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩
lemma induced_compose [tβ : topological_space β] [tγ : topological_space γ]
{f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) :=
topological_space_eq $ funext $ assume s, propext $
⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁.symm ▸ h₂.symm ▸ ⟨s, hs, rfl⟩,
assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩
lemma coinduced_id [t : topological_space α] : t.coinduced id = t :=
topological_space_eq rfl
lemma coinduced_compose [tα : topological_space α]
{f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) :=
topological_space_eq rfl
end galois_connection
/- constructions using the complete lattice structure -/
section constructions
open topological_space
variables {α : Type u} {β : Type v}
instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) :=
⟨⊤⟩
lemma t2_space_top : @t2_space α ⊤ :=
{ t2 := assume x y hxy, ⟨{x}, {y}, trivial, trivial, mem_insert _ _, mem_insert _ _,
eq_empty_iff_forall_not_mem.2 $ by intros z hz; simp at hz; cc⟩ }
instance : topological_space empty := ⊤
instance : topological_space unit := ⊤
instance : topological_space bool := ⊤
instance : topological_space ℕ := ⊤
instance : topological_space ℤ := ⊤
instance sierpinski_space : topological_space Prop :=
generate_from {{true}}
instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) :=
induced subtype.val t
instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) :=
coinduced (quot.mk r) t
instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) :=
coinduced quotient.mk t
instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) :=
induced prod.fst t₁ ⊔ induced prod.snd t₂
instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) :=
coinduced sum.inl t₁ ⊓ coinduced sum.inr t₂
instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) :=
⨅a, coinduced (sigma.mk a) (t₂ a)
instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) :=
⨆a, induced (λf, f a) (t₂ a)
lemma quotient_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) : closure (quotient.mk '' s) = univ :=
begin
ext x,
suffices : x ∈ closure (quotient.mk '' s), by simp [this],
rw mem_closure_iff,
intros U U_op x_in_U,
let V := quotient.mk ⁻¹' U,
cases quotient.exists_rep x with y y_x,
have y_in_V : y ∈ V, by simp [mem_preimage_eq, y_x, x_in_U],
have V_op : is_open V := U_op,
have : V ∩ s ≠ ∅ := mem_closure_iff.1 (H y) V V_op y_in_V,
rcases exists_mem_of_ne_empty this with ⟨w, w_in_V, w_in_range⟩,
exact ne_empty_of_mem ⟨by tauto, mem_image_of_mem quotient.mk w_in_range⟩
end
lemma generate_from_le {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) :
generate_from g ≤ t :=
generate_from_le_iff_subset_is_open.2 h
protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α :=
{ is_open := λs, a ∈ s → s ∈ f.sets,
is_open_univ := assume s, univ_mem_sets,
is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat),
is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) }
lemma gc_nhds (a : α) :
@galois_connection _ (order_dual (filter α)) _ _ (λt, @nhds α t a) (topological_space.nhds_adjoint a) :=
assume t (f : filter α), show f ≤ @nhds α t a ↔ _, from iff.intro
(assume h s hs has, h $ @mem_nhds_sets α t a s hs has)
(assume h, le_infi $ assume u, le_infi $ assume ⟨hau, hu⟩, le_principal_iff.2 $ h _ hu hau)
lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) :
@nhds α t₂ a ≤ @nhds α t₁ a := (gc_nhds a).monotone_l h
lemma nhds_supr {ι : Sort*} {t : ι → topological_space α} {a : α} :
@nhds α (supr t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).l_supr
lemma nhds_Sup {s : set (topological_space α)} {a : α} :
@nhds α (Sup s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).l_Sup
lemma nhds_sup {t₁ t₂ : topological_space α} {a : α} :
@nhds α (t₁ ⊔ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).l_sup
lemma nhds_bot {a : α} : @nhds α ⊥ a = ⊤ := (gc_nhds a).l_bot
private lemma separated_by_f
[tα : topological_space α] [tβ : topological_space β] [t2_space β]
(f : α → β) (hf : induced f tβ ≤ tα) {x y : α} (h : f x ≠ f y) :
∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ :=
let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in
⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv,
by rw [←preimage_inter, uv, preimage_empty]⟩
instance {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) :=
⟨assume x y h,
separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩
instance [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] :
t2_space (α × β) :=
⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h,
or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h))
(λ h₁, separated_by_f prod.fst le_sup_left h₁)
(λ h₂, separated_by_f prod.snd le_sup_right h₂)⟩
instance Pi.t2_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] :
t2_space (Πa, β a) :=
⟨assume x y h,
let ⟨i, hi⟩ := not_forall.mp (mt funext h) in
separated_by_f (λz, z i) (le_supr _ i) hi⟩
end constructions
namespace topological_space
/- countability axioms
For our applications we are interested that there exists a countable basis, but we do not need the
concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins.
-/
variables {α : Type u} [t : topological_space α]
include t
/-- A topological basis is one that satisfies the necessary conditions so that
it suffices to take unions of the basis sets to get a topology (without taking
finite intersections as well). -/
def is_topological_basis (s : set (set α)) : Prop :=
(∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧
(⋃₀ s) = univ ∧
t = generate_from s
lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) :
is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅}) :=
let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅} in
⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩,
have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union,
eq₁ ▸ eq₂ ▸ assume x h,
⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b,
by simpa [ie] using ne_empty_of_mem h⟩, ie⟩, h, subset.refl _⟩,
eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, by simp; exact (@empty_ne_univ _ ⟨a⟩).symm⟩, mem_univ _⟩,
have generate_from s = generate_from b',
from le_antisymm
(generate_from_le $ assume s hs,
by_cases
(assume : s = ∅, by rw [this]; apply @is_open_empty _ _)
(assume : s ≠ ∅, generate_open.basic _ ⟨{s}, by simp [this, hs]⟩))
(generate_from_le $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩,
eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)),
this ▸ hs⟩
lemma is_topological_basis_of_open_of_nhds {s : set (set α)}
(h_open : ∀ u ∈ s, _root_.is_open u)
(h_nhds : ∀(a:α) (u : set α), a ∈ u → _root_.is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) :
is_topological_basis s :=
⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩,
h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩
(is_open_inter _ _ _ (h_open _ ht₁) (h_open _ ht₂)),
eq_univ_iff_forall.2 $ assume a,
let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial (is_open_univ _) in
⟨u, h₁, h₂⟩,
le_antisymm
(assume u hu,
(@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau,
let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in
by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ by simp [hvu]))
(generate_from_le h_open)⟩
lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)}
(hb : is_topological_basis b) : s ∈ (nhds a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s :=
begin
rw [hb.2.2, nhds_generate_from, infi_sets_eq'],
{ simpa [and_comm, and.left_comm] },
{ exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩,
have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩,
let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in
⟨u, ⟨hu₂, hu₁⟩, by simpa using hu₃⟩ },
{ suffices : a ∈ (⋃₀ b), { simpa [and_comm] },
{ rw [hb.2.1], trivial } }
end
lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)}
(hb : is_topological_basis b) (hs : s ∈ b) : _root_.is_open s :=
is_open_iff_mem_nhds.2 $ λ a as,
(mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩
lemma mem_basis_subset_of_mem_open {b : set (set α)}
(hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u)
(ou : _root_.is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u :=
(mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au
lemma sUnion_basis_of_is_open {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) :
∃ S ⊆ B, u = ⋃₀ S :=
⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a,
⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in
⟨b, ⟨hb, bu⟩, ab⟩,
λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩
lemma Union_basis_of_is_open {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) :
∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B :=
let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in
⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩
variables (α)
/-- A separable space is one with a countable dense subset. -/
class separable_space : Prop :=
(exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ)
/-- A first-countable space is one in which every point has a
countable neighborhood basis. -/
class first_countable_topology : Prop :=
(nhds_generated_countable : ∀a:α, ∃s:set (set α), countable s ∧ nhds a = (⨅t∈s, principal t))
/-- A second-countable space is one with a countable basis. -/
class second_countable_topology : Prop :=
(is_open_generated_countable : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b)
instance second_countable_topology.to_first_countable_topology
[second_countable_topology α] : first_countable_topology α :=
let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in
⟨assume a, ⟨{s | a ∈ s ∧ s ∈ b},
countable_subset (assume x ⟨_, hx⟩, hx) hb, by rw [eq, nhds_generate_from]⟩⟩
lemma is_open_generated_countable_inter [second_countable_topology α] :
∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b :=
let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in
let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ ⋂₀ s ≠ ∅} in
⟨b',
countable_image _ $ countable_subset (by simp {contextual:=tt}) (countable_set_of_finite_subset hb₁),
assume ⟨s, ⟨_, _, hn⟩, hp⟩, hn hp,
is_topological_basis_of_subbasis hb₂⟩
instance second_countable_topology.to_separable_space
[second_countable_topology α] : separable_space α :=
let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in
have nhds_eq : ∀a, nhds a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val),
by intro a; rw [eq, nhds_generate_from]; simp [infi_subtype],
have ∀s∈b, ∃a, a ∈ s, from assume s hs, exists_mem_of_ne_empty $ assume eq, hb₂ $ eq ▸ hs,
have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simp only [skolem] at this; exact this,
let ⟨f, hf⟩ := this in
⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}),
countable_bUnion hb₁ (by simp [countable_Union_Prop]),
set.ext $ assume a,
have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial,
let ⟨t, ht₁, ht₂⟩ := this in
have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩,
suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥,
by simpa [closure_eq_nhds, nhds_eq, infi_inf w],
infi_neq_bot_of_directed ⟨a⟩
(assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩,
have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩,
let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in
⟨⟨s₃, has₃, hs₃⟩, begin
simp only [le_principal_iff, mem_principal_sets],
simp at hs, split; apply inter_subset_inter_left; simp [hs]
end⟩)
(assume ⟨s, has, hs⟩,
have s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h}) ≠ ∅,
from ne_empty_of_mem ⟨hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, by simp⟩⟩,
by simp [this]) ⟩⟩
lemma is_open_sUnion_countable [second_countable_topology α]
(S : set (set α)) (H : ∀ s ∈ S, _root_.is_open s) :
∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S :=
let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in
begin
let B' := {b ∈ B | ∃ s ∈ S, b ⊆ s},
rcases axiom_of_choice (λ b:B', b.2.2) with ⟨f, hf⟩,
change B' → set α at f,
haveI : encodable B' := (countable_subset (sep_subset _ _) cB).to_encodable,
have : range f ⊆ S := range_subset_iff.2 (λ x, (hf x).fst),
exact ⟨_, countable_range f, this,
subset.antisymm (sUnion_subset_sUnion this) $
sUnion_subset $ λ s hs x xs,
let ⟨b, hb, xb, bs⟩ := mem_basis_subset_of_mem_open bB xs (H _ hs) in
⟨_, ⟨⟨_, hb, _, hs, bs⟩, rfl⟩, (hf _).snd xb⟩⟩
end
end topological_space
section limit
variables {α : Type u} [inhabited α] [topological_space α]
open classical
/-- If `f` is a filter, then `lim f` is a limit of the filter, if it exists. -/
noncomputable def lim (f : filter α) : α := epsilon $ λa, f ≤ nhds a
lemma lim_spec {f : filter α} (h : ∃a, f ≤ nhds a) : f ≤ nhds (lim f) := epsilon_spec h
variables [t2_space α] {f : filter α}
lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : lim f = a :=
eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot hf $ le_inf (lim_spec ⟨_, h⟩) h
@[simp] lemma lim_nhds_eq {a : α} : lim (nhds a) = a :=
lim_eq nhds_neq_bot (le_refl _)
@[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) :
lim (nhds a ⊓ principal s) = a :=
lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left
end limit
|
190ba0e3db213ac17ccde880b3f47cf58709b8dc | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/logic/embedding.lean | 78b42038babec5b46ac5b74542e646f94730c61a | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 6,438 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
Injective functions.
-/
import data.equiv.basic data.option.basic data.subtype
universes u v w x
namespace function
structure embedding (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inj : injective to_fun)
infixr ` ↪ `:25 := embedding
instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) := ⟨_, embedding.to_fun⟩
end function
protected def equiv.to_embedding {α : Sort u} {β : Sort v} (f : α ≃ β) : α ↪ β :=
⟨f, f.injective⟩
@[simp] theorem equiv.to_embedding_coe_fn {α : Sort u} {β : Sort v} (f : α ≃ β) :
(f.to_embedding : α → β) = f := rfl
namespace function
namespace embedding
@[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g :=
by cases f; cases g; simpa using funext h
lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g :=
⟨ext, λ h _, by rw h⟩
@[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl
@[simp] theorem coe_fn_mk {α β} (f : α → β) (i) :
(@mk _ _ f i : α → β) = f := rfl
theorem inj' {α β} : ∀ (f : α ↪ β), injective f
| ⟨f, hf⟩ := hf
@[refl] protected def refl (α : Sort*) : α ↪ α :=
⟨id, injective_id⟩
@[trans] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ :=
⟨_, injective_comp g.inj' f.inj'⟩
@[simp] theorem refl_apply {α} (x : α) : embedding.refl α x = x := rfl
@[simp] theorem trans_apply {α β γ} (f : α ↪ β) (g : β ↪ γ) (a : α) :
(f.trans g) a = g (f a) := rfl
protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x}
(e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) :=
(equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding)
protected noncomputable def of_surjective {α β} {f : β → α} (hf : surjective f) :
α ↪ β :=
⟨surj_inv hf, injective_surj_inv _⟩
protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) :
α ≃ β :=
equiv.of_bijective ⟨f.inj, hf⟩
protected def of_not_nonempty {α β} (hα : ¬ nonempty α) : α ↪ β :=
⟨λa, (hα ⟨a⟩).elim, assume a, (hα ⟨a⟩).elim⟩
noncomputable def set_value {α β} (f : α ↪ β) (a : α) (b : β) : α ↪ β :=
by haveI := classical.dec; exact
if h : ∃ a', f a' = b then
(equiv.swap a (classical.some h)).to_embedding.trans f
else
⟨λ a', if a' = a then b else f a',
λ a₁ a₂ e, begin
simp at e, split_ifs at e with h₁ h₂,
{ cc },
{ cases h ⟨_, e.symm⟩ },
{ cases h ⟨_, e⟩ },
{ exact f.2 e }
end⟩
theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) : set_value f a b a = b :=
begin
rw [set_value],
cases classical.dec (∃ a', f a' = b);
dsimp [dite], {simp},
simp [equiv.swap_apply_left],
apply classical.some_spec h
end
/-- Embedding into `option` -/
protected def some {α} : α ↪ option α :=
⟨some, option.injective_some α⟩
def subtype {α} (p : α → Prop) : subtype p ↪ α :=
⟨subtype.val, λ _ _, subtype.eq'⟩
/-- Restrict the codomain of an embedding. -/
def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p :=
⟨λ a, ⟨f a, H a⟩, λ a b h, f.inj (@congr_arg _ _ _ _ subtype.val h)⟩
@[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) :
cod_restrict p f H a = ⟨f a, H a⟩ := rfl
def prod_congr {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ :=
⟨assume ⟨a, b⟩, (e₁ a, e₂ b),
assume ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ h,
have a₁ = a₂ ∧ b₁ = b₂, from (prod.mk.inj h).imp (assume h, e₁.inj h) (assume h, e₂.inj h),
this.left ▸ this.right ▸ rfl⟩
section sum
open sum
def sum_congr {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ :=
⟨assume s, match s with inl a := inl (e₁ a) | inr b := inr (e₂ b) end,
assume s₁ s₂ h, match s₁, s₂, h with
| inl a₁, inl a₂, h := congr_arg inl $ e₁.inj $ inl.inj h
| inr b₁, inr b₂, h := congr_arg inr $ e₂.inj $ inr.inj h
end⟩
@[simp] theorem sum_congr_apply_inl {α β γ δ}
(e₁ : α ↪ β) (e₂ : γ ↪ δ) (a) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := rfl
@[simp] theorem sum_congr_apply_inr {α β γ δ}
(e₁ : α ↪ β) (e₂ : γ ↪ δ) (b) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := rfl
end sum
section sigma
open sigma
def sigma_congr_right {α : Type*} {β γ : α → Type*} (e : ∀ a, β a ↪ γ a) : sigma β ↪ sigma γ :=
⟨λ ⟨a, b⟩, ⟨a, e a b⟩, λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ h, begin
injection h with h₁ h₂, subst a₂,
congr,
exact (e a₁).2 (eq_of_heq h₂)
end⟩
end sigma
def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) :=
⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).inj (congr_fun h a)⟩
def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w}
(e : α ↪ β) : (γ → α) ↪ (γ → β) :=
Pi_congr_right (λ _, e)
noncomputable def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ]
(e : α ↪ β) : (α → γ) ↪ (β → γ) :=
by haveI := classical.prop_decidable; exact
let f' : (α → γ) → (β → γ) := λf b, if h : ∃c, e c = b then f (classical.some h) else default γ in
⟨f', assume f₁ f₂ h, funext $ assume c,
have ∃c', e c' = e c, from ⟨c, rfl⟩,
have eq' : f' f₁ (e c) = f' f₂ (e c), from congr_fun h _,
have eq_b : classical.some this = c, from e.inj $ classical.some_spec this,
by simp [f', this, if_pos, eq_b] at eq'; assumption⟩
protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β)
(h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} :=
⟨subtype.map f h, subtype.map_injective h f.2⟩
open set
protected def image {α β} (f : α ↪ β) : set α ↪ set β :=
⟨image f, injective_image f.2⟩
end embedding
end function
namespace set
/-- The injection map is an embedding between subsets. -/
def embedding_of_subset {α} {s t : set α} (h : s ⊆ t) : s ↪ t :=
⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by congr; injection h⟩
end set
|
cc82ece8a427acc2acdd00713da2a4b875a37f80 | ba4794a0deca1d2aaa68914cd285d77880907b5c | /src/game/world2/level5.lean | d299382ca3286d3bc19c1f8f33e6937af7ff2a46 | [
"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,068 | lean | import mynat.definition -- hide
import mynat.add -- hide
import game.world2.level4 -- hide
namespace mynat -- hide
/- Axiom : one_eq_succ_zero
1 = succ(0)
-/
/-
# Addition World
## Level 5: `succ_eq_add_one`
I've just added `one_eq_succ_zero` (a proof of `1 = succ(0)`) to your list of theorems; this is true
by definition of $1$, but we didn't need it until now.
Levels 5 and 6 are the two last levels in Addition World.
Level 5 involves the number $1$. When you see a $1$ in your goal,
you can write `rw one_eq_succ_zero` to get back
to something which only mentions `0`. This is a good move because $0$ is easier for us to
manipulate than $1$ right now, because we have
some theorems about $0$ (`zero_add`, `add_zero`), but, other than `1 = succ(0)`,
no theorems at all which mention $1$. Let's prove one now.
-/
/- Theorem
For any natural number $n$, we have
$$ \operatorname{succ}(n) = n+1. $$
-/
theorem succ_eq_add_one (n : mynat) : succ n = n + 1 :=
begin [less_leaky]
rw one_eq_succ_zero,
rw add_succ,
rw add_zero,
refl,
end
end mynat -- hide
|
ffac7411498a495c6827690a634eb856b9022c81 | fffbc47930dc6615e66ece42324ce57a21d5b64b | /src/tactic/interactive.lean | c5ebe161126ab542c88ba44eb73fcb421dff1824 | [
"Apache-2.0"
] | permissive | skbaek/mathlib | 3caae8ae413c66862293a95fd2fbada3647b1228 | f25340175631cdc85ad768a262433f968d0d6450 | refs/heads/master | 1,588,130,123,636 | 1,558,287,609,000 | 1,558,287,609,000 | 160,935,713 | 0 | 0 | Apache-2.0 | 1,544,271,146,000 | 1,544,271,146,000 | null | UTF-8 | Lean | false | false | 22,415 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison
-/
import tactic.core data.list.defs
open lean
open lean.parser
local postfix `?`:9001 := optional
local postfix *:9001 := many
namespace tactic
namespace interactive
open interactive interactive.types expr
/-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal.
Never fails. Useful for debugging. -/
meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit :=
do max ← i_to_expr_strict max >>= tactic.eval_expr nat,
λ s, match _root_.try_for max (tac s) with
| some r := r
| none := (tactic.trace "try_for timeout, using sorry" >> admit) s
end
/-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/
meta def substs (l : parse ident*) : tactic unit :=
l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible)
/-- Unfold coercion-related definitions -/
meta def unfold_coes (loc : parse location) : tactic unit :=
unfold [
``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe,
``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift,
``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc
/-- Unfold auxiliary definitions associated with the current declaration. -/
meta def unfold_aux : tactic unit :=
do tgt ← target,
name ← decl_name,
let to_unfold := (tgt.list_names_with_prefix name),
guard (¬ to_unfold.empty),
-- should we be using simp_lemmas.mk_default?
simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change
/-- For debugging only. This tactic checks the current state for any
missing dropped goals and restores them. Useful when there are no
goals to solve but "result contains meta-variables". -/
meta def recover : tactic unit :=
metavariables >>= tactic.set_goals
/-- Like `try { tac }`, but in the case of failure it continues
from the failure state instead of reverting to the original state. -/
meta def continue (tac : itactic) : tactic unit :=
λ s, result.cases_on (tac s)
(λ a, result.success ())
(λ e ref, result.success ())
/-- Move goal `n` to the front. -/
meta def swap (n := 2) : tactic unit :=
do gs ← get_goals,
match gs.nth (n-1) with
| (some g) := set_goals (g :: gs.remove_nth (n-1))
| _ := skip
end
/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/
meta def clear_ : tactic unit := tactic.repeat $ do
l ← local_context,
l.reverse.mfirst $ λ h, do
name.mk_string s p ← return $ local_pp_name h,
guard (s.front = '_'),
cl ← infer_type h >>= is_class, guard (¬ cl),
tactic.clear h
meta def apply_iff_congr_core : tactic unit :=
applyc ``iff_of_eq
meta def congr_core' : tactic unit :=
do tgt ← target,
apply_eq_congr_core tgt
<|> apply_heq_congr_core
<|> apply_iff_congr_core
<|> fail "congr tactic failed"
/--
Same as the `congr` tactic, but takes an optional argument which gives
the depth of recursive applications. This is useful when `congr`
is too aggressive in breaking down the goal. For example, given
`⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y`
and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. -/
meta def congr' : parse (with_desc "n" small_nat)? → tactic unit
| (some 0) := failed
| o := focus1 (assumption <|> (congr_core' >>
all_goals (reflexivity <|> `[apply proof_irrel_heq] <|>
`[apply proof_irrel] <|> try (congr' (nat.pred <$> o)))))
/--
Acts like `have`, but removes a hypothesis with the same name as
this one. For example if the state is `h : p ⊢ goal` and `f : p → q`,
then after `replace h := f h` the goal will be `h : q ⊢ goal`,
where `have h := f h` would result in the state `h : p, h : q ⊢ goal`.
This can be used to simulate the `specialize` and `apply at` tactics
of Coq. -/
meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit :=
do let h := h.get_or_else `this,
old ← try_core (get_local h),
«have» h q₁ q₂,
match old, q₂ with
| none, _ := skip
| some o, some _ := tactic.clear o
| some o, none := swap >> tactic.clear o >> swap
end
/-- Make every propositions in the context decidable -/
meta def classical := tactic.classical
private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name)
| (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x)
| _ := fail "parse error"
private meta def generalize_arg_p : parser (pexpr × name) :=
with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux
lemma {u} generalize_a_aux {α : Sort u}
(h : ∀ x : Sort u, (α → x) → x) : α := h α id
/--
Like `generalize` but also considers assumptions
specified by the user. The user can also specify to
omit the goal.
-/
meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":")
(p : parse generalize_arg_p)
(l : parse location) :
tactic unit :=
do h' ← get_unused_name `h,
x' ← get_unused_name `x,
g ← if ¬ l.include_goal then
do refine ``(generalize_a_aux _),
some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h')
else pure none,
n ← l.get_locals >>= tactic.revert_lst,
generalize h () p,
intron n,
match g with
| some (x',h') :=
do tactic.apply h',
tactic.clear h',
tactic.clear x'
| none := return ()
end
/--
Similar to `refine` but generates equality proof obligations
for every discrepancy between the goal and the type of the rule.
-/
meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit :=
do v ← mk_mvar,
if sym.is_some
then refine ``(eq.mp %%v %%r)
else refine ``(eq.mpr %%v %%r),
gs ← get_goals,
set_goals [v],
try (congr' n),
gs' ← get_goals,
set_goals $ gs' ++ gs
meta def clean_ids : list name :=
[``id, ``id_rhs, ``id_delta, ``hidden]
/--
Remove identity functions from a term. These are normally
automatically generated with terms like `show t, from p` or
`(p : t)` which translate to some variant on `@id t p` in
order to retain the type. -/
meta def clean (q : parse texpr) : tactic unit :=
do tgt : expr ← target,
e ← i_to_expr_strict ``(%%q : %%tgt),
tactic.exact $ e.replace (λ e n,
match e with
| (app (app (const n _) _) e') :=
if n ∈ clean_ids then some e' else none
| (app (lam _ _ _ (var 0)) e') := some e'
| _ := none
end)
meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) :=
do e ← to_expr e,
t ← infer_type e,
let struct_n : name := t.get_app_fn.const_name,
fields ← expanded_field_list struct_n,
let exp_fields := fields.filter (λ x, x.2 ∈ missing),
exp_fields.mmap $ λ ⟨p,n⟩,
(prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e]
meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e :=
do some str ← pure (e.get_structure_instance_info)
| e.traverse collect_struct',
v ← monad_lift mk_mvar,
modify (list.cons (v,str)),
pure $ to_pexpr v
meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) :=
prod.map id list.reverse <$> (collect_struct' e).run []
meta def refine_one (str : structure_instance_info) :
tactic $ list (expr×structure_instance_info) :=
do tgt ← target,
let struct_n : name := tgt.get_app_fn.const_name,
exp_fields ← expanded_field_list struct_n,
let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names),
(src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd),
let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names),
let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names),
vs ← mk_mvar_list missing_f'.length,
(field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _),
e' ← to_expr $ pexpr.mk_structure_instance
{ struct := some struct_n
, field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names
, field_values := field_values ++ vs.map to_pexpr ++ src_field_vals },
tactic.exact e',
gs ← with_enable_tags (
mzip_with (λ (n : name × name) v, do
set_goals [v],
try (interactive.unfold (provided.map $ λ ⟨s,f⟩, f.update_prefix s) (loc.ns [none])),
apply_auto_param
<|> apply_opt_param
<|> (set_main_tag [`_field,n.2,n.1]),
get_goals)
missing_f' vs),
set_goals gs.join,
return new_goals.join
meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) :=
do set_goals [e],
rs ← refine_one str,
gs ← get_goals,
gs' ← rs.mmap refine_recursively,
return $ gs'.join ++ gs
/--
`refine_struct { .. }` acts like `refine` but works only with structure instance
literals. It creates a goal for each missing field and tags it with the name of the
field so that `have_field` can be used to generically refer to the field currently
being refined.
As an example, we can use `refine_struct` to automate the construction semigroup
instances:
```
refine_struct ( { .. } : semigroup α ),
-- case semigroup, mul
-- α : Type u,
-- ⊢ α → α → α
-- case semigroup, mul_assoc
-- α : Type u,
-- ⊢ ∀ (a b c : α), a * b * c = a * (b * c)
```
-/
meta def refine_struct : parse texpr → tactic unit | e :=
do (x,xs) ← collect_struct e,
refine x,
gs ← get_goals,
xs' ← xs.mmap refine_recursively,
set_goals (xs'.join ++ gs)
/--
`guard_hyp h := t` fails if the hypothesis `h` does not have type `t`.
We use this tactic for writing tests.
Fixes `guard_hyp` by instantiating meta variables
-/
meta def guard_hyp' (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p
/--
`guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast
to `guard_expr`, this tests strict (syntactic) equality.
We use this tactic for writing tests.
-/
meta def guard_expr_strict (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do e ← to_expr p, guard (t = e)
/--
`guard_target_strict t` fails if the target of the main goal is not syntactically `t`.
We use this tactic for writing tests.
-/
meta def guard_target_strict (p : parse texpr) : tactic unit :=
do t ← target, guard_expr_strict t p
/--
`guard_hyp_strict h := t` fails if the hypothesis `h` does not have type syntactically equal
to `t`.
We use this tactic for writing tests.
-/
meta def guard_hyp_strict (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p
meta def guard_hyp_nums (n : ℕ) : tactic unit :=
do k ← local_context,
guard (n = k.length) <|> fail format!"{k.length} hypotheses found"
meta def guard_tags (tags : parse ident*) : tactic unit :=
do (t : list name) ← get_main_tag,
guard (t = tags)
meta def get_current_field : tactic name :=
do [_,field,str] ← get_main_tag,
expr.const_name <$> resolve_name (field.update_prefix str)
meta def field (n : parse ident) (tac : itactic) : tactic unit :=
do gs ← get_goals,
ts ← gs.mmap get_tag,
([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n),
set_goals [g.1],
tac, done,
set_goals $ gs'.map prod.fst
/--
`have_field`, used after `refine_struct _` poses `field` as a local constant
with the type of the field of the current goal:
```
refine_struct ({ .. } : semigroup α),
{ have_field, ... },
{ have_field, ... },
```
behaves like
```
refine_struct ({ .. } : semigroup α),
{ have field := @semigroup.mul, ... },
{ have field := @semigroup.mul_assoc, ... },
```
-/
meta def have_field : tactic unit :=
propagate_tags $
get_current_field
>>= mk_const
>>= note `field none
>> return ()
/-- `apply_field` functions as `have_field, apply field, clear field` -/
meta def apply_field : tactic unit :=
propagate_tags $
get_current_field >>= applyc
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times.
`n` is 50 by default. `hs` can contain user attributes: in this case all theorems with this
attribute are added to the list of rules.
example, with or without user attribute:
```
@[user_attribute]
meta def mono_rules : user_attribute :=
{ name := `mono_rules,
descr := "lemmas usable to prove monotonicity" }
attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right
lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) :
a + c * e + a + c + 0 ≤ b + d * e + b + d + e :=
by apply_rules mono_rules
-- any of the following lines would also work:
-- add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3
-- by apply_rules [add_le_add, mul_le_mul_of_nonneg_right]
-- by apply_rules [mono_rules]
```
-/
meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) : tactic unit :=
tactic.apply_rules hs n
meta def return_cast (f : option expr) (t : option (expr × expr))
(es : list (expr × expr × expr))
(e x x' eq_h : expr) :
tactic (option (expr × expr) × list (expr × expr × expr)) :=
(do guard (¬ e.has_var),
unify x x',
u ← mk_meta_univ,
f ← f <|> mk_mapp ``_root_.id [(expr.sort u : expr)],
t' ← infer_type e,
some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es),
infer_type e >>= is_def_eq t,
unify f f',
return (some (f,t), (e,x',eq_h) :: es)) <|>
return (t, es)
meta def list_cast_of_aux (x : expr) (t : option (expr × expr))
(es : list (expr × expr × expr)) :
expr → tactic (option (expr × expr) × list (expr × expr × expr))
| e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h
| e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h
| e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x'
| e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h
| e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x'
| e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h
| e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h
| e := return (t,es)
meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) :=
(list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e)
private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name)
| (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x)
| _ := fail "parse error"
private meta def h_generalize_arg_p : parser (pexpr × name) :=
with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux
/--
`h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with
`x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple
times (not necessarily with the same proof), they are all replaced by `x`. `cast`
`eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated
as casts.
`h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`.
`h_generalize Hx : e == x with _` chooses automatically chooses the name of
assumption `α = β`.
`h_generalize! Hx : e == x` reverts `Hx`.
when `Hx` is omitted, assumption `Hx : e == x` is not added.
-/
meta def h_generalize (rev : parse (tk "!")?)
(h : parse ident_?)
(_ : parse (tk ":"))
(arg : parse h_generalize_arg_p)
(eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) :
tactic unit :=
do let (e,n) := arg,
let h' := if h = `_ then none else h,
h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string),
e ← to_expr e,
tgt ← target,
((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found",
interactive.generalize h' () (to_pexpr e, n),
asm ← get_local h',
v ← get_local n,
hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]),
(eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do
h ← if h ≠ `_ then pure h else get_unused_name `h,
() <$ note h none eq_h ),
hs.mmap' (λ h,
do h' ← assert `h h,
tactic.exact asm,
try (rewrite_target h'),
tactic.clear h' ),
when h.is_some (do
(to_expr ``(heq_of_eq_rec_left %%eq_h %%asm)
<|> to_expr ``(heq_of_eq_mp %%eq_h %%asm))
>>= note h' none >> pure ()),
tactic.clear asm,
when rev.is_some (interactive.revert [n])
/-- `choose a b h using hyp` takes an hypothesis `hyp` of the form
`∀ (x : X) (y : Y), ∃ (a : A) (b : B), P x y a b` for some `P : X → Y → A → B → Prop` and outputs
into context a function `a : X → Y → A`, `b : X → Y → B` and a proposition `h` stating
`∀ (x : X) (y : Y), P x y (a x y) (b x y)`. It presumably also works with dependent versions.
Example:
```lean
example (h : ∀n m : ℕ, ∃i j, m = n + i ∨ m + j = n) : true :=
begin
choose i j h using h,
guard_hyp i := ℕ → ℕ → ℕ,
guard_hyp j := ℕ → ℕ → ℕ,
guard_hyp h := ∀ (n m : ℕ), m = n + i n m ∨ m + j n m = n,
trivial
end
```
-/
meta def choose (first : parse ident) (names : parse ident*) (tgt : parse (tk "using" *> texpr)?) :
tactic unit := do
tgt ← match tgt with
| none := get_local `this
| some e := tactic.i_to_expr_strict e
end,
tactic.choose tgt (first :: names),
try (interactive.simp none tt [simp_arg_type.expr ``(exists_prop)] [] (loc.ns $ some <$> names)),
try (tactic.clear tgt)
meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do e ← to_expr p, is_def_eq t e
/--
`guard_target t` fails if the target of the main goal is not `t`.
We use this tactic for writing tests.
-/
meta def guard_target' (p : parse texpr) : tactic unit :=
do t ← target, guard_expr_eq' t p
/--
a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true,
unfolding only `reducible` constants. -/
meta def triv : tactic unit :=
tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "triv tactic failed"
/--
Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`.
Unlike `existsi`, `x` is elaborated with respect to the expected type.
`use` will alternatively take a list of terms `[x0, ..., xn]`.
`use` will work with constructors of arbitrary inductive types.
Examples:
example (α : Type) : ∃ S : set α, S = S :=
by use ∅
example : ∃ x : ℤ, x = x :=
by use 42
example : ∃ a b c : ℤ, a + b + c = 6 :=
by use [1, 2, 3]
example : ∃ p : ℤ × ℤ, p.1 = 1 :=
by use ⟨1, 42⟩
example : Σ x y : ℤ, (ℤ × ℤ) × ℤ :=
by use [1, 2, 3, 4, 5]
inductive foo
| mk : ℕ → bool × ℕ → ℕ → foo
example : foo :=
by use [100, tt, 4, 3]
-/
meta def use (l : parse pexpr_list_or_texpr) : tactic unit :=
tactic.use l >> try triv
/--
`clear_aux_decl` clears every `aux_decl` in the local context for the current goal.
This includes the induction hypothesis when using the equation compiler and
`_let_match` and `_fun_match`.
It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these
auxiliary declarations, and produce an error saying the recursion is not well founded.
-/
meta def clear_aux_decl : tactic unit := tactic.clear_aux_decl
meta def loc.get_local_pp_names : loc → tactic (list name)
| loc.wildcard := list.map expr.local_pp_name <$> local_context
| (loc.ns l) := return l.reduce_option
meta def loc.get_local_uniq_names (l : loc) : tactic (list name) :=
list.map expr.local_uniq_name <$> l.get_locals
/--
The logic of `change x with y at l` fails when there are dependencies.
`change'` mimics the behavior of `change`, except in the case of `change x with y at l`.
In this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses in `l`.
As long as `x` and `y` are defeq, it should never fail.
-/
meta def change' (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit
| none (loc.ns [none]) := do e ← i_to_expr q, change_core e none
| none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh)
| none _ := fail "change-at does not support multiple locations"
| (some w) l :=
do l' ← loc.get_local_pp_names l,
l'.mmap' (λ e, try (change_with_at q w e)),
when l.include_goal $ change q w (loc.ns [none])
private meta def opt_dir_with : parser (option (bool × name)) :=
(do tk "with",
arrow ← (tk "<-")?,
h ← ident,
return (arrow.is_some, h)) <|> return none
/--
`set a := t with h` is a variant of `let a := t`.
It adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can.
`set a := t with ←h` will add `h : t = a` instead.
`set! a := t with h` does not do any replacing.
-/
meta def set (h_simp : parse (tk "!")?) (a : parse ident) (tp : parse ((tk ":") >> texpr)?) (_ : parse (tk ":=")) (pv : parse texpr)
(rev_name : parse opt_dir_with) :=
do let vt := match tp with | some t := t | none := pexpr.mk_placeholder end,
let pv := ``(%%pv : %%vt),
v ← to_expr pv,
tp ← infer_type v,
definev a tp v,
when h_simp.is_none $ change' pv (some (expr.const a [])) loc.wildcard,
match rev_name with
| some (flip, id) :=
do nv ← get_local a,
pf ← to_expr (cond flip ``(%%pv = %%nv) ``(%%nv = %%pv)) >>= assert id,
reflexivity
| none := skip
end
/--
`clear_except h₀ h₁` deletes all the assumptions it can except for `h₀` and `h₁`.
-/
meta def clear_except (xs : parse ident *) : tactic unit :=
do let ns := name_set.of_list xs,
local_context >>= mmap' (λ h : expr,
when (¬ ns.contains h.local_pp_name) $
try $ tactic.clear h) ∘ list.reverse
end interactive
end tactic
|
a30969197b76df9e1ffb414d617a7c5def629038 | 32da3d0f92cab08875472ef6cacc1931c2b3eafa | /src/analysis/special_functions/pow.lean | fbb65a3a64face765e5b8b12b325bcc12ec7842d | [
"Apache-2.0"
] | permissive | karthiknadig/mathlib | b6073c3748860bfc9a3e55da86afcddba62dc913 | 33a86cfff12d7f200d0010cd03b95e9b69a6c1a5 | refs/heads/master | 1,676,389,371,851 | 1,610,061,127,000 | 1,610,061,127,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 61,295 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel,
Rémy Degenne
-/
import analysis.special_functions.trigonometric
import analysis.calculus.extend_deriv
/-!
# Power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ennreal`
We construct the power functions `x ^ y` where
* `x` and `y` are complex numbers,
* or `x` and `y` are real numbers,
* or `x` is a nonnegative real number and `y` is a real number;
* or `x` is a number from `[0, +∞]` (a.k.a. `ennreal`) and `y` is a real number.
We also prove basic properties of these functions.
-/
noncomputable theory
open_locale classical real topological_space nnreal
namespace complex
/-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal
determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for
`y ≠ 0`. -/
noncomputable def cpow (x y : ℂ) : ℂ :=
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y)
noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩
@[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl
lemma cpow_def (x y : ℂ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y) := rfl
@[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def]
@[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 :=
by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] }
@[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 :=
by simp [cpow_def, *]
@[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x :=
if hx : x = 0 then by simp [hx, cpow_def]
else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx]
@[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 :=
by rw cpow_def; split_ifs; simp [one_ne_zero, *] at *
lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z :=
by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at *
lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) :
x ^ (y * z) = (x ^ y) ^ z :=
begin
simp [cpow_def],
split_ifs;
simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at *
end
lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ :=
by simp [cpow_def]; split_ifs; simp [exp_neg]
lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ :=
by simpa using cpow_neg x 1
@[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n
| 0 := by simp
| (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ,
complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul]
else by simp [cpow_add, hx, pow_add, cpow_nat_cast n]
@[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n
| (n : ℕ) := by simp; refl
| -[1+ n] := by rw fpow_neg_succ_of_nat;
simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div,
int.cast_coe_nat, cpow_nat_cast]
lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x :=
have (log x * (↑n)⁻¹).im = (log x).im / n,
by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im,
of_real_re, of_real_im]; simp,
have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π,
from (le_total (log x).im 0).elim
(λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg]
... ≤ ((log x).im * 1) / n : (le_div_iff (nat.cast_pos.2 hn : (0 : ℝ) < _)).mpr
(mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)
... = (log x * (↑n)⁻¹).im : by simp [this],
this.symm ▸ le_trans (div_nonpos_of_nonpos_of_nonneg h n.cast_nonneg)
(le_of_lt real.pi_pos)⟩)
(λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos)
(div_nonneg h n.cast_nonneg),
calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this]
... ≤ (log x).im : (div_le_iff' (nat.cast_pos.2 hn : (0 : ℝ) < _)).mpr
(mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)
... ≤ _ : by simp [log, arg_le_pi]⟩),
by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2,
inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)),
cpow_one]
end complex
namespace real
/-- The real power function `x^y`, defined as the real part of the complex power function.
For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`.
For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex
determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (πy)`. -/
noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re
noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩
@[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl
lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl
lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y) :=
by simp only [rpow_def, complex.cpow_def];
split_ifs;
simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul,
(complex.of_real_mul _ _).symm, complex.exp_of_real_re] at *
lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) :=
by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)]
lemma exp_mul (x y : ℝ) : exp (x * y) = (exp x) ^ y :=
by rw [rpow_def_of_pos (exp_pos _), log_exp]
lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 :=
by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] }
open_locale real
lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) :=
begin
rw [rpow_def, complex.cpow_def, if_neg],
have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I,
simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx,
complex.abs_of_real, complex.of_real_mul], ring,
{ rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos,
← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul,
complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im,
real.log_neg_eq_log],
ring },
{ rw complex.of_real_eq_zero, exact ne_of_lt hx }
end
lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y) * cos (y * π) :=
by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _
lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y :=
by rw rpow_def_of_pos hx; apply exp_pos
@[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def]
@[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 :=
by simp [rpow_def, *]
@[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def]
@[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def]
lemma zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 :=
by { by_cases h : x = 0; simp [h, zero_le_one] }
lemma zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x :=
by { by_cases h : x = 0; simp [h, zero_le_one] }
lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y :=
by rw [rpow_def_of_nonneg hx];
split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)]
lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y :=
begin
rcases lt_trichotomy 0 x with (hx|rfl|hx),
{ rw [abs_of_pos hx, abs_of_pos (rpow_pos_of_pos hx _)] },
{ rw [abs_zero, abs_of_nonneg (rpow_nonneg_of_nonneg le_rfl _)] },
{ rw [abs_of_neg hx, rpow_def_of_neg hx, rpow_def_of_pos (neg_pos.2 hx), log_neg_eq_log,
abs_mul, abs_of_pos (exp_pos _)],
exact mul_le_of_le_one_right (exp_pos _).le (abs_cos_le_one _) }
end
end real
namespace complex
lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) :=
by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx]
@[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y :=
begin
rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def],
split_ifs;
simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add,
add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I,
(complex.of_real_mul _ _).symm, -complex.of_real_mul] at *
end
@[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) :=
by rw ← abs_cpow_real; simp [-abs_cpow_real]
end complex
namespace real
variables {x y z : ℝ}
lemma rpow_add {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z :=
by simp only [rpow_def_of_pos hx, mul_add, exp_add]
lemma rpow_add' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z :=
begin
rcases le_iff_eq_or_lt.1 hx with H|pos,
{ simp only [← H, h, rpow_eq_zero_iff_of_nonneg, true_and, zero_rpow, eq_self_iff_true, ne.def,
not_false_iff, zero_eq_mul],
by_contradiction F,
push_neg at F,
apply h,
simp [F] },
{ exact rpow_add pos _ _ }
end
/-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for
`x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish.
The inequality is always true, though, and given in this lemma. -/
lemma le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) :=
begin
rcases le_iff_eq_or_lt.1 hx with H|pos,
{ by_cases h : y + z = 0,
{ simp only [H.symm, h, rpow_zero],
calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 :
mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one
... = 1 : by simp },
{ simp [rpow_add', ← H, h] } },
{ simp [rpow_add pos] }
end
lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z :=
by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _),
complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx];
simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm,
complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos]
lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ :=
by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at *
lemma rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z :=
by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv]
lemma rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) :
x ^ (y - z) = x ^ y / x ^ z :=
by { simp only [sub_eq_add_neg] at h ⊢, simp only [rpow_add' hx h, rpow_neg hx, div_eq_mul_inv] }
@[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n :=
by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast,
complex.of_real_nat_cast, complex.of_real_re]
@[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n :=
by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast,
complex.of_real_int_cast, complex.of_real_re]
lemma rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ :=
begin
suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹, by exact_mod_cast H,
simp only [rpow_int_cast, fpow_one, fpow_neg],
end
lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z :=
begin
iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *,
{ have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂,
have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂,
rw [log_mul (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]},
{ exact h₁},
{ exact h},
{ exact mul_nonneg h h₁},
end
lemma inv_rpow (hx : 0 ≤ x) (y : ℝ) : (x⁻¹)^y = (x^y)⁻¹ :=
begin
by_cases hy0 : y = 0, { simp [*] },
by_cases hx0 : x = 0, { simp [*] },
simp only [real.rpow_def_of_nonneg hx, real.rpow_def_of_nonneg (inv_nonneg.2 hx), if_false,
hx0, mt inv_eq_zero.1 hx0, log_inv, ← neg_mul_eq_neg_mul, exp_neg]
end
lemma div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x^z / y^z :=
by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy]
lemma log_rpow {x : ℝ} (hx : 0 < x) (y : ℝ) : log (x^y) = y * (log x) :=
begin
apply exp_injective,
rw [exp_log (rpow_pos_of_pos hx y), ← exp_log hx, mul_comm, rpow_def_of_pos (exp_pos (log x)) y],
end
lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z :=
begin
rw le_iff_eq_or_lt at hx, cases hx,
{ rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ },
rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp],
exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz
end
lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z :=
begin
rcases eq_or_lt_of_le h₁ with rfl|h₁', { refl },
rcases eq_or_lt_of_le h₂ with rfl|h₂', { simp },
exact le_of_lt (rpow_lt_rpow h h₁' h₂')
end
lemma rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y :=
⟨lt_imp_lt_of_le_imp_le $ λ h, rpow_le_rpow hy h (le_of_lt hz), λ h, rpow_lt_rpow hx h hz⟩
lemma rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y :=
le_iff_le_iff_lt_iff_lt.2 $ rpow_lt_rpow_iff hy hx hz
lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z :=
begin
repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]},
rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx),
end
lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z :=
begin
repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]},
rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx),
end
lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) :
x^y < x^z :=
begin
repeat {rw [rpow_def_of_pos hx0]},
rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1),
end
lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) :
x^y ≤ x^z :=
begin
repeat {rw [rpow_def_of_pos hx0]},
rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1),
end
lemma rpow_lt_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x < 1) (hz : 0 < z) : x^z < 1 :=
by { rw ← one_rpow z, exact rpow_lt_rpow hx1 hx2 hz }
lemma rpow_le_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 :=
by { rw ← one_rpow z, exact rpow_le_rpow hx1 hx2 hz }
lemma rpow_lt_one_of_one_lt_of_neg {x z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 :=
by { convert rpow_lt_rpow_of_exponent_lt hx hz, exact (rpow_zero x).symm }
lemma rpow_le_one_of_one_le_of_nonpos {x z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 :=
by { convert rpow_le_rpow_of_exponent_le hx hz, exact (rpow_zero x).symm }
lemma one_lt_rpow {x z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z :=
by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz }
lemma one_le_rpow {x z : ℝ} (hx : 1 ≤ x) (hz : 0 ≤ z) : 1 ≤ x^z :=
by { rw ← one_rpow z, exact rpow_le_rpow zero_le_one hx hz }
lemma one_lt_rpow_of_pos_of_lt_one_of_neg (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) :
1 < x^z :=
by { convert rpow_lt_rpow_of_exponent_gt hx1 hx2 hz, exact (rpow_zero x).symm }
lemma one_le_rpow_of_pos_of_le_one_of_nonpos (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) :
1 ≤ x^z :=
by { convert rpow_le_rpow_of_exponent_ge hx1 hx2 hz, exact (rpow_zero x).symm }
lemma rpow_lt_one_iff_of_pos (hx : 0 < x) : x ^ y < 1 ↔ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y :=
by rw [rpow_def_of_pos hx, exp_lt_one_iff, mul_neg_iff, log_pos_iff hx, log_neg_iff hx]
lemma rpow_lt_one_iff (hx : 0 ≤ x) : x ^ y < 1 ↔ x = 0 ∧ y ≠ 0 ∨ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y :=
begin
rcases hx.eq_or_lt with (rfl|hx),
{ rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, zero_lt_one] },
{ simp [rpow_lt_one_iff_of_pos hx, hx.ne.symm] }
end
lemma one_lt_rpow_iff_of_pos (hx : 0 < x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ x < 1 ∧ y < 0 :=
by rw [rpow_def_of_pos hx, one_lt_exp_iff, mul_pos_iff, log_pos_iff hx, log_neg_iff hx]
lemma one_lt_rpow_iff (hx : 0 ≤ x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ 0 < x ∧ x < 1 ∧ y < 0 :=
begin
rcases hx.eq_or_lt with (rfl|hx),
{ rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, (@zero_lt_one ℝ _ _).not_lt] },
{ simp [one_lt_rpow_iff_of_pos hx, hx] }
end
lemma rpow_le_one_iff_of_pos (hx : 0 < x) : x ^ y ≤ 1 ↔ 1 ≤ x ∧ y ≤ 0 ∨ x ≤ 1 ∧ 0 ≤ y :=
by rw [rpow_def_of_pos hx, exp_le_one_iff, mul_nonpos_iff, log_nonneg_iff hx, log_nonpos_iff hx]
lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) :
(x ^ n) ^ (n⁻¹ : ℝ) = x :=
have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn,
by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one]
lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) :
(x ^ (n⁻¹ : ℝ)) ^ n = x :=
have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn,
by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one]
section prove_rpow_is_continuous
lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) :=
suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)),
by { convert h, ext p, rw rpow_def_of_pos p.2 },
continuous_exp.comp $
(show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from
continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id)
lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) :=
suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)),
by { convert h, ext p, rw [rpow_def_of_neg p.2, log_neg_eq_log] },
(continuous_exp.comp $
(show continuous $ (λp:{p:ℝ//0<p},
log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩),
from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $
continuous_fst.comp continuous_subtype_val).mul
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul
(continuous_cos.comp $
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const)
lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) :
continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) :=
begin
cases lt_trichotomy 0 x,
exact continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h)
(mem_nhds_sets (by { convert (is_open_lt' (0:ℝ)).prod is_open_univ, ext, finish }) h),
cases h,
{ exact absurd h.symm hx },
exact continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h)
(mem_nhds_sets (by { convert (is_open_gt' (0:ℝ)).prod is_open_univ, ext, finish }) h)
end
lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) :=
continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩,
begin
by_cases hx₀ : x₀ = 0,
{ simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), metric.tendsto_nhds_nhds],
assume ε ε0,
rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩,
let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos,
let δ := min (min q (ε ^ (1 / q))) (1/2),
have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num),
have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _),
have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _),
have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num),
use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩,
simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk],
assume h, rw max_lt_iff at h, cases h with xδ yy₀,
have qy : q < y, calc q < y₀ / 2 : q_lt
... = y₀ - y₀ / 2 : (sub_half _).symm
... ≤ y₀ - δ : by linarith
... < y : sub_lt_of_abs_sub_lt_left yy₀,
calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _
... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy
... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} }
... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} }
... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }},
{ exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1
(continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at }
end
lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) :
continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) :=
continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy)
(mem_nhds_sets (by { convert is_open_univ.prod (is_open_lt' (0:ℝ)), ext, finish }) hy)
lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) :
continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) :=
by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x }
variables {α : Type*} [topological_space α] {f g : α → ℝ}
/--
`real.rpow` is continuous at all points except for the lower half of the y-axis.
In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`.
Multiple forms of the claim is provided in the current section.
-/
lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) :=
continuous_iff_continuous_at.2 $ λ a,
begin
show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a,
refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _),
{ replace h := h a, cases h,
{ exact continuous_at_rpow_of_ne_zero h _ },
{ exact continuous_at_rpow_of_pos h _ }},
end
lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg
lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg
end prove_rpow_is_continuous
section prove_rpow_is_differentiable
lemma has_deriv_at_rpow_of_pos {x : ℝ} (h : 0 < x) (p : ℝ) :
has_deriv_at (λ x, x^p) (p * x^(p-1)) x :=
begin
have : has_deriv_at (λ x, exp (log x * p)) (p * x^(p-1)) x,
{ convert (has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_gt h)).mul_const p) using 1,
field_simp [rpow_def_of_pos h, mul_sub, exp_sub, exp_log h, ne_of_gt h],
ring },
apply this.congr_of_eventually_eq,
have : set.Ioi (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Ioi h,
exact filter.eventually_of_mem this (λ y hy, rpow_def_of_pos hy _)
end
lemma has_deriv_at_rpow_of_neg {x : ℝ} (h : x < 0) (p : ℝ) :
has_deriv_at (λ x, x^p) (p * x^(p-1)) x :=
begin
have : has_deriv_at (λ x, exp (log x * p) * cos (p * π)) (p * x^(p-1)) x,
{ convert ((has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_lt h)).mul_const p)).mul_const _
using 1,
field_simp [rpow_def_of_neg h, mul_sub, exp_sub, sub_mul, cos_sub, exp_log_of_neg h, ne_of_lt h],
ring },
apply this.congr_of_eventually_eq,
have : set.Iio (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Iio h,
exact filter.eventually_of_mem this (λ y hy, rpow_def_of_neg hy _)
end
lemma has_deriv_at_rpow {x : ℝ} (h : x ≠ 0) (p : ℝ) :
has_deriv_at (λ x, x^p) (p * x^(p-1)) x :=
begin
rcases lt_trichotomy x 0 with H|H|H,
{ exact has_deriv_at_rpow_of_neg H p },
{ exact (h H).elim },
{ exact has_deriv_at_rpow_of_pos H p },
end
lemma has_deriv_at_rpow_zero_of_one_le {p : ℝ} (h : 1 ≤ p) :
has_deriv_at (λ x, x^p) (p * (0 : ℝ)^(p-1)) 0 :=
begin
apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, has_deriv_at_rpow hx p),
{ exact (continuous_rpow_of_pos (λ _, (lt_of_lt_of_le zero_lt_one h))
continuous_id continuous_const).continuous_at },
{ rcases le_iff_eq_or_lt.1 h with rfl|h,
{ simp [continuous_const.continuous_at] },
{ exact (continuous_const.mul (continuous_rpow_of_pos (λ _, sub_pos_of_lt h)
continuous_id continuous_const)).continuous_at } }
end
lemma has_deriv_at_rpow_of_one_le (x : ℝ) {p : ℝ} (h : 1 ≤ p) :
has_deriv_at (λ x, x^p) (p * x^(p-1)) x :=
begin
by_cases hx : x = 0,
{ rw hx, exact has_deriv_at_rpow_zero_of_one_le h },
{ exact has_deriv_at_rpow hx p }
end
end prove_rpow_is_differentiable
section sqrt
lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) :=
begin
funext, by_cases h : 0 ≤ x,
{ rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h],
norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ },
{ replace h : x < 0 := lt_of_not_ge h,
have : 1 / (2:ℝ) * π = π / (2:ℝ), ring,
rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] }
end
end sqrt
end real
section measurability_real
lemma real.measurable_rpow : measurable (λ p : ℝ × ℝ, p.1 ^ p.2) :=
begin
have h_meas : is_measurable {p : ℝ × ℝ | p.1 = 0} :=
(is_closed_singleton.preimage continuous_fst).is_measurable,
refine measurable_of_measurable_union_cover {p : ℝ × ℝ | p.1 = 0} {p : ℝ × ℝ | p.1 ≠ 0} h_meas
h_meas.compl _ _ _,
{ intro x, simp [em (x.fst = 0)], },
{ have h_eq_ite : (λ a : {p : ℝ × ℝ | p.fst = 0}, (a:ℝ×ℝ).fst ^ (a:ℝ×ℝ).snd) =
λ a : {p : ℝ × ℝ | p.fst = 0}, ite ((a:ℝ×ℝ).snd = 0) 1 0,
{ ext1 a,
have h_fst_zero : (a:ℝ×ℝ).fst = 0, from a.prop,
rw h_fst_zero,
split_ifs with h_snd,
{ rw h_snd,
exact real.rpow_zero _, },
exact real.zero_rpow h_snd, },
rw h_eq_ite,
change measurable ((λ x : ℝ, ite (x = 0) (1:ℝ) (0:ℝ))
∘ (λ a : {p : ℝ × ℝ | p.fst = 0}, (a:ℝ×ℝ).snd)),
refine measurable.comp _ (measurable_snd.comp measurable_subtype_coe),
exact measurable.ite (is_measurable_singleton 0) measurable_const measurable_const, },
{ refine continuous.measurable _,
rw continuous_iff_continuous_at,
intro x,
change continuous_at ((λ a : ℝ × ℝ, a.fst ^ a.snd)
∘ (λ a : {p : ℝ × ℝ | p.fst ≠ 0}, (a:ℝ×ℝ))) x,
refine continuous_at.comp _ continuous_at_subtype_coe,
change continuous_at (λ (p : ℝ × ℝ), p.fst ^ p.snd) x.val,
have h_x : x.val = (x.val.fst, x.val.snd), by simp,
rw h_x,
exact real.continuous_at_rpow_of_ne_zero x.prop _, },
end
lemma measurable.rpow {α} [measurable_space α] {f g : α → ℝ} (hf : measurable f)
(hg : measurable g) :
measurable (λ a : α, (f a) ^ (g a)) :=
begin
change measurable ((λ p : ℝ × ℝ, p.1 ^ p.2) ∘ (λ a : α, (f a, g a))),
exact real.measurable_rpow.comp (measurable.prod hf hg),
end
lemma real.measurable_rpow_const {y : ℝ} : measurable (λ x : ℝ, x ^ y) :=
begin
change measurable ((λ p : ℝ × ℝ, p.1 ^ p.2) ∘ (λ x : ℝ, (id x, (λ x, y) x))),
refine real.measurable_rpow.comp (measurable.prod measurable_id _),
change measurable (λ (a : ℝ), y),
exact measurable_const,
end
lemma measurable.rpow_const {α} [measurable_space α] {f : α → ℝ} (hf : measurable f) {y : ℝ} :
measurable (λ a : α, (f a) ^ y) :=
hf.rpow measurable_const
end measurability_real
section differentiability
open real
variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} (p : ℝ)
/- Differentiability statements for the power of a function, when the function does not vanish
and the exponent is arbitrary-/
lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) :
has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x :=
begin
convert (has_deriv_at_rpow hx p).comp_has_deriv_within_at x hf using 1,
ring
end
lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hx : f x ≠ 0) :
has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hf.rpow p hx
end
lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) :
differentiable_within_at ℝ (λx, (f x)^p) s x :=
(hf.has_deriv_within_at.rpow p hx).differentiable_within_at
@[simp] lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
differentiable_at ℝ (λx, (f x)^p) x :=
(hf.has_deriv_at.rpow p hx).differentiable_at
lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) :
differentiable_on ℝ (λx, (f x)^p) s :=
λx h, (hf x h).rpow p (hx x h)
@[simp] lemma differentiable.rpow (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) :
differentiable ℝ (λx, (f x)^p) :=
λx, (hf x).rpow p (hx x)
lemma deriv_within_rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) :=
(hf.has_deriv_within_at.rpow p hx).deriv_within hxs
@[simp] lemma deriv_rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) :=
(hf.has_deriv_at.rpow p hx).deriv
/- Differentiability statements for the power of a function, when the function may vanish
but the exponent is at least one. -/
variable {p}
lemma has_deriv_within_at.rpow_of_one_le (hf : has_deriv_within_at f f' s x) (hp : 1 ≤ p) :
has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x :=
begin
convert (has_deriv_at_rpow_of_one_le (f x) hp).comp_has_deriv_within_at x hf using 1,
ring
end
lemma has_deriv_at.rpow_of_one_le (hf : has_deriv_at f f' x) (hp : 1 ≤ p) :
has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hf.rpow_of_one_le hp
end
lemma differentiable_within_at.rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) :
differentiable_within_at ℝ (λx, (f x)^p) s x :=
(hf.has_deriv_within_at.rpow_of_one_le hp).differentiable_within_at
@[simp] lemma differentiable_at.rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) :
differentiable_at ℝ (λx, (f x)^p) x :=
(hf.has_deriv_at.rpow_of_one_le hp).differentiable_at
lemma differentiable_on.rpow_of_one_le (hf : differentiable_on ℝ f s) (hp : 1 ≤ p) :
differentiable_on ℝ (λx, (f x)^p) s :=
λx h, (hf x h).rpow_of_one_le hp
@[simp] lemma differentiable.rpow_of_one_le (hf : differentiable ℝ f) (hp : 1 ≤ p) :
differentiable ℝ (λx, (f x)^p) :=
λx, (hf x).rpow_of_one_le hp
lemma deriv_within_rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) :=
(hf.has_deriv_within_at.rpow_of_one_le hp).deriv_within hxs
@[simp] lemma deriv_rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) :
deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) :=
(hf.has_deriv_at.rpow_of_one_le hp).deriv
/- Differentiability statements for the square root of a function, when the function does not
vanish -/
lemma has_deriv_within_at.sqrt (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) :
has_deriv_within_at (λ y, sqrt (f y)) (f' / (2 * sqrt (f x))) s x :=
begin
simp only [sqrt_eq_rpow],
convert hf.rpow (1/2) hx,
rcases lt_trichotomy (f x) 0 with H|H|H,
{ have A : (f x)^((1:ℝ)/2) = 0,
{ rw rpow_def_of_neg H,
have : cos (1/2 * π) = 0, by { convert cos_pi_div_two using 2, ring },
rw [this],
simp },
have B : f x ^ ((1:ℝ) / 2 - 1) = 0,
{ rw rpow_def_of_neg H,
have : cos (π/2 - π) = 0, by simp [cos_sub],
have : cos (((1:ℝ)/2 - 1) * π) = 0, by { convert this using 2, ring },
rw this,
simp },
rw [A, B],
simp },
{ exact (hx H).elim },
{ have A : 0 < (f x)^((1:ℝ)/2) := rpow_pos_of_pos H _,
have B : (f x) ^ (-(1:ℝ)) = (f x)^(-((1:ℝ)/2)) * (f x)^(-((1:ℝ)/2)),
{ rw [← rpow_add H],
congr,
norm_num },
rw [sub_eq_add_neg, rpow_add H, B, rpow_neg (le_of_lt H)],
field_simp [hx, ne_of_gt A],
ring }
end
lemma has_deriv_at.sqrt (hf : has_deriv_at f f' x) (hx : f x ≠ 0) :
has_deriv_at (λ y, sqrt (f y)) (f' / (2 * sqrt(f x))) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hf.sqrt hx
end
lemma differentiable_within_at.sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) :
differentiable_within_at ℝ (λx, sqrt (f x)) s x :=
(hf.has_deriv_within_at.sqrt hx).differentiable_within_at
@[simp] lemma differentiable_at.sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
differentiable_at ℝ (λx, sqrt (f x)) x :=
(hf.has_deriv_at.sqrt hx).differentiable_at
lemma differentiable_on.sqrt (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) :
differentiable_on ℝ (λx, sqrt (f x)) s :=
λx h, (hf x h).sqrt (hx x h)
@[simp] lemma differentiable.sqrt (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) :
differentiable ℝ (λx, sqrt (f x)) :=
λx, (hf x).sqrt (hx x)
lemma deriv_within_sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, sqrt (f x)) s x = (deriv_within f s x) / (2 * sqrt (f x)) :=
(hf.has_deriv_within_at.sqrt hx).deriv_within hxs
@[simp] lemma deriv_sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
deriv (λx, sqrt (f x)) x = (deriv f x) / (2 * sqrt (f x)) :=
(hf.has_deriv_at.sqrt hx).deriv
end differentiability
section limits
open real filter
/-- The function `x ^ y` tends to `+∞` at `+∞` for any positive real `y`. -/
lemma tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ y) at_top at_top :=
begin
rw tendsto_at_top_at_top,
intro b,
use (max b 0) ^ (1/y),
intros x hx,
exact le_of_max_le_left
(by { convert rpow_le_rpow (rpow_nonneg_of_nonneg (le_max_right b 0) (1/y)) hx (le_of_lt hy),
rw [← rpow_mul (le_max_right b 0), (eq_div_iff (ne_of_gt hy)).mp rfl, rpow_one] }),
end
/-- The function `x ^ (-y)` tends to `0` at `+∞` for any positive real `y`. -/
lemma tendsto_rpow_neg_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ (-y)) at_top (𝓝 0) :=
tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top 0) (λ x hx, (rpow_neg (le_of_lt hx) y).symm))
(tendsto.inv_tendsto_at_top (tendsto_rpow_at_top hy))
/-- The function `x ^ (a / (b * x + c))` tends to `1` at `+∞`, for any real numbers `a`, `b`, and
`c` such that `b` is nonzero. -/
lemma tendsto_rpow_div_mul_add (a b c : ℝ) (hb : 0 ≠ b) :
tendsto (λ x, x ^ (a / (b*x+c))) at_top (𝓝 1) :=
begin
refine tendsto.congr' _ ((tendsto_exp_nhds_0_nhds_1.comp
(by simpa only [mul_zero, pow_one] using ((@tendsto_const_nhds _ _ _ a _).mul
(tendsto_div_pow_mul_exp_add_at_top b c 1 hb (by norm_num))))).comp (tendsto_log_at_top)),
apply eventually_eq_of_mem (Ioi_mem_at_top (0:ℝ)),
intros x hx,
simp only [set.mem_Ioi, function.comp_app] at hx ⊢,
rw [exp_log hx, ← exp_log (rpow_pos_of_pos hx (a / (b * x + c))), log_rpow hx (a / (b * x + c))],
field_simp,
end
/-- The function `x ^ (1 / x)` tends to `1` at `+∞`. -/
lemma tendsto_rpow_div : tendsto (λ x, x ^ ((1:ℝ) / x)) at_top (𝓝 1) :=
by { convert tendsto_rpow_div_mul_add (1:ℝ) _ (0:ℝ) zero_ne_one, ring }
/-- The function `x ^ (-1 / x)` tends to `1` at `+∞`. -/
lemma tendsto_rpow_neg_div : tendsto (λ x, x ^ (-(1:ℝ) / x)) at_top (𝓝 1) :=
by { convert tendsto_rpow_div_mul_add (-(1:ℝ)) _ (0:ℝ) zero_ne_one, ring }
end limits
namespace nnreal
/-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` and `y : ℝ ` as the
restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`,
one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/
noncomputable def rpow (x : ℝ≥0) (y : ℝ) : ℝ≥0 :=
⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩
noncomputable instance : has_pow ℝ≥0 ℝ := ⟨rpow⟩
@[simp] lemma rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y := rfl
@[simp, norm_cast] lemma coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y := rfl
@[simp] lemma rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 :=
nnreal.eq $ real.rpow_zero _
@[simp] lemma rpow_eq_zero_iff {x : ℝ≥0} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 :=
begin
rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero],
exact real.rpow_eq_zero_iff_of_nonneg x.2
end
@[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ≥0) ^ x = 0 :=
nnreal.eq $ real.zero_rpow h
@[simp] lemma rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x :=
nnreal.eq $ real.rpow_one _
@[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 :=
nnreal.eq $ real.one_rpow _
lemma rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z :=
nnreal.eq $ real.rpow_add (zero_lt_iff_ne_zero.2 hx) _ _
lemma rpow_add' (x : ℝ≥0) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z :=
nnreal.eq $ real.rpow_add' x.2 h
lemma rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z :=
nnreal.eq $ real.rpow_mul x.2 y z
lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ :=
nnreal.eq $ real.rpow_neg x.2 _
lemma rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x ⁻¹ :=
by simp [rpow_neg]
lemma rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z :=
nnreal.eq $ real.rpow_sub (zero_lt_iff_ne_zero.2 hx) y z
lemma rpow_sub' (x : ℝ≥0) {y z : ℝ} (h : y - z ≠ 0) :
x ^ (y - z) = x ^ y / x ^ z :=
nnreal.eq $ real.rpow_sub' x.2 h
lemma inv_rpow (x : ℝ≥0) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ :=
nnreal.eq $ real.inv_rpow x.2 y
lemma div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z :=
nnreal.eq $ real.div_rpow x.2 y.2 z
@[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n :=
nnreal.eq $ by simpa only [coe_rpow, coe_pow] using real.rpow_nat_cast x n
lemma mul_rpow {x y : ℝ≥0} {z : ℝ} : (x*y)^z = x^z * y^z :=
nnreal.eq $ real.mul_rpow x.2 y.2
lemma rpow_le_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z :=
real.rpow_le_rpow x.2 h₁ h₂
lemma rpow_lt_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z :=
real.rpow_lt_rpow x.2 h₁ h₂
lemma rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y :=
real.rpow_lt_rpow_iff x.2 y.2 hz
lemma rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y :=
real.rpow_le_rpow_iff x.2 y.2 hz
lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z :=
real.rpow_lt_rpow_of_exponent_lt hx hyz
lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z :=
real.rpow_le_rpow_of_exponent_le hx hyz
lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) :
x^y < x^z :=
real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz
lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) :
x^y ≤ x^z :=
real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz
lemma rpow_lt_one {x : ℝ≥0} {z : ℝ} (hx : 0 ≤ x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 :=
real.rpow_lt_one hx hx1 hz
lemma rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 :=
real.rpow_le_one x.2 hx2 hz
lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 :=
real.rpow_lt_one_of_one_lt_of_neg hx hz
lemma rpow_le_one_of_one_le_of_nonpos {x : ℝ≥0} {z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 :=
real.rpow_le_one_of_one_le_of_nonpos hx hz
lemma one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z :=
real.one_lt_rpow hx hz
lemma one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z :=
real.one_le_rpow h h₁
lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1)
(hz : z < 0) : 1 < x^z :=
real.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz
lemma one_le_rpow_of_pos_of_le_one_of_nonpos {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1)
(hz : z ≤ 0) : 1 ≤ x^z :=
real.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 hz
lemma pow_nat_rpow_nat_inv (x : ℝ≥0) {n : ℕ} (hn : 0 < n) :
(x ^ n) ^ (n⁻¹ : ℝ) = x :=
by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn }
lemma rpow_nat_inv_pow_nat (x : ℝ≥0) {n : ℕ} (hn : 0 < n) :
(x ^ (n⁻¹ : ℝ)) ^ n = x :=
by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn }
lemma continuous_at_rpow {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) :
continuous_at (λp:ℝ≥0×ℝ, p.1^p.2) (x, y) :=
begin
have : (λp:ℝ≥0×ℝ, p.1^p.2) = nnreal.of_real ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:ℝ≥0 × ℝ, (p.1.1, p.2)),
{ ext p,
rw [coe_rpow, nnreal.coe_of_real _ (real.rpow_nonneg_of_nonneg p.1.2 _)],
refl },
rw this,
refine nnreal.continuous_of_real.continuous_at.comp (continuous_at.comp _ _),
{ apply real.continuous_at_rpow,
simp at h,
rw ← (nnreal.coe_eq_zero x) at h,
exact h },
{ exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at }
end
lemma of_real_rpow_of_nonneg {x y : ℝ} (hx : 0 ≤ x) :
nnreal.of_real (x ^ y) = (nnreal.of_real x) ^ y :=
begin
nth_rewrite 0 ← nnreal.coe_of_real x hx,
rw [←nnreal.coe_rpow, nnreal.of_real_coe],
end
end nnreal
section measurability_nnreal
lemma nnreal.measurable_rpow : measurable (λ p : ℝ≥0 × ℝ, p.1 ^ p.2) :=
begin
have h_rw : (λ p : ℝ≥0 × ℝ, p.1 ^ p.2) = (λ p : ℝ≥0 × ℝ, nnreal.of_real(↑(p.1) ^ p.2)),
{ ext1 a,
rw [←nnreal.coe_rpow, nnreal.of_real_coe], },
rw h_rw,
exact (measurable_fst.nnreal_coe.rpow measurable_snd).nnreal_of_real,
end
lemma measurable.nnreal_rpow {α} [measurable_space α] {f : α → ℝ≥0} (hf : measurable f)
{g : α → ℝ} (hg : measurable g) :
measurable (λ a : α, (f a) ^ (g a)) :=
begin
change measurable ((λ p : ℝ≥0 × ℝ, p.1 ^ p.2) ∘ (λ a : α, (f a, g a))),
exact nnreal.measurable_rpow.comp (measurable.prod hf hg),
end
lemma nnreal.measurable_rpow_const {y : ℝ} : measurable (λ a : ℝ≥0, a ^ y) :=
begin
have h_rw : (λ a : ℝ≥0, a ^ y) = (λ a : ℝ≥0, nnreal.of_real(↑a ^ y)),
{ ext1 a,
rw [←nnreal.coe_rpow, nnreal.of_real_coe], },
rw h_rw,
exact nnreal.measurable_coe.rpow_const.nnreal_of_real,
end
lemma measurable.nnreal_rpow_const {α} [measurable_space α] {f : α → ℝ≥0} (hf : measurable f)
{y : ℝ} :
measurable (λ a : α, (f a) ^ y) :=
hf.nnreal_rpow measurable_const
end measurability_nnreal
open filter
lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → ℝ≥0} {v : α → ℝ} {x : ℝ≥0} {y : ℝ}
(hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) :
tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) :=
tendsto.comp (nnreal.continuous_at_rpow h) (hx.prod_mk_nhds hy)
namespace nnreal
lemma continuous_at_rpow_const {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 ≤ y) :
continuous_at (λ z, z^y) x :=
h.elim (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inl h)) $
λ h, h.eq_or_lt.elim
(λ h, h ▸ by simp only [rpow_zero, continuous_at_const])
(λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inr h))
lemma continuous_rpow_const {y : ℝ} (h : 0 ≤ y) :
continuous (λ x : ℝ≥0, x^y) :=
continuous_iff_continuous_at.2 $ λ x, continuous_at_rpow_const (or.inr h)
end nnreal
namespace ennreal
/-- The real power function `x^y` on extended nonnegative reals, defined for `x : ennreal` and
`y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values
for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and
`⊤ ^ x = 1 / 0 ^ x`). -/
noncomputable def rpow : ennreal → ℝ → ennreal
| (some x) y := if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0)
| none y := if 0 < y then ⊤ else if y = 0 then 1 else 0
noncomputable instance : has_pow ennreal ℝ := ⟨rpow⟩
@[simp] lemma rpow_eq_pow (x : ennreal) (y : ℝ) : rpow x y = x ^ y := rfl
@[simp] lemma rpow_zero {x : ennreal} : x ^ (0 : ℝ) = 1 :=
by cases x; { dsimp only [(^), rpow], simp [lt_irrefl] }
lemma top_rpow_def (y : ℝ) : (⊤ : ennreal) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 :=
rfl
@[simp] lemma top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ennreal) ^ y = ⊤ :=
by simp [top_rpow_def, h]
@[simp] lemma top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ennreal) ^ y = 0 :=
by simp [top_rpow_def, asymm h, ne_of_lt h]
@[simp] lemma zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ennreal) ^ y = 0 :=
begin
rw [← ennreal.coe_zero, ← ennreal.some_eq_coe],
dsimp only [(^), rpow],
simp [h, asymm h, ne_of_gt h],
end
@[simp] lemma zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ennreal) ^ y = ⊤ :=
begin
rw [← ennreal.coe_zero, ← ennreal.some_eq_coe],
dsimp only [(^), rpow],
simp [h, ne_of_gt h],
end
lemma zero_rpow_def (y : ℝ) : (0 : ennreal) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ :=
begin
rcases lt_trichotomy 0 y with H|rfl|H,
{ simp [H, ne_of_gt, zero_rpow_of_pos, lt_irrefl] },
{ simp [lt_irrefl] },
{ simp [H, asymm H, ne_of_lt, zero_rpow_of_neg] }
end
@[norm_cast] lemma coe_rpow_of_ne_zero {x : ℝ≥0} (h : x ≠ 0) (y : ℝ) :
(x : ennreal) ^ y = (x ^ y : ℝ≥0) :=
begin
rw [← ennreal.some_eq_coe],
dsimp only [(^), rpow],
simp [h]
end
@[norm_cast] lemma coe_rpow_of_nonneg (x : ℝ≥0) {y : ℝ} (h : 0 ≤ y) :
(x : ennreal) ^ y = (x ^ y : ℝ≥0) :=
begin
by_cases hx : x = 0,
{ rcases le_iff_eq_or_lt.1 h with H|H,
{ simp [hx, H.symm] },
{ simp [hx, zero_rpow_of_pos H, nnreal.zero_rpow (ne_of_gt H)] } },
{ exact coe_rpow_of_ne_zero hx _ }
end
lemma coe_rpow_def (x : ℝ≥0) (y : ℝ) :
(x : ennreal) ^ y = if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) := rfl
@[simp] lemma rpow_one (x : ennreal) : x ^ (1 : ℝ) = x :=
by cases x; dsimp only [(^), rpow]; simp [zero_lt_one, not_lt_of_le zero_le_one]
@[simp] lemma one_rpow (x : ℝ) : (1 : ennreal) ^ x = 1 :=
by { rw [← coe_one, coe_rpow_of_ne_zero one_ne_zero], simp }
@[simp] lemma rpow_eq_zero_iff {x : ennreal} {y : ℝ} :
x ^ y = 0 ↔ (x = 0 ∧ 0 < y) ∨ (x = ⊤ ∧ y < 0) :=
begin
cases x,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] },
{ by_cases h : x = 0,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] },
{ simp [coe_rpow_of_ne_zero h, h] } }
end
@[simp] lemma rpow_eq_top_iff {x : ennreal} {y : ℝ} :
x ^ y = ⊤ ↔ (x = 0 ∧ y < 0) ∨ (x = ⊤ ∧ 0 < y) :=
begin
cases x,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] },
{ by_cases h : x = 0,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] },
{ simp [coe_rpow_of_ne_zero h, h] } }
end
lemma rpow_eq_top_of_nonneg (x : ennreal) {y : ℝ} (hy0 : 0 ≤ y) : x ^ y = ⊤ → x = ⊤ :=
begin
rw ennreal.rpow_eq_top_iff,
intro h,
cases h,
{ exfalso, rw lt_iff_not_ge at h, exact h.right hy0, },
{ exact h.left, },
end
lemma rpow_ne_top_of_nonneg {x : ennreal} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y ≠ ⊤ :=
mt (ennreal.rpow_eq_top_of_nonneg x hy0) h
lemma rpow_lt_top_of_nonneg {x : ennreal} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y < ⊤ :=
ennreal.lt_top_iff_ne_top.mpr (ennreal.rpow_ne_top_of_nonneg hy0 h)
lemma rpow_add {x : ennreal} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y + z) = x ^ y * x ^ z :=
begin
cases x, { exact (h'x rfl).elim },
have : x ≠ 0 := λ h, by simpa [h] using hx,
simp [coe_rpow_of_ne_zero this, nnreal.rpow_add this]
end
lemma rpow_neg (x : ennreal) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ :=
begin
cases x,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [top_rpow_of_pos, top_rpow_of_neg, H, neg_pos.mpr] },
{ by_cases h : x = 0,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [h, zero_rpow_of_pos, zero_rpow_of_neg, H, neg_pos.mpr] },
{ have A : x ^ y ≠ 0, by simp [h],
simp [coe_rpow_of_ne_zero h, ← coe_inv A, nnreal.rpow_neg] } }
end
lemma rpow_neg_one (x : ennreal) : x ^ (-1 : ℝ) = x ⁻¹ :=
by simp [rpow_neg]
lemma rpow_mul (x : ennreal) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z :=
begin
cases x,
{ rcases lt_trichotomy y 0 with Hy|Hy|Hy;
rcases lt_trichotomy z 0 with Hz|Hz|Hz;
simp [Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos,
mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] },
{ by_cases h : x = 0,
{ rcases lt_trichotomy y 0 with Hy|Hy|Hy;
rcases lt_trichotomy z 0 with Hz|Hz|Hz;
simp [h, Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos,
mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] },
{ have : x ^ y ≠ 0, by simp [h],
simp [coe_rpow_of_ne_zero h, coe_rpow_of_ne_zero this, nnreal.rpow_mul] } }
end
@[simp, norm_cast] lemma rpow_nat_cast (x : ennreal) (n : ℕ) : x ^ (n : ℝ) = x ^ n :=
begin
cases x,
{ cases n;
simp [top_rpow_of_pos (nat.cast_add_one_pos _), top_pow (nat.succ_pos _)] },
{ simp [coe_rpow_of_nonneg _ (nat.cast_nonneg n)] }
end
@[norm_cast] lemma coe_mul_rpow (x y : ℝ≥0) (z : ℝ) :
((x : ennreal) * y) ^ z = x^z * y^z :=
begin
rcases lt_trichotomy z 0 with H|H|H,
{ by_cases hx : x = 0; by_cases hy : y = 0,
{ simp [hx, hy, zero_rpow_of_neg, H] },
{ have : (y : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy],
simp [hx, hy, zero_rpow_of_neg, H, with_top.top_mul this] },
{ have : (x : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx],
simp [hx, hy, zero_rpow_of_neg H, with_top.mul_top this] },
{ rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul,
coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy],
simp [hx, hy] } },
{ simp [H] },
{ by_cases hx : x = 0; by_cases hy : y = 0,
{ simp [hx, hy, zero_rpow_of_pos, H] },
{ have : (y : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy],
simp [hx, hy, zero_rpow_of_pos H, with_top.top_mul this] },
{ have : (x : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx],
simp [hx, hy, zero_rpow_of_pos H, with_top.mul_top this] },
{ rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul,
coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy],
simp [hx, hy] } },
end
lemma mul_rpow_of_ne_top {x y : ennreal} (hx : x ≠ ⊤) (hy : y ≠ ⊤) (z : ℝ) :
(x * y) ^ z = x^z * y^z :=
begin
lift x to ℝ≥0 using hx,
lift y to ℝ≥0 using hy,
exact coe_mul_rpow x y z
end
lemma mul_rpow_of_ne_zero {x y : ennreal} (hx : x ≠ 0) (hy : y ≠ 0) (z : ℝ) :
(x * y) ^ z = x ^ z * y ^ z :=
begin
rcases lt_trichotomy z 0 with H|H|H,
{ cases x; cases y,
{ simp [hx, hy, top_rpow_of_neg, H] },
{ have : y ≠ 0, by simpa using hy,
simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] },
{ have : x ≠ 0, by simpa using hx,
simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] },
{ have hx' : x ≠ 0, by simpa using hx,
have hy' : y ≠ 0, by simpa using hy,
simp only [some_eq_coe],
rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul,
coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'],
simp [hx', hy'] } },
{ simp [H] },
{ cases x; cases y,
{ simp [hx, hy, top_rpow_of_pos, H] },
{ have : y ≠ 0, by simpa using hy,
simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] },
{ have : x ≠ 0, by simpa using hx,
simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] },
{ have hx' : x ≠ 0, by simpa using hx,
have hy' : y ≠ 0, by simpa using hy,
simp only [some_eq_coe],
rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul,
coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'],
simp [hx', hy'] } }
end
lemma mul_rpow_of_nonneg (x y : ennreal) {z : ℝ} (hz : 0 ≤ z) :
(x * y) ^ z = x ^ z * y ^ z :=
begin
rcases le_iff_eq_or_lt.1 hz with H|H, { simp [← H] },
by_cases h : x = 0 ∨ y = 0,
{ cases h; simp [h, zero_rpow_of_pos H] },
push_neg at h,
exact mul_rpow_of_ne_zero h.1 h.2 z
end
lemma inv_rpow_of_pos {x : ennreal} {y : ℝ} (hy : 0 < y) : (x⁻¹) ^ y = (x ^ y)⁻¹ :=
begin
by_cases h0 : x = 0,
{ rw [h0, zero_rpow_of_pos hy, inv_zero, top_rpow_of_pos hy], },
by_cases h_top : x = ⊤,
{ rw [h_top, top_rpow_of_pos hy, inv_top, zero_rpow_of_pos hy], },
rw ←coe_to_nnreal h_top,
have h : x.to_nnreal ≠ 0,
{ rw [ne.def, to_nnreal_eq_zero_iff],
simp [h0, h_top], },
rw [←coe_inv h, coe_rpow_of_nonneg _ (le_of_lt hy), coe_rpow_of_nonneg _ (le_of_lt hy), ←coe_inv],
{ rw coe_eq_coe,
exact nnreal.inv_rpow x.to_nnreal y, },
{ simp [h], },
end
lemma rpow_le_rpow {x y : ennreal} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z :=
begin
rcases le_iff_eq_or_lt.1 h₂ with H|H, { simp [← H, le_refl] },
cases y, { simp [top_rpow_of_pos H] },
cases x, { exact (not_top_le_coe h₁).elim },
simp at h₁,
simp [coe_rpow_of_nonneg _ h₂, nnreal.rpow_le_rpow h₁ h₂]
end
lemma rpow_lt_rpow {x y : ennreal} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z :=
begin
cases x, { exact (not_top_lt h₁).elim },
cases y, { simp [top_rpow_of_pos h₂, coe_rpow_of_nonneg _ (le_of_lt h₂)] },
simp at h₁,
simp [coe_rpow_of_nonneg _ (le_of_lt h₂), nnreal.rpow_lt_rpow h₁ h₂]
end
lemma rpow_lt_rpow_of_exponent_lt {x : ennreal} {y z : ℝ} (hx : 1 < x) (hx' : x ≠ ⊤) (hyz : y < z) :
x^y < x^z :=
begin
lift x to ℝ≥0 using hx',
rw [one_lt_coe_iff] at hx,
simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)),
nnreal.rpow_lt_rpow_of_exponent_lt hx hyz]
end
lemma rpow_le_rpow_of_exponent_le {x : ennreal} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z :=
begin
cases x,
{ rcases lt_trichotomy y 0 with Hy|Hy|Hy;
rcases lt_trichotomy z 0 with Hz|Hz|Hz;
simp [Hy, Hz, top_rpow_of_neg, top_rpow_of_pos, le_refl];
linarith },
{ simp only [one_le_coe_iff, some_eq_coe] at hx,
simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)),
nnreal.rpow_le_rpow_of_exponent_le hx hyz] }
end
lemma rpow_lt_rpow_of_exponent_gt {x : ennreal} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) :
x^y < x^z :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top),
simp at hx0 hx1,
simp [coe_rpow_of_ne_zero (ne_of_gt hx0), nnreal.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz]
end
lemma rpow_le_rpow_of_exponent_ge {x : ennreal} {y z : ℝ} (hx1 : x ≤ 1) (hyz : z ≤ y) :
x^y ≤ x^z :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx1 coe_lt_top),
by_cases h : x = 0,
{ rcases lt_trichotomy y 0 with Hy|Hy|Hy;
rcases lt_trichotomy z 0 with Hz|Hz|Hz;
simp [Hy, Hz, h, zero_rpow_of_neg, zero_rpow_of_pos, le_refl];
linarith },
{ simp at hx1,
simp [coe_rpow_of_ne_zero h,
nnreal.rpow_le_rpow_of_exponent_ge (bot_lt_iff_ne_bot.mpr h) hx1 hyz] }
end
lemma rpow_lt_one {x : ennreal} {z : ℝ} (hx : x < 1) (hz : 0 < z) : x^z < 1 :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx le_top),
simp only [coe_lt_one_iff] at hx,
simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.rpow_lt_one (zero_le x) hx hz],
end
lemma rpow_le_one {x : ennreal} {z : ℝ} (hx : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx coe_lt_top),
simp only [coe_le_one_iff] at hx,
simp [coe_rpow_of_nonneg _ hz, nnreal.rpow_le_one hx hz],
end
lemma rpow_lt_one_of_one_lt_of_neg {x : ennreal} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 :=
begin
cases x,
{ simp [top_rpow_of_neg hz, ennreal.zero_lt_one] },
{ simp only [some_eq_coe, one_lt_coe_iff] at hx,
simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)),
nnreal.rpow_lt_one_of_one_lt_of_neg hx hz] },
end
lemma rpow_le_one_of_one_le_of_neg {x : ennreal} {z : ℝ} (hx : 1 ≤ x) (hz : z < 0) : x^z ≤ 1 :=
begin
cases x,
{ simp [top_rpow_of_neg hz, ennreal.zero_lt_one] },
{ simp only [one_le_coe_iff, some_eq_coe] at hx,
simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)),
nnreal.rpow_le_one_of_one_le_of_nonpos hx (le_of_lt hz)] },
end
lemma one_lt_rpow {x : ennreal} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z :=
begin
cases x,
{ simp [top_rpow_of_pos hz] },
{ simp only [some_eq_coe, one_lt_coe_iff] at hx,
simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_lt_rpow hx hz] }
end
lemma one_le_rpow {x : ennreal} {z : ℝ} (hx : 1 ≤ x) (hz : 0 < z) : 1 ≤ x^z :=
begin
cases x,
{ simp [top_rpow_of_pos hz] },
{ simp only [one_le_coe_iff, some_eq_coe] at hx,
simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_le_rpow hx (le_of_lt hz)] },
end
lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ennreal} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1)
(hz : z < 0) : 1 < x^z :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx2 le_top),
simp only [coe_lt_one_iff, coe_pos] at ⊢ hx1 hx2,
simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz],
end
lemma one_le_rpow_of_pos_of_le_one_of_neg {x : ennreal} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1)
(hz : z < 0) : 1 ≤ x^z :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx2 coe_lt_top),
simp only [coe_le_one_iff, coe_pos] at ⊢ hx1 hx2,
simp [coe_rpow_of_ne_zero (ne_of_gt hx1),
nnreal.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 (le_of_lt hz)],
end
lemma to_nnreal_rpow (x : ennreal) (z : ℝ) : (x.to_nnreal) ^ z = (x ^ z).to_nnreal :=
begin
rcases lt_trichotomy z 0 with H|H|H,
{ cases x, { simp [H, ne_of_lt] },
by_cases hx : x = 0,
{ simp [hx, H, ne_of_lt] },
{ simp [coe_rpow_of_ne_zero hx] } },
{ simp [H] },
{ cases x, { simp [H, ne_of_gt] },
simp [coe_rpow_of_nonneg _ (le_of_lt H)] }
end
lemma to_real_rpow (x : ennreal) (z : ℝ) : (x.to_real) ^ z = (x ^ z).to_real :=
by rw [ennreal.to_real, ennreal.to_real, ←nnreal.coe_rpow, ennreal.to_nnreal_rpow]
end ennreal
section measurability_ennreal
lemma ennreal.measurable_rpow : measurable (λ p : ennreal × ℝ, p.1 ^ p.2) :=
begin
refine ennreal.measurable_of_measurable_nnreal_prod _ _,
{ simp_rw ennreal.coe_rpow_def,
refine measurable.ite _ measurable_const nnreal.measurable_rpow.ennreal_coe,
exact is_measurable.inter (measurable_fst (is_measurable_singleton 0))
(measurable_snd is_measurable_Iio), },
{ simp_rw ennreal.top_rpow_def,
refine measurable.ite is_measurable_Ioi measurable_const _,
exact measurable.ite (is_measurable_singleton 0) measurable_const measurable_const, },
end
lemma measurable.ennreal_rpow {α} [measurable_space α] {f : α → ennreal} (hf : measurable f)
{g : α → ℝ} (hg : measurable g) :
measurable (λ a : α, (f a) ^ (g a)) :=
begin
change measurable ((λ p : ennreal × ℝ, p.1 ^ p.2) ∘ (λ a, (f a, g a))),
exact ennreal.measurable_rpow.comp (measurable.prod hf hg),
end
lemma ennreal.measurable_rpow_const {y : ℝ} : measurable (λ a : ennreal, a ^ y) :=
begin
change measurable ((λ p : ennreal × ℝ, p.1 ^ p.2) ∘ (λ a, (a, y))),
refine ennreal.measurable_rpow.comp (measurable.prod measurable_id _),
dsimp only,
exact measurable_const,
end
lemma measurable.ennreal_rpow_const {α} [measurable_space α] {f : α → ennreal} (hf : measurable f)
{y : ℝ} :
measurable (λ a : α, (f a) ^ y) :=
hf.ennreal_rpow measurable_const
lemma ae_measurable.ennreal_rpow_const {α} [measurable_space α] {f : α → ennreal}
{μ : measure_theory.measure α} (hf : ae_measurable f μ) {y : ℝ} :
ae_measurable (λ a : α, (f a) ^ y) μ :=
ennreal.measurable_rpow_const.comp_ae_measurable hf
end measurability_ennreal
|
8801ac1a295c9346ed112b16f22db85af4d2cbb9 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/measure_theory/group/prod.lean | d14568da744e7f7de1ca719fea72dcdc416c35eb | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 11,242 | lean | /-
Copyright (c) 2021 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import measure_theory.constructions.prod
/-!
# Measure theory in the product of groups
In this file we show properties about measure theory in products of topological groups
and properties of iterated integrals in topological groups.
These lemmas show the uniqueness of left invariant measures on locally compact groups, up to
scaling. In this file we follow the proof and refer to the book *Measure Theory* by Paul Halmos.
The idea of the proof is to use the translation invariance of measures to prove `μ(F) = c * μ(E)`
for two sets `E` and `F`, where `c` is a constant that does not depend on `μ`. Let `e` and `f` be
the characteristic functions of `E` and `F`.
Assume that `μ` and `ν` are left-invariant measures. Then the map `(x, y) ↦ (y * x, x⁻¹)`
preserves the measure `μ.prod ν`, which means that
```
∫ x, ∫ y, h x y ∂ν ∂μ = ∫ x, ∫ y, h (y * x) x⁻¹ ∂ν ∂μ
```
If we apply this to `h x y := e x * f y⁻¹ / ν ((λ h, h * y⁻¹) ⁻¹' E)`, we can rewrite the RHS to
`μ(F)`, and the LHS to `c * μ(E)`, where `c = c(ν)` does not depend on `μ`.
Applying this to `μ` and to `ν` gives `μ (F) / μ (E) = ν (F) / ν (E)`, which is the uniqueness up to
scalar multiplication.
The proof in [Halmos] seems to contain an omission in §60 Th. A, see
`measure_theory.measure_lintegral_div_measure` and
https://math.stackexchange.com/questions/3974485/does-right-translation-preserve-finiteness-for-a-left-invariant-measure
## Todo
Much of the results in this file work in a group with measurable multiplication instead of a
topological group
-/
noncomputable theory
open topological_space set (hiding prod_eq) function
open_locale classical ennreal pointwise
namespace measure_theory
open measure
variables {G : Type*} [topological_space G] [measurable_space G] [second_countable_topology G]
variables [borel_space G] [group G] [topological_group G]
variables (μ ν : measure G) [sigma_finite ν] [sigma_finite μ]
/-- This condition is part of the definition of a measurable group in [Halmos, §59].
There, the map in this lemma is called `S`. -/
@[to_additive map_prod_sum_eq]
lemma map_prod_mul_eq [is_mul_left_invariant ν] :
map (λ z : G × G, (z.1, z.1 * z.2)) (μ.prod ν) = μ.prod ν :=
begin
refine (prod_eq _).symm, intros s t hs ht,
simp_rw [map_apply (measurable_fst.prod_mk (measurable_fst.mul measurable_snd)) (hs.prod ht),
prod_apply ((measurable_fst.prod_mk (measurable_fst.mul measurable_snd)) (hs.prod ht)),
preimage_preimage],
conv_lhs { congr, skip, funext, rw [mk_preimage_prod_right_fn_eq_if ((*) x), measure_if] },
simp_rw [measure_preimage_mul, lintegral_indicator _ hs, set_lintegral_const, mul_comm]
end
/-- The function we are mapping along is `SR` in [Halmos, §59],
where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/
@[to_additive map_prod_add_eq_swap]
lemma map_prod_mul_eq_swap [is_mul_left_invariant μ] :
map (λ z : G × G, (z.2, z.2 * z.1)) (μ.prod ν) = ν.prod μ :=
begin
rw [← prod_swap],
simp_rw [map_map (measurable_snd.prod_mk (measurable_snd.mul measurable_fst)) measurable_swap],
exact map_prod_mul_eq ν μ
end
/-- The function we are mapping along is `S⁻¹` in [Halmos, §59],
where `S` is the map in `map_prod_mul_eq`. -/
@[to_additive map_prod_neg_add_eq]
lemma map_prod_inv_mul_eq [is_mul_left_invariant ν] :
map (λ z : G × G, (z.1, z.1⁻¹ * z.2)) (μ.prod ν) = μ.prod ν :=
(homeomorph.shear_mul_right G).to_measurable_equiv.map_apply_eq_iff_map_symm_apply_eq.mp $
map_prod_mul_eq μ ν
/-- The function we are mapping along is `S⁻¹R` in [Halmos, §59],
where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/
@[to_additive map_prod_neg_add_eq_swap]
lemma map_prod_inv_mul_eq_swap [is_mul_left_invariant μ] :
map (λ z : G × G, (z.2, z.2⁻¹ * z.1)) (μ.prod ν) = ν.prod μ :=
begin
rw [← prod_swap],
simp_rw
[map_map (measurable_snd.prod_mk $ measurable_snd.inv.mul measurable_fst) measurable_swap],
exact map_prod_inv_mul_eq ν μ
end
/-- The function we are mapping along is `S⁻¹RSR` in [Halmos, §59],
where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/
@[to_additive map_prod_add_neg_eq]
lemma map_prod_mul_inv_eq [is_mul_left_invariant μ] [is_mul_left_invariant ν] :
map (λ z : G × G, (z.2 * z.1, z.1⁻¹)) (μ.prod ν) = μ.prod ν :=
begin
let S := (homeomorph.shear_mul_right G).to_measurable_equiv,
suffices : map ((λ z : G × G, (z.2, z.2⁻¹ * z.1)) ∘ (λ z : G × G, (z.2, z.2 * z.1))) (μ.prod ν) =
μ.prod ν,
{ convert this, ext1 ⟨x, y⟩, simp },
simp_rw [← map_map (measurable_snd.prod_mk (measurable_snd.inv.mul measurable_fst))
(measurable_snd.prod_mk (measurable_snd.mul measurable_fst)), map_prod_mul_eq_swap μ ν,
map_prod_inv_mul_eq_swap ν μ]
end
@[to_additive] lemma quasi_measure_preserving_inv [is_mul_left_invariant μ] :
quasi_measure_preserving (has_inv.inv : G → G) μ μ :=
begin
refine ⟨measurable_inv, absolutely_continuous.mk $ λ s hsm hμs, _⟩,
rw [map_apply measurable_inv hsm, inv_preimage],
have hf : measurable (λ z : G × G, (z.2 * z.1, z.1⁻¹)) :=
(measurable_snd.mul measurable_fst).prod_mk measurable_fst.inv,
suffices : map (λ z : G × G, (z.2 * z.1, z.1⁻¹)) (μ.prod μ) (s⁻¹ ×ˢ s⁻¹) = 0,
{ simpa only [map_prod_mul_inv_eq μ μ, prod_prod, mul_eq_zero, or_self] using this },
have hsm' : measurable_set (s⁻¹ ×ˢ s⁻¹) := hsm.inv.prod hsm.inv,
simp_rw [map_apply hf hsm', prod_apply_symm (hf hsm'), preimage_preimage, mk_preimage_prod,
inv_preimage, set.inv_inv, measure_mono_null (inter_subset_right _ _) hμs, lintegral_zero]
end
@[to_additive]
lemma measure_inv_null [is_mul_left_invariant μ] {E : set G} :
μ ((λ x, x⁻¹) ⁻¹' E) = 0 ↔ μ E = 0 :=
begin
refine ⟨λ hE, _, (quasi_measure_preserving_inv μ).preimage_null⟩,
convert (quasi_measure_preserving_inv μ).preimage_null hE,
exact set.inv_inv.symm
end
@[to_additive]
lemma measurable_measure_mul_right {E : set G} (hE : measurable_set E) :
measurable (λ x, μ ((λ y, y * x) ⁻¹' E)) :=
begin
suffices : measurable (λ y,
μ ((λ x, (x, y)) ⁻¹' ((λ z : G × G, ((1 : G), z.1 * z.2)) ⁻¹' ((univ : set G) ×ˢ E)))),
{ convert this, ext1 x, congr' 1 with y : 1, simp },
apply measurable_measure_prod_mk_right,
exact measurable_const.prod_mk (measurable_fst.mul measurable_snd) (measurable_set.univ.prod hE)
end
@[to_additive]
lemma lintegral_lintegral_mul_inv [is_mul_left_invariant μ] [is_mul_left_invariant ν]
(f : G → G → ℝ≥0∞) (hf : ae_measurable (uncurry f) (μ.prod ν)) :
∫⁻ x, ∫⁻ y, f (y * x) x⁻¹ ∂ν ∂μ = ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ :=
begin
have h : measurable (λ z : G × G, (z.2 * z.1, z.1⁻¹)) :=
(measurable_snd.mul measurable_fst).prod_mk measurable_fst.inv,
have h2f : ae_measurable (uncurry $ λ x y, f (y * x) x⁻¹) (μ.prod ν),
{ apply hf.comp_measurable' h (map_prod_mul_inv_eq μ ν).absolutely_continuous },
simp_rw [lintegral_lintegral h2f, lintegral_lintegral hf],
conv_rhs { rw [← map_prod_mul_inv_eq μ ν] },
symmetry,
exact lintegral_map' (hf.mono' (map_prod_mul_inv_eq μ ν).absolutely_continuous) h,
end
@[to_additive]
lemma measure_mul_right_null [is_mul_left_invariant μ] {E : set G} (y : G) :
μ ((λ x, x * y) ⁻¹' E) = 0 ↔ μ E = 0 :=
calc μ ((λ x, x * y) ⁻¹' E) = 0 ↔ μ (has_inv.inv ⁻¹' ((λ x, y⁻¹ * x) ⁻¹' (has_inv.inv ⁻¹' E))) = 0 :
by simp only [preimage_preimage, mul_inv_rev, inv_inv]
... ↔ μ E = 0 : by simp only [measure_inv_null μ, measure_preimage_mul]
@[to_additive]
lemma measure_mul_right_ne_zero [is_mul_left_invariant μ] {E : set G}
(h2E : μ E ≠ 0) (y : G) : μ ((λ x, x * y) ⁻¹' E) ≠ 0 :=
(not_iff_not_of_iff (measure_mul_right_null μ y)).mpr h2E
/-- A technical lemma relating two different measures. This is basically [Halmos, §60 Th. A].
Note that if `f` is the characteristic function of a measurable set `F` this states that
`μ F = c * μ E` for a constant `c` that does not depend on `μ`.
There seems to be a gap in the last step of the proof in [Halmos].
In the last line, the equality `g(x⁻¹)ν(Ex⁻¹) = f(x)` holds if we can prove that
`0 < ν(Ex⁻¹) < ∞`. The first inequality follows from §59, Th. D, but I couldn't find the second
inequality. For this reason, we use a compact `E` instead of a measurable `E` as in [Halmos], and
additionally assume that `ν` is a regular measure (we only need that it is finite on compact
sets). -/
@[to_additive]
lemma measure_lintegral_div_measure [t2_space G] [is_mul_left_invariant μ]
[is_mul_left_invariant ν] [regular ν] {E : set G} (hE : is_compact E) (h2E : ν E ≠ 0)
(f : G → ℝ≥0∞) (hf : measurable f) :
μ E * ∫⁻ y, f y⁻¹ / ν ((λ h, h * y⁻¹) ⁻¹' E) ∂ν = ∫⁻ x, f x ∂μ :=
begin
have Em := hE.measurable_set,
symmetry,
set g := λ y, f y⁻¹ / ν ((λ h, h * y⁻¹) ⁻¹' E),
have hg : measurable g := (hf.comp measurable_inv).div
((measurable_measure_mul_right ν Em).comp measurable_inv),
rw [← set_lintegral_one, ← lintegral_indicator _ Em,
← lintegral_lintegral_mul (measurable_const.indicator Em).ae_measurable hg.ae_measurable,
← lintegral_lintegral_mul_inv μ ν],
swap, { exact (((measurable_const.indicator Em).comp measurable_fst).mul
(hg.comp measurable_snd)).ae_measurable },
have mE : ∀ x : G, measurable (λ y, ((λ z, z * x) ⁻¹' E).indicator (λ z, (1 : ℝ≥0∞)) y) :=
λ x, measurable_const.indicator (measurable_mul_const _ Em),
have : ∀ x y, E.indicator (λ (z : G), (1 : ℝ≥0∞)) (y * x) =
((λ z, z * x) ⁻¹' E).indicator (λ (b : G), 1) y,
{ intros x y, symmetry, convert indicator_comp_right (λ y, y * x), ext1 z, refl },
have h3E : ∀ y, ν ((λ x, x * y) ⁻¹' E) ≠ ∞ :=
λ y, (is_compact.measure_lt_top $ (homeomorph.mul_right _).compact_preimage.mpr hE).ne,
simp_rw [this, lintegral_mul_const _ (mE _), lintegral_indicator _ (measurable_mul_const _ Em),
set_lintegral_one, g, inv_inv,
ennreal.mul_div_cancel' (measure_mul_right_ne_zero ν h2E _) (h3E _)]
end
/-- This is roughly the uniqueness (up to a scalar) of left invariant Borel measures on a second
countable locally compact group. The uniqueness of Haar measure is proven from this in
`measure_theory.measure.haar_measure_unique` -/
@[to_additive]
lemma measure_mul_measure_eq [t2_space G] [is_mul_left_invariant μ]
[is_mul_left_invariant ν] [regular ν] {E F : set G}
(hE : is_compact E) (hF : measurable_set F) (h2E : ν E ≠ 0) : μ E * ν F = ν E * μ F :=
begin
have h1 := measure_lintegral_div_measure ν ν hE h2E (F.indicator (λ x, 1))
(measurable_const.indicator hF),
have h2 := measure_lintegral_div_measure μ ν hE h2E (F.indicator (λ x, 1))
(measurable_const.indicator hF),
rw [lintegral_indicator _ hF, set_lintegral_one] at h1 h2,
rw [← h1, mul_left_comm, h2],
end
end measure_theory
|
8f449a11d42e7e66b1127b55981bbd7bbfdf52c9 | 6065973b1fa7bbacba932011c9e2f32bf7bdd6c1 | /src/data/equiv/basic.lean | e35503af7d6e6a8176ccd8999e3ae69c88759566 | [
"Apache-2.0"
] | permissive | khmacdonald/mathlib | 90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb | 3669cb35c578441812ad30fd967d21a94b6f387e | refs/heads/master | 1,675,863,801,090 | 1,609,761,876,000 | 1,609,761,876,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 84,994 | 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
/-!
# 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 injective_coe_fn : 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₂ :=
injective_coe_fn.eq_iff
@[ext] lemma ext {f g : equiv α β} (H : ∀ x, f x = g x) : f = g :=
injective_coe_fn (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.inv_fun (e : α ≃ β) : β → α := e.symm
initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)
/-- 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
/-- 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
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
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
/-- 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_apply_apply {δ} (ab : α ≃ β) (cd : γ ≃ δ) (e : α ≃ γ) (x) :
ab.equiv_congr cd e x = cd (e (ab.symm x)) := rfl
/-- If `α` is equivalent to `β`, then `perm α` is equivalent to `perm β`. -/
def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β :=
equiv_congr e e
@[simp] lemma perm_congr_apply {α β : Type*} (e : α ≃ β) (p : equiv.perm α) (x) :
e.perm_congr p x = e (p (e.symm x)) := rfl
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 {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s :=
by { rw [← set.image_comp], simp }
@[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
/-- If `α` is an empty type, then it is equivalent to the `empty` type. -/
def equiv_empty (h : α → false) : α ≃ empty :=
⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩
/-- `false` is equivalent to `empty`. -/
def false_equiv_empty : false ≃ empty :=
equiv_empty _root_.id
/-- If `α` is an empty type, then it is equivalent to the `pempty` type in any universe. -/
def {u' v'} equiv_pempty {α : Sort v'} (h : α → false) : α ≃ pempty.{u'} :=
⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩
/-- `false` is equivalent to `pempty`. -/
def false_equiv_pempty : false ≃ pempty :=
equiv_pempty _root_.id
/-- `empty` is equivalent to `pempty`. -/
def empty_equiv_pempty : empty ≃ pempty :=
equiv_pempty $ empty.rec _
/-- `pempty` types from any two universes are equivalent. -/
def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} :=
equiv_pempty pempty.elim
/-- If `α` is not `nonempty`, then it is equivalent to `empty`. -/
def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty :=
equiv_empty $ assume a, h ⟨a⟩
/-- If `α` is not `nonempty`, then it is equivalent to `pempty`. -/
def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty :=
equiv_pempty $ assume a, h ⟨a⟩
/-- 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 {rhs_md := semireducible, simp_rhs := tt}]
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 {rhs_md := semireducible, simp_rhs := tt}]
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 }⟩
/-- The sort of maps from `punit` is equivalent to the codomain. -/
def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α :=
⟨λ f, f punit.star, λ a u, a, λ f, by { ext ⟨⟩, refl }, λ u, rfl⟩
/-- The sort of maps from `true` is equivalent to the codomain. -/
def true_arrow_equiv (α : Sort*) : (true → α) ≃ α :=
⟨λ f, f trivial, λ a u, a, λ f, by { ext ⟨⟩, refl }, λ u, rfl⟩
/-- The sort of maps from `empty` is equivalent to `punit`. -/
def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} :=
⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩
/-- The sort of maps from `pempty` is equivalent to `punit`. -/
def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} :=
⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩
/-- The sort of maps from `false` is equivalent to `punit`. -/
def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} :=
calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _)
... ≃ punit : empty_arrow_equiv_punit _
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] }
section
/-- `punit` is a right identity for type product up to an equivalence. -/
@[simps apply] 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 apply {rhs_md := semireducible, simp_rhs := tt}]
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 (λ ⟨_, e⟩, e.rec _)
/-- `empty` type is a left absorbing element for type product up to an equivalence. -/
def empty_prod (α : Type*) : empty × α ≃ empty :=
equiv_empty (λ ⟨e, _⟩, e.rec _)
/-- `pempty` type is a right absorbing element for type product up to an equivalence. -/
def prod_pempty (α : Type*) : α × pempty ≃ pempty :=
equiv_pempty (λ ⟨_, e⟩, e.rec _)
/-- `pempty` type is a left absorbing element for type product up to an equivalence. -/
def pempty_prod (α : Type*) : pempty × α ≃ pempty :=
equiv_pempty (λ ⟨e, _⟩, e.rec _)
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. -/
def sum_empty (α : Type*) : α ⊕ empty ≃ α :=
⟨sum.elim id (empty.rec _),
inl,
λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl },
λ a, rfl⟩
@[simp] lemma sum_empty_apply_inl {α} (a) : sum_empty α (sum.inl a) = a := rfl
/-- The sum of `empty` with any `Sort*` is equivalent to the right summand. -/
def empty_sum (α : Sort*) : empty ⊕ α ≃ α :=
(sum_comm _ _).trans $ sum_empty _
@[simp] lemma empty_sum_apply_inr {α} (a) : empty_sum α (sum.inr a) = a := rfl
/-- Sum with `pempty` is equivalent to the original type. -/
def sum_pempty (α : Type*) : α ⊕ pempty ≃ α :=
⟨sum.elim id (pempty.rec _),
inl,
λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl },
λ a, rfl⟩
@[simp] lemma sum_pempty_apply_inl {α} (a) : sum_pempty α (sum.inl a) = a := rfl
/-- The sum of `pempty` with any `Sort*` is equivalent to the right summand. -/
def pempty_sum (α : Sort*) : pempty ⊕ α ≃ α :=
(sum_comm _ _).trans $ sum_pempty _
@[simp] lemma pempty_sum_apply_inr {α} (a) : pempty_sum α (sum.inr a) = a := 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
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 fun_unique
variables (α β) [unique α]
/-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/
@[simps] def fun_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 }
end fun_unique
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). -/
def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) :
(Π x : Σ i, β i, γ x.1 x.2) ≃ (Π a b, γ a b) :=
{ to_fun := λ f x y, f ⟨x,y⟩,
inv_fun := λ f x, f x.1 x.2,
left_inv := λ f, funext $ λ ⟨x,y⟩, rfl,
right_inv := λ f, funext $ λ x, funext $ λ y, rfl }
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 }
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 }⟩
/-- Functions `α → β → γ` are equivalent to functions on `α × β`. -/
def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) :=
⟨uncurry, curry, curry_uncurry, uncurry_curry⟩
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 `β`. -/
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 _ _ }
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}`. -/
def subtype_congr {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_congr_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β)
(h : ∀ (a : α), p a ↔ q (e a)) (x : {x // p x}) :
e.subtype_congr h x = ⟨e x, (h _).1 x.2⟩ :=
rfl
@[simp] lemma subtype_congr_symm_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β)
(h : ∀ (a : α), p a ↔ q (e a)) (y : {y // q y}) :
(e.subtype_congr h).symm y = ⟨e.symm y, (h _).2 $ (e.apply_symm_apply y).symm ▸ y.2⟩ :=
rfl
/-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to
`{x // q x}`. -/
@[simps {rhs_md := semireducible, simp_rhs := tt}]
def subtype_congr_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : {x // p x} ≃ {x // q x} :=
subtype_congr (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_congr 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_congr_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q :=
subtype_congr (equiv.refl α) (assume a, h ▸ iff.rfl)
/-- The subtypes corresponding to equal sets are equivalent. -/
@[simps apply {rhs_md := semireducible, simp_rhs := tt}]
def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t :=
subtype_congr_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⟩
/-- 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_congr_right $ λ x, exists_prop
/-- 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_congr_right $
assume x,
⟨and.right, λ h₁, ⟨h h₁, h₁⟩⟩
/-- If a proposition holds for all elements, then the subtype is
equivalent to the original type. -/
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_congr_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⟩
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_congr_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
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 $ λ ⟨x, h⟩, not_mem_empty x h
/-- An empty set is equivalent to a `pempty` type. -/
protected def pempty (α) : (∅ : set α) ≃ pempty :=
equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h
/-- 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
-- TODO: Any reason to use the same universe?
/-- 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_congr 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_congr_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_congr_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 {rhs_md := semireducible}]
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, this],
end
/-- If `f : α → β` is an injective function, then `α` is equivalent to the range of `f`. -/
@[simps apply]
protected noncomputable def range {α β} (f : α → β) (H : injective f) :
α ≃ range f :=
{ to_fun := λ x, ⟨f x, mem_range_self _⟩,
inv_fun := λ x, classical.some x.2,
left_inv := λ x, H (classical.some_spec (show f x ∈ range f, from mem_range_self _)),
right_inv := λ x, subtype.eq $ classical.some_spec x.2 }
theorem apply_range_symm {α β} (f : α → β) (H : injective f) (b : range f) :
f ((set.range f H).symm b) = b :=
begin
conv_rhs { rw ←((set.range f H).right_inv b), },
simp,
end
/-- If `α` is equivalent to `β`, then `set α` is equivalent to `set β`. -/
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` is a bijective function, then its domain is equivalent to its codomain. -/
@[simps apply {rhs_md := semireducible, simp_rhs := tt}]
noncomputable def of_bijective {α β} (f : α → β) (hf : bijective f) : α ≃ β :=
(equiv.set.range 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
/-- If `f` is an injective function, then its domain is equivalent to its range. -/
@[simps apply {rhs_md := semireducible, simp_rhs := tt}]
noncomputable def of_injective {α β} (f : α → β) (hf : injective f) : α ≃ _root_.set.range f :=
of_bijective (λ x, ⟨f x, set.mem_range_self x⟩)
⟨λ x y hxy, hf $ by injections, λ ⟨_, x, rfl⟩, ⟨x, rfl⟩⟩
/-- 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⟩
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 _ _ _
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 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
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
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
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
instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton
instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton
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 _ _ }
/-- `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 _ 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
|
9bef3cffab2e4e37e05ec65f41283d69e732602f | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/bicategory/basic.lean | c69c681a711bf28b2e862db7379b9d49674f2f86 | [
"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,637 | lean | /-
Copyright (c) 2021 Yuma Mizuno. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yuma Mizuno
-/
import category_theory.isomorphism
import tactic.slice
/-!
# Bicategories
In this file we define typeclass for bicategories.
A bicategory `B` consists of
* objects `a : B`,
* 1-morphisms `f : a ⟶ b` between objects `a b : B`, and
* 2-morphisms `η : f ⟶ g` beween 1-morphisms `f g : a ⟶ b` between objects `a b : B`.
We use `u`, `v`, and `w` as the universe variables for objects, 1-morphisms, and 2-morphisms,
respectively.
A typeclass for bicategories extends `category_theory.category_struct` typeclass. This means that
we have
* a composition `f ≫ g : a ⟶ c` for each 1-morphisms `f : a ⟶ b` and `g : b ⟶ c`, and
* a identity `𝟙 a : a ⟶ a` for each object `a : B`.
For each object `a b : B`, the collection of 1-morphisms `a ⟶ b` has a category structure. The
2-morphisms in the bicategory are implemented as the morphisms in this family of categories.
The composition of 1-morphisms is in fact a object part of a functor
`(a ⟶ b) ⥤ (b ⟶ c) ⥤ (a ⟶ c)`. The definition of bicategories in this file does not
require this functor directly. Instead, it requires the whiskering functions. For a 1-morphism
`f : a ⟶ b` and a 2-morphism `η : g ⟶ h` between 1-morphisms `g h : b ⟶ c`, there is a
2-morphism `whisker_left f η : f ≫ g ⟶ f ≫ h`. Similarly, for a 2-morphism `η : f ⟶ g`
between 1-morphisms `f g : a ⟶ b` and a 1-morphism `f : b ⟶ c`, there is a 2-morphism
`whisker_right η h : f ≫ h ⟶ g ≫ h`. These satisfy the exchange law
`whisker_left f θ ≫ whisker_right η i = whisker_right η h ≫ whisker_left g θ`,
which is required as an axiom in the definition here.
-/
namespace category_theory
universes w v u
open category iso
/--
In a bicategory, we can compose the 1-morphisms `f : a ⟶ b` and `g : b ⟶ c` to obtain
a 1-morphism `f ≫ g : a ⟶ c`. This composition does not need to be strictly associative,
but there is a specified associator, `α_ f g h : (f ≫ g) ≫ h ≅ f ≫ (g ≫ h)`.
There is an identity 1-morphism `𝟙 a : a ⟶ a`, with specified left and right unitor
isomorphisms `λ_ f : 𝟙 a ≫ f ≅ f` and `ρ_ f : f ≫ 𝟙 a ≅ f`.
These associators and unitors satisfy the pentagon and triangle equations.
See https://ncatlab.org/nlab/show/bicategory.
-/
@[nolint check_univs] -- intended to be used with explicit universe parameters
class bicategory (B : Type u) extends category_struct.{v} B :=
-- category structure on the collection of 1-morphisms:
(hom_category : ∀ (a b : B), category.{w} (a ⟶ b) . tactic.apply_instance)
-- left whiskering:
(whisker_left {a b c : B} (f : a ⟶ b) {g h : b ⟶ c} (η : g ⟶ h) : f ≫ g ⟶ f ≫ h)
(infixr ` ◁ `:81 := whisker_left)
-- right whiskering:
(whisker_right {a b c : B} {f g : a ⟶ b} (η : f ⟶ g) (h : b ⟶ c) : f ≫ h ⟶ g ≫ h)
(infixl ` ▷ `:81 := whisker_right)
-- associator:
(associator {a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) :
(f ≫ g) ≫ h ≅ f ≫ (g ≫ h))
(notation `α_` := associator)
-- left unitor:
(left_unitor {a b : B} (f : a ⟶ b) : 𝟙 a ≫ f ≅ f)
(notation `λ_` := left_unitor)
-- right unitor:
(right_unitor {a b : B} (f : a ⟶ b) : f ≫ 𝟙 b ≅ f)
(notation `ρ_` := right_unitor)
-- axioms for left whiskering:
(whisker_left_id' : ∀ {a b c} (f : a ⟶ b) (g : b ⟶ c),
f ◁ 𝟙 g = 𝟙 (f ≫ g) . obviously)
(whisker_left_comp' : ∀ {a b c} (f : a ⟶ b) {g h i : b ⟶ c} (η : g ⟶ h) (θ : h ⟶ i),
f ◁ (η ≫ θ) = f ◁ η ≫ f ◁ θ . obviously)
(id_whisker_left' : ∀ {a b} {f g : a ⟶ b} (η : f ⟶ g),
𝟙 a ◁ η = (λ_ f).hom ≫ η ≫ (λ_ g).inv . obviously)
(comp_whisker_left' : ∀ {a b c d} (f : a ⟶ b) (g : b ⟶ c) {h h' : c ⟶ d} (η : h ⟶ h'),
(f ≫ g) ◁ η = (α_ f g h).hom ≫ f ◁ g ◁ η ≫ (α_ f g h').inv . obviously)
-- axioms for right whiskering:
(id_whisker_right' : ∀ {a b c} (f : a ⟶ b) (g : b ⟶ c),
𝟙 f ▷ g = 𝟙 (f ≫ g) . obviously)
(comp_whisker_right' : ∀ {a b c} {f g h : a ⟶ b} (η : f ⟶ g) (θ : g ⟶ h) (i : b ⟶ c),
(η ≫ θ) ▷ i = η ▷ i ≫ θ ▷ i . obviously)
(whisker_right_id' : ∀ {a b} {f g : a ⟶ b} (η : f ⟶ g),
η ▷ 𝟙 b = (ρ_ f).hom ≫ η ≫ (ρ_ g).inv . obviously)
(whisker_right_comp' : ∀ {a b c d} {f f' : a ⟶ b} (η : f ⟶ f') (g : b ⟶ c) (h : c ⟶ d),
η ▷ (g ≫ h) = (α_ f g h).inv ≫ η ▷ g ▷ h ≫ (α_ f' g h).hom . obviously)
-- associativity of whiskerings:
(whisker_assoc' : ∀ {a b c d} (f : a ⟶ b) {g g' : b ⟶ c} (η : g ⟶ g') (h : c ⟶ d),
(f ◁ η) ▷ h = (α_ f g h).hom ≫ f ◁ (η ▷ h) ≫ (α_ f g' h).inv . obviously)
-- exchange law of left and right whiskerings:
(whisker_exchange' : ∀ {a b c} {f g : a ⟶ b} {h i : b ⟶ c} (η : f ⟶ g) (θ : h ⟶ i),
f ◁ θ ≫ η ▷ i = η ▷ h ≫ g ◁ θ . obviously)
-- pentagon identity:
(pentagon' : ∀ {a b c d e} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e),
(α_ f g h).hom ▷ i ≫ (α_ f (g ≫ h) i).hom ≫ f ◁ (α_ g h i).hom =
(α_ (f ≫ g) h i).hom ≫ (α_ f g (h ≫ i)).hom . obviously)
-- triangle identity:
(triangle' : ∀ {a b c} (f : a ⟶ b) (g : b ⟶ c),
(α_ f (𝟙 b) g).hom ≫ f ◁ (λ_ g).hom = (ρ_ f).hom ▷ g . obviously)
-- The precedence of the whiskerings is higher than that of the composition `≫`.
localized "infixr (name := bicategory.whisker_left) ` ◁ `:81 := bicategory.whisker_left"
in bicategory
localized "infixl (name := bicategory.whisker_right) ` ▷ `:81 := bicategory.whisker_right"
in bicategory
localized "notation (name := bicategory.associator) `α_` := bicategory.associator"
in bicategory
localized "notation (name := bicategory.left_unitor) `λ_` := bicategory.left_unitor"
in bicategory
localized "notation (name := bicategory.right_unitor) `ρ_` := bicategory.right_unitor"
in bicategory
namespace bicategory
/-!
### Simp-normal form for 2-morphisms
Rewriting involving associators and unitors could be very complicated. We try to ease this
complexity by putting carefully chosen simp lemmas that rewrite any 2-morphisms into simp-normal
form defined below. Rewriting into simp-normal form is also useful when applying (forthcoming)
`coherence` tactic.
The simp-normal form of 2-morphisms is defined to be an expression that has the minimal number of
parentheses. More precisely,
1. it is a composition of 2-morphisms like `η₁ ≫ η₂ ≫ η₃ ≫ η₄ ≫ η₅` such that each `ηᵢ` is
either a structural 2-morphisms (2-morphisms made up only of identities, associators, unitors)
or non-structural 2-morphisms, and
2. each non-structural 2-morphism in the composition is of the form `f₁ ◁ f₂ ◁ f₃ ◁ η ▷ f₄ ▷ f₅`,
where each `fᵢ` is a 1-morphism that is not the identity or a composite and `η` is a
non-structural 2-morphisms that is also not the identity or a composite.
Note that `f₁ ◁ f₂ ◁ f₃ ◁ η ▷ f₄ ▷ f₅` is actually `f₁ ◁ (f₂ ◁ (f₃ ◁ ((η ▷ f₄) ▷ f₅)))`.
-/
restate_axiom whisker_left_id'
restate_axiom whisker_left_comp'
restate_axiom id_whisker_left'
restate_axiom comp_whisker_left'
restate_axiom id_whisker_right'
restate_axiom comp_whisker_right'
restate_axiom whisker_right_id'
restate_axiom whisker_right_comp'
restate_axiom whisker_assoc'
restate_axiom whisker_exchange'
restate_axiom pentagon'
restate_axiom triangle'
attribute [simp] pentagon triangle
attribute [reassoc]
whisker_left_comp id_whisker_left comp_whisker_left
comp_whisker_right whisker_right_id whisker_right_comp
whisker_assoc whisker_exchange pentagon triangle
/-
The following simp attributes are put in order to rewrite any 2-morphisms into normal forms. There
are associators and unitors in the RHS in the several simp lemmas here (e.g. `id_whisker_left`),
which at first glance look more complicated than the LHS, but they will be eventually reduced by the
pentagon or the triangle identities, and more generally, (forthcoming) `coherence` tactic.
-/
attribute [simp]
whisker_left_id whisker_left_comp id_whisker_left comp_whisker_left
id_whisker_right comp_whisker_right whisker_right_id whisker_right_comp
whisker_assoc
attribute [instance] hom_category
variables {B : Type u} [bicategory.{w v} B] {a b c d e : B}
@[simp, reassoc]
lemma hom_inv_whisker_left (f : a ⟶ b) {g h : b ⟶ c} (η : g ≅ h) :
f ◁ η.hom ≫ f ◁ η.inv = 𝟙 (f ≫ g) :=
by rw [←whisker_left_comp, hom_inv_id, whisker_left_id]
@[simp, reassoc]
lemma hom_inv_whisker_right {f g : a ⟶ b} (η : f ≅ g) (h : b ⟶ c) :
η.hom ▷ h ≫ η.inv ▷ h = 𝟙 (f ≫ h) :=
by rw [←comp_whisker_right, hom_inv_id, id_whisker_right]
@[simp, reassoc]
lemma inv_hom_whisker_left (f : a ⟶ b) {g h : b ⟶ c} (η : g ≅ h) :
f ◁ η.inv ≫ f ◁ η.hom = 𝟙 (f ≫ h) :=
by rw [←whisker_left_comp, inv_hom_id, whisker_left_id]
@[simp, reassoc]
lemma inv_hom_whisker_right {f g : a ⟶ b} (η : f ≅ g) (h : b ⟶ c) :
η.inv ▷ h ≫ η.hom ▷ h = 𝟙 (g ≫ h) :=
by rw [←comp_whisker_right, inv_hom_id, id_whisker_right]
/-- The left whiskering of a 2-isomorphism is a 2-isomorphism. -/
@[simps]
def whisker_left_iso (f : a ⟶ b) {g h : b ⟶ c} (η : g ≅ h) :
f ≫ g ≅ f ≫ h :=
{ hom := f ◁ η.hom,
inv := f ◁ η.inv }
instance whisker_left_is_iso (f : a ⟶ b) {g h : b ⟶ c} (η : g ⟶ h) [is_iso η] :
is_iso (f ◁ η) :=
is_iso.of_iso (whisker_left_iso f (as_iso η))
@[simp]
lemma inv_whisker_left (f : a ⟶ b) {g h : b ⟶ c} (η : g ⟶ h) [is_iso η] :
inv (f ◁ η) = f ◁ (inv η) :=
by { ext, simp only [←whisker_left_comp, whisker_left_id, is_iso.hom_inv_id] }
/-- The right whiskering of a 2-isomorphism is a 2-isomorphism. -/
@[simps]
def whisker_right_iso {f g : a ⟶ b} (η : f ≅ g) (h : b ⟶ c) :
f ≫ h ≅ g ≫ h :=
{ hom := η.hom ▷ h,
inv := η.inv ▷ h }
instance whisker_right_is_iso {f g : a ⟶ b} (η : f ⟶ g) (h : b ⟶ c) [is_iso η] :
is_iso (η ▷ h) :=
is_iso.of_iso (whisker_right_iso (as_iso η) h)
@[simp]
lemma inv_whisker_right {f g : a ⟶ b} (η : f ⟶ g) (h : b ⟶ c) [is_iso η] :
inv (η ▷ h) = (inv η) ▷ h :=
by { ext, simp only [←comp_whisker_right, id_whisker_right, is_iso.hom_inv_id] }
@[simp, reassoc]
lemma pentagon_inv (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) :
f ◁ (α_ g h i).inv ≫ (α_ f (g ≫ h) i).inv ≫ (α_ f g h).inv ▷ i =
(α_ f g (h ≫ i)).inv ≫ (α_ (f ≫ g) h i).inv :=
eq_of_inv_eq_inv (by simp)
@[simp, reassoc]
lemma pentagon_inv_inv_hom_hom_inv (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) :
(α_ f (g ≫ h) i).inv ≫ (α_ f g h).inv ▷ i ≫ (α_ (f ≫ g) h i).hom =
f ◁ (α_ g h i).hom ≫ (α_ f g (h ≫ i)).inv :=
by { rw [←cancel_epi (f ◁ (α_ g h i).inv), ←cancel_mono (α_ (f ≫ g) h i).inv], simp }
@[simp, reassoc]
lemma pentagon_inv_hom_hom_hom_inv (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) :
(α_ (f ≫ g) h i).inv ≫ (α_ f g h).hom ▷ i ≫ (α_ f (g ≫ h) i).hom =
(α_ f g (h ≫ i)).hom ≫ f ◁ (α_ g h i).inv :=
eq_of_inv_eq_inv (by simp)
@[simp, reassoc]
lemma pentagon_hom_inv_inv_inv_inv (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) :
f ◁ (α_ g h i).hom ≫ (α_ f g (h ≫ i)).inv ≫ (α_ (f ≫ g) h i).inv =
(α_ f (g ≫ h) i).inv ≫ (α_ f g h).inv ▷ i :=
by simp [←cancel_epi (f ◁ (α_ g h i).inv)]
@[simp, reassoc]
lemma pentagon_hom_hom_inv_hom_hom (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) :
(α_ (f ≫ g) h i).hom ≫ (α_ f g (h ≫ i)).hom ≫ f ◁ (α_ g h i).inv =
(α_ f g h).hom ▷ i ≫ (α_ f (g ≫ h) i).hom :=
eq_of_inv_eq_inv (by simp)
@[simp, reassoc]
lemma pentagon_hom_inv_inv_inv_hom (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) :
(α_ f g (h ≫ i)).hom ≫ f ◁ (α_ g h i).inv ≫ (α_ f (g ≫ h) i).inv =
(α_ (f ≫ g) h i).inv ≫ (α_ f g h).hom ▷ i :=
by { rw [←cancel_epi (α_ f g (h ≫ i)).inv, ←cancel_mono ((α_ f g h).inv ▷ i)], simp }
@[simp, reassoc]
lemma pentagon_hom_hom_inv_inv_hom (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) :
(α_ f (g ≫ h) i).hom ≫ f ◁ (α_ g h i).hom ≫ (α_ f g (h ≫ i)).inv =
(α_ f g h).inv ▷ i ≫ (α_ (f ≫ g) h i).hom :=
eq_of_inv_eq_inv (by simp)
@[simp, reassoc]
lemma pentagon_inv_hom_hom_hom_hom (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) :
(α_ f g h).inv ▷ i ≫ (α_ (f ≫ g) h i).hom ≫ (α_ f g (h ≫ i)).hom =
(α_ f (g ≫ h) i).hom ≫ f ◁ (α_ g h i).hom :=
by simp [←cancel_epi ((α_ f g h).hom ▷ i)]
@[simp, reassoc]
lemma pentagon_inv_inv_hom_inv_inv (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) (i : d ⟶ e) :
(α_ f g (h ≫ i)).inv ≫ (α_ (f ≫ g) h i).inv ≫ (α_ f g h).hom ▷ i =
f ◁ (α_ g h i).inv ≫ (α_ f (g ≫ h) i).inv :=
eq_of_inv_eq_inv (by simp)
lemma triangle_assoc_comp_left (f : a ⟶ b) (g : b ⟶ c) :
(α_ f (𝟙 b) g).hom ≫ f ◁ (λ_ g).hom = (ρ_ f).hom ▷ g :=
triangle f g
@[simp, reassoc]
lemma triangle_assoc_comp_right (f : a ⟶ b) (g : b ⟶ c) :
(α_ f (𝟙 b) g).inv ≫ (ρ_ f).hom ▷ g = f ◁ (λ_ g).hom :=
by rw [←triangle, inv_hom_id_assoc]
@[simp, reassoc]
lemma triangle_assoc_comp_right_inv (f : a ⟶ b) (g : b ⟶ c) :
(ρ_ f).inv ▷ g ≫ (α_ f (𝟙 b) g).hom = f ◁ (λ_ g).inv :=
by simp [←cancel_mono (f ◁ (λ_ g).hom)]
@[simp, reassoc]
lemma triangle_assoc_comp_left_inv (f : a ⟶ b) (g : b ⟶ c) :
f ◁ (λ_ g).inv ≫ (α_ f (𝟙 b) g).inv = (ρ_ f).inv ▷ g :=
by simp [←cancel_mono ((ρ_ f).hom ▷ g)]
@[reassoc]
lemma associator_naturality_left {f f' : a ⟶ b} (η : f ⟶ f') (g : b ⟶ c) (h : c ⟶ d) :
(η ▷ g) ▷ h ≫ (α_ f' g h).hom = (α_ f g h).hom ≫ η ▷ (g ≫ h) :=
by simp
@[reassoc]
lemma associator_inv_naturality_left {f f' : a ⟶ b} (η : f ⟶ f') (g : b ⟶ c) (h : c ⟶ d) :
η ▷ (g ≫ h) ≫ (α_ f' g h).inv = (α_ f g h).inv ≫ (η ▷ g) ▷ h :=
by simp
@[reassoc]
lemma whisker_right_comp_symm {f f' : a ⟶ b} (η : f ⟶ f') (g : b ⟶ c) (h : c ⟶ d) :
(η ▷ g) ▷ h = (α_ f g h).hom ≫ η ▷ (g ≫ h) ≫ (α_ f' g h).inv :=
by simp
@[reassoc]
lemma associator_naturality_middle (f : a ⟶ b) {g g' : b ⟶ c} (η : g ⟶ g') (h : c ⟶ d) :
(f ◁ η) ▷ h ≫ (α_ f g' h).hom = (α_ f g h).hom ≫ f ◁ (η ▷ h) :=
by simp
@[reassoc]
lemma associator_inv_naturality_middle (f : a ⟶ b) {g g' : b ⟶ c} (η : g ⟶ g') (h : c ⟶ d) :
f ◁ (η ▷ h) ≫ (α_ f g' h).inv = (α_ f g h).inv ≫ (f ◁ η) ▷ h :=
by simp
@[reassoc]
lemma whisker_assoc_symm (f : a ⟶ b) {g g' : b ⟶ c} (η : g ⟶ g') (h : c ⟶ d) :
f ◁ (η ▷ h) = (α_ f g h).inv ≫ (f ◁ η) ▷ h ≫ (α_ f g' h).hom :=
by simp
@[reassoc]
lemma associator_naturality_right (f : a ⟶ b) (g : b ⟶ c) {h h' : c ⟶ d} (η : h ⟶ h') :
(f ≫ g) ◁ η ≫ (α_ f g h').hom = (α_ f g h).hom ≫ f ◁ (g ◁ η) :=
by simp
@[reassoc]
lemma associator_inv_naturality_right (f : a ⟶ b) (g : b ⟶ c) {h h' : c ⟶ d} (η : h ⟶ h') :
f ◁ (g ◁ η) ≫ (α_ f g h').inv = (α_ f g h).inv ≫ (f ≫ g) ◁ η :=
by simp
@[reassoc]
lemma comp_whisker_left_symm (f : a ⟶ b) (g : b ⟶ c) {h h' : c ⟶ d} (η : h ⟶ h') :
f ◁ (g ◁ η) = (α_ f g h).inv ≫ (f ≫ g) ◁ η ≫ (α_ f g h').hom :=
by simp
@[reassoc]
lemma left_unitor_naturality {f g : a ⟶ b} (η : f ⟶ g) :
𝟙 a ◁ η ≫ (λ_ g).hom = (λ_ f).hom ≫ η :=
by simp
@[reassoc]
lemma left_unitor_inv_naturality {f g : a ⟶ b} (η : f ⟶ g) :
η ≫ (λ_ g).inv = (λ_ f).inv ≫ 𝟙 a ◁ η :=
by simp
lemma id_whisker_left_symm {f g : a ⟶ b} (η : f ⟶ g) :
η = (λ_ f).inv ≫ 𝟙 a ◁ η ≫ (λ_ g).hom :=
by simp
@[reassoc]
lemma right_unitor_naturality {f g : a ⟶ b} (η : f ⟶ g) :
η ▷ 𝟙 b ≫ (ρ_ g).hom = (ρ_ f).hom ≫ η :=
by simp
@[reassoc]
lemma right_unitor_inv_naturality {f g : a ⟶ b} (η : f ⟶ g) :
η ≫ (ρ_ g).inv = (ρ_ f).inv ≫ η ▷ 𝟙 b :=
by simp
lemma whisker_right_id_symm {f g : a ⟶ b} (η : f ⟶ g) :
η = (ρ_ f).inv ≫ η ▷ 𝟙 b ≫ (ρ_ g).hom :=
by simp
lemma whisker_left_iff {f g : a ⟶ b} (η θ : f ⟶ g) :
(𝟙 a ◁ η = 𝟙 a ◁ θ) ↔ (η = θ) :=
by simp
lemma whisker_right_iff {f g : a ⟶ b} (η θ : f ⟶ g) :
(η ▷ 𝟙 b = θ ▷ 𝟙 b) ↔ (η = θ) :=
by simp
/--
We state it as a simp lemma, which is regarded as an involved version of
`id_whisker_right f g : 𝟙 f ▷ g = 𝟙 (f ≫ g)`.
-/
@[reassoc, simp]
lemma left_unitor_whisker_right (f : a ⟶ b) (g : b ⟶ c) :
(λ_ f).hom ▷ g = (α_ (𝟙 a) f g).hom ≫ (λ_ (f ≫ g)).hom :=
by rw [←whisker_left_iff, whisker_left_comp, ←cancel_epi (α_ _ _ _).hom,
←cancel_epi ((α_ _ _ _).hom ▷ _), pentagon_assoc, triangle,
←associator_naturality_middle, ←comp_whisker_right_assoc, triangle,
associator_naturality_left]; apply_instance
@[reassoc, simp]
lemma left_unitor_inv_whisker_right (f : a ⟶ b) (g : b ⟶ c) :
(λ_ f).inv ▷ g = (λ_ (f ≫ g)).inv ≫ (α_ (𝟙 a) f g).inv :=
eq_of_inv_eq_inv (by simp)
@[reassoc, simp]
lemma whisker_left_right_unitor (f : a ⟶ b) (g : b ⟶ c) :
f ◁ (ρ_ g).hom = (α_ f g (𝟙 c)).inv ≫ (ρ_ (f ≫ g)).hom :=
by rw [←whisker_right_iff, comp_whisker_right, ←cancel_epi (α_ _ _ _).inv,
←cancel_epi (f ◁ (α_ _ _ _).inv), pentagon_inv_assoc, triangle_assoc_comp_right,
←associator_inv_naturality_middle, ←whisker_left_comp_assoc, triangle_assoc_comp_right,
associator_inv_naturality_right]; apply_instance
@[reassoc, simp]
lemma whisker_left_right_unitor_inv (f : a ⟶ b) (g : b ⟶ c) :
f ◁ (ρ_ g).inv = (ρ_ (f ≫ g)).inv ≫ (α_ f g (𝟙 c)).hom :=
eq_of_inv_eq_inv (by simp)
/-
It is not so obvious whether `left_unitor_whisker_right` or `left_unitor_comp` should be a simp
lemma. Our choice is the former. One reason is that the latter yields the following loop:
[id_whisker_left] : 𝟙 a ◁ (ρ_ f).hom ==> (λ_ (f ≫ 𝟙 b)).hom ≫ (ρ_ f).hom ≫ (λ_ f).inv
[left_unitor_comp] : (λ_ (f ≫ 𝟙 b)).hom ==> (α_ (𝟙 a) f (𝟙 b)).inv ≫ (λ_ f).hom ▷ 𝟙 b
[whisker_right_id] : (λ_ f).hom ▷ 𝟙 b ==> (ρ_ (𝟙 a ≫ f)).hom ≫ (λ_ f).hom ≫ (ρ_ f).inv
[right_unitor_comp] : (ρ_ (𝟙 a ≫ f)).hom ==> (α_ (𝟙 a) f (𝟙 b)).hom ≫ 𝟙 a ◁ (ρ_ f).hom
-/
@[reassoc]
lemma left_unitor_comp (f : a ⟶ b) (g : b ⟶ c) :
(λ_ (f ≫ g)).hom = (α_ (𝟙 a) f g).inv ≫ (λ_ f).hom ▷ g :=
by simp
@[reassoc]
lemma left_unitor_comp_inv (f : a ⟶ b) (g : b ⟶ c) :
(λ_ (f ≫ g)).inv = (λ_ f).inv ▷ g ≫ (α_ (𝟙 a) f g).hom :=
by simp
@[reassoc]
lemma right_unitor_comp (f : a ⟶ b) (g : b ⟶ c) :
(ρ_ (f ≫ g)).hom = (α_ f g (𝟙 c)).hom ≫ f ◁ (ρ_ g).hom :=
by simp
@[reassoc]
lemma right_unitor_comp_inv (f : a ⟶ b) (g : b ⟶ c) :
(ρ_ (f ≫ g)).inv = f ◁ (ρ_ g).inv ≫ (α_ f g (𝟙 c)).inv :=
by simp
@[simp]
lemma unitors_equal : (λ_ (𝟙 a)).hom = (ρ_ (𝟙 a)).hom :=
by rw [←whisker_left_iff, ←cancel_epi (α_ _ _ _).hom, ←cancel_mono (ρ_ _).hom, triangle,
←right_unitor_comp, right_unitor_naturality]; apply_instance
@[simp]
lemma unitors_inv_equal : (λ_ (𝟙 a)).inv = (ρ_ (𝟙 a)).inv :=
by simp [iso.inv_eq_inv]
end bicategory
end category_theory
|
be624aa4bbff4f2cc3b279edcb0d7499a5ad1526 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/fintype/fin.lean | 6246fedbb11011568426ae0a1c17ab7e1bb863a0 | [
"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 | 1,351 | lean | /-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import data.fin.basic
import data.fintype.basic
/-!
# The structure of `fintype (fin n)`
This file contains some basic results about the `fintype` instance for `fin`,
especially properties of `finset.univ : finset (fin n)`.
-/
open finset
open fintype
namespace fin
@[simp]
lemma univ_filter_zero_lt {n : ℕ} :
(univ : finset (fin n.succ)).filter (λ i, 0 < i) =
univ.map (fin.succ_embedding _).to_embedding :=
begin
ext i,
simp only [mem_filter, mem_map, mem_univ, true_and,
function.embedding.coe_fn_mk, exists_true_left],
split,
{ refine cases _ _ i,
{ rintro ⟨⟨⟩⟩ },
{ intros j _, exact ⟨j, rfl⟩ } },
{ rintro ⟨i, _, rfl⟩,
exact succ_pos _ },
end
@[simp]
lemma univ_filter_succ_lt {n : ℕ} (j : fin n) :
(univ : finset (fin n.succ)).filter (λ i, j.succ < i) =
(univ.filter (λ i, j < i)).map (fin.succ_embedding _).to_embedding :=
begin
ext i,
simp only [mem_filter, mem_map, mem_univ, true_and,
function.embedding.coe_fn_mk, exists_true_left],
split,
{ refine cases _ _ i,
{ rintro ⟨⟨⟩⟩ },
{ intros i hi,
refine ⟨i, succ_lt_succ_iff.mp hi, rfl⟩ } },
{ rintro ⟨i, hi, rfl⟩, simpa },
end
end fin
|
5fbed85d6ac98e4760ecdfcc2716a21772a83c3f | fe84e287c662151bb313504482b218a503b972f3 | /src/commutative_algebra/book/sec_elements.lean | 074b8b9067ec9152de3a86ae64d31aec12e30e25 | [] | 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 | 40,441 | lean | import algebra.ring data.complex.basic data.zmod.basic
import data.nat.prime data.int.gcd data.nat.choose algebra.gcd_monoid.basic data.finsupp
import data.list.min_max data.polynomial
import data.nat.square_free
import ring_theory.integral_domain
import tactic.ring tactic.squeeze
namespace sec_elements
universes u₀ u₁
variables {A : Type u₀} [comm_ring A] {B : Type u₁} [comm_ring B]
variable (f : A →+* B)
/- -------------------------------------------------------- -/
/- defn-el-props -/
def inverse (a : A) := {b : A // a * b = 1}
def is_invertible (a : A) := nonempty (inverse a)
noncomputable def inv (a : A) (h : is_invertible a) :=
classical.choice h
def is_regular (a : A) : Prop := ∀ (x : A) (e : a * x = 0), x = 0
def is_zero_divisor (a : A) := ¬ (is_regular a)
def nilpotent_witness (a : A) := {n : ℕ // a ^ n = 0}
def is_nilpotent (a : A) := nonempty (nilpotent_witness a)
def is_jacobian (a : A) := ∀ (b : A), is_invertible (1 - a * b)
def is_idempotent (a : A) := a ^ 2 = a
lemma is_idempotent' (a : A) : is_idempotent a ↔ a * (1 - a) = 0 :=
by { dsimp[is_idempotent],
rw[pow_two,mul_sub,mul_one,sub_eq_zero],
split; intro e; exact e.symm}
def inverse_hom {a : A} (u : inverse a) : inverse (f a) :=
⟨f u.val,by { rw[← f.map_mul,u.property, f.map_one]}⟩
lemma is_invertible_hom {a : A} (h : is_invertible a) : is_invertible (f a) :=
by { apply nonempty.elim h, intro u, use inverse_hom f u }
def nilpotent_witness_hom {a : A} (n : nilpotent_witness a) : nilpotent_witness (f a) :=
⟨n.val, by { rw[← f.map_pow a n.val, n.property, f.map_zero] } ⟩
lemma is_nilpotent_hom {a : A} (h : is_nilpotent a) : is_nilpotent (f a) :=
by { apply nonempty.elim h, intro n, use nilpotent_witness_hom f n }
lemma is_idempotent_hom {a : A} (h : is_idempotent a) : is_idempotent (f a) :=
by { change a ^ 2 = a at h, change (f a) ^ 2 = f a, rw[← f.map_pow, h] }
/- -------------------------------------------------------- -/
/- prop-inv-unique -/
instance inverse_unique (a : A) : subsingleton (inverse a) :=
⟨λ ⟨b₀,h₀⟩ ⟨b₁,h₁⟩ , begin apply subtype.eq, change b₀ = b₁,
rw[← mul_one b₀,← h₁,← mul_assoc,mul_comm b₀,h₀,one_mul],
end ⟩
/- -------------------------------------------------------- -/
/- eg-C-el-props -/
namespace integral_domain
variables {D : Type*} [comm_ring D] [is_domain D] (a : D)
lemma is_regular_iff : (is_regular a ↔ a ≠ 0) :=
begin
split,
{rintro h_reg a_eq_0, exact zero_ne_one (h_reg 1 (a_eq_0.symm ▸ (zero_mul 1))).symm},
{intros a_ne_0 b e,
rcases eq_zero_or_eq_zero_of_mul_eq_zero e with ha | hb,
{exact (a_ne_0 ha).elim},{exact hb}}
end
lemma is_nilpotent_iff : (is_nilpotent a ↔ a = 0) :=
begin
split,
{rintro ⟨⟨n,e⟩⟩,induction n with n ih,
{rw[pow_zero] at e,exact (zero_ne_one e.symm).elim},
{rw[pow_succ] at e,rcases eq_zero_or_eq_zero_of_mul_eq_zero e with h | h,
{exact h},{exact ih h}
}
},{
intro h,rw[h],exact ⟨⟨1,pow_one 0⟩⟩
}
end
lemma is_idempotent_iff : (is_idempotent a ↔ a = 0 ∨ a = 1) :=
begin
rw[is_idempotent'],split,
{intro e,rcases eq_zero_or_eq_zero_of_mul_eq_zero e with h0 | h1,
{exact or.inl h0},
{exact or.inr (sub_eq_zero.mp h1).symm,}
},{
rintro (h | h); rw[h],rw[zero_mul],rw[sub_self,mul_zero],
}
end
end integral_domain
namespace field
variables {F : Type*} [field F] (a : F)
lemma is_invertible_iff : (is_invertible a ↔ a ≠ 0) :=
begin
split,
{rintro ⟨⟨ai,ai_prop⟩⟩ a_eq_0,rw[a_eq_0,zero_mul] at ai_prop,
exact zero_ne_one ai_prop
},{intro a_ne_0,use a⁻¹,exact mul_inv_cancel a_ne_0,}
end
lemma is_regular_iff : (is_regular a ↔ a ≠ 0) :=
begin
split,
{rintro h_reg a_eq_0, exact zero_ne_one (h_reg 1 (a_eq_0.symm ▸ (zero_mul 1))).symm},
{intros a_ne_0 b e,exact calc
b = 1 * b : (one_mul b).symm
... = 0 : by rw[← inv_mul_cancel a_ne_0,mul_assoc,e,mul_zero],}
end
end field
namespace C_el_props
lemma ℂ_el_props (z : ℂ) :
(is_invertible z ↔ z ≠ 0) ∧
(is_regular z ↔ z ≠ 0) ∧
(is_nilpotent z ↔ z = 0) ∧
(is_idempotent z ↔ (z = 0 ∨ z = 1)) :=
begin
split,exact field.is_invertible_iff z,
split,exact integral_domain.is_regular_iff z,
split,exact integral_domain.is_nilpotent_iff z,
exact integral_domain.is_idempotent_iff z,
end
end C_el_props
/- -------------------------------------------------------- -/
/- eg-Zn-el-props -/
namespace zmod_el_props
variables (n : ℕ) [fact (n > 0)]
namespace int
def gcd_a (x y : ℤ) : ℤ :=
x.sign * (nat.gcd_a x.nat_abs y.nat_abs)
def gcd_b (x y : ℤ) : ℤ :=
y.sign * (nat.gcd_b x.nat_abs y.nat_abs)
lemma nat_abs_eq_sign_mul_self : ∀ (x : ℤ),
(x.nat_abs : ℤ) = x.sign * x
| (0 : ℕ) := rfl
| ((n + 1) : ℕ) := by {rw[int.nat_abs_of_nat,int.sign,_root_.one_mul],}
| (-[1+ m]) := by {rw[int.nat_abs,int.sign,← neg_eq_neg_one_mul],refl}
lemma gcd_eq_gcd_ab (x y : ℤ) :
(gcd x y) = x * (gcd_a x y) + y * (gcd_b x y) :=
begin
let d := nat.gcd x.nat_abs y.nat_abs,
let a := nat.gcd_a x.nat_abs y.nat_abs,
let b := nat.gcd_b x.nat_abs y.nat_abs,
change (d : ℤ) = x * (x.sign * a) + y * (y.sign * b),
let h : (d : ℤ) = x.nat_abs * a + y.nat_abs * b:=
by {dsimp[d,a,b],exact nat.gcd_eq_gcd_ab x.nat_abs y.nat_abs},
rw[← _root_.mul_assoc,← _root_.mul_assoc,mul_comm x,mul_comm y],
rw[← nat_abs_eq_sign_mul_self x,← nat_abs_eq_sign_mul_self y],
exact h,
end
end int
namespace nat
def sup_monoid : add_comm_monoid ℕ := {
zero := 0,
add := λ (a b : ℕ), ite (a ≤ b) b a,
add_zero := λ a, by
{dsimp[has_add.add],split_ifs,exact (nat.eq_zero_of_le_zero h).symm,refl},
zero_add := λ a, by
{dsimp[has_add.add],split_ifs,refl,exact (h (nat.zero_le a)).elim},
add_comm := λ a b, by
{change ℕ at a,
dsimp[has_add.add],split_ifs with hab hba,
{exact le_antisymm hba hab},{refl},{refl},
{exact (h (le_of_lt (lt_of_not_ge hab))).elim},
},
add_assoc := λ a b c, by {
dsimp[has_add.add],split_ifs with hab hbc hac hac hbc; try {refl},
{exact (hac (le_trans hab hbc)).elim},
{replace hbc := lt_of_not_ge hbc,
replace hab := lt_of_not_ge hab,
exact (not_le_of_gt (lt_trans hbc hab) hac).elim,
}
},
}
end nat
lemma is_invertible_iff (a : ℤ) :
(is_invertible (a : zmod n)) ↔ gcd a n = 1 :=
begin
let en : ((n : ℕ) : ℤ) = n := rfl,
split,
{
rintro ⟨b₀,hab⟩,
let d := gcd a n,change d = 1,
have : d = d.nat_abs :=
((int.coe_nat_abs_eq_normalize d).trans (normalize_gcd a n)).symm,
rw[this,← int.coe_nat_one],congr,
let b : ℤ := b₀.val,
have : (b : zmod n) = b₀ := by {rw[int.cast_coe_nat,b₀.nat_cast_zmod_val],},
rw[← this,← int.cast_mul] at hab,
have : (((a * b - 1) : ℤ) : (zmod n)) = 0 :=
by {rw[int.cast_sub,hab,int.cast_one,sub_self],},
rcases (zmod.int_coe_zmod_eq_zero_iff_dvd (a * b - 1) n).mp this with ⟨c,e⟩,
change a * b - 1 = n * c at e,
replace e : a * b = n * c + 1 := by {rw[← e,sub_add,sub_self,sub_zero],},
let ha : d ∣ a := by {dsimp[d],rw[en], exact gcd_dvd_left a n},
let hn : d ∣ n := by {dsimp[d],rw[en], exact gcd_dvd_right a n},
let hab : d ∣ (n * c + 1) := e ▸ (dvd_mul_of_dvd_left ha b),
rcases ((dvd_add_iff_right (dvd_mul_of_dvd_left hn c)).mpr hab) with ⟨u,eu⟩,
replace eu := congr_arg int.nat_abs eu,
change 1 = (d * u).nat_abs at eu,rw[int.nat_abs_mul] at eu,
exact (nat.mul_eq_one_iff.mp eu.symm).left,
},{
let d := gcd a n,
let b := int.gcd_a a n,
let q := int.gcd_b a n,
have e : d = a * b + n * q := int.gcd_eq_gcd_ab a n,
intro h, change d = 1 at h,rw[e,← en] at h,
replace h := eq_sub_of_add_eq h,
have : (a : zmod n) * (b : zmod n) = 1 :=
by {rw[← int.cast_mul,h,int.cast_sub,int.cast_mul,int.cast_coe_nat],
rw[zmod.nat_cast_self,zero_mul,sub_zero,int.cast_one],},
exact ⟨⟨(b : zmod n),this⟩⟩
}
end
lemma is_invertible_iff' (a : ℕ) :
(is_invertible (a : zmod n)) ↔
(∀ (p : ℕ), (nat.prime p) → (p ∣ n) → ¬ (p ∣ a)) :=
begin
rw[← int.cast_coe_nat,is_invertible_iff],
dsimp[gcd,int.gcd],rw[← int.coe_nat_one,int.coe_nat_inj'],
split,
{intros h p p_prime p_dvd_n p_dvd_a,
have : p ∣ 1 := h ▸ (nat.dvd_gcd p_dvd_a p_dvd_n),
exact nat.prime.not_dvd_one p_prime this,
},
{intro h,by_contradiction h',
let d := nat.gcd a n,
let p := nat.min_fac d,
let p_prime : p.prime := nat.min_fac_prime h',
let p_dvd_d : p ∣ d := nat.min_fac_dvd d,
let p_dvd_a : p ∣ a := dvd_trans p_dvd_d (nat.gcd_dvd_left a n),
let p_dvd_n : p ∣ n := dvd_trans p_dvd_d (nat.gcd_dvd_right a n),
exact h p p_prime p_dvd_n p_dvd_a,
}
end
lemma is_regular_iff (a : ℕ) :
(is_regular (a : zmod n)) ↔ (is_invertible (a : zmod n)) :=
begin
split,
{intro h,
let f : (zmod n) → (zmod n) := λ x, a * x,
have : function.injective f := λ x₁ x₂ e,
by {rw[← sub_eq_zero] at e ⊢,
dsimp[f] at e,rw[← mul_sub] at e,
exact h _ e
},
rcases (fintype.injective_iff_surjective.mp this 1) with ⟨b,e⟩,
dsimp[f] at e,exact ⟨⟨b,e⟩⟩,
},{
rintros ⟨⟨b,eab⟩⟩ x eax,rw[mul_comm] at eab,
exact calc
x = 1 * x : (one_mul x).symm
... = 0 : by rw[← eab,mul_assoc,eax,mul_zero b],
}
end
lemma is_nilpotent_iff (a : ℕ) :
(is_nilpotent (a : zmod n)) ↔
(∀ (p : ℕ), (nat.prime p) → (p ∣ n) → (p ∣ a)) :=
begin
split,
{rintro ⟨⟨k,e⟩⟩ p p_prime p_dvd_n,
rw[← nat.cast_pow] at e,
replace e := dvd_trans p_dvd_n ((zmod.nat_coe_zmod_eq_zero_iff_dvd _ _).mp e) ,
exact nat.prime.dvd_of_dvd_pow p_prime e,
},{
have hn : n > 0 := fact.elim (by { apply_instance }),
rcases nat.dvd_square_free_radical (ne_of_gt hn) with ⟨k,⟨q,hq⟩⟩,
intro h,
rcases (nat.square_free_radical_dvd_iff (ne_of_gt hn) a).mpr h with ⟨r,hr⟩,
have ha : a ^ k = n * (q * r ^ k) :=
by { rw[hr,mul_pow,hq,mul_assoc] },
have hz : (n : zmod n) = 0 := zmod.nat_cast_self n,
have := calc
(a : zmod n) ^ k = (((a ^ k) : ℕ) : zmod n) : by rw[nat.cast_pow]
... = 0 : by {rw[ha,nat.cast_mul,nat.cast_mul,nat.cast_pow,hz,zero_mul]},
exact ⟨⟨k,this⟩⟩,
}
end
end zmod_el_props
/- -------------------------------------------------------- -/
/- prop-inv-prod -/
variable (A)
def inverse_one : inverse (1 : A) := ⟨1,mul_one 1⟩
variable {A}
def inverse_prod_equiv (a b : A) :
inverse (a * b) ≃ ((inverse b) × (inverse a)) := {
to_fun := λ ⟨u,e⟩, ⟨⟨a * u,by {rw[← e],ring}⟩,
⟨b * u,by {rw[← e],ring}⟩⟩ ,
inv_fun := λ ⟨⟨v,ev⟩,⟨u,eu⟩⟩,
⟨v * u, calc (a * b) * (v * u) = (a * u) * (b * v) : by ring
... = 1 : by rw[eu,ev,mul_one],
⟩,
left_inv := λ u, by {apply subsingleton.elim},
right_inv := λ ⟨v,u⟩, by {apply prod.ext;apply subsingleton.elim},
}
def inverse_inv (a : A) (u : inverse a) : inverse u.val :=
⟨a,by {rw[mul_comm,u.property]}⟩
variable (A)
lemma is_invertible_one : is_invertible (1 : A) :=
⟨inverse_one A⟩
variable {A}
lemma is_invertible_mul_iff (a b : A) :
is_invertible (a * b) ↔ (is_invertible a) ∧ (is_invertible b) :=
begin
split,
{rintro ⟨uv⟩,let uv' := (inverse_prod_equiv a b).to_fun uv,
exact ⟨⟨uv'.2⟩,⟨uv'.1⟩⟩},
{rintro ⟨⟨u⟩,⟨v⟩⟩, exact ⟨(inverse_prod_equiv a b).inv_fun ⟨v,u⟩⟩,}
end
/- -------------------------------------------------------- -/
/- prop-regular-prod -/
variable (A)
def is_regular_one : is_regular (1 : A) :=
λ x h, by {rw[one_mul] at h, exact h}
variable {A}
def is_regular_mul_iff {a b : A} :
is_regular (a * b) ↔ (is_regular a) ∧ (is_regular b) :=
begin
split,
{intro hab,split,
{intros x e,
have e' : (a * b) * x = b * (a * x) := by ring,
rw[e,mul_zero] at e',exact hab _ e',},
{intros x e,
have e' : (a * b) * x = a * (b * x) := by ring,
rw[e,mul_zero] at e',exact hab _ e',},
},
{rintro ⟨ha,hb⟩ x e,rw[mul_assoc] at e,
replace e := ha (b * x) e,replace e := hb x e,exact e,
}
end
def is_regular_of_invertible {a : A} : is_invertible a → is_regular a :=
λ ⟨u⟩ x e, calc
x = (1 : A) * x : (one_mul x).symm
... = (a * u.val) * x : by rw[u.property]
... = u.val * (a * x) : by ring
... = 0 : by rw[e,mul_zero]
/- -------------------------------------------------------- -/
/- prop-finite-regular -/
lemma invertible_of_regular_of_finite [fintype A]
{a : A} : (is_regular a) → (is_invertible a) :=
begin
intro ha,
let f : A → A := λ x, a * x,
have hf : function.injective f :=
λ x₀ x₁ e, begin
let e' := calc
a * (x₀ - x₁) = (a * x₀) - (a * x₁) : mul_sub _ _ _
... = (f x₀) - (f x₁) : rfl
... = 0 : by rw[e,sub_self],
exact sub_eq_zero.mp (ha _ e')
end,
let hf' := fintype.injective_iff_surjective.mp hf,
rcases (hf' 1) with ⟨u,hu⟩,
exact ⟨⟨u,hu⟩⟩
end
/- -------------------------------------------------------- -/
/- prop-nilpotent-sum -/
lemma is_nilpotent_zero : is_nilpotent (0 : A) :=
⟨⟨1,pow_one 0⟩⟩
lemma is_nilpotent_add {a b : A} :
is_nilpotent a → is_nilpotent b → is_nilpotent (a + b) :=
begin
intros ha hb,
rcases ha with ⟨_|n,ea⟩,
{exact ⟨⟨0,by {rw[pow_zero] at ea ⊢,exact ea} ⟩⟩},
rcases hb with ⟨_|m,eb⟩,
{exact ⟨⟨0,by {rw[pow_zero] at eb ⊢,exact eb} ⟩⟩},
constructor,
use n + m + 1,rw[add_pow],
rw[← @finset.sum_const_zero A ℕ (finset.range (n + m + 1).succ)],
congr,ext i,
by_cases hi : i ≥ n + 1,
{rw[← nat.add_sub_of_le hi,pow_add,ea],repeat {rw[zero_mul]},},
{change ¬ (i > n) at hi,
replace hi := le_of_not_gt hi,
have := nat.add_sub_of_le hi,
have : n + m + 1 - i = (m + 1) + (n - i) := by {
rw[← this,add_comm i,add_assoc,nat.add_sub_cancel],
rw[add_assoc,add_comm i,← add_assoc,nat.add_sub_cancel,add_comm],
},
rw[this,pow_add,eb,zero_mul,mul_zero,zero_mul],
}
end
lemma is_nilpotent_smul (a : A) {b : A} :
is_nilpotent b → is_nilpotent (a * b) :=
λ ⟨⟨n,e⟩⟩, by {
have e' : (a * b) ^ n = 0 := by { rw[mul_pow,e,mul_zero],},
exact ⟨⟨n,e'⟩⟩
}
lemma is_nilpotent_neg {b : A} :
is_nilpotent b → is_nilpotent (-b) :=
λ h, by {rw[neg_eq_neg_one_mul],exact is_nilpotent_smul (-1) h}
lemma is_nilpotent_sub {a b : A} :
is_nilpotent a → is_nilpotent b → is_nilpotent (a - b) :=
λ ha hb, by {rw[sub_eq_add_neg],apply is_nilpotent_add,
exact ha,apply is_nilpotent_neg,exact hb}
/- -------------------------------------------------------- -/
/- prop-nilpotent-inv -/
def geometric_series (a : A) (n : ℕ) :=
(finset.range n).sum (λ i, a ^ i)
lemma geometric_sum (a : A) (n : ℕ) :
(1 - a) * (geometric_series a n) = 1 - a ^ n :=
begin
induction n with n ih,
{change (1 - a) * 0 = 1 - a ^ 0,rw[mul_zero,pow_zero,sub_self],},
{have : geometric_series a n.succ = a ^ n + geometric_series a n :=
by {dsimp[geometric_series],rw[finset.sum_range_succ,add_comm]},
rw[this,mul_add,ih,nat.succ_eq_add_one,pow_add,pow_one],
rw[sub_mul,one_mul,mul_comm a],
repeat {rw[sub_eq_add_neg]},
rw[add_comm,add_assoc,← add_assoc (- (a^n)),neg_add_self,zero_add],
}
end
def one_add_nilp_inv {a : A} :
∀ (h : nilpotent_witness a), inverse (1 + a)
| ⟨n,e⟩ := ⟨geometric_series (-a) n, by {
let u := geometric_series (-a) n, change (1 + a) * u = 1,
let e' : (1 - (- a)) * u = 1 - (- a) ^ n :=
by {dsimp[u],exact geometric_sum (- a) n},
rw[sub_neg_eq_add,neg_eq_neg_one_mul,mul_pow,e,mul_zero,sub_zero] at e',
exact e'
} ⟩
lemma one_add_nilp_inv' {a : A} :
is_nilpotent a → is_invertible (1 + a) :=
λ ⟨h⟩, ⟨one_add_nilp_inv h⟩
/- -------------------------------------------------------- -/
lemma is_jacobian_zero : is_jacobian (0 : A) := λ b,
begin
rw[zero_mul, sub_zero], exact is_invertible_one A
end
lemma is_jacobian_add {a b : A}
(ha : is_jacobian a) (hb : is_jacobian b) : is_jacobian (a + b) :=
begin
intro x,
rcases (ha x) with ⟨u,hu⟩,
rcases (hb (x * u)) with ⟨v,hv⟩,
use u * v,
rw[add_mul, sub_mul, add_mul, one_mul, ← sub_sub, mul_assoc, mul_assoc],
have hu' : ((1 - a * x) * u) * v = 1 * v := congr_arg (λ t, t * v) hu,
rw [one_mul, sub_mul, one_mul, sub_mul, mul_assoc, mul_assoc] at hu',
rw [sub_mul, one_mul, mul_assoc, mul_assoc] at hv,
rw[hu', hv],
end
lemma is_jacobian_smul (a : A) {b : A} (hb : is_jacobian b) :
is_jacobian (a * b) :=
begin
rw[mul_comm],
intro x, rw[mul_assoc], exact hb (a * x)
end
lemma is_jacobian_of_nilpotent {a : A} (ha : is_nilpotent a) :
is_jacobian a :=
begin
intro x,
rw [sub_eq_add_neg],
apply one_add_nilp_inv',
rw[mul_comm, ← neg_mul],
exact is_nilpotent_smul (-x) ha,
end
/- -------------------------------------------------------- -/
/- cor-nilp-inv -/
lemma inv_add_nilp_inv {u a : A} :
is_invertible u → is_nilpotent a → is_invertible (u + a) :=
λ ⟨⟨v,euv⟩⟩ ea,
begin
have : u + a = u * (1 + v * a) :=
by { rw[mul_add,← mul_assoc,euv,mul_one,one_mul], },
rw[this,is_invertible_mul_iff],
split,
{exact ⟨⟨v,euv⟩⟩},
{exact one_add_nilp_inv' (is_nilpotent_smul v ea)}
end
/- -------------------------------------------------------- -/
/- prop-idempotent-ops -/
namespace idempotent
variable (A)
lemma zero_mem : is_idempotent (0 : A) :=
by {dsimp[is_idempotent],rw[pow_two,mul_zero]}
lemma one_mem : is_idempotent (1 : A) :=
by {dsimp[is_idempotent],rw[pow_two,mul_one]}
variable {A}
lemma pow_eq_self {a : A} (h : is_idempotent a) (n : ℕ) :
a ^ n.succ = a :=
begin
induction n with n ih,
{ rw[pow_one] },
{ rw[pow_succ, ih, ← pow_two], exact h }
end
lemma mul_self {a : A} (h : is_idempotent a) : a * a = a :=
by { rw[← pow_two], exact h }
def not (a : A) := 1 - a
def and (a b : A) := a * b
def or (a b : A) := a + b - a * b
def xor (a b : A) := a + b - 2 * a * b
lemma one_sub_mem {a : A} :
is_idempotent a → is_idempotent (1 - a) :=
by {
dsimp[is_idempotent],rw[pow_two,pow_two],intro e,
rw[mul_sub,mul_one,sub_mul,one_mul,e,sub_self,sub_zero],
}
lemma mul_mem {a b : A} :
is_idempotent a → is_idempotent b → is_idempotent (a * b) :=
by {
intros ea eb, dsimp[is_idempotent] at *,
rw[pow_two] at *,
rw[mul_assoc,mul_comm b,mul_assoc a,eb,← mul_assoc,ea],
}
lemma add_sub_mul_mem {a b : A} :
is_idempotent a → is_idempotent b → is_idempotent (a + b - a * b) :=
by {
intros ea eb,
have : a + b - a * b = 1 - (1 - a) * (1 - b) := by ring,
rw[this],
apply one_sub_mem, apply mul_mem; apply one_sub_mem; assumption,
}
def invol (a : A) := 1 - 2 * a
lemma invol_square {a : A} (ha : is_idempotent a) :
(invol a) ^ 2 = 1 :=
begin
dsimp[invol,is_idempotent] at ha,
have : (1 - 2 * a) ^ 2 = 1 - 4 * (a - a ^ 2) :=
by {rw[pow_two,pow_two],ring},
rw[ha,sub_self,mul_zero,sub_zero] at this,
exact this,
end
lemma eq_of_sub_nilp {e₀ e₁ : A}
(h₀ : is_idempotent e₀) (h₁ : is_idempotent e₁)
(h : is_nilpotent (e₀ - e₁)) : e₀ = e₁ :=
begin
dsimp[is_idempotent] at h₀ h₁,rw[pow_two] at h₀ h₁,
let x := e₀ - e₁,
let u := 1 - 2 * e₀,
let v := 1 + u * x,
have hv : is_invertible v := one_add_nilp_inv' (is_nilpotent_smul u h),
have hvx := calc
v * x = (e₀ * e₀ - e₀) * (4 * e₁ - 2 * e₀ - 1) +
(e₁ * e₁ - e₁) * (1 - 2 * e₀) :
by {dsimp[v,u,x],ring}
... = 0 : by {rw[h₀,h₁,sub_self,sub_self,zero_mul,zero_mul,zero_add],},
have hx : x = 0 := (is_regular_of_invertible hv) x hvx,
rw[← sub_eq_zero],
exact hx,
end
def lift : ∀ (e : A) (h : nilpotent_witness (e * (1 - e))), A :=
λ e ⟨n,hx⟩, e ^ (n + 2) * geometric_series (1 - e ^ (n + 2) - (1 - e) ^ (n + 2)) n
def lift_spec (e : A) (h : nilpotent_witness (e * (1 - e))) :
pprod (is_idempotent (lift e h)) (nilpotent_witness ((lift e h) - e)) :=
begin
rcases h with ⟨n,hx⟩,
let x := e * (1 - e), change x ^ n = 0 at hx,
let y := 1 - e ^ (n + 2) - (1 - e) ^ (n + 2),
let u := geometric_series y n,
let e₁ := e ^ (n + 2) * u,
have : lift e ⟨n,hx⟩ = e₁ := rfl,
rw[this],
let f := λ (i : ℕ), e ^ i * (1 - e) ^ (n + 2 - i) * nat.choose (n + 2) i,
let z := (finset.range (n + 1)).sum
(λ j, e ^ j * (1 - e) ^ (n - j) * (nat.choose (n + 2) (j + 1))),
let xz := (finset.range (n + 1)).sum (f ∘ nat.succ),
have hxz : x * z = xz := by {
dsimp[xz,x],rw[finset.mul_sum],apply finset.sum_congr rfl,intros i hi,
replace hi : i ≤ n := nat.le_of_lt_succ (finset.mem_range.mp hi),
have : (f ∘ nat.succ) i = f (i + 1) := rfl, rw[this], dsimp[f],
have : n + 2 - (i + 1) = (n - i) + 1 := calc
n + 2 - (i + 1) = n + 1 - i : by {rw[nat.succ_sub_succ]}
... = (i + (n - i)) + 1 - i : by {rw[nat.add_sub_of_le hi]}
... = (n - i) + 1 : by {simp only [add_comm,add_assoc,nat.add_sub_cancel_left],},
rw[this,pow_succ,pow_succ],repeat {rw[mul_assoc]},congr' 1,
repeat {rw[← mul_assoc]},rw[mul_comm (1 - e) (e ^ i)],
},
have hf₀ : f 0 = (1 - e) ^ (n + 2) :=
by {dsimp[f],rw[nat.choose,nat.cast_one,mul_one,pow_zero,one_mul],},
have hf₁ : f (n + 2) = e ^ (n + 2) :=
by {dsimp[f],rw[nat.choose_self,nat.cast_one,nat.sub_self,pow_zero,mul_one,mul_one],},
dsimp[f] at hf₀ hf₁,
have := calc
(1 : A) = (1 : A) ^ (n + 2) : (one_pow (n + 2)).symm
... = (e + (1 - e)) ^ (n + 2) :
by {congr,rw[add_sub,add_comm,add_sub_cancel]}
... = (finset.range (n + 2).succ).sum f : add_pow e (1 - e) (n + 2)
... = e ^ (n + 2) + (finset.range (n + 2)).sum f :
by {rw[finset.sum_range_succ,hf₁,add_comm],}
... = e ^ (n + 2) + (xz + (1 - e) ^ (n + 2)) :
by { congr' 1,rw[finset.sum_range_succ'],
change xz + _ = _,congr' 1}
... = e ^ (n + 2) + (x * z + (1 - e) ^ (n + 2)) : by {rw[hxz]},
have hxyz := calc
y = 1 - e ^ (n + 2) - (1 - e) ^ (n + 2) : rfl
... = (e ^ (n + 2) + (x * z + (1 - e) ^ (n + 2))) - e ^ (n + 2) - (1 - e) ^ (n + 2) :
by {congr' 2}
... = x * z : by {simp only [sub_eq_add_neg,add_comm,add_left_comm,
add_neg_cancel_left,add_neg_cancel_right],},
have hy : y ^ n = 0 := by {rw[hxyz,mul_pow,hx,zero_mul],},
have hu : (1 - y) * u = 1 := by {rw[geometric_sum y n,hy,sub_zero]},
have : 1 - y = e ^ (n + 2) + (1 - e) ^ (n + 2) :=
calc 1 - y = 1 - (1 - e ^ (n + 2) - (1 - e) ^ (n + 2)) : by {simp only [y]}
... = e ^ (n + 2) + (1 - e) ^ (n + 2) : by rw[sub_sub,sub_sub_cancel],
let hu' := hu, rw[this] at hu',
have := calc
1 - e₁ = (e ^ (n + 2) + (1 - e) ^ (n + 2)) * u - e₁ : by {rw[hu'],}
... = e ^ (n + 2) * u + (1 - e) ^ (n + 2) * u - e ^ (n + 2) * u :
by {rw[add_mul],}
... = (1 - e) ^ (n + 2) * u : by {rw[add_comm,add_sub_cancel]},
have := calc
e₁ * (1 - e₁) = (e ^ (n + 2) * u) * (1 - e₁) : rfl
... = u * (e ^ (n + 2) * (1 - e₁)) : by {rw[mul_comm (e ^ (n + 2))],rw[← mul_assoc],}
... = u * (e ^ (n + 2) * (1 - e) ^ (n + 2) * u) : by {rw[this,mul_assoc]}
... = u * (x ^ (n + 2) * u) : by {rw[mul_pow,pow_add],}
... = 0 : by {rw[pow_add,hx,zero_mul,zero_mul,mul_zero],},
split, exact (is_idempotent' e₁).mpr this,
let w := geometric_series e (n + 1),
have hw : x * w = e - e ^ (n + 2) := calc
x * w = e * ((1 - e) * w) : by {dsimp[x],rw[mul_assoc]}
... = e * (1 - e ^ (n + 1)) : by {rw[geometric_sum e (n + 1)],}
... = e - e ^ (n + 2) : by {rw[mul_sub,mul_one,pow_succ e (n + 1)],},
have hu'' : u = 1 + x * z * u := by {
rw[sub_mul,hxyz,one_mul] at hu,rw[← hu,sub_add_cancel],
},
have := calc
e₁ - e = e ^ (n + 2) * u - e : rfl
... = e ^ (n + 2) * (1 + x * z * u) - e : by {congr' 2}
... = (e ^ (n + 2) * (x * z * u) + e ^ (n + 2)) - e :
by {rw[mul_add,mul_one,add_comm],}
... = x * (e ^ (n + 2) * z * u) - (e - e ^ (n + 2)) :
by {rw[← sub_add,sub_eq_add_neg,sub_eq_add_neg],
rw[← mul_assoc,← mul_assoc,mul_comm (e ^ (n + 2))],
repeat {rw[add_assoc]},rw[add_comm (e ^ (n + 2))],
repeat {rw[mul_assoc]},}
... = x * (e ^ (n + 2) * z * u - w) : by {rw[mul_sub,hw],},
have : (e₁ - e) ^ n = 0 := by {rw[this,mul_pow,hx,zero_mul],},
exact ⟨n,this⟩,
end
lemma lift_unique (e e₁ : A)
(h : nilpotent_witness (e * (1 - e))) (hi : is_idempotent e₁)
(hn : is_nilpotent (e₁ - e)) : e₁ = lift e h :=
begin
rcases lift_spec e h with ⟨hi',hn'⟩,
apply eq_of_sub_nilp hi hi',
have : e₁ - lift e h = (e₁ - e) - (lift e h - e) :=
by {rw[sub_sub_sub_cancel_right],},
rw[this],apply is_nilpotent_sub hn ⟨hn'⟩
end
/- -------------------------------------------------------- -/
/- rem-lifting -/
def lift' : ∀ (e : A) (h : nilpotent_witness (e * (1 - e))), A :=
λ e ⟨n,hx⟩,
let x := e * (1 - e) in
let b := (finset.range n).sum (λ k, ((x ^ k) * nat.choose (2 * k + 1) k)) in
e + (2 * e - 1) * b * x
/-
lemma lift_eq (e : A) (h : nilpotent_witness (e * (1 - e))) :
lift' e h = lift e h := sorry
-/
end idempotent
/- -------------------------------------------------------- -/
/- prop-poly-el-props -/
namespace poly_el_props
open polynomial
variables [decidable_eq A] (p : polynomial A)
lemma leading_mul {p q : polynomial A} {n m : ℕ}
(hp : ∀ i, i > n → p.coeff i = 0) (hq : ∀ j, j > m → q.coeff j = 0) :
(∀ k, k > n + m → (p * q).coeff k = 0) ∧
(p * q).coeff (n + m) = (p.coeff n) * (q.coeff m) :=
begin
split,
{ intros k hk,
rw[coeff_mul], apply finset.sum_eq_zero,
rintro ⟨i,j⟩ hij,
replace hij : i + j = k := finset.nat.mem_antidiagonal.mp hij,
change p.coeff i * q.coeff j = 0,
by_cases hi : i > n,
{ rw[hp i hi, zero_mul] },
{ replace hi : i ≤ n := le_of_not_gt hi,
have hj : j > m := begin
apply lt_of_not_ge, intro hj',
have := lt_of_le_of_lt (add_le_add hi hj') hk,
rw[hij] at this, exact lt_irrefl k this,
end,
rw[hq j hj, mul_zero],
}
},{
rw[coeff_mul],
let nm : ℕ × ℕ := ⟨n,m⟩,
have hnm : nm ∈ finset.nat.antidiagonal (n + m) :=
finset.nat.mem_antidiagonal.mpr rfl,
have h_single : ∀ (x : ℕ × ℕ) (hx₀ : x ∈ finset.nat.antidiagonal (n + m))
(hx₁ : x ≠ nm), (p.coeff x.1) * (q.coeff x.2) = 0 :=
begin
intros,
replace hx₁ : x.1 ≠ n := λ e, hx₁ ((finset.nat.antidiagonal_congr hx₀ hnm).mpr e),
replace hx₀ : x.1 + x.2 = n + m := finset.nat.mem_antidiagonal.mp hx₀,
by_cases hx₂ : x.1 ≥ n,
{ rw[hp x.1 (lt_of_le_of_ne hx₂ hx₁.symm), zero_mul] },
{ have : x.2 > m := lt_of_not_ge (λ hk, by {
have := add_lt_add_of_lt_of_le (lt_of_not_ge hx₂) hk,
rw[hx₀] at this, exact lt_irrefl (n + m) this
}),
rw[hq x.2 this, mul_zero]
}
end,
rw[finset.sum_eq_single_of_mem nm hnm h_single]
}
end
lemma trailing_mul {p q : polynomial A} {n m : ℕ}
(hp : ∀ i, i < n → p.coeff i = 0) (hq : ∀ j, j < m → q.coeff j = 0) :
(∀ k, k < n + m → (p * q).coeff k = 0) ∧
(p * q).coeff (n + m) = (p.coeff n) * (q.coeff m) :=
begin
split,
{ intros k hk,
rw[coeff_mul], apply finset.sum_eq_zero,
rintro ⟨i,j⟩ hij,
replace hij : i + j = k := finset.nat.mem_antidiagonal.mp hij,
change p.coeff i * q.coeff j = 0,
by_cases hi : i < n,
{ rw[hp i hi, zero_mul] },
{ replace hi : n ≤ i := le_of_not_gt hi,
have hj : j < m := begin
apply lt_of_not_ge, intro hj',
have := lt_of_lt_of_le hk (add_le_add hi hj'),
rw[hij] at this, exact lt_irrefl k this,
end,
rw[hq j hj, mul_zero],
}
},{
rw[coeff_mul],
let nm : ℕ × ℕ := ⟨n,m⟩,
have hnm : nm ∈ finset.nat.antidiagonal (n + m) :=
finset.nat.mem_antidiagonal.mpr rfl,
have h_single : ∀ (x : ℕ × ℕ) (hx₀ : x ∈ finset.nat.antidiagonal (n + m))
(hx₁ : x ≠ nm), (p.coeff x.1) * (q.coeff x.2) = 0 :=
begin
intros,
replace hx₁ : x.1 ≠ n := λ e, hx₁ ((finset.nat.antidiagonal_congr hx₀ hnm).mpr e),
replace hx₀ : x.1 + x.2 = n + m := finset.nat.mem_antidiagonal.mp hx₀,
by_cases hx₂ : x.1 ≤ n,
{ rw[hp x.1 (lt_of_le_of_ne hx₂ hx₁), zero_mul] },
{ have : x.2 < m := lt_of_not_ge (λ hk, by {
have := add_lt_add_of_lt_of_le (lt_of_not_ge hx₂) hk,
rw[hx₀] at this, exact lt_irrefl (n + m) this
}),
rw[hq x.2 this, mul_zero]
}
end,
rw[finset.sum_eq_single_of_mem nm hnm h_single]
}
end
lemma nat_degree_spec (p : polynomial A) :
(∀ (i : ℕ), i > p.nat_degree → p.coeff i = 0) ∧
(p = 0 ∨ p.coeff p.nat_degree ≠ 0) :=
begin
by_cases hp : p = 0,
{ split,
{ intros i hi, rw[hp, coeff_zero], },
{ left, exact hp }
},
{ split,
{ intros i hi,
by_cases hc : p.coeff i = 0, { assumption },
exfalso,
exact lt_irrefl i (lt_of_le_of_lt (le_nat_degree_of_ne_zero hc) hi)
},
{ exact or.inr (leading_coeff_ne_zero.mpr hp) }
}
end
noncomputable def div_X_aux : ℕ → polynomial A
| 0 := 0
| (n + 1) := monomial n 1
noncomputable def div_X (f : polynomial A) : polynomial A :=
div_by_monic f X
lemma div_X_prop (f : polynomial A) : f = C (coeff f 0) + X * (div_X f) :=
begin
have := mod_by_monic_X_sub_C_eq_C_eval f 0,
rw[C.map_zero,sub_zero,← coeff_zero_eq_eval_zero] at this,
rw[← this], symmetry,
exact mod_by_monic_add_div f monic_X
end
lemma div_X_deg {f : polynomial A} {n : ℕ} (h : f.nat_degree ≤ n.succ) :
(div_X f).nat_degree ≤ n :=
begin
nontriviality A,
have := nat_degree_div_by_monic f monic_X,
rw[nat_degree_X] at this,
change (div_X f).nat_degree = f.nat_degree.pred at this,
rw[this],
exact nat.pred_le_iff.mpr h
end
example (a b c d : ℕ) (h1 : a ≤ b) (h2 : c < d) : a + c < b + d := by library_search
lemma is_regular_bot (n : ℕ)
(h₀ : ∀ i, i < n → coeff p i = 0) (h₁ : is_regular (coeff p n)) :
is_regular p :=
begin
intros q hpq,
ext k, rw[coeff_zero],
induction k using nat.strong_induction_on with k ih,
change ∀ (m : ℕ), m < k → q.coeff m = 0 at ih,
have := (trailing_mul h₀ ih).2,
rw[hpq, coeff_zero] at this,
exact h₁ (q.coeff k) this.symm
end
lemma is_regular_top (h : is_regular (leading_coeff p)) : is_regular p :=
begin
intros q hpq,
by_cases hq : q = 0, {assumption}, exfalso,
have hq' := leading_coeff_ne_zero.mpr hq,
have hpq' : p.leading_coeff * q.leading_coeff ≠ 0 := begin
intro e,
exact hq' (h q.leading_coeff e),
end,
have hpq'' := leading_coeff_mul' hpq',
rw[← hpq'', hpq, leading_coeff_zero] at hpq',
exact hpq' rfl,
end
lemma is_nilpotent_iff :
is_nilpotent p ↔ (∀ n, is_nilpotent (coeff p n)) :=
begin
let ev : polynomial A →+* A := eval_ring_hom 0,
have h₀ : ∀ (q : polynomial A), is_nilpotent q → is_nilpotent (q.coeff 0) :=
by { intros q hq, rw[coeff_zero_eq_eval_zero], exact is_nilpotent_hom ev hq},
have h₁ : ∀ (a : A), is_nilpotent a ↔ is_nilpotent (C a) := λ a, by {
split; intro h, { exact is_nilpotent_hom C h },
{ have := h₀ (C a) h, rw[coeff_C_zero] at this, exact this }
},
have h₂ : ∀ (d : ℕ) (q : polynomial A) (hq : q.nat_degree ≤ d),
is_nilpotent q ↔ (∀ n, is_nilpotent (coeff q n)) :=
begin
intro d, induction d with d hd; intros q hq;
have hq' := nat_degree_le_iff_coeff_eq_zero.mp hq,
{ let c := q.coeff 0,
have hc : q = C c := by {
ext, cases n,
{ rw[coeff_C_zero] },
{ rw[hq' n.succ,coeff_C,if_neg (n.succ_ne_zero)], exact n.zero_lt_succ }
},
split,
{ intros h n, rw[hc, ← h₁] at h, cases n,
{ exact h },
{ rw[hq' n.succ n.succ_pos], exact is_nilpotent_zero }
},
{ intro h, replace h := h 0, change is_nilpotent c at h,
rw[hc, ← h₁ c], exact h
}
},
{ let r := div_X q,
let c := q.coeff 0,
have hrc : q = (C c) + X * r := div_X_prop q,
have hr : r.nat_degree ≤ d := div_X_deg hq,
have hr' := nat_degree_le_iff_coeff_eq_zero.mp hr,
have hrq : ∀ (n : ℕ), r.coeff n = q.coeff n.succ :=
λ n, by
rw[hrc,coeff_add,coeff_C_ne_zero n.succ_ne_zero,zero_add,coeff_X_mul],
split,
{ intros hnq n, cases n,
{ exact h₀ q hnq },
{ rw[← hrq n],
have : is_nilpotent (C c) := is_nilpotent_hom C (h₀ q hnq),
have := is_nilpotent_sub hnq this,
rw[hrc, add_comm, add_sub_cancel] at this,
rcases this with ⟨m,hm⟩,
rw[mul_pow] at hm,
have hnr : is_nilpotent r :=
by { use m, exact (monic_X_pow m).mul_right_eq_zero_iff.mp hm},
exact (hd r hr).mp hnr n,
}
},{
intro hnq,
rw[hrc],
have hnc : is_nilpotent (C c) := is_nilpotent_hom C (hnq 0),
have hnr : is_nilpotent r := (hd r hr).mpr (λ n, by { rw[hrq n], exact hnq n.succ, }),
exact is_nilpotent_add hnc (is_nilpotent_smul X hnr),
}
}
end,
exact h₂ p.nat_degree p (le_refl _),
end
/-
lemma is_invertible_iff :
is_invertible p ↔
(is_invertible (coeff p 0)) ∧ (∀ n : ℕ, (is_nilpotent (coeff p n.succ))) :=
sorry
-/
lemma is_idempotent_aux {p : polynomial A} (h₀ : p.coeff 0 = 0) (h₁ : is_idempotent p) : p = 0 :=
begin
replace h₁ := idempotent.mul_self h₁,
ext n, rw[coeff_zero],
induction n using nat.strong_induction_on with n ih,
cases n,
{ exact h₀ },
{ rw[← h₁, coeff_mul],
apply finset.sum_eq_zero,
rintro ⟨i,j⟩ hij,
replace hij : i + j = n.succ := finset.nat.mem_antidiagonal.mp hij,
change p.coeff i * p.coeff j = 0,
cases j,
{ rw[h₀, mul_zero] },
{ replace hij : i + j = n := nat.succ_inj'.mp hij,
have : i < (i + j).succ := lt_of_le_of_lt le_self_add (i + j).lt_succ_self,
rw[hij] at this,
rw[ih i this, zero_mul]
}
}
end
lemma is_idempotent_iff :
is_idempotent p ↔
(is_idempotent (coeff p 0)) ∧ (p = C (p.coeff 0)) :=
begin
split,
{ let e := coeff p 0,
intro hp,
have he : is_idempotent (eval 0 p) :=
is_idempotent_hom (eval_ring_hom (0 : A)) hp,
rw [← coeff_zero_eq_eval_zero p] at he,
change is_idempotent e at he,
let q := (C (1 - e)) * p,
have hq : is_idempotent q :=
idempotent.mul_mem (is_idempotent_hom C (idempotent.one_sub_mem he)) hp,
have hqc : coeff q 0 = 0 := begin
dsimp[q], rw[coeff_zero_eq_eval_zero, eval_C_mul, mul_comm, ← coeff_zero_eq_eval_zero],
exact (is_idempotent' e).mp he,
end,
have hqz : q = 0 := is_idempotent_aux hqc hq,
dsimp[q] at hqz,
rw[ring_hom.map_sub, ring_hom.map_one, sub_mul, one_mul] at hqz,
replace hqz := eq_of_sub_eq_zero hqz,
let r := (C e) - p,
have hr : is_idempotent r := begin
change r ^ 2 = r,
dsimp[r],
rw[pow_two, mul_sub, sub_mul, sub_mul, mul_comm p],
rw[← hqz, idempotent.mul_self hp, sub_self, sub_zero],
rw[← ring_hom.map_mul, idempotent.mul_self he],
end,
have hr' : r.coeff 0 = 0 := by rw[coeff_sub, coeff_C_zero, sub_self],
exact ⟨he,(eq_of_sub_eq_zero (is_idempotent_aux hr' hr)).symm⟩,
},
{ rintro ⟨h₀,h₁⟩,
rw[h₁],
exact is_idempotent_hom C h₀,
}
end
end poly_el_props
/- -------------------------------------------------------- -/
/- prop-idempotent-splitting -/
namespace idempotent
variables {e : A} (he : is_idempotent e)
include he
def axis := {b : A // b * e = b}
namespace axis
def mk (b : A) (hb : b * e = b) : axis he := ⟨b,hb⟩
instance : has_zero (axis he) := ⟨⟨(0 : A),zero_mul e⟩⟩
instance : has_one (axis he) := ⟨⟨e,by {rw[← pow_two],exact he}⟩⟩
instance : has_neg (axis he) :=
⟨λ b, axis.mk he (- b.val) (by {rw[← neg_mul_eq_neg_mul,b.property]})⟩
instance : has_add (axis he) :=
⟨λ b₁ b₂, axis.mk he (b₁.val + b₂.val) (by {rw[add_mul,b₁.property,b₂.property]})⟩
instance : has_mul (axis he) :=
⟨λ b₁ b₂, axis.mk he (b₁.val * b₂.val) (by {rw[mul_assoc,b₂.property]})⟩
@[simp] lemma val_zero : (0 : axis he).val = 0 := rfl
@[simp] lemma val_one : (1 : axis he).val = e := rfl
@[simp] lemma val_neg (b : axis he) : (- b).val = - (b.val) := rfl
@[simp] lemma val_add (b₁ b₂ : axis he) : (b₁ + b₂).val = b₁.val + b₂.val := rfl
@[simp] lemma val_mul (b₁ b₂ : axis he) : (b₁ * b₂).val = b₁.val * b₂.val := rfl
instance : comm_ring (axis he) := {
zero := has_zero.zero,
one := has_one.one,
mul := has_mul.mul,
add := has_add.add,
neg := has_neg.neg,
zero_add := λ a, subtype.eq $ by {rw[val_add,val_zero,zero_add]},
add_zero := λ a, subtype.eq $ by {rw[val_add,val_zero,add_zero]},
add_left_neg := λ a, subtype.eq $ by {rw[val_add,val_neg,add_left_neg,val_zero]},
add_comm := λ a b, subtype.eq $ by {rw[val_add,val_add,add_comm]},
add_assoc := λ a b c, subtype.eq $ by {repeat {rw[val_add]},apply add_assoc},
one_mul := λ a, subtype.eq $ by {rw[val_mul,val_one,mul_comm,a.property]},
mul_one := λ a, subtype.eq $ by {rw[val_mul,val_one,a.property]},
mul_comm := λ a b, subtype.eq $ by {rw[val_mul,val_mul,mul_comm]},
mul_assoc := λ a b c, subtype.eq $ by {repeat {rw[val_mul]},apply mul_assoc},
left_distrib := λ a b c, subtype.eq $ by {rw[val_mul,val_add,val_add,val_mul,val_mul,left_distrib]},
right_distrib := λ a b c, subtype.eq $ by {rw[val_mul,val_add,val_add,val_mul,val_mul,right_distrib]},
}
def proj : A →+* axis he := {
to_fun := λ a, ⟨a * e,by {dsimp[is_idempotent] at he, rw[mul_assoc,← pow_two,he]}⟩,
map_zero' := subtype.eq $ by { change 0 * e = 0, rw[zero_mul] },
map_add' := λ a b, by { apply subtype.eq,
change (a + b) * e = a * e + b * e,
rw[add_mul]},
map_one' := subtype.eq $ by { change 1 * e = e, rw[one_mul] },
map_mul' := λ a b, by { dsimp[is_idempotent] at he, rw[pow_two] at he,
apply subtype.eq,
change (a * b) * e = (a * e) * (b * e),
rw[mul_assoc a e,← mul_assoc e b e,mul_comm e b,
mul_assoc b e,he,mul_assoc]}
}
def split : A →+* (axis he) × (axis (one_sub_mem he)) := {
to_fun := λ a, ⟨(proj he a),(proj (one_sub_mem he) a)⟩,
map_zero' := by { ext1, exact (proj _).map_zero, exact (proj _).map_zero},
map_one' := by { ext1, exact (proj _).map_one, exact (proj _).map_one},
map_add' := λ a b, by { ext1, exact (proj _).map_add _ _, exact (proj _).map_add _ _},
map_mul' := λ a b, by { ext1, exact (proj _).map_mul _ _, exact (proj _).map_mul _ _}
}
lemma mul_eq_zero (b : axis he) (c : axis (one_sub_mem he)) :
b.val * c.val = 0 := by {
rcases b with ⟨b,hb⟩,
rcases c with ⟨c,hc⟩,
change b * c = 0,
exact calc
b * c = (b * e) * (c * (1 - e)) : by rw[hb,hc]
... = b * (e * (1 - e)) * c : by {rw[mul_comm c,mul_assoc,mul_assoc,mul_assoc]}
... = 0 : by {rw[(is_idempotent' e).mp he,mul_zero,zero_mul]}
}
def combine : (axis he) × (axis (one_sub_mem he)) →+* A := {
to_fun := λ bc, bc.1.val + bc.2.val,
map_zero' := zero_add _,
map_one' := by {change e + (1 - e) = 1,rw[add_sub_cancel'_right]},
map_add' := λ bc₁ bc₂, by {
rcases bc₁ with ⟨⟨b₁,hb₁⟩,⟨c₁,hc₁⟩⟩,
rcases bc₂ with ⟨⟨b₂,hb₂⟩,⟨c₂,hc₂⟩⟩,
change (b₁ + b₂) + (c₁ + c₂) = (b₁ + c₁) + (b₂ + c₂),
rw[add_assoc,← add_assoc b₂,add_comm b₂ c₁,add_assoc,add_assoc],
},
map_mul' := λ bc₁ bc₂, by {
rcases bc₁ with ⟨⟨b₁,hb₁⟩,⟨c₁,hc₁⟩⟩,
rcases bc₂ with ⟨⟨b₂,hb₂⟩,⟨c₂,hc₂⟩⟩,
change (b₁ * b₂) + (c₁ * c₂) = (b₁ + c₁) * (b₂ + c₂),
have ebc : b₁ * c₂ = 0 := mul_eq_zero he ⟨b₁,hb₁⟩ ⟨c₂,hc₂⟩,
have ecb : b₂ * c₁ = 0 := mul_eq_zero he ⟨b₂,hb₂⟩ ⟨c₁,hc₁⟩,
rw[mul_comm] at ecb,
rw[mul_add,add_mul,add_mul,ebc,ecb,zero_add,add_zero],
}
}
lemma combine_split (a : A) : combine he (split he a) = a :=
by { change a * e + a * (1 - e) = a,
rw[mul_sub,mul_one,add_sub_cancel'_right]}
lemma split_combine (bc : (axis he) × (axis (one_sub_mem he))) :
split he (combine he bc) = bc :=
by {
have he' : e * (1 - e) = 0 := (is_idempotent' e).mp he,
rcases bc with ⟨⟨b,hb⟩,⟨c,hc⟩⟩,
ext1; apply subtype.eq,
{change (b + c) * e = b,
rw[← hc,add_mul,hb,mul_assoc,mul_comm (1 - e),he',mul_zero,add_zero],},
{change (b + c) * (1 - e) = c,
rw[← hb,add_mul,hc,mul_assoc,he',mul_zero,zero_add],}
}
end axis
end idempotent
end sec_elements |
54db9134b2828128630507aaeb53d231bd18cfa5 | b2fe74b11b57d362c13326bc5651244f111fa6f4 | /src/analysis/normed_space/inner_product.lean | feceecd1f0f11d0c109867a3ff8de36a9b0f74ad | [
"Apache-2.0"
] | permissive | midfield/mathlib | c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7 | 775edc615ecec631d65b6180dbcc7bc26c3abc26 | refs/heads/master | 1,675,330,551,921 | 1,608,304,514,000 | 1,608,304,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 81,248 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis
-/
import linear_algebra.bilinear_form
import linear_algebra.sesquilinear_form
import analysis.special_functions.pow
import topology.metric_space.pi_Lp
import data.complex.is_R_or_C
/-!
# Inner Product Space
This file defines inner product spaces and proves its basic properties.
An inner product space is a vector space endowed with an inner product. It generalizes the notion of
dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between
two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero.
We define both the real and complex cases at the same time using the `is_R_or_C` typeclass.
## Main results
- We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic
properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ`
or `ℂ`, through the `is_R_or_C` typeclass.
- We show that if `f i` is an inner product space for each `i`, then so is `Π i, f i`
- We define `euclidean_space 𝕜 n` to be `n → 𝕜` for any `fintype n`, and show that
this an inner product space.
- Existence of orthogonal projection onto nonempty complete subspace:
Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace.
Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`.
The point `v` is usually called the orthogonal projection of `u` onto `K`.
## Notation
We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively.
We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`,
which respectively introduce the plain notation `⟪·, ·⟫` for the the real and complex inner product.
## Implementation notes
We choose the convention that inner products are conjugate linear in the first argument and linear
in the second.
## TODO
- Fix the section on the existence of minimizers and orthogonal projections to make sure that it
also applies in the complex case.
## Tags
inner product space, norm
## References
* [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*]
* [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*]
The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html>
-/
noncomputable theory
open is_R_or_C real
open_locale big_operators classical
variables {𝕜 E F : Type*} [is_R_or_C 𝕜]
/-- Syntactic typeclass for types endowed with an inner product -/
class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜)
export has_inner (inner)
notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y
notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y
section notations
localized "notation `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space
localized "notation `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space
end notations
/--
An inner product space is a vector space with an additional operation called inner product.
The norm could be derived from the inner product, instead we require the existence of a norm and
the fact that `∥x∥^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product
spaces.
To construct a norm from an inner product, see `inner_product_space.of_core`.
-/
class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜]
extends normed_group E, normed_space 𝕜 E, has_inner 𝕜 E :=
(norm_sq_eq_inner : ∀ (x : E), ∥x∥^2 = re (inner x x))
(conj_sym : ∀ x y, conj (inner y x) = inner x y)
(nonneg_im : ∀ x, im (inner x x) = 0)
(add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z)
(smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y)
/- This instance generates the type-class problem `inner_product_space ?m E` when looking for
`normed_group E`. However, since `?m` can only ever be `ℝ` or `ℂ`, this should not cause
problems. -/
attribute [nolint dangerous_instance] inner_product_space.to_normed_group
/-!
### Constructing a normed space structure from an inner product
In the definition of an inner product space, we require the existence of a norm, which is equal
(but maybe not defeq) to the square root of the scalar product. This makes it possible to put
an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good
properties. However, sometimes, one would like to define the norm starting only from a well-behaved
scalar product. This is what we implement in this paragraph, starting from a structure
`inner_product_space.core` stating that we have a nice scalar product.
Our goal here is not to develop a whole theory with all the supporting API, as this will be done
below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as
possible to the construction of the norm and the proof of the triangular inequality.
Warning: Do not use this `core` structure if the space you are interested in already has a norm
instance defined on it, otherwise this will create a second non-defeq norm instance!
-/
/-- A structure requiring that a scalar product is positive definite and symmetric, from which one
can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/
@[nolint has_inhabited_instance]
structure inner_product_space.core
(𝕜 : Type*) (F : Type*)
[is_R_or_C 𝕜] [add_comm_group F] [semimodule 𝕜 F] :=
(inner : F → F → 𝕜)
(conj_sym : ∀ x y, conj (inner y x) = inner x y)
(nonneg_im : ∀ x, im (inner x x) = 0)
(nonneg_re : ∀ x, 0 ≤ re (inner x x))
(definite : ∀ x, inner x x = 0 → x = 0)
(add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z)
(smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y)
/- We set `inner_product_space.core` to be a class as we will use it as such in the construction
of the normed space structure that it produces. However, all the instances we will use will be
local to this proof. -/
attribute [class] inner_product_space.core
namespace inner_product_space.of_core
variables [add_comm_group F] [semimodule 𝕜 F] [c : inner_product_space.core 𝕜 F]
include c
local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y
local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _
local notation `reK` := @is_R_or_C.re 𝕜 _
local notation `absK` := @is_R_or_C.abs 𝕜 _
local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _
local postfix `†`:90 := @is_R_or_C.conj 𝕜 _
/-- Inner product defined by the `inner_product_space.core` structure. -/
def to_has_inner : has_inner 𝕜 F := { inner := c.inner }
local attribute [instance] to_has_inner
/-- The norm squared function for `inner_product_space.core` structure. -/
def norm_sq (x : F) := reK ⟪x, x⟫
local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _
lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y
lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _
lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 := c.nonneg_im _
lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 := c.nonneg_im _
lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ :=
c.add_left _ _ _
lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ :=
by rw [←inner_conj_sym, inner_add_left, ring_hom.map_add]; simp only [inner_conj_sym]
lemma inner_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ :=
begin
rw ext_iff,
exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩
end
lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ :=
by rw [←inner_conj_sym, conj_re]
lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ :=
by rw [←inner_conj_sym, conj_im]
lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ :=
c.smul_left _ _ _
lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ :=
by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_hom.map_mul]
lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 :=
by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_hom.map_zero]
lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 :=
by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_hom.map_zero]
lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 :=
iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left })
lemma inner_self_re_to_K {x : F} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ :=
by norm_num [ext_iff, inner_self_nonneg_im]
lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ :=
by rw [←inner_conj_sym, abs_conj]
lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ :=
by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp }
lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ :=
by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym]
lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ :=
by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] }
lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ :=
by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] }
lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) :=
by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), }
/-- Expand `inner (x + y) (x + y)` -/
lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ :=
by simp only [inner_add_left, inner_add_right]; ring
/- Expand `inner (x - y) (x - y)` -/
lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ :=
by simp only [inner_sub_left, inner_sub_right]; ring
/--
Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia.
We need this for the `core` structure to prove the triangle inequality below when
showing the core is a normed group.
-/
lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ :=
begin
by_cases hy : y = 0,
{ rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] },
{ change y ≠ 0 at hy,
have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h,
set T := ⟪y, x⟫ / ⟪y, y⟫ with hT,
have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm,
have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm,
have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫,
{ rw [mul_div_assoc],
have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ :=
by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul],
rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] },
have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp only [inner_self_re_to_K],
have h₅ : re ⟪y, y⟫ > 0,
{ refine lt_of_le_of_ne inner_self_nonneg _,
intro H,
apply hy',
rw ext_iff,
exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ },
have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅,
have hmain := calc
0 ≤ re ⟪x - T • y, x - T • y⟫
: inner_self_nonneg
... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫
: by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂]
... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫)
: by simp [inner_smul_left, inner_smul_right, mul_assoc]
... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫)
: by field_simp [-mul_re, inner_conj_sym, hT, conj_div, h₁, h₃]
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫)
: by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc]
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫)
: by conv_lhs { rw [h₄] }
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫
: by rw [div_re_of_real]
... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫
: by rw [inner_mul_conj_re_abs]
... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫
: by rw is_R_or_C.abs_mul,
have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith,
have := (mul_le_mul_right h₅).mpr hmain',
rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this }
end
/-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root
of the scalar product. -/
def to_has_norm : has_norm F :=
{ norm := λ x, sqrt (re ⟪x, x⟫) }
local attribute [instance] to_has_norm
lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (re ⟪x, x⟫) := rfl
lemma inner_self_eq_norm_square (x : F) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ :=
by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫),
sqrt_mul_self inner_self_nonneg]
lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ∥x∥ := rfl
/-- Cauchy–Schwarz inequality with norm -/
lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ :=
nonneg_le_nonneg_of_squares_le (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _))
begin
have H : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = re ⟪y, y⟫ * re ⟪x, x⟫,
{ simp only [inner_self_eq_norm_square], ring, },
rw H,
conv
begin
to_lhs, congr, rw[inner_abs_conj_sym],
end,
exact inner_mul_inner_self_le y x,
end
/-- Normed group structure constructed from an `inner_product_space.core` structure -/
def to_normed_group : normed_group F :=
normed_group.of_core F
{ norm_eq_zero_iff := assume x,
begin
split,
{ intro H,
change sqrt (re ⟪x, x⟫) = 0 at H,
rw [sqrt_eq_zero inner_self_nonneg] at H,
apply (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).mp,
rw ext_iff,
exact ⟨by simp [H], by simp [inner_self_im_zero]⟩ },
{ rintro rfl,
change sqrt (re ⟪0, 0⟫) = 0,
simp only [sqrt_zero, inner_zero_right, add_monoid_hom.map_zero] }
end,
triangle := assume x y,
begin
have h₁ : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := abs_inner_le_norm _ _,
have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _,
have h₃ : re ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := by linarith,
have h₄ : re ⟪y, x⟫ ≤ ∥x∥ * ∥y∥ := by rwa [←inner_conj_sym, conj_re],
have : ∥x + y∥ * ∥x + y∥ ≤ (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥),
{ simp [←inner_self_eq_norm_square, inner_add_add_self, add_mul, mul_add, mul_comm],
linarith },
exact nonneg_le_nonneg_of_squares_le (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this
end,
norm_neg := λ x, by simp only [norm, inner_neg_left, neg_neg, inner_neg_right] }
local attribute [instance] to_normed_group
/-- Normed space structure constructed from a `inner_product_space.core` structure -/
def to_normed_space : normed_space 𝕜 F :=
{ norm_smul_le := assume r x,
begin
rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc],
rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self, of_real_re],
{ simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] },
{ exact norm_sq_nonneg r }
end }
end inner_product_space.of_core
/-- Given a `inner_product_space.core` structure on a space, one can use it to turn
the space into an inner product space, constructing the norm out of the inner product -/
def inner_product_space.of_core [add_comm_group F] [semimodule 𝕜 F]
(c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F :=
begin
letI : normed_group F := @inner_product_space.of_core.to_normed_group 𝕜 F _ _ _ c,
letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c,
exact { norm_sq_eq_inner := λ x,
begin
have h₁ : ∥x∥^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl,
have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg,
simp [h₁, sqr_sqrt, h₂],
end,
..c }
end
/-! ### Properties of inner product spaces -/
variables [inner_product_space 𝕜 E] [inner_product_space ℝ F]
local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y
local notation `IK` := @is_R_or_C.I 𝕜 _
local notation `absR` := _root_.abs
local notation `absK` := @is_R_or_C.abs 𝕜 _
local postfix `†`:90 := @is_R_or_C.conj 𝕜 _
local postfix `⋆`:90 := complex.conj
export inner_product_space (norm_sq_eq_inner)
section basic_properties
lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _
lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := inner_conj_sym x y
lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 :=
⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩
lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 := inner_product_space.nonneg_im _
lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_product_space.nonneg_im _
lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ :=
inner_product_space.add_left _ _ _
lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ :=
begin
rw [←inner_conj_sym, inner_add_left, ring_hom.map_add],
conv_rhs { rw ←inner_conj_sym, conv { congr, skip, rw ←inner_conj_sym } }
end
lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ :=
by rw [←inner_conj_sym, conj_re]
lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ :=
by rw [←inner_conj_sym, conj_im]
lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ :=
inner_product_space.smul_left _ _ _
lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left
lemma inner_smul_real_left {x y : E} {r : ℝ} : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ :=
by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl }
lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ :=
by rw [←inner_conj_sym, inner_smul_left, ring_hom.map_mul, conj_conj, inner_conj_sym]
lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right
lemma inner_smul_real_right {x y : E} {r : ℝ} : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ :=
by { rw [inner_smul_right, algebra.smul_def], refl }
/-- The inner product as a sesquilinear form. -/
def sesq_form_of_inner : sesq_form 𝕜 E (conj_to_ring_equiv 𝕜) :=
{ sesq := λ x y, ⟪y, x⟫, -- Note that sesquilinear forms are linear in the first argument
sesq_add_left := λ x y z, inner_add_right,
sesq_add_right := λ x y z, inner_add_left,
sesq_smul_left := λ r x y, inner_smul_right,
sesq_smul_right := λ r x y, inner_smul_left }
/-- The real inner product as a bilinear form. -/
def bilin_form_of_real_inner : bilin_form ℝ F :=
{ bilin := inner,
bilin_add_left := λ x y z, inner_add_left,
bilin_smul_left := λ a x y, inner_smul_left,
bilin_add_right := λ x y z, inner_add_right,
bilin_smul_right := λ a x y, inner_smul_right }
/-- An inner product with a sum on the left. -/
lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) :
⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ :=
sesq_form.map_sum_right (sesq_form_of_inner) _ _ _
/-- An inner product with a sum on the right. -/
lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) :
⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ :=
sesq_form.map_sum_left (sesq_form_of_inner) _ _ _
@[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 :=
by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_hom.map_zero, zero_mul]
lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 :=
by simp only [inner_zero_left, add_monoid_hom.map_zero]
@[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 :=
by rw [←inner_conj_sym, inner_zero_left, ring_hom.map_zero]
lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 :=
by simp only [inner_zero_right, add_monoid_hom.map_zero]
lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ :=
by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2
lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x
@[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 :=
begin
split,
{ intro h,
have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp [h.1],
rw [←norm_sq_eq_inner x] at h₁,
rw [←norm_eq_zero],
exact pow_eq_zero h₁ },
{ rintro rfl,
exact inner_zero_left }
end
@[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 :=
begin
split,
{ intro h,
rw ←inner_self_eq_zero,
have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg,
have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁,
rw is_R_or_C.ext_iff,
exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ },
{ rintro rfl,
simp only [inner_zero_left, add_monoid_hom.map_zero] }
end
lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 :=
by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h }
@[simp] lemma inner_self_re_to_K {x : E} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ :=
by rw is_R_or_C.ext_iff; exact ⟨by simp, by simp [inner_self_nonneg_im]⟩
lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ :=
begin
have H : ⟪x, x⟫ = (re ⟪x, x⟫ : 𝕜) + im ⟪x, x⟫ * I,
{ rw re_add_im, },
rw [H, is_add_hom.map_add re ((re ⟪x, x⟫) : 𝕜) (((im ⟪x, x⟫) : 𝕜) * I)],
rw [mul_re, I_re, mul_zero, I_im, zero_sub, tactic.ring.add_neg_eq_sub],
rw [of_real_re, of_real_im, sub_zero, inner_self_nonneg_im],
simp only [abs_of_real, add_zero, of_real_zero, zero_mul],
exact (_root_.abs_of_nonneg inner_self_nonneg).symm,
end
lemma inner_self_abs_to_K {x : E} : (absK ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ :=
by { rw[←inner_self_re_abs], exact inner_self_re_to_K }
lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ :=
by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h }
lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ :=
by rw [←inner_conj_sym, abs_conj]
@[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ :=
by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp }
@[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ :=
by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym]
lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp
@[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ :=
by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩
lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ :=
by { simp [sub_eq_add_neg, inner_add_left] }
lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ :=
by { simp [sub_eq_add_neg, inner_add_right] }
lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) :=
by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), }
/-- Expand `⟪x + y, x + y⟫` -/
lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ :=
by simp only [inner_add_left, inner_add_right]; ring
/-- Expand `⟪x + y, x + y⟫_ℝ` -/
lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ :=
begin
have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl,
simp [inner_add_add_self, this],
ring,
end
/- Expand `⟪x - y, x - y⟫` -/
lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ :=
by simp only [inner_sub_left, inner_sub_right]; ring
/-- Expand `⟪x - y, x - y⟫_ℝ` -/
lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ :=
begin
have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl,
simp [inner_sub_sub_self, this],
ring,
end
/-- Parallelogram law -/
lemma parallelogram_law {x y : E} :
⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) :=
by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm]
/-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/
lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ :=
begin
by_cases hy : y = 0,
{ rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] },
{ change y ≠ 0 at hy,
have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h,
set T := ⟪y, x⟫ / ⟪y, y⟫ with hT,
have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm,
have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm,
have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫,
{ rw [mul_div_assoc],
have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ :=
by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul],
rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] },
have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp,
have h₅ : re ⟪y, y⟫ > 0,
{ refine lt_of_le_of_ne inner_self_nonneg _,
intro H,
apply hy',
rw is_R_or_C.ext_iff,
exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ },
have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅,
have hmain := calc
0 ≤ re ⟪x - T • y, x - T • y⟫
: inner_self_nonneg
... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫
: by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂]
... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫)
: by simp [inner_smul_left, inner_smul_right, mul_assoc]
... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫)
: by field_simp [-mul_re, hT, conj_div, h₁, h₃, inner_conj_sym]
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫)
: by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc]
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫)
: by conv_lhs { rw [h₄] }
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫
: by rw [div_re_of_real]
... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫
: by rw [inner_mul_conj_re_abs]
... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫
: by rw is_R_or_C.abs_mul,
have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith,
have := (mul_le_mul_right h₅).mpr hmain',
rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this }
end
/-- Cauchy–Schwarz inequality for real inner products. -/
lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ :=
begin
have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl,
have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y,
dsimp at h₂,
have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ,
rw [h₁] at h₂,
simpa [h₃] using h₂,
end
/-- A family of vectors is linearly independent if they are nonzero
and orthogonal. -/
lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E}
(hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v :=
begin
rw linear_independent_iff',
intros s g hg i hi,
have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j),
{ rw inner_sum,
symmetry,
convert finset.sum_eq_single i _ _,
{ rw inner_smul_right },
{ intros j hj hji,
rw [inner_smul_right, ho i j hji.symm, mul_zero] },
{ exact λ h, false.elim (h hi) } },
simpa [hg, hz] using h'
end
end basic_properties
section norm
lemma norm_eq_sqrt_inner (x : E) : ∥x∥ = sqrt (re ⟪x, x⟫) :=
begin
have h₁ : ∥x∥^2 = re ⟪x, x⟫ := norm_sq_eq_inner x,
have h₂ := congr_arg sqrt h₁,
simpa using h₂,
end
lemma norm_eq_sqrt_real_inner (x : F) : ∥x∥ = sqrt ⟪x, x⟫_ℝ :=
by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h }
lemma inner_self_eq_norm_square (x : E) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ :=
by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫),
sqrt_mul_self inner_self_nonneg]
lemma real_inner_self_eq_norm_square (x : F) : ⟪x, x⟫_ℝ = ∥x∥ * ∥x∥ :=
by { have h := @inner_self_eq_norm_square ℝ F _ _ x, simpa using h }
/-- Expand the square -/
lemma norm_add_pow_two {x y : E} : ∥x + y∥^2 = ∥x∥^2 + 2 * (re ⟪x, y⟫) + ∥y∥^2 :=
begin
repeat {rw [pow_two, ←inner_self_eq_norm_square]},
rw[inner_add_add_self, two_mul],
simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add],
rw [←inner_conj_sym, conj_re],
end
/-- Expand the square -/
lemma norm_add_pow_two_real {x y : F} : ∥x + y∥^2 = ∥x∥^2 + 2 * ⟪x, y⟫_ℝ + ∥y∥^2 :=
by { have h := @norm_add_pow_two ℝ F _ _, simpa using h }
/-- Expand the square -/
lemma norm_add_mul_self {x y : E} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * (re ⟪x, y⟫) + ∥y∥ * ∥y∥ :=
by { repeat {rw [← pow_two]}, exact norm_add_pow_two }
/-- Expand the square -/
lemma norm_add_mul_self_real {x y : F} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ :=
by { have h := @norm_add_mul_self ℝ F _ _, simpa using h }
/-- Expand the square -/
lemma norm_sub_pow_two {x y : E} : ∥x - y∥^2 = ∥x∥^2 - 2 * (re ⟪x, y⟫) + ∥y∥^2 :=
begin
repeat {rw [pow_two, ←inner_self_eq_norm_square]},
rw[inner_sub_sub_self],
calc
re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫)
= re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp
... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring
... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[inner_conj_sym]
... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[conj_re]
... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring
end
/-- Expand the square -/
lemma norm_sub_pow_two_real {x y : F} : ∥x - y∥^2 = ∥x∥^2 - 2 * ⟪x, y⟫_ℝ + ∥y∥^2 :=
by { have h := @norm_sub_pow_two ℝ F _ _, simpa using h }
/-- Expand the square -/
lemma norm_sub_mul_self {x y : E} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * re ⟪x, y⟫ + ∥y∥ * ∥y∥ :=
by { repeat {rw [← pow_two]}, exact norm_sub_pow_two }
/-- Expand the square -/
lemma norm_sub_mul_self_real {x y : F} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ :=
by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h }
/-- Cauchy–Schwarz inequality with norm -/
lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ :=
nonneg_le_nonneg_of_squares_le (mul_nonneg (norm_nonneg _) (norm_nonneg _))
begin
have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = (re ⟪x, x⟫) * (re ⟪y, y⟫),
simp only [inner_self_eq_norm_square], ring,
rw this,
conv_lhs { congr, skip, rw [inner_abs_conj_sym] },
exact inner_mul_inner_self_le _ _
end
/-- Cauchy–Schwarz inequality with norm -/
lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ :=
by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h }
include 𝕜
lemma parallelogram_law_with_norm {x y : E} :
∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) :=
begin
simp only [(inner_self_eq_norm_square _).symm],
rw[←add_monoid_hom.map_add, parallelogram_law, two_mul, two_mul],
simp only [add_monoid_hom.map_add],
end
omit 𝕜
lemma parallelogram_law_with_norm_real {x y : F} :
∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) :=
by { have h := @parallelogram_law_with_norm ℝ F _ _ x y, simpa using h }
/-- Polarization identity: The real inner product, in terms of the norm. -/
lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) :
⟪x, y⟫_ℝ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 :=
by rw norm_add_mul_self; ring
/-- Polarization identity: The real inner product, in terms of the norm. -/
lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) :
⟪x, y⟫_ℝ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 :=
by rw norm_sub_mul_self; ring
/-- Pythagorean theorem, if-and-only-if vector inner product form. -/
lemma norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero (x y : F) :
∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 :=
begin
rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero],
norm_num
end
/-- Pythagorean theorem, vector inner product form. -/
lemma norm_add_square_eq_norm_square_add_norm_square_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) :
∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ :=
begin
rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero],
apply or.inr,
simp only [h, zero_re'],
end
/-- Pythagorean theorem, vector inner product form. -/
lemma norm_add_square_eq_norm_square_add_norm_square_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) :
∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ :=
(norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero x y).2 h
/-- Pythagorean theorem, subtracting vectors, if-and-only-if vector
inner product form. -/
lemma norm_sub_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero (x y : F) :
∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 :=
begin
rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero,
mul_eq_zero],
norm_num
end
/-- Pythagorean theorem, subtracting vectors, vector inner product
form. -/
lemma norm_sub_square_eq_norm_square_add_norm_square_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) :
∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ :=
(norm_sub_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero x y).2 h
/-- The sum and difference of two vectors are orthogonal if and only
if they have the same norm. -/
lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ∥x∥ = ∥y∥ :=
begin
conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) },
simp only [←inner_self_eq_norm_square, inner_add_left, inner_sub_right,
real_inner_comm y x, sub_eq_zero, re_to_real],
split,
{ intro h,
rw [add_comm] at h,
linarith },
{ intro h,
linarith }
end
/-- The real inner product of two vectors, divided by the product of their
norms, has absolute value at most 1. -/
lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) ≤ 1 :=
begin
rw _root_.abs_div,
by_cases h : 0 = absR (∥x∥ * ∥y∥),
{ rw [←h, div_zero],
norm_num },
{ change 0 ≠ absR (∥x∥ * ∥y∥) at h,
rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (∥x∥ * ∥y∥))) h),
convert abs_real_inner_le_norm x y using 1,
rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y), mul_one] }
end
/-- The inner product of a vector with a multiple of itself. -/
lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (∥x∥ * ∥x∥) :=
by rw [real_inner_smul_left, ←real_inner_self_eq_norm_square]
/-- The inner product of a vector with a multiple of itself. -/
lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (∥x∥ * ∥x∥) :=
by rw [inner_smul_right, ←real_inner_self_eq_norm_square]
/-- The inner product of a nonzero vector with a nonzero multiple of
itself, divided by the product of their norms, has absolute value
1. -/
lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul
{x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : abs ⟪x, r • x⟫ / (∥x∥ * ∥r • x∥) = 1 :=
begin
have hx' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx],
have hr' : abs r ≠ 0 := by simp [is_R_or_C.abs_eq_zero, hr],
rw [inner_smul_right, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_square, norm_smul],
rw [is_R_or_C.norm_eq_abs, ←mul_assoc, ←div_div_eq_div_mul, mul_div_cancel _ hx',
←div_div_eq_div_mul, mul_comm, mul_div_cancel _ hr', div_self hx'],
end
/-- The inner product of a nonzero vector with a nonzero multiple of
itself, divided by the product of their norms, has absolute value
1. -/
lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul
{x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 :=
begin
rw ← abs_to_real,
exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr
end
/-- The inner product of a nonzero vector with a positive multiple of
itself, divided by the product of their norms, has value 1. -/
lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul
{x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 :=
begin
rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r),
mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self],
exact mul_ne_zero (ne_of_gt hr)
(λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h)))
end
/-- The inner product of a nonzero vector with a negative multiple of
itself, divided by the product of their norms, has value -1. -/
lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul
{x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = -1 :=
begin
rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r),
mul_assoc, abs_of_neg hr, ←neg_mul_eq_neg_mul, div_neg_eq_neg_div, div_self],
exact mul_ne_zero (ne_of_lt hr)
(λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h)))
end
/-- The inner product of two vectors, divided by the product of their
norms, has absolute value 1 if and only if they are nonzero and one is
a multiple of the other. One form of equality case for Cauchy-Schwarz. -/
lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : E) :
abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) :=
begin
split,
{ intro h,
have hx0 : x ≠ 0,
{ intro hx0,
rw [hx0, inner_zero_left, zero_div] at h,
norm_num at h,
exact h },
refine and.intro hx0 _,
set r := ⟪x, y⟫ / (∥x∥ * ∥x∥) with hr,
use r,
set t := y - r • x with ht,
have ht0 : ⟪x, t⟫ = 0,
{ rw [ht, inner_sub_right, inner_smul_right, hr],
norm_cast,
rw [←inner_self_eq_norm_square, inner_self_re_to_K,
div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] },
replace h : ∥r • x∥ / ∥t + r • x∥ = 1,
{ rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right,
is_R_or_C.abs_div, is_R_or_C.abs_mul, ←inner_self_re_abs,
inner_self_eq_norm_square] at h,
norm_cast at h,
rwa [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, ←mul_assoc, mul_comm,
mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), ←is_R_or_C.norm_eq_abs,
←norm_smul] at h },
have hr0 : r ≠ 0,
{ intro hr0,
rw [hr0, zero_smul, norm_zero, zero_div] at h,
norm_num at h },
refine and.intro hr0 _,
have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2,
{ rw [eq_of_div_eq_one h] },
replace h2 : ⟪r • x, r • x⟫ = ⟪t, t⟫ + ⟪t, r • x⟫ + ⟪r • x, t⟫ + ⟪r • x, r • x⟫,
{ rw [pow_two, pow_two, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square ] at h2,
have h2' := congr_arg (λ z : ℝ, (z : 𝕜)) h2,
simp_rw [inner_self_re_to_K, inner_add_add_self] at h2',
exact h2' },
conv at h2 in ⟪r • x, t⟫ { rw [inner_smul_left, ht0, mul_zero] },
symmetry' at h2,
have h₁ : ⟪t, r • x⟫ = 0 := by { rw [inner_smul_right, ←inner_conj_sym, ht0], simp },
rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2,
rw h2 at ht,
exact eq_of_sub_eq_zero ht.symm },
{ intro h,
rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩,
rw [hy, is_R_or_C.abs_div],
norm_cast,
rw [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm],
exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr }
end
/-- The inner product of two vectors, divided by the product of their
norms, has absolute value 1 if and only if they are nonzero and one is
a multiple of the other. One form of equality case for Cauchy-Schwarz. -/
lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) :
absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) :=
begin
have := @abs_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ x y,
simpa [coe_real_eq_id] using this,
end
/--
If the inner product of two vectors is equal to the product of their norms, then the two vectors
are multiples of each other. One form of the equality case for Cauchy-Schwarz.
-/
lemma abs_inner_eq_norm_iff (x y : E) (hx0 : x ≠ 0) (hy0 : y ≠ 0):
abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x :=
begin
have hx0' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx0],
have hy0' : ∥y∥ ≠ 0 := by simp [norm_eq_zero, hy0],
have hxy0 : ∥x∥ * ∥y∥ ≠ 0 := by simp [hx0', hy0'],
have h₁ : abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1,
{ refine ⟨_ ,_⟩,
{ intro h,
norm_cast,
rw [is_R_or_C.abs_div, h, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm],
exact div_self hxy0 },
{ intro h,
norm_cast at h,
rwa [is_R_or_C.abs_div, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm,
div_eq_one_iff_eq hxy0] at h } },
rw [h₁, abs_inner_div_norm_mul_norm_eq_one_iff x y],
have : x ≠ 0 := λ h, (hx0' $ norm_eq_zero.mpr h),
simp [this]
end
/-- The inner product of two vectors, divided by the product of their
norms, has value 1 if and only if they are nonzero and one is
a positive multiple of the other. -/
lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) :
⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) :=
begin
split,
{ intro h,
have ha := h,
apply_fun absR at ha,
norm_num at ha,
rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩,
use [hx, r],
refine and.intro _ hy,
by_contradiction hrneg,
rw hy at h,
rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx
(lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h,
norm_num at h },
{ intro h,
rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩,
rw hy,
exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr }
end
/-- The inner product of two vectors, divided by the product of their
norms, has value -1 if and only if they are nonzero and one is
a negative multiple of the other. -/
lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) :
⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) :=
begin
split,
{ intro h,
have ha := h,
apply_fun absR at ha,
norm_num at ha,
rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩,
use [hx, r],
refine and.intro _ hy,
by_contradiction hrpos,
rw hy at h,
rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx
(lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h,
norm_num at h },
{ intro h,
rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩,
rw hy,
exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr }
end
/-- The inner product of two weighted sums, where the weights in each
sum add to 0, in terms of the norms of pairwise differences. -/
lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ}
(v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ}
(v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) :
⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ =
(-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 :=
by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right,
real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two,
←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib,
finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul,
h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum,
neg_div, finset.sum_div, mul_div_assoc, mul_assoc]
end norm
/-! ### Inner product space structure on product spaces -/
/-
If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space,
then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm,
we use instead `pi_Lp 2 one_le_two f` for the product space, which is endowed with the `L^2` norm.
-/
instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*)
[Π i, inner_product_space 𝕜 (f i)] : inner_product_space 𝕜 (pi_Lp 2 one_le_two f) :=
{ inner := λ x y, ∑ i, inner (x i) (y i),
norm_sq_eq_inner :=
begin
intro x,
have h₁ : ∑ (i : ι), ∥x i∥ ^ (2 : ℕ) = ∑ (i : ι), ∥x i∥ ^ (2 : ℝ),
{ apply finset.sum_congr rfl,
intros j hj,
simp [←rpow_nat_cast] },
have h₂ : 0 ≤ ∑ (i : ι), ∥x i∥ ^ (2 : ℝ),
{ rw [←h₁],
exact finset.sum_nonneg (λ (j : ι) (hj : j ∈ finset.univ), pow_nonneg (norm_nonneg (x j)) 2) },
simp [norm, add_monoid_hom.map_sum, ←norm_sq_eq_inner],
rw [←rpow_nat_cast ((∑ (i : ι), ∥x i∥ ^ (2 : ℝ)) ^ (2 : ℝ)⁻¹) 2],
rw [←rpow_mul h₂],
norm_num [h₁],
end,
conj_sym :=
begin
intros x y,
unfold inner,
rw [←finset.sum_hom finset.univ conj],
apply finset.sum_congr rfl,
rintros z -,
apply inner_conj_sym,
apply_instance
end,
nonneg_im :=
begin
intro x,
unfold inner,
rw[←finset.sum_hom finset.univ im],
apply finset.sum_eq_zero,
rintros z -,
exact inner_self_nonneg_im,
apply_instance
end,
add_left := λ x y z,
show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i),
by simp only [inner_add_left, finset.sum_add_distrib],
smul_left := λ x y r,
show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i),
by simp only [finset.mul_sum, inner_smul_left]
}
/-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/
instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 :=
{ inner := (λ x y, (conj x) * y),
norm_sq_eq_inner := λ x, by unfold inner; rw [mul_comm, mul_conj, of_real_re, norm_sq, norm_sq_eq_def],
conj_sym := λ x y, by simp [mul_comm],
nonneg_im := λ x, by rw[mul_im, conj_re, conj_im]; ring,
add_left := λ x y z, by simp [inner, add_mul],
smul_left := λ x y z, by simp [inner, mul_assoc] }
/-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional
space use `euclidean_space 𝕜 (fin n)`. -/
@[reducible, nolint unused_arguments]
def euclidean_space (𝕜 : Type*) [is_R_or_C 𝕜]
(n : Type*) [fintype n] : Type* := pi_Lp 2 one_le_two (λ (i : n), 𝕜)
section is_R_or_C_to_real
variables {G : Type*}
variables (𝕜 E)
include 𝕜
/-- A general inner product implies a real inner product. This is not registered as an instance
since it creates problems with the case `𝕜 = ℝ`. -/
def has_inner.is_R_or_C_to_real : has_inner ℝ E :=
{ inner := λ x y, re ⟪x, y⟫ }
/-- A general inner product space structure implies a real inner product structure. This is not
registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a
proof to obtain a real inner product space structure from a given `𝕜`-inner product space
structure. -/
def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E :=
{ norm_sq_eq_inner := norm_sq_eq_inner,
conj_sym := λ x y, inner_re_symm,
nonneg_im := λ x, rfl,
add_left := λ x y z, by {
change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫,
simp [inner_add_left] },
smul_left := λ x y r, by {
change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫,
simp [inner_smul_left] },
..has_inner.is_R_or_C_to_real 𝕜 E,
..normed_space.restrict_scalars ℝ 𝕜 E }
variable {E}
lemma real_inner_eq_re_inner (x y : E) :
@has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl
omit 𝕜
/-- A complex inner product implies a real inner product -/
instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G :=
inner_product_space.is_R_or_C_to_real ℂ G
end is_R_or_C_to_real
section deriv
variables [normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E]
lemma is_bounded_bilinear_map_inner : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) :=
{ add_left := λ _ _ _, inner_add_left,
smul_left := λ r x y,
by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left],
add_right := λ _ _ _, inner_add_right,
smul_right := λ r x y,
by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right],
bound := ⟨1, zero_lt_one, λ x y,
by { rw [one_mul, is_R_or_C.norm_eq_abs], exact abs_inner_le_norm x y, }⟩ }
lemma times_cont_diff_inner {n} : times_cont_diff ℝ n (λ p : E × E, ⟪p.1, p.2⟫) :=
is_bounded_bilinear_map_inner.times_cont_diff
lemma times_cont_diff_at_inner {p : E × E} {n} :
times_cont_diff_at ℝ n (λ p : E × E, ⟪p.1, p.2⟫) p :=
times_cont_diff_inner.times_cont_diff_at
lemma differentiable_inner : differentiable ℝ (λ p : E × E, ⟪p.1, p.2⟫) :=
times_cont_diff_inner.differentiable le_rfl
lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) :=
differentiable_inner.continuous
variables {G : Type*} [normed_group G] [normed_space ℝ G]
{f g : G → E} {f' g' : G →L[ℝ] E} {s : set G} {x : G} {n : with_top ℕ}
include 𝕜
lemma times_cont_diff_within_at.inner (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_at_inner.comp_times_cont_diff_within_at x (hf.prod hg)
lemma times_cont_diff_at.inner (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.inner hg
lemma times_cont_diff_on.inner (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).inner (hg x hx)
lemma times_cont_diff.inner (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g) :
times_cont_diff ℝ n (λ x, ⟪f x, g x⟫) :=
times_cont_diff_inner.comp (hf.prod hg)
lemma differentiable_within_at.inner (hf : differentiable_within_at ℝ f s x)
(hg : differentiable_within_at ℝ g s x) :
differentiable_within_at ℝ (λ x, ⟪f x, g x⟫) s x :=
((differentiable_inner _).has_fderiv_at.comp_has_fderiv_within_at x
(hf.prod hg).has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.inner (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) :
differentiable_at ℝ (λ x, ⟪f x, g x⟫) x :=
(differentiable_inner _).comp x (hf.prod hg)
lemma differentiable_on.inner (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) :
differentiable_on ℝ (λ x, ⟪f x, g x⟫) s :=
λ x hx, (hf x hx).inner (hg x hx)
lemma differentiable.inner (hf : differentiable ℝ f) (hg : differentiable ℝ g) :
differentiable ℝ (λ x, ⟪f x, g x⟫) :=
λ x, (hf x).inner (hg x)
end deriv
section pi_Lp
local attribute [reducible] pi_Lp
variables {ι : Type*} [fintype ι]
instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance
@[simp] lemma findim_euclidean_space :
finite_dimensional.findim 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp
lemma findim_euclidean_space_fin {n : ℕ} :
finite_dimensional.findim 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp
end pi_Lp
/-! ### Orthogonal projection in inner product spaces -/
section orthogonal
open filter
/--
Existence of minimizers
Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset.
Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`.
-/
-- FIXME this monolithic proof causes a deterministic timeout with `-T50000`
-- It should be broken in a sequence of more manageable pieces,
-- perhaps with individual statements for the three steps below.
theorem exists_norm_eq_infi_of_complete_convex {K : set F} (ne : K.nonempty) (h₁ : is_complete K)
(h₂ : convex K) : ∀ u : F, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u,
begin
let δ := ⨅ w : K, ∥u - w∥,
letI : nonempty K := ne.to_subtype,
have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _),
have δ_le : ∀ w : K, δ ≤ ∥u - w∥,
from cinfi_le ⟨0, set.forall_range_iff.2 $ λ _, norm_nonneg _⟩,
have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩,
-- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K`
-- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`);
-- maybe this should be a separate lemma
have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1),
{ have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from
λ n, lt_add_of_le_of_pos (le_refl _) nat.one_div_pos_of_nat,
have h := λ n, exists_lt_of_cinfi_lt (hδ n),
let w : ℕ → K := λ n, classical.some (h n),
exact ⟨w, λ n, classical.some_spec (h n)⟩ },
rcases exists_seq with ⟨w, hw⟩,
have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (nhds δ),
{ have h : tendsto (λ n:ℕ, δ) at_top (nhds δ) := tendsto_const_nhds,
have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (nhds δ),
{ convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] },
exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h'
(λ x, δ_le _) (λ x, le_of_lt (hw _)) },
-- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence
have seq_is_cauchy : cauchy_seq (λ n, ((w n):F)),
{ rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals
let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))),
use (λn, sqrt (b n)),
split,
-- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)`
assume n, exact sqrt_nonneg _,
split,
-- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)`
assume p q N hp hq,
let wp := ((w p):F), let wq := ((w q):F),
let a := u - wq, let b := u - wp,
let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1),
have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ =
2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) :=
calc
4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥
= (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring
... = (absR ((2:ℝ)) * ∥u - half•(wq + wp)∥) * (absR ((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ :
by { rw _root_.abs_of_nonneg, exact add_nonneg zero_le_one zero_le_one }
... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ :
by simp [norm_smul]
... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ :
begin
rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0),
← one_add_one_eq_two, add_smul],
simp only [one_smul],
have eq₁ : wp - wq = a - b := calc
wp - wq = (u - wq) - (u - wp) : by rw [sub_sub_assoc_swap, add_sub_assoc, sub_add_sub_cancel']
... = a - b : rfl,
have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel,
rw [eq₁, eq₂],
end
... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm,
have eq : δ ≤ ∥u - half • (wq + wp)∥,
{ rw smul_add,
apply δ_le', apply h₂,
repeat {exact subtype.mem _},
repeat {exact le_of_lt one_half_pos},
exact add_halves 1 },
have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥,
{ mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ },
have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) :=
mul_self_le_mul_self (norm_nonneg _)
(le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)),
have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) :=
mul_self_le_mul_self (norm_nonneg _)
(le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)),
rw dist_eq_norm,
apply nonneg_le_nonneg_of_squares_le, { exact sqrt_nonneg _ },
rw mul_self_sqrt,
exact calc
∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ :
by { rw ← this, simp }
... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _
... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ :
sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _
... = 8 * δ * div + 4 * div * div : by ring,
exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat))
(mul_nonneg (mul_nonneg (by norm_num) (le_of_lt nat.one_div_pos_of_nat)) (le_of_lt nat.one_div_pos_of_nat)),
-- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)`
apply tendsto.comp,
{ convert continuous_sqrt.continuous_at, exact sqrt_zero.symm },
have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (nhds (0:ℝ)),
{ convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat,
simp only [mul_zero] },
have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (nhds (0:ℝ)),
{ convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat,
simp only [mul_zero] },
have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0:ℝ)),
{ convert this.mul tendsto_one_div_add_at_top_nhds_0_nat,
simp only [mul_zero] },
convert eq₁.add eq₂, simp only [add_zero] },
-- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`.
-- Prove that it satisfies all requirements.
rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩,
use v, use hv,
have h_cont : continuous (λ v, ∥u - v∥) :=
continuous.comp continuous_norm (continuous.sub continuous_const continuous_id),
have : tendsto (λ n, ∥u - w n∥) at_top (nhds ∥u - v∥),
convert (tendsto.comp h_cont.continuous_at w_tendsto),
exact tendsto_nhds_unique this norm_tendsto,
exact subtype.mem _
end
/-- Characterization of minimizers for the projection on a convex set in a real inner product
space. -/
theorem norm_eq_infi_iff_real_inner_le_zero {K : set F} (h : convex K) {u : F} {v : F}
(hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 :=
iff.intro
begin
assume eq w hw,
let δ := ⨅ w : K, ∥u - w∥, let p := ⟪u - v, w - v⟫_ℝ, let q := ∥w - v∥^2,
letI : nonempty K := ⟨⟨v, hv⟩⟩,
have zero_le_δ : 0 ≤ δ,
apply le_cinfi, intro, exact norm_nonneg _,
have δ_le : ∀ w : K, δ ≤ ∥u - w∥,
assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _,
have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩,
have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q,
assume θ hθ₁ hθ₂,
have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ*θ*∥w - v∥^2 :=
calc
∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 :
begin
simp only [pow_two], apply mul_self_le_mul_self (norm_nonneg _),
rw [eq], apply δ_le',
apply h hw hv,
exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _],
end
... = ∥(u - v) - θ • (w - v)∥^2 :
begin
have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v),
{ rw [smul_sub, sub_smul, one_smul],
simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] },
rw this
end
... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 :
begin
rw [norm_sub_pow_two, inner_smul_right, norm_smul],
simp only [pow_two],
show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+absR (θ)*∥w-v∥*(absR (θ)*∥w-v∥)=
∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥),
rw abs_of_pos hθ₁, ring
end,
have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), abel,
rw [eq₁, le_add_iff_nonneg_right] at this,
have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring,
rw eq₂ at this,
have := le_of_sub_nonneg (nonneg_of_mul_nonneg_left this hθ₁),
exact this,
by_cases hq : q = 0,
{ rw hq at this,
have : p ≤ 0,
have := this (1:ℝ) (by norm_num) (by norm_num),
linarith,
exact this },
{ have q_pos : 0 < q,
apply lt_of_le_of_ne, exact pow_two_nonneg _, intro h, exact hq h.symm,
by_contradiction hp, rw not_le at hp,
let θ := min (1:ℝ) (p / q),
have eq₁ : θ*q ≤ p := calc
θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (pow_two_nonneg _)
... = p : div_mul_cancel _ hq,
have : 2 * p ≤ p := calc
2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) }
... ≤ p : eq₁,
linarith }
end
begin
assume h,
letI : nonempty K := ⟨⟨v, hv⟩⟩,
apply le_antisymm,
{ apply le_cinfi, assume w,
apply nonneg_le_nonneg_of_squares_le (norm_nonneg _),
have := h w w.2,
exact calc
∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:F) - v) : by linarith
... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:F) - v) + ∥(w:F) - v∥^2 :
by { rw pow_two, refine le_add_of_nonneg_right _, exact pow_two_nonneg _ }
... = ∥(u - v) - (w - v)∥^2 : norm_sub_pow_two.symm
... = ∥u - w∥ * ∥u - w∥ :
by { have : (u - v) - (w - v) = u - w, abel, rw [this, pow_two] } },
{ show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩,
apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ }
end
/--
Existence of projections on complete subspaces.
Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace.
Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`.
This point `v` is usually called the orthogonal projection of `u` onto `K`.
-/
theorem exists_norm_eq_infi_of_complete_subspace (K : subspace 𝕜 E)
(h : is_complete (↑K : set E)) : ∀ u : E, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (K : set E), ∥u - w∥ :=
begin
letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E,
letI : module ℝ E := restrict_scalars.semimodule ℝ 𝕜 E,
letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _,
let K' : subspace ℝ E := submodule.restrict_scalars ℝ K,
exact exists_norm_eq_infi_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex
end
/--
Characterization of minimizers in the projection on a subspace, in the real case.
Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace.
Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if
for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`).
This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over
any `is_R_or_C` field.
-/
theorem norm_eq_infi_iff_real_inner_eq_zero (K : subspace ℝ F) {u : F} {v : F}
(hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set F), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 :=
iff.intro
begin
assume h,
have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0,
{ rwa [norm_eq_infi_iff_real_inner_le_zero] at h, exacts [K.convex, hv] },
assume w hw,
have le : ⟪u - v, w⟫_ℝ ≤ 0,
let w' := w + v,
have : w' ∈ K := submodule.add_mem _ hw hv,
have h₁ := h w' this,
have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg],
rw h₂ at h₁, exact h₁,
have ge : ⟪u - v, w⟫_ℝ ≥ 0,
let w'' := -w + v,
have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv,
have h₁ := h w'' this,
have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg],
rw [h₂, inner_neg_right] at h₁,
linarith,
exact le_antisymm le ge
end
begin
assume h,
have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0,
assume w hw,
let w' := w - v,
have : w' ∈ K := submodule.sub_mem _ hw hv,
have h₁ := h w' this,
exact le_of_eq h₁,
rwa norm_eq_infi_iff_real_inner_le_zero,
exacts [submodule.convex _, hv]
end
/--
Characterization of minimizers in the projection on a subspace.
Let `u` be a point in an inner product space, and let `K` be a nonempty subspace.
Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if
for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`)
-/
theorem norm_eq_infi_iff_inner_eq_zero (K : subspace 𝕜 E) {u : E} {v : E}
(hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set E), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 :=
begin
letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E,
letI : module ℝ E := restrict_scalars.semimodule ℝ 𝕜 E,
letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _,
let K' : subspace ℝ E := K.restrict_scalars ℝ,
split,
{ assume H,
have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infi_iff_real_inner_eq_zero K' hv).1 H,
assume w hw,
apply ext,
{ simp [A w hw] },
{ symmetry, calc
im (0 : 𝕜) = 0 : im.map_zero
... = re ⟪u - v, (-I) • w⟫ : (A _ (K.smul_mem (-I) hw)).symm
... = re ((-I) * ⟪u - v, w⟫) : by rw inner_smul_right
... = im ⟪u - v, w⟫ : by simp } },
{ assume H,
have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0,
{ assume w hw,
rw [real_inner_eq_re_inner, H w hw],
exact zero_re' },
exact (norm_eq_infi_iff_real_inner_eq_zero K' hv).2 this }
end
/-- The orthogonal projection onto a complete subspace, as an
unbundled function. This definition is only intended for use in
setting up the bundled version `orthogonal_projection` and should not
be used once that is defined. -/
def orthogonal_projection_fn {K : subspace 𝕜 E} (h : is_complete (K : set E)) (v : E) :=
(exists_norm_eq_infi_of_complete_subspace K h v).some
/-- The unbundled orthogonal projection is in the given subspace.
This lemma is only intended for use in setting up the bundled version
and should not be used once that is defined. -/
lemma orthogonal_projection_fn_mem {K : submodule 𝕜 E} (h : is_complete (K : set E)) (v : E) :
orthogonal_projection_fn h v ∈ K :=
(exists_norm_eq_infi_of_complete_subspace K h v).some_spec.some
/-- The characterization of the unbundled orthogonal projection. This
lemma is only intended for use in setting up the bundled version
and should not be used once that is defined. -/
lemma orthogonal_projection_fn_inner_eq_zero {K : submodule 𝕜 E} (h : is_complete (K : set E))
(v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection_fn h v, w⟫ = 0 :=
begin
rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem h v),
exact (exists_norm_eq_infi_of_complete_subspace K h v).some_spec.some_spec
end
/-- The unbundled orthogonal projection is the unique point in `K`
with the orthogonality property. This lemma is only intended for use
in setting up the bundled version and should not be used once that is
defined. -/
lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero {K : submodule 𝕜 E}
(h : is_complete (K : set E)) {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) :
v = orthogonal_projection_fn h u :=
begin
rw [←sub_eq_zero, ←inner_self_eq_zero],
have hvs : v - orthogonal_projection_fn h u ∈ K :=
submodule.sub_mem K hvm (orthogonal_projection_fn_mem h u),
have huo : ⟪u - orthogonal_projection_fn h u, v - orthogonal_projection_fn h u⟫ = 0 :=
orthogonal_projection_fn_inner_eq_zero h u _ hvs,
have huv : ⟪u - v, v - orthogonal_projection_fn h u⟫ = 0 := hvo _ hvs,
have houv : ⟪(u - orthogonal_projection_fn h u) - (u - v), v - orthogonal_projection_fn h u⟫ = 0,
{ rw [inner_sub_left, huo, huv, sub_zero] },
rwa sub_sub_sub_cancel_left at houv
end
/-- The orthogonal projection onto a complete subspace. For most
purposes, `orthogonal_projection`, which removes the `is_complete`
hypothesis and is the identity map when the subspace is not complete,
should be used instead. -/
def orthogonal_projection_of_complete {K : submodule 𝕜 E} (h : is_complete (K : set E)) :
linear_map 𝕜 E E :=
{ to_fun := orthogonal_projection_fn h,
map_add' := λ x y, begin
have hm : orthogonal_projection_fn h x + orthogonal_projection_fn h y ∈ K :=
submodule.add_mem K (orthogonal_projection_fn_mem h x) (orthogonal_projection_fn_mem h y),
have ho :
∀ w ∈ K, ⟪x + y - (orthogonal_projection_fn h x + orthogonal_projection_fn h y), w⟫ = 0,
{ intros w hw,
rw [add_sub_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero h _ w hw,
orthogonal_projection_fn_inner_eq_zero h _ w hw, add_zero] },
rw eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hm ho
end,
map_smul' := λ c x, begin
have hm : c • orthogonal_projection_fn h x ∈ K :=
submodule.smul_mem K _ (orthogonal_projection_fn_mem h x),
have ho : ∀ w ∈ K, ⟪c • x - c • orthogonal_projection_fn h x, w⟫ = 0,
{ intros w hw,
rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero h _ w hw, mul_zero] },
rw eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hm ho
end }
/-- The orthogonal projection onto a subspace, which is expected to be
complete. If the subspace is not complete, this uses the identity map
instead. -/
def orthogonal_projection (K : submodule 𝕜 E) : linear_map 𝕜 E E :=
if h : is_complete (K : set E) then orthogonal_projection_of_complete h else linear_map.id
/-- The definition of `orthogonal_projection` using `if`. -/
lemma orthogonal_projection_def (K : submodule 𝕜 E) :
orthogonal_projection K =
if h : is_complete (K : set E) then orthogonal_projection_of_complete h else linear_map.id :=
rfl
@[simp]
lemma orthogonal_projection_fn_eq {K : submodule 𝕜 E} (h : is_complete (K : set E)) (v : E) :
orthogonal_projection_fn h v = orthogonal_projection K v :=
by { rw [orthogonal_projection_def, dif_pos h], refl }
/-- The orthogonal projection is in the given subspace. -/
lemma orthogonal_projection_mem {K : submodule 𝕜 E} (h : is_complete (K : set E)) (v : E) :
orthogonal_projection K v ∈ K :=
begin
rw ←orthogonal_projection_fn_eq h,
exact orthogonal_projection_fn_mem h v
end
/-- The characterization of the orthogonal projection. -/
@[simp]
lemma orthogonal_projection_inner_eq_zero (K : submodule 𝕜 E) (v : E) :
∀ w ∈ K, ⟪v - orthogonal_projection K v, w⟫ = 0 :=
begin
simp_rw orthogonal_projection_def,
split_ifs,
{ exact orthogonal_projection_fn_inner_eq_zero h v },
{ simp },
end
/-- The orthogonal projection is the unique point in `K` with the
orthogonality property. -/
lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero {K : submodule 𝕜 E}
(h : is_complete (K : set E)) {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) :
v = orthogonal_projection K u :=
begin
rw ←orthogonal_projection_fn_eq h,
exact eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hvm hvo
end
/-- The subspace of vectors orthogonal to a given subspace. -/
def submodule.orthogonal (K : submodule 𝕜 E) : submodule 𝕜 E :=
{ carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0},
zero_mem' := λ _ _, inner_zero_right,
add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero],
smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] }
/-- When a vector is in `K.orthogonal`. -/
lemma submodule.mem_orthogonal (K : submodule 𝕜 E) (v : E) :
v ∈ K.orthogonal ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 :=
iff.rfl
/-- When a vector is in `K.orthogonal`, with the inner product the
other way round. -/
lemma submodule.mem_orthogonal' (K : submodule 𝕜 E) (v : E) :
v ∈ K.orthogonal ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 :=
by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym]
/-- A vector in `K` is orthogonal to one in `K.orthogonal`. -/
lemma submodule.inner_right_of_mem_orthogonal {u v : E} {K : submodule 𝕜 E} (hu : u ∈ K)
(hv : v ∈ K.orthogonal) : ⟪u, v⟫ = 0 :=
(K.mem_orthogonal v).1 hv u hu
/-- A vector in `K.orthogonal` is orthogonal to one in `K`. -/
lemma submodule.inner_left_of_mem_orthogonal {u v : E} {K : submodule 𝕜 E} (hu : u ∈ K)
(hv : v ∈ K.orthogonal) : ⟪v, u⟫ = 0 :=
by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv
/-- `K` and `K.orthogonal` have trivial intersection. -/
lemma submodule.orthogonal_disjoint (K : submodule 𝕜 E) : disjoint K K.orthogonal :=
begin
simp_rw [submodule.disjoint_def, submodule.mem_orthogonal],
exact λ x hx ho, inner_self_eq_zero.1 (ho x hx)
end
variables (𝕜 E)
/-- `submodule.orthogonal` gives a `galois_connection` between
`submodule 𝕜 E` and its `order_dual`. -/
lemma submodule.orthogonal_gc :
@galois_connection (submodule 𝕜 E) (order_dual $ submodule 𝕜 E) _ _
submodule.orthogonal submodule.orthogonal :=
λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu),
λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩
variables {𝕜 E}
/-- `submodule.orthogonal` reverses the `≤` ordering of two
subspaces. -/
lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) :
K₂.orthogonal ≤ K₁.orthogonal :=
(submodule.orthogonal_gc 𝕜 E).monotone_l h
/-- `K` is contained in `K.orthogonal.orthogonal`. -/
lemma submodule.le_orthogonal_orthogonal (K : submodule 𝕜 E) : K ≤ K.orthogonal.orthogonal :=
(submodule.orthogonal_gc 𝕜 E).le_u_l _
/-- The inf of two orthogonal subspaces equals the subspace orthogonal
to the sup. -/
lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) :
K₁.orthogonal ⊓ K₂.orthogonal = (K₁ ⊔ K₂).orthogonal :=
(submodule.orthogonal_gc 𝕜 E).l_sup.symm
/-- The inf of an indexed family of orthogonal subspaces equals the
subspace orthogonal to the sup. -/
lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) :
(⨅ i, (K i).orthogonal) = (supr K).orthogonal :=
(submodule.orthogonal_gc 𝕜 E).l_supr.symm
/-- The inf of a set of orthogonal subspaces equals the subspace
orthogonal to the sup. -/
lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) :
(⨅ K ∈ s, submodule.orthogonal K) = (Sup s).orthogonal :=
(submodule.orthogonal_gc 𝕜 E).l_Sup.symm
/-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁.orthogonal ⊓ K₂` span `K₂`. -/
lemma submodule.sup_orthogonal_inf_of_is_complete {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂)
(hc : is_complete (K₁ : set E)) : K₁ ⊔ (K₁.orthogonal ⊓ K₂) = K₂ :=
begin
ext x,
rw submodule.mem_sup,
rcases exists_norm_eq_infi_of_complete_subspace K₁ hc x with ⟨v, hv, hvm⟩,
rw norm_eq_infi_iff_inner_eq_zero K₁ hv at hvm,
split,
{ rintro ⟨y, hy, z, hz, rfl⟩,
exact K₂.add_mem (h hy) hz.2 },
{ exact λ hx, ⟨v, hv, x - v, ⟨(K₁.mem_orthogonal' _).2 hvm, K₂.sub_mem hx (h hv)⟩,
add_sub_cancel'_right _ _⟩ }
end
/-- If `K` is complete, `K` and `K.orthogonal` span the whole
space. -/
lemma submodule.sup_orthogonal_of_is_complete {K : submodule 𝕜 E} (h : is_complete (K : set E)) :
K ⊔ K.orthogonal = ⊤ :=
begin
convert submodule.sup_orthogonal_inf_of_is_complete (le_top : K ≤ ⊤) h,
simp
end
/-- If `K` is complete, `K` and `K.orthogonal` are complements of each
other. -/
lemma submodule.is_compl_orthogonal_of_is_complete {K : submodule 𝕜 E}
(h : is_complete (K : set E)) : is_compl K K.orthogonal :=
⟨K.orthogonal_disjoint, le_of_eq (submodule.sup_orthogonal_of_is_complete h).symm⟩
@[simp] lemma submodule.top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E).orthogonal = ⊥ :=
begin
ext,
rw [submodule.mem_bot, submodule.mem_orthogonal],
exact ⟨λ h, inner_self_eq_zero.mp (h x submodule.mem_top), by { rintro rfl, simp }⟩
end
@[simp] lemma submodule.bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E).orthogonal = ⊤ :=
begin
rw [← submodule.top_orthogonal_eq_bot, eq_top_iff],
exact submodule.le_orthogonal_orthogonal ⊤
end
lemma submodule.eq_top_iff_orthogonal_eq_bot {K : submodule 𝕜 E} (hK : is_complete (K : set E)) :
K = ⊤ ↔ K.orthogonal = ⊥ :=
begin
refine ⟨by { rintro rfl, exact submodule.top_orthogonal_eq_bot }, _⟩,
intro h,
have : K ⊔ K.orthogonal = ⊤ := submodule.sup_orthogonal_of_is_complete hK,
rwa [h, sup_comm, bot_sup_eq] at this,
end
open finite_dimensional
/-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁`
containined in it, the dimensions of `K₁` and the intersection of its
orthogonal subspace with `K₂` add to that of `K₂`. -/
lemma submodule.findim_add_inf_findim_orthogonal {K₁ K₂ : submodule 𝕜 E}
[finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) :
findim 𝕜 K₁ + findim 𝕜 (K₁.orthogonal ⊓ K₂ : submodule 𝕜 E) = findim 𝕜 K₂ :=
begin
haveI := submodule.finite_dimensional_of_le h,
have hd := submodule.dim_sup_add_dim_inf_eq K₁ (K₁.orthogonal ⊓ K₂),
rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, findim_bot,
submodule.sup_orthogonal_inf_of_is_complete h
(submodule.complete_of_finite_dimensional _)] at hd,
rw add_zero at hd,
exact hd.symm
end
end orthogonal
|
d48d1ffcd94359647b48d8a13c04b5facc8efb2a | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/data/mv_polynomial/variables.lean | 785cc0105cbc8d097075567031331059399af74e | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 23,096 | 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, Johan Commelin, Mario Carneiro
-/
import data.mv_polynomial.monad
import data.set.disjointed
/-!
# Degrees and variables of polynomials
This file establishes many results about the degree and variable sets of a multivariate polynomial.
The *variable set* of a polynomial $P \in R[X]$ is a `finset` containing each $x \in X$
that appears in a monomial in $P$.
The *degree set* of a polynomial $P \in R[X]$ is a `multiset` containing, for each $x$ in the
variable set, $n$ copies of $x$, where $n$ is the maximum number of copies of $x$ appearing in a
monomial of $P$.
## Main declarations
* `mv_polynomial.degrees p` : the multiset of variables representing the union of the multisets
corresponding to each non-zero monomial in `p`.
For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then `degrees p = {x, x, y, y, y}`
* `mv_polynomial.vars p` : the finset of variables occurring in `p`.
For example if `p = x⁴y+yz` then `vars p = {x, y, z}`
* `mv_polynomial.degree_of n p : ℕ` : the total degree of `p` with respect to the variable `n`.
For example if `p = x⁴y+yz` then `degree_of y p = 1`.
* `mv_polynomial.total_degree p : ℕ` :
the max of the sizes of the multisets `s` whose monomials `X^s` occur in `p`.
For example if `p = x⁴y+yz` then `total_degree p = 5`.
## Notation
As in other polynomial files, we typically use the notation:
+ `σ τ : Type*` (indexing the variables)
+ `R : Type*` `[comm_semiring R]` (the coefficients)
+ `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set.
This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s`
+ `r : R`
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : mv_polynomial σ R`
-/
noncomputable theory
open_locale classical big_operators
open set function finsupp add_monoid_algebra
open_locale big_operators
universes u v w
variables {R : Type u} {S : Type v}
namespace mv_polynomial
variables {σ τ : Type*} {r : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section comm_semiring
variables [comm_semiring R] {p q : mv_polynomial σ R}
section degrees
/-! ### `degrees` -/
/--
The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset.
(For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.)
-/
def degrees (p : mv_polynomial σ R) : multiset σ :=
p.support.sup (λs:σ →₀ ℕ, s.to_multiset)
lemma degrees_monomial (s : σ →₀ ℕ) (a : R) : degrees (monomial s a) ≤ s.to_multiset :=
finset.sup_le $ assume t h,
begin
have := finsupp.support_single_subset h,
rw [finset.mem_singleton] at this,
rw this
end
lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : R) (ha : a ≠ 0) :
degrees (monomial s a) = s.to_multiset :=
le_antisymm (degrees_monomial s a) $ finset.le_sup $
by rw [support_monomial, if_neg ha, finset.mem_singleton]
lemma degrees_C (a : R) : degrees (C a : mv_polynomial σ R) = 0 :=
multiset.le_zero.1 $ degrees_monomial _ _
lemma degrees_X' (n : σ) : degrees (X n : mv_polynomial σ R) ≤ {n} :=
le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _
@[simp] lemma degrees_X [nontrivial R] (n : σ) : degrees (X n : mv_polynomial σ R) = {n} :=
(degrees_monomial_eq _ _ one_ne_zero).trans (to_multiset_single _ _)
@[simp] lemma degrees_zero : degrees (0 : mv_polynomial σ R) = 0 :=
by { rw ← C_0, exact degrees_C 0 }
@[simp] lemma degrees_one : degrees (1 : mv_polynomial σ R) = 0 := degrees_C 1
lemma degrees_add (p q : mv_polynomial σ R) : (p + q).degrees ≤ p.degrees ⊔ q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
have := finsupp.support_add hb, rw finset.mem_union at this,
cases this,
{ exact le_sup_left_of_le (finset.le_sup this) },
{ exact le_sup_right_of_le (finset.le_sup this) },
end
lemma degrees_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) :
(∑ i in s, f i).degrees ≤ s.sup (λi, (f i).degrees) :=
begin
refine s.induction _ _,
{ simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_refl _ },
{ assume i s his ih,
rw [finset.sup_insert, finset.sum_insert his],
exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) }
end
lemma degrees_mul (p q : mv_polynomial σ R) : (p * q).degrees ≤ p.degrees + q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
have := support_mul p q hb,
simp only [finset.mem_bUnion, finset.mem_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.to_multiset_add],
exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂)
end
lemma degrees_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) :
(∏ i in s, f i).degrees ≤ ∑ i in s, (f i).degrees :=
begin
refine s.induction _ _,
{ simp only [finset.prod_empty, finset.sum_empty, degrees_one] },
{ assume i s his ih,
rw [finset.prod_insert his, finset.sum_insert his],
exact le_trans (degrees_mul _ _) (add_le_add_left ih _) }
end
lemma degrees_pow (p : mv_polynomial σ R) :
∀(n : ℕ), (p^n).degrees ≤ n • p.degrees
| 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end
| (n + 1) := by { rw [pow_succ, add_smul, add_comm, one_smul],
exact le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _) }
lemma mem_degrees {p : mv_polynomial σ R} {i : σ} :
i ∈ p.degrees ↔ ∃ d, p.coeff d ≠ 0 ∧ i ∈ d.support :=
by simp only [degrees, multiset.mem_sup, ← mem_support_iff,
finsupp.mem_to_multiset, exists_prop]
lemma le_degrees_add {p q : mv_polynomial σ R} (h : p.degrees.disjoint q.degrees) :
p.degrees ≤ (p + q).degrees :=
begin
apply finset.sup_le,
intros d hd,
rw multiset.disjoint_iff_ne at h,
rw multiset.le_iff_count,
intros i,
rw [degrees, multiset.count_sup],
simp only [finsupp.count_to_multiset],
by_cases h0 : d = 0,
{ simp only [h0, zero_le, finsupp.zero_apply], },
{ refine @finset.le_sup _ _ _ (p + q).support _ d _,
rw [mem_support_iff, coeff_add],
suffices : q.coeff d = 0,
{ rwa [this, add_zero, coeff, ← finsupp.mem_support_iff], },
rw [← finsupp.support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty] at h0,
obtain ⟨j, hj⟩ := h0,
contrapose! h,
rw mem_support_iff at hd,
refine ⟨j, _, j, _, rfl⟩,
all_goals { rw mem_degrees, refine ⟨d, _, hj⟩, assumption } }
end
lemma degrees_add_of_disjoint
{p q : mv_polynomial σ R} (h : multiset.disjoint p.degrees q.degrees) :
(p + q).degrees = p.degrees ∪ q.degrees :=
begin
apply le_antisymm,
{ apply degrees_add },
{ apply multiset.union_le,
{ apply le_degrees_add h },
{ rw add_comm, apply le_degrees_add h.symm } }
end
lemma degrees_map [comm_semiring S] (p : mv_polynomial σ R) (f : R →+* S) :
(map f p).degrees ⊆ p.degrees :=
begin
dsimp only [degrees],
apply multiset.subset_of_le,
apply finset.sup_mono,
apply mv_polynomial.support_map_subset
end
lemma degrees_rename (f : σ → τ) (φ : mv_polynomial σ R) :
(rename f φ).degrees ⊆ (φ.degrees.map f) :=
begin
intros i,
rw [mem_degrees, multiset.mem_map],
rintro ⟨d, hd, hi⟩,
obtain ⟨x, rfl, hx⟩ := coeff_rename_ne_zero _ _ _ hd,
simp only [map_domain, finsupp.mem_support_iff] at hi,
rw [sum_apply, finsupp.sum] at hi,
contrapose! hi,
rw [finset.sum_eq_zero],
intros j hj,
simp only [exists_prop, mem_degrees] at hi,
specialize hi j ⟨x, hx, hj⟩,
rw [single_apply, if_neg hi],
end
lemma degrees_map_of_injective [comm_semiring S] (p : mv_polynomial σ R)
{f : R →+* S} (hf : injective f) : (map f p).degrees = p.degrees :=
by simp only [degrees, mv_polynomial.support_map_of_injective _ hf]
end degrees
section vars
/-! ### `vars` -/
/-- `vars p` is the set of variables appearing in the polynomial `p` -/
def vars (p : mv_polynomial σ R) : finset σ := p.degrees.to_finset
@[simp] lemma vars_0 : (0 : mv_polynomial σ R).vars = ∅ :=
by rw [vars, degrees_zero, multiset.to_finset_zero]
@[simp] lemma vars_monomial (h : r ≠ 0) : (monomial s r).vars = s.support :=
by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset]
@[simp] lemma vars_C : (C r : mv_polynomial σ R).vars = ∅ :=
by rw [vars, degrees_C, multiset.to_finset_zero]
@[simp] lemma vars_X [nontrivial R] : (X n : mv_polynomial σ R).vars = {n} :=
by rw [X, vars_monomial (@one_ne_zero R _ _), finsupp.support_single_ne_zero (one_ne_zero : 1 ≠ 0)]
lemma mem_vars (i : σ) :
i ∈ p.vars ↔ ∃ (d : σ →₀ ℕ) (H : d ∈ p.support), i ∈ d.support :=
by simp only [vars, multiset.mem_to_finset, mem_degrees, mem_support_iff,
exists_prop]
lemma mem_support_not_mem_vars_zero
{f : mv_polynomial σ R} {x : σ →₀ ℕ} (H : x ∈ f.support) {v : σ} (h : v ∉ vars f) :
x v = 0 :=
begin
rw [vars, multiset.mem_to_finset] at h,
rw ← finsupp.not_mem_support_iff,
contrapose! h,
unfold degrees,
rw (show f.support = insert x f.support, from eq.symm $ finset.insert_eq_of_mem H),
rw finset.sup_insert,
simp only [multiset.mem_union, multiset.sup_eq_union],
left,
rwa [←to_finset_to_multiset, multiset.mem_to_finset] at h,
end
lemma vars_add_subset (p q : mv_polynomial σ R) :
(p + q).vars ⊆ p.vars ∪ q.vars :=
begin
intros x hx,
simp only [vars, finset.mem_union, multiset.mem_to_finset] at hx ⊢,
simpa using multiset.mem_of_le (degrees_add _ _) hx,
end
lemma vars_add_of_disjoint (h : disjoint p.vars q.vars) :
(p + q).vars = p.vars ∪ q.vars :=
begin
apply finset.subset.antisymm (vars_add_subset p q),
intros x hx,
simp only [vars, multiset.disjoint_to_finset] at h hx ⊢,
rw [degrees_add_of_disjoint h, multiset.to_finset_union],
exact hx
end
section mul
lemma vars_mul (φ ψ : mv_polynomial σ R) : (φ * ψ).vars ⊆ φ.vars ∪ ψ.vars :=
begin
intro i,
simp only [mem_vars, finset.mem_union],
rintro ⟨d, hd, hi⟩,
rw [mem_support_iff, coeff_mul] at hd,
contrapose! hd, cases hd,
rw finset.sum_eq_zero,
rintro ⟨d₁, d₂⟩ H,
rw finsupp.mem_antidiagonal_support at H,
subst H,
obtain H|H : i ∈ d₁.support ∨ i ∈ d₂.support,
{ simpa only [finset.mem_union] using finsupp.support_add hi, },
{ suffices : coeff d₁ φ = 0, by simp [this],
rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, },
{ suffices : coeff d₂ ψ = 0, by simp [this],
rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, },
end
@[simp] lemma vars_one : (1 : mv_polynomial σ R).vars = ∅ :=
vars_C
lemma vars_pow (φ : mv_polynomial σ R) (n : ℕ) : (φ ^ n).vars ⊆ φ.vars :=
begin
induction n with n ih,
{ simp },
{ rw pow_succ,
apply finset.subset.trans (vars_mul _ _),
exact finset.union_subset (finset.subset.refl _) ih }
end
/--
The variables of the product of a family of polynomials
are a subset of the union of the sets of variables of each polynomial.
-/
lemma vars_prod {ι : Type*} {s : finset ι} (f : ι → mv_polynomial σ R) :
(∏ i in s, f i).vars ⊆ s.bUnion (λ i, (f i).vars) :=
begin
apply s.induction_on,
{ simp },
{ intros a s hs hsub,
simp only [hs, finset.bUnion_insert, finset.prod_insert, not_false_iff],
apply finset.subset.trans (vars_mul _ _),
exact finset.union_subset_union (finset.subset.refl _) hsub }
end
section integral_domain
variables {A : Type*} [integral_domain A]
lemma vars_C_mul (a : A) (ha : a ≠ 0) (φ : mv_polynomial σ A) : (C a * φ).vars = φ.vars :=
begin
ext1 i,
simp only [mem_vars, exists_prop, mem_support_iff],
apply exists_congr,
intro d,
apply and_congr _ iff.rfl,
rw [coeff_C_mul, mul_ne_zero_iff, eq_true_intro ha, true_and],
end
end integral_domain
end mul
section sum
variables {ι : Type*} (t : finset ι) (φ : ι → mv_polynomial σ R)
lemma vars_sum_subset :
(∑ i in t, φ i).vars ⊆ finset.bUnion t (λ i, (φ i).vars) :=
begin
apply t.induction_on,
{ simp },
{ intros a s has hsum,
rw [finset.bUnion_insert, finset.sum_insert has],
refine finset.subset.trans (vars_add_subset _ _)
(finset.union_subset_union (finset.subset.refl _) _),
assumption }
end
lemma vars_sum_of_disjoint (h : pairwise $ disjoint on (λ i, (φ i).vars)) :
(∑ i in t, φ i).vars = finset.bUnion t (λ i, (φ i).vars) :=
begin
apply t.induction_on,
{ simp },
{ intros a s has hsum,
rw [finset.bUnion_insert, finset.sum_insert has, vars_add_of_disjoint, hsum],
unfold pairwise on_fun at h,
rw hsum,
simp only [finset.disjoint_iff_ne] at h ⊢,
intros v hv v2 hv2,
rw finset.mem_bUnion at hv2,
rcases hv2 with ⟨i, his, hi⟩,
refine h a i _ _ hv _ hi,
rintro rfl,
contradiction }
end
end sum
section map
variables [comm_semiring S] (f : R →+* S)
variable (p)
lemma vars_map : (map f p).vars ⊆ p.vars :=
by simp [vars, degrees_map]
variable {f}
lemma vars_map_of_injective (hf : injective f) :
(map f p).vars = p.vars :=
by simp [vars, degrees_map_of_injective _ hf]
lemma vars_monomial_single (i : σ) {e : ℕ} {r : R} (he : e ≠ 0) (hr : r ≠ 0) :
(monomial (finsupp.single i e) r).vars = {i} :=
by rw [vars_monomial hr, finsupp.support_single_ne_zero he]
lemma vars_eq_support_bUnion_support : p.vars = p.support.bUnion finsupp.support :=
by { ext i, rw [mem_vars, finset.mem_bUnion] }
end map
end vars
section degree_of
/-! ### `degree_of` -/
/-- `degree_of n p` gives the highest power of X_n that appears in `p` -/
def degree_of (n : σ) (p : mv_polynomial σ R) : ℕ := p.degrees.count n
end degree_of
section total_degree
/-! ### `total_degree` -/
/-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/
def total_degree (p : mv_polynomial σ R) : ℕ := p.support.sup (λs, s.sum $ λn e, e)
lemma total_degree_eq (p : mv_polynomial σ R) :
p.total_degree = p.support.sup (λm, m.to_multiset.card) :=
begin
rw [total_degree],
congr, funext m,
exact (finsupp.card_to_multiset _).symm
end
lemma total_degree_le_degrees_card (p : mv_polynomial σ R) :
p.total_degree ≤ p.degrees.card :=
begin
rw [total_degree_eq],
exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs)
end
@[simp] lemma total_degree_C (a : R) : (C a : mv_polynomial σ R).total_degree = 0 :=
nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn,
have _ := finsupp.support_single_subset hn,
begin
rw [finset.mem_singleton] at this,
subst this,
exact le_refl _
end
@[simp] lemma total_degree_zero : (0 : mv_polynomial σ R).total_degree = 0 :=
by rw [← C_0]; exact total_degree_C (0 : R)
@[simp] lemma total_degree_one : (1 : mv_polynomial σ R).total_degree = 0 :=
total_degree_C (1 : R)
@[simp] lemma total_degree_X {R} [comm_semiring R] [nontrivial R] (s : σ) :
(X s : mv_polynomial σ R).total_degree = 1 :=
begin
rw [total_degree, support_X],
simp only [finset.sup, sum_single_index, finset.fold_singleton, sup_bot_eq],
end
lemma total_degree_add (a b : mv_polynomial σ R) :
(a + b).total_degree ≤ max a.total_degree b.total_degree :=
finset.sup_le $ assume n hn,
have _ := finsupp.support_add hn,
begin
rw finset.mem_union at this,
cases this,
{ exact le_max_left_of_le (finset.le_sup this) },
{ exact le_max_right_of_le (finset.le_sup this) }
end
lemma total_degree_mul (a b : mv_polynomial σ R) :
(a * b).total_degree ≤ a.total_degree + b.total_degree :=
finset.sup_le $ assume n hn,
have _ := add_monoid_algebra.support_mul a b hn,
begin
simp only [finset.mem_bUnion, finset.mem_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.sum_add_index],
{ exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) },
{ assume a, refl },
{ assume a b₁ b₂, refl }
end
lemma total_degree_pow (a : mv_polynomial σ R) (n : ℕ) :
(a ^ n).total_degree ≤ n * a.total_degree :=
begin
induction n with n ih,
{ simp only [nat.nat_zero_eq_zero, zero_mul, pow_zero, total_degree_one] },
rw pow_succ,
calc total_degree (a * a ^ n) ≤ a.total_degree + (a^n).total_degree : total_degree_mul _ _
... ≤ a.total_degree + n * a.total_degree : add_le_add_left ih _
... = (n+1) * a.total_degree : by rw [add_mul, one_mul, add_comm]
end
lemma total_degree_list_prod :
∀(s : list (mv_polynomial σ R)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum
| [] := by rw [@list.prod_nil (mv_polynomial σ R) _, total_degree_one]; refl
| (p :: ps) :=
begin
rw [@list.prod_cons (mv_polynomial σ R) _, list.map, list.sum_cons],
exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _)
end
lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ R)) :
s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum :=
begin
refine quotient.induction_on s (assume l, _),
rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum],
exact total_degree_list_prod l
end
lemma total_degree_finset_prod {ι : Type*}
(s : finset ι) (f : ι → mv_polynomial σ R) :
(s.prod f).total_degree ≤ ∑ i in s, (f i).total_degree :=
begin
refine le_trans (total_degree_multiset_prod _) _,
rw [multiset.map_map],
refl
end
lemma exists_degree_lt [fintype σ] (f : mv_polynomial σ R) (n : ℕ)
(h : f.total_degree < n * fintype.card σ) {d : σ →₀ ℕ} (hd : d ∈ f.support) :
∃ i, d i < n :=
begin
contrapose! h,
calc n * fintype.card σ
= ∑ s:σ, n : by rw [finset.sum_const, nat.nsmul_eq_mul, mul_comm, finset.card_univ]
... ≤ ∑ s, d s : finset.sum_le_sum (λ s _, h s)
... ≤ d.sum (λ i e, e) : by { rw [finsupp.sum_fintype], intros, refl }
... ≤ f.total_degree : finset.le_sup hd,
end
lemma coeff_eq_zero_of_total_degree_lt {f : mv_polynomial σ R} {d : σ →₀ ℕ}
(h : f.total_degree < ∑ i in d.support, d i) :
coeff d f = 0 :=
begin
classical,
rw [total_degree, finset.sup_lt_iff] at h,
{ specialize h d, rw mem_support_iff at h,
refine not_not.mp (mt h _), exact lt_irrefl _, },
{ exact lt_of_le_of_lt (nat.zero_le _) h, }
end
lemma total_degree_rename_le (f : σ → τ) (p : mv_polynomial σ R) :
(rename f p).total_degree ≤ p.total_degree :=
finset.sup_le $ assume b,
begin
assume h,
rw rename_eq at h,
have h' := finsupp.map_domain_support h,
rw finset.mem_image at h',
rcases h' with ⟨s, hs, rfl⟩,
rw finsupp.sum_map_domain_index,
exact le_trans (le_refl _) (finset.le_sup hs),
exact assume _, rfl,
exact assume _ _ _, rfl
end
end total_degree
section eval_vars
/-! ### `vars` and `eval` -/
variables [comm_semiring S]
lemma eval₂_hom_eq_constant_coeff_of_vars (f : R →+* S) {g : σ → S}
{p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) :
eval₂_hom f g p = f (constant_coeff p) :=
begin
conv_lhs { rw p.as_sum },
simp only [ring_hom.map_sum, eval₂_hom_monomial],
by_cases h0 : constant_coeff p = 0,
work_on_goal 0
{ rw [h0, f.map_zero, finset.sum_eq_zero],
intros d hd },
work_on_goal 1
{ rw [finset.sum_eq_single (0 : σ →₀ ℕ)],
{ rw [finsupp.prod_zero_index, mul_one],
refl },
intros d hd hd0, },
repeat
{ obtain ⟨i, hi⟩ : d.support.nonempty,
{ rw [constant_coeff_eq, coeff, ← finsupp.not_mem_support_iff] at h0,
rw [finset.nonempty_iff_ne_empty, ne.def, finsupp.support_eq_empty],
rintro rfl, contradiction },
rw [finsupp.prod, finset.prod_eq_zero hi, mul_zero],
rw [hp, zero_pow (nat.pos_of_ne_zero $ finsupp.mem_support_iff.mp hi)],
rw [mem_vars],
exact ⟨d, hd, hi⟩ },
{ rw [constant_coeff_eq, coeff, ← ne.def, ← finsupp.mem_support_iff] at h0,
intro, contradiction }
end
lemma aeval_eq_constant_coeff_of_vars [algebra R S] {g : σ → S}
{p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) :
aeval g p = algebra_map _ _ (constant_coeff p) :=
eval₂_hom_eq_constant_coeff_of_vars _ hp
lemma eval₂_hom_congr' {f₁ f₂ : R →+* S} {g₁ g₂ : σ → S} {p₁ p₂ : mv_polynomial σ R} :
f₁ = f₂ → (∀ i, i ∈ p₁.vars → i ∈ p₂.vars → g₁ i = g₂ i) → p₁ = p₂ →
eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ :=
begin
rintro rfl h rfl,
rename [p₁ p, f₁ f],
rw p.as_sum,
simp only [ring_hom.map_sum, eval₂_hom_monomial],
apply finset.sum_congr rfl,
intros d hd,
congr' 1,
simp only [finsupp.prod],
apply finset.prod_congr rfl,
intros i hi,
have : i ∈ p.vars, { rw mem_vars, exact ⟨d, hd, hi⟩ },
rw h i this this,
end
lemma vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) :
(bind₁ f φ).vars ⊆ φ.vars.bUnion (λ i, (f i).vars) :=
begin
calc (bind₁ f φ).vars
= (φ.support.sum (λ (x : σ →₀ ℕ), (bind₁ f) (monomial x (coeff x φ)))).vars :
by { rw [← alg_hom.map_sum, ← φ.as_sum], }
... ≤ φ.support.bUnion (λ (i : σ →₀ ℕ), ((bind₁ f) (monomial i (coeff i φ))).vars) :
vars_sum_subset _ _
... = φ.support.bUnion (λ (d : σ →₀ ℕ), (C (coeff d φ) * ∏ i in d.support, f i ^ d i).vars) :
by simp only [bind₁_monomial]
... ≤ φ.support.bUnion (λ (d : σ →₀ ℕ), d.support.bUnion (λ i, (f i).vars)) : _ -- proof below
... ≤ φ.vars.bUnion (λ (i : σ), (f i).vars) : _, -- proof below
{ apply finset.bUnion_mono,
intros d hd,
calc (C (coeff d φ) * ∏ (i : σ) in d.support, f i ^ d i).vars
≤ (C (coeff d φ)).vars ∪ (∏ (i : σ) in d.support, f i ^ d i).vars : vars_mul _ _
... ≤ (∏ (i : σ) in d.support, f i ^ d i).vars :
by simp only [finset.empty_union, vars_C, finset.le_iff_subset, finset.subset.refl]
... ≤ d.support.bUnion (λ (i : σ), (f i ^ d i).vars) : vars_prod _
... ≤ d.support.bUnion (λ (i : σ), (f i).vars) : _,
apply finset.bUnion_mono,
intros i hi,
apply vars_pow, },
{ intro j,
simp_rw finset.mem_bUnion,
rintro ⟨d, hd, ⟨i, hi, hj⟩⟩,
exact ⟨i, (mem_vars _).mpr ⟨d, hd, hi⟩, hj⟩ }
end
lemma mem_vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) {j : τ}
(h : j ∈ (bind₁ f φ).vars) :
∃ (i : σ), i ∈ φ.vars ∧ j ∈ (f i).vars :=
by simpa only [exists_prop, finset.mem_bUnion, mem_support_iff, ne.def] using vars_bind₁ f φ h
lemma vars_rename (f : σ → τ) (φ : mv_polynomial σ R) :
(rename f φ).vars ⊆ (φ.vars.image f) :=
begin
intros i hi,
simp only [vars, exists_prop, multiset.mem_to_finset, finset.mem_image] at hi ⊢,
simpa only [multiset.mem_map] using degrees_rename _ _ hi
end
lemma mem_vars_rename (f : σ → τ) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (rename f φ).vars) :
∃ (i : σ), i ∈ φ.vars ∧ f i = j :=
by simpa only [exists_prop, finset.mem_image] using vars_rename f φ h
end eval_vars
end comm_semiring
end mv_polynomial
|
db6da1d88753cd15f11cbbe3184bbb48475c06f5 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Elab/Match.lean | e0ed3d50d5422780017e5a4667eb9bcf270e2e02 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 58,941 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Match.Match
import Lean.Meta.GeneralizeVars
import Lean.Meta.ForEachExpr
import Lean.Elab.AuxDiscr
import Lean.Elab.BindersUtil
import Lean.Elab.PatternVar
import Lean.Elab.Quotation.Precheck
import Lean.Elab.SyntheticMVars
namespace Lean.Elab.Term
open Meta
open Lean.Parser.Term
private def expandSimpleMatch (stx : Syntax) (discr : Term) (lhsVar : Ident) (rhs : Term) (expectedType? : Option Expr) : TermElabM Expr := do
let newStx ← `(let $lhsVar := $discr; $rhs)
withMacroExpansion stx newStx <| elabTerm newStx expectedType?
private def mkUserNameFor (e : Expr) : TermElabM Name := do
match e with
/- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/
| .fvar fvarId => mkFreshUserName (← fvarId.getUserName)
| _ => mkFreshBinderName
/--
We treat `@x` as atomic to avoid unnecessary extra local declarations from being
inserted into the local context. Recall that `expandMatchAltsIntoMatch` uses `@` modifier.
Thus this is kind of discriminant is quite common.
Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression.
This can happen due to error recovery. Example
```
example : (p ∨ p) → p := fun h => match
```
If we don't abort, the elaborator loops because we will keep trying to expand
```
match
```
into
```
let d := <Syntax.missing>; match
```
Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/
def isAtomicDiscr? (discr : Syntax) : TermElabM (Option Expr) := do
match discr with
| `($x:ident) => isLocalIdent? x
| `(@$x:ident) => isLocalIdent? x
| _ => if discr.isMissing then throwAbortTerm else return none
-- See expandNonAtomicDiscrs?
private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do
let term := discr[1]
match (← isAtomicDiscr? term) with
| some e@(Expr.fvar fvarId) =>
let localDecl ← fvarId.getDecl
if !isAuxDiscrName localDecl.userName then
addTermInfo term e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?`
else
instantiateMVars localDecl.value
| _ => throwErrorAt discr "unexpected discriminant"
structure Discr where
expr : Expr
/-- `some h` if discriminant is annotated with the `h : ` notation. -/
h? : Option Syntax := none
deriving Inhabited
structure ElabMatchTypeAndDiscrsResult where
discrs : Array Discr
matchType : Expr
/-- `true` when performing dependent elimination. We use this to decide whether we optimize the "match unit" case.
See `isMatchUnit?`. -/
isDep : Bool
alts : Array MatchAltView
private partial def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptMotive : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr)
: TermElabM ElabMatchTypeAndDiscrsResult := do
if matchOptMotive.isNone then
elabDiscrs 0 #[]
else
-- motive := leading_parser atomic ("(" >> nonReservedSymbol "motive" >> " := ") >> termParser >> ")"
let matchTypeStx := matchOptMotive[0][3]
let matchType ← elabType matchTypeStx
let (discrs, isDep) ← elabDiscrsWitMatchType matchType
return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews }
where
/-- Easy case: elaborate discriminant when the match-type has been explicitly provided by the user. -/
elabDiscrsWitMatchType (matchType : Expr) : TermElabM (Array Discr × Bool) := do
let mut discrs := #[]
let mut i := 0
let mut matchType := matchType
let mut isDep := false
for discrStx in discrStxs do
i := i + 1
matchType ← whnf matchType
match matchType with
| Expr.forallE _ d b _ =>
let discr ← fullApproxDefEq <| elabTermEnsuringType discrStx[1] d
trace[Elab.match] "discr #{i} {discr} : {d}"
if b.hasLooseBVars then
isDep := true
matchType := b.instantiate1 discr
discrs := discrs.push { expr := discr }
| _ =>
throwError "invalid motive provided to match-expression, function type with arity #{discrStxs.size} expected"
return (discrs, isDep)
markIsDep (r : ElabMatchTypeAndDiscrsResult) :=
{ r with isDep := true }
/-- Elaborate discriminants inferring the match-type -/
elabDiscrs (i : Nat) (discrs : Array Discr) : TermElabM ElabMatchTypeAndDiscrsResult := do
if h : i < discrStxs.size then
let discrStx := discrStxs.get ⟨i, h⟩
let discr ← elabAtomicDiscr discrStx
let discr ← instantiateMVars discr
let userName ← mkUserNameFor discr
let h? := if discrStx[0].isNone then none else some discrStx[0][0]
let discrs := discrs.push { expr := discr, h? }
let mut result ← elabDiscrs (i + 1) discrs
let matchTypeBody ← kabstract result.matchType discr
if matchTypeBody.hasLooseBVars then
result := markIsDep result
/-
We use `transform (usedLetOnly := true)` to eliminate unnecessary let-expressions.
This transformation was added to address issue #1155, and avoid an unnecessary dependency.
In issue #1155, `discrType` was of the form `let _discr := OfNat.ofNat ... 0 ?m; ...`, and not removing
the unnecessary `let-expr` was introducing an artificial dependency to `?m`.
TODO: make sure that even when this kind of artificial dependecy occurs we catch it before sending
the term to the kernel.
-/
let discrType ← transform (usedLetOnly := true) (← instantiateMVars (← inferType discr))
let matchType := Lean.mkForall userName BinderInfo.default discrType matchTypeBody
return { result with matchType }
else
return { discrs, alts := matchAltViews, isDep := false, matchType := expectedType }
def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do
matchAlts.mapM fun matchAlt => do
let patterns ← matchAlt.patterns.mapM expandMacros
pure { matchAlt with patterns := patterns }
private def getMatchGeneralizing? : Syntax → Option Bool
| `(match (generalizing := true) $[$motive]? $_discrs,* with $_alts:matchAlt*) => some true
| `(match (generalizing := false) $[$motive]? $_discrs,* with $_alts:matchAlt*) => some false
| _ => none
/-- Given `stx` a match-expression, return its alternatives. -/
private def getMatchAlts : Syntax → Array MatchAltView
| `(match $[$gen]? $[$motive]? $_discrs,* with $alts:matchAlt*) =>
alts.filterMap fun alt => match alt with
| `(matchAltExpr| | $patterns,* => $rhs) => some {
ref := alt,
patterns := patterns,
rhs := rhs
}
| _ => none
| _ => #[]
@[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do
let e ← elabTerm stx[1] expectedType?
return mkInaccessible e
open Lean.Elab.Term.Quotation in
@[builtinQuotPrecheck Lean.Parser.Term.match] def precheckMatch : Precheck
| `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do
discrs.forM precheck
for (pats, rhs) in patss.zip rhss do
let vars ← try
getPatternsVars pats
catch | _ => return -- can happen in case of pattern antiquotations
Quotation.withNewLocals (getPatternVarNames vars) <| precheck rhs
| _ => throwUnsupportedSyntax
/-- We convert the collected `PatternVar`s intro `PatternVarDecl` -/
structure PatternVarDecl where
fvarId : FVarId
private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α :=
let rec loop (i : Nat) (decls : Array PatternVarDecl) (userNames : Array Name) := do
if h : i < pVars.size then
let var := pVars.get ⟨i, h⟩
let type ← mkFreshTypeMVar
withLocalDecl var.getId BinderInfo.default type fun x =>
loop (i+1) (decls.push { fvarId := x.fvarId! }) (userNames.push Name.anonymous)
else
k decls
loop 0 #[] #[]
/-!
Remark: when performing dependent pattern matching, we often had to write code such as
```lean
def Vec.map' (f : α → β) (xs : Vec α n) : Vec β n :=
match n, xs with
| _, nil => nil
| _, cons a as => cons (f a) (map' f as)
```
We had to include `n` and the `_`s because the type of `xs` depends on `n`.
Moreover, `nil` and `cons a as` have different types.
This was quite tedious. So, we have implemented an automatic "discriminant refinement procedure".
The procedure is based on the observation that we get a type error whenenver we forget to include `_`s
and the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant
is an indexed family, and add their indices as new discriminants.
The current implementation, adds indices as they are found, and does not
try to "sort" the new discriminants.
If the refinement process fails, we report the original error message.
-/
/-- Auxiliary structure for storing an type mismatch exception when processing the
pattern #`idx` of some alternative. -/
structure PatternElabException where
ex : Exception
patternIdx : Nat -- Discriminant that sh
pathToIndex : List Nat -- Path to the problematic inductive type index that produced the type mismatch
/--
This method is part of the "discriminant refinement" procedure. It in invoked when the
type of the `pattern` does not match the expected type. The expected type is based on the
motive computed using the `match` discriminants.
It tries to compute a path to an index of the discriminant type.
For example, suppose the user has written
```
inductive Mem (a : α) : List α → Prop where
| head {as} : Mem a (a::as)
| tail {as} : Mem a as → Mem a (a'::as)
infix:50 " ∈ " => Mem
example (a b : Nat) (h : a ∈ [b]) : b = a :=
match h with
| Mem.head => rfl
```
The motive for the match is `a ∈ [b] → b = a`, and get a type mismatch between the type
of `Mem.head` and `a ∈ [b]`. This procedure return the path `[2, 1]` to the index `b`.
We use it to produce the following refinement
```
example (a b : Nat) (h : a ∈ [b]) : b = a :=
match b, h with
| _, Mem.head => rfl
```
which produces the new motive `(x : Nat) → a ∈ [x] → x = a`
After this refinement step, the `match` is elaborated successfully.
This method relies on the fact that the dependent pattern matcher compiler solves equations
between indices of indexed inductive families.
The following kinds of equations are supported by this compiler:
- `x = t`
- `t = x`
- `ctor ... = ctor ...`
where `x` is a free variable, `t` is an arbitrary term, and `ctor` is constructor.
Our procedure ensures that "information" is not lost, and will *not* succeed in an
example such as
```
example (a b : Nat) (f : Nat → Nat) (h : f a ∈ [f b]) : f b = f a :=
match h with
| Mem.head => rfl
```
and will not add `f b` as a new discriminant. We may add an option in the future to
enable this more liberal form of refinement.
-/
private partial def findDiscrRefinementPath (pattern : Expr) (expected : Expr) : OptionT MetaM (List Nat) := do
goType (← instantiateMVars (← inferType pattern)) expected
where
checkCompatibleApps (t d : Expr) : OptionT MetaM Unit := do
guard d.isApp
guard <| t.getAppNumArgs == d.getAppNumArgs
let tFn := t.getAppFn
let dFn := d.getAppFn
guard <| tFn.isConst && dFn.isConst
guard (← isDefEq tFn dFn)
-- Visitor for inductive types
goType (t d : Expr) : OptionT MetaM (List Nat) := do
let t ← whnf t
let d ← whnf d
checkCompatibleApps t d
matchConstInduct t.getAppFn (fun _ => failure) fun info _ => do
let tArgs := t.getAppArgs
let dArgs := d.getAppArgs
for i in [:info.numParams] do
let tArg := tArgs[i]!
let dArg := dArgs[i]!
unless (← isDefEq tArg dArg) do
return i :: (← goType tArg dArg)
for i in [info.numParams : tArgs.size] do
let tArg := tArgs[i]!
let dArg := dArgs[i]!
unless (← isDefEq tArg dArg) do
return i :: (← goIndex tArg dArg)
failure
-- Visitor for indexed families
goIndex (t d : Expr) : OptionT MetaM (List Nat) := do
let t ← whnfD t
let d ← whnfD d
if t.isFVar || d.isFVar then
return [] -- Found refinement path
else
checkCompatibleApps t d
matchConstCtor t.getAppFn (fun _ => failure) fun info _ => do
let tArgs := t.getAppArgs
let dArgs := d.getAppArgs
for i in [:info.numParams] do
let tArg := tArgs[i]!
let dArg := dArgs[i]!
unless (← isDefEq tArg dArg) do
failure
for i in [info.numParams : tArgs.size] do
let tArg := tArgs[i]!
let dArg := dArgs[i]!
unless (← isDefEq tArg dArg) do
return i :: (← goIndex tArg dArg)
failure
private partial def eraseIndices (type : Expr) : MetaM Expr := do
let type' ← whnfD type
matchConstInduct type'.getAppFn (fun _ => return type) fun info _ => do
let args := type'.getAppArgs
let params ← args[:info.numParams].toArray.mapM eraseIndices
let result := mkAppN type'.getAppFn params
let resultType ← inferType result
let (newIndices, _, _) ← forallMetaTelescopeReducing resultType (some (args.size - info.numParams))
return mkAppN result newIndices
private def withPatternElabConfig (x : TermElabM α) : TermElabM α :=
withoutErrToSorry <| withReader (fun ctx => { ctx with inPattern := true }) <| x
private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr × Expr) :=
withReader (fun ctx => { ctx with implicitLambda := false }) do
let mut patterns := #[]
let mut matchType := matchType
for idx in [:patternStxs.size] do
let patternStx := patternStxs[idx]!
matchType ← whnf matchType
match matchType with
| Expr.forallE _ d b _ =>
let pattern ← do
let s ← saveState
try
liftM <| withSynthesize <| withPatternElabConfig <| elabTermEnsuringType patternStx d
catch ex : Exception =>
restoreState s
match (← liftM <| commitIfNoErrors? <| withPatternElabConfig do elabTermAndSynthesize patternStx (← eraseIndices d)) with
| some pattern =>
match (← findDiscrRefinementPath pattern d |>.run) with
| some path =>
restoreState s
-- Wrap the type mismatch exception for the "discriminant refinement" feature.
throwThe PatternElabException { ex := ex, patternIdx := idx, pathToIndex := path }
| none => restoreState s; throw ex
| none => throw ex
matchType := b.instantiate1 pattern
patterns := patterns.push pattern
| _ => throwError "unexpected match type"
return (patterns, matchType)
open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult)
namespace ToDepElimPattern
private def throwInvalidPattern (e : Expr) : MetaM α :=
throwError "invalid pattern {indentExpr e}"
structure State where
patternVars : Array Expr := #[]
structure Context where
/--
When visiting an assigned metavariable, if it has an user-name. We save it here.
We want to preserve these user-names when generating new pattern variables. -/
userName : Name := Name.anonymous
/--
Pattern variables that were explicitly provided by the user.
Recall that implicit parameters and `_` are elaborated as metavariables, and then converted into pattern variables
by the `normalize` procedure.
-/
explicitPatternVars : Array FVarId := #[]
abbrev M := ReaderT Context $ StateRefT State TermElabM
/-- Return true iff `e` is an explicit pattern variable provided by the user. -/
def isExplicitPatternVar (e : Expr) : M Bool := do
if e.isFVar then
return (← read).explicitPatternVars.any (· == e.fvarId!)
else
return false
/--
Helper function for "saving" the user name associated with `mvarId` (if it is not "anonymous") before visiting `x`
The auto generalization feature will uses synthetic holes to preserve the name of the free variable included during generalization.
For example, if we are generalizing a free variable `bla`, we add the synthetic hole `?bla` for the pattern. We use synthetic hole
because we don't know whether `?bla` will become an inaccessible pattern or not.
The `withMVar` method makes sure we don't "lose" this name when `isDefEq` perform assignments of the form `?bla := ?m` where `?m` has no user name.
This can happen, for example, when the user provides a `_` pattern, or for implicit fields.
-/
private def withMVar (mvarId : MVarId) (x : M α) : M α := do
let localDecl ← getMVarDecl mvarId
if !localDecl.userName.isAnonymous && (← read).userName.isAnonymous then
withReader (fun ctx => { ctx with userName := localDecl.userName }) x
else
x
/--
Creating a mapping containing `b ↦ e'` where `patternWithRef e' = some (stx, b)`,
and `e'` is a subterm of `e`.
This is a helper function for `whnfPreservingPatternRef`. -/
private def mkPatternRefMap (e : Expr) : ExprMap Expr :=
runST go
where
go (σ) : ST σ (ExprMap Expr) := do
let map : ST.Ref σ (ExprMap Expr) ← ST.mkRef {}
e.forEach fun e => do
match patternWithRef? e with
| some (_, b) => map.modify (·.insert b e)
| none => return ()
map.get
/--
Try to restore `Syntax` ref information stored in `map` after
applying `whnf` at `whnfPreservingPatternRef`.
It assumes `map` has been constructed using `mkPatternRefMap`.
-/
private def applyRefMap (e : Expr) (map : ExprMap Expr) : Expr :=
e.replace fun e =>
match patternWithRef? e with
| some _ => some e -- stop `e` already has annotation
| none => match map.find? e with
| some eWithRef => some eWithRef -- stop `e` found annotation
| none => none -- continue
/--
Applies `whnf` but tries to preserve `PatternWithRef` information.
This is a bit hackish, but it is necessary for providing proper
jump-to-definition information in examples such as
```
def f (x : Nat) : Nat :=
match x with
| 0 => 1
| y + 1 => y
```
Without this trick, the `PatternWithRef` is lost for the `y` at the pattern `y+1`.
-/
private def whnfPreservingPatternRef (e : Expr) : MetaM Expr := do
let eNew ← whnf e
if eNew.isConstructorApp (← getEnv) then
return eNew
else
return applyRefMap eNew (mkPatternRefMap e)
/--
Normalize the pattern and collect all patterns variables (explicit and implicit).
This method is the one that decides where the inaccessible annotations must be inserted.
The pattern variables are both free variables (for explicit pattern variables) and metavariables (for implicit ones).
Recall that `mkLambdaFVars` now allows us to abstract both free variables and metavariables.
-/
partial def normalize (e : Expr) : M Expr := do
match inaccessible? e with
| some e => processInaccessible e
| none =>
match patternWithRef? e with
| some (ref, e) => return mkPatternWithRef (← normalize e) ref
| none =>
match e.arrayLit? with
| some (α, lits) => mkArrayLit α (← lits.mapM normalize)
| none =>
if let some e := Match.isNamedPattern? e then
let x := e.getArg! 1
let p := e.getArg! 2
let h := e.getArg! 3
unless x.consumeMData.isFVar && h.consumeMData.isFVar do
throwError "unexpected occurrence of auxiliary declaration 'namedPattern'"
addVar x
let p ← normalize p
addVar h
return mkApp4 e.getAppFn (e.getArg! 0) x p h
else if isMatchValue e then
return e
else if e.isFVar then
if (← isExplicitPatternVar e) then
processVar e
else
return mkInaccessible e
else if e.getAppFn.isMVar then
let eNew ← instantiateMVars e
if eNew != e then
withMVar e.getAppFn.mvarId! <| normalize eNew
else if e.isMVar then
withMVar e.mvarId! <| processVar e
else
throwInvalidPattern e
else
let eNew ← whnfPreservingPatternRef e
if eNew != e then
normalize eNew
else
matchConstCtor e.getAppFn
(fun _ => return mkInaccessible (← eraseInaccessibleAnnotations (← instantiateMVars e)))
(fun v _ => do
let args := e.getAppArgs
unless args.size == v.numParams + v.numFields do
throwInvalidPattern e
let params := args.extract 0 v.numParams
let params ← params.mapM fun p => instantiateMVars p
let fields := args.extract v.numParams args.size
let fields ← fields.mapM normalize
return mkAppN e.getAppFn (params ++ fields))
where
addVar (e : Expr) : M Unit := do
let e ← erasePatternRefAnnotations e
unless (← get).patternVars.contains e do
modify fun s => { s with patternVars := s.patternVars.push e }
processVar (e : Expr) : M Expr := do
let e' ← erasePatternRefAnnotations e
if (← get).patternVars.contains e' then
return mkInaccessible (← eraseInaccessibleAnnotations e)
else
if e'.isMVar then
e'.mvarId!.setTag (← read).userName
modify fun s => { s with patternVars := s.patternVars.push e' }
return e
processInaccessible (e : Expr) : M Expr := do
let e' ← erasePatternRefAnnotations e
match e' with
| Expr.fvar _ =>
if (← isExplicitPatternVar e') then
processVar e
else
return mkInaccessible e
| _ =>
if e'.getAppFn.isMVar then
let eNew ← instantiateMVars e'
if eNew != e' then
withMVar e'.getAppFn.mvarId! <| processInaccessible eNew
else if e'.isMVar then
withMVar e'.mvarId! <| processVar e'
else
throwInvalidPattern e
else
return mkInaccessible (← eraseInaccessibleAnnotations (← instantiateMVars e))
/--
Auxiliary function for combining the `matchType` and all patterns into a single expression.
We use it before we abstract all patterns variables. -/
private partial def packMatchTypePatterns (matchType : Expr) (ps : Array Expr) : MetaM Expr :=
ps.foldlM (init := matchType) fun result p => mkAppM ``PProd.mk #[result, p]
/-- The inverse of `packMatchTypePatterns`. -/
private partial def unpackMatchTypePatterns (p : Expr) : Expr × Array Expr :=
if p.isAppOf ``PProd.mk then
let (matchType, ps) := unpackMatchTypePatterns (p.getArg! 2)
(matchType, ps.push (p.getArg! 3))
else
(p, #[])
/--
Convert a (normalized) pattern encoded as an `Expr` into a `Pattern`.
This method assumes that `e` has been normalized and the explicit and implicit (i.e., metavariables) pattern variables have
already been abstracted and converted back into new free variables.
-/
private partial def toPattern (e : Expr) : MetaM Pattern := do
match inaccessible? e with
| some e => return Pattern.inaccessible e
| none =>
match e.arrayLit? with
| some (α, lits) => return Pattern.arrayLit α (← lits.mapM toPattern)
| none =>
if let some e := Match.isNamedPattern? e then
let p ← toPattern <| e.getArg! 2
match e.getArg! 1, e.getArg! 3 with
| Expr.fvar x, Expr.fvar h => return Pattern.as x p h
| _, _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'"
else if isMatchValue e then
return Pattern.val e
else if e.isFVar then
return Pattern.var e.fvarId!
else
matchConstCtor e.getAppFn (fun _ => unreachable!) fun v us => do
let args := e.getAppArgs
let params := args.extract 0 v.numParams
let params ← params.mapM fun p => instantiateMVars p
let fields := args.extract v.numParams args.size
let fields ← fields.mapM toPattern
return Pattern.ctor v.name us params.toList fields.toList
structure TopSort.State where
visitedFVars : FVarIdSet := {}
visitedMVars : MVarIdSet := {}
result : Array Expr := #[]
abbrev TopSortM := StateRefT TopSort.State TermElabM
/--
Topological sort. We need it because inaccessible patterns may contain pattern variables that are declared later.
That is, processing patterns from left to right to do not guarantee that the pattern variables are collected in the
"right" order. "Right" here means pattern `x` must occur befor pattern `y` if `y`s type depends on `x`.
-/
private partial def topSort (patternVars : Array Expr) : TermElabM (Array Expr) := do
let (_, s) ← patternVars.mapM visit |>.run {}
return s.result
where
visit (e : Expr) : TopSortM Unit := do
match e with
| Expr.proj _ _ e => visit e
| Expr.forallE _ d b _ => visit d; visit b
| Expr.lam _ d b _ => visit d; visit b
| Expr.letE _ t v b _ => visit t; visit v; visit b
| Expr.app f a => visit f; visit a
| Expr.mdata _ b => visit b
| Expr.mvar mvarId =>
let v ← instantiateMVars e
if !v.isMVar then
visit v
else if patternVars.contains e then
unless (← get).visitedMVars.contains mvarId do
modify fun s => { s with visitedMVars := s.visitedMVars.insert mvarId }
let mvarDecl ← getMVarDecl mvarId
visit mvarDecl.type
modify fun s => { s with result := s.result.push e }
| Expr.fvar fvarId =>
if patternVars.contains e then
unless (← get).visitedFVars.contains fvarId do
modify fun s => { s with visitedFVars := s.visitedFVars.insert fvarId }
visit (← fvarId.getType)
modify fun s => { s with result := s.result.push e }
| _ => return ()
/--
Save pattern information in the info tree, and remove `patternWithRef?` annotations.
-/
partial def savePatternInfo (p : Expr) : TermElabM Expr :=
go p |>.run false
where
/-- The `Bool` context is true iff we are inside of an "inaccessible" pattern. -/
go (p : Expr) : ReaderT Bool TermElabM Expr := do
match p with
| .forallE n d b bi => withLocalDecl n bi (← go d) fun x => do mkForallFVars #[x] (← go (b.instantiate1 x))
| .lam n d b bi => withLocalDecl n bi (← go d) fun x => do mkLambdaFVars #[x] (← go (b.instantiate1 x))
| .letE n t v b .. => withLetDecl n (← go t) (← go v) fun x => do mkLetFVars #[x] (← go (b.instantiate1 x))
| .app f a => return mkApp (← go f) (← go a)
| .proj _ _ b => return p.updateProj! (← go b)
| .mdata k b =>
if inaccessible? p |>.isSome then
return mkMData k (← withReader (fun _ => false) (go b))
else if let some (stx, p) := patternWithRef? p then
Elab.withInfoContext' (go p) fun p => do
/- If `p` is a free variable and we are not inside of an "inaccessible" pattern, this `p` is a binder. -/
mkTermInfo Name.anonymous stx p (isBinder := p.isFVar && !(← read))
else
return mkMData k (← go b)
| _ => return p
/--
Main method for `withDepElimPatterns`.
- `PatternVarDecls`: are the explicit pattern variables provided by the user.
- `ps`: are the patterns provided by the user.
- `matchType`: the expected typ for this branch. It depends on the explicit pattern variables and the implicit ones that are still represented as metavariables,
and are found by this function.
- `k` is the continuation that is executed in an updated local context with the all pattern variables (explicit and implicit). Note that, `patternVarDecls` are all
replaced since they may depend on implicit pattern variables (i.e., metavariables) that are converted into new free variables by this method.
-/
partial def main (patternVarDecls : Array PatternVarDecl) (ps : Array Expr) (matchType : Expr) (k : Array LocalDecl → Array Pattern → Expr → TermElabM α) : TermElabM α := do
let explicitPatternVars := patternVarDecls.map fun decl => decl.fvarId
let (ps, s) ← ps.mapM normalize |>.run { explicitPatternVars } |>.run {}
let patternVars ← topSort s.patternVars
trace[Elab.match] "patternVars after topSort: {patternVars}"
for explicit in explicitPatternVars do
unless patternVars.any (· == mkFVar explicit) do
withInPattern do
throwError "invalid patterns, `{mkFVar explicit}` is an explicit pattern variable, but it only occurs in positions that are inaccessible to pattern matching{indentD (MessageData.joinSep (ps.toList.map (MessageData.ofExpr .)) m!"\n\n")}"
let packed ← pack patternVars ps matchType
trace[Elab.match] "packed: {packed}"
let lctx := explicitPatternVars.foldl (init := (← getLCtx)) fun lctx d => lctx.erase d
withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do
check packed
unpack packed fun patternVars patterns matchType => do
let localDecls ← patternVars.mapM fun x => x.fvarId!.getDecl
trace[Elab.match] "patternVars: {patternVars}, matchType: {matchType}"
k localDecls (← patterns.mapM fun p => toPattern p) matchType
where
pack (patternVars : Array Expr) (ps : Array Expr) (matchType : Expr) : MetaM Expr := do
/-
Recall that some of the `patternVars` are metavariables without a user facing name.
Thus, this method tries to infer names for them using `ps` before performing the `mkLambdaFVars` abstraction.
Let `?m` be a metavariable in `patternVars` without a user facing name.
The heuristic uses the patterns `ps`. We traverse the patterns from right to left searching for applications
`f ... ?m`. The name for the corresponding `f`-parameter is used to name `?m`.
We search from right to left to make sure we visit a pattern before visiting its indices. Example:
```
#[@List.cons α i ?m, @HList.cons α β i ?m a as, @Member.head α i ?m]
```
-/
let setMVarsAt (e : Expr) : StateRefT (Array MVarId) MetaM Unit := do
let mvarIds ← setMVarUserNamesAt (← erasePatternRefAnnotations e) patternVars
modify (· ++ mvarIds)
let go : StateRefT (Array MVarId) MetaM Expr := do
try
for p in ps.reverse do
setMVarsAt p
mkLambdaFVars patternVars (← packMatchTypePatterns matchType ps) (binderInfoForMVars := BinderInfo.default)
finally
resetMVarUserNames (← get)
go |>.run' #[]
unpack (packed : Expr) (k : (patternVars : Array Expr) → (patterns : Array Expr) → (matchType : Expr) → TermElabM α) : TermElabM α :=
let rec go (packed : Expr) (patternVars : Array Expr) : TermElabM α := do
match packed with
| .lam n d b _ =>
withLocalDeclD n (← erasePatternRefAnnotations (← eraseInaccessibleAnnotations d)) fun patternVar =>
go (b.instantiate1 patternVar) (patternVars.push patternVar)
| _ =>
let (matchType, patterns) := unpackMatchTypePatterns packed
let matchType ← erasePatternRefAnnotations (← eraseInaccessibleAnnotations matchType)
let patterns ← patterns.mapM (savePatternInfo ·)
k patternVars patterns matchType
go packed #[]
end ToDepElimPattern
def withDepElimPatterns (patternVarDecls : Array PatternVarDecl) (ps : Array Expr) (matchType : Expr) (k : Array LocalDecl → Array Pattern → Expr → TermElabM α) : TermElabM α := do
ToDepElimPattern.main patternVarDecls ps matchType k
private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr)
(k : AltLHS → Expr → TermElabM α) : ExceptT PatternElabException TermElabM α := do
let (patterns, matchType) ← withSynthesize <| elabPatterns patternStxs matchType
id (α := TermElabM α) do
trace[Elab.match] "patterns: {patterns}"
withDepElimPatterns patternVarDecls patterns matchType fun localDecls patterns matchType => do
k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType
/--
Try to clear the free variables in `toClear` and auxiliary discriminants, and then execute `k` in the updated local context.
If `type` or another local variables depends on a free variable in `toClear`, then it is not cleared.
-/
private def withToClear (toClear : Array FVarId) (type : Expr) (k : TermElabM α) : TermElabM α := do
if toClear.isEmpty then
k
else
let toClear ← sortFVarIds toClear
trace[Elab.match] ">> toClear {toClear.map mkFVar}"
let mut lctx ← getLCtx
let mut localInsts ← getLocalInstances
for fvarId in toClear.reverse do
if !(← dependsOn type fvarId) then
if !(← lctx.anyM fun localDecl => pure (localDecl.fvarId != fvarId) <&&> localDeclDependsOn localDecl fvarId) then
lctx := lctx.erase fvarId
localInsts := localInsts.filter fun localInst => localInst.fvar.fvarId! != fvarId
withLCtx lctx localInsts k
private def withoutAuxDiscrs (matchType : Expr) (k : TermElabM α) : TermElabM α := do
let mut toClear := #[]
for localDecl in (← getLCtx) do
if isAuxDiscrName localDecl.userName || isAuxFunDiscrName localDecl.userName then
toClear := toClear.push localDecl.fvarId
withToClear toClear matchType k
/--
Generate equalities `h : discr = pattern` for discriminants annotated with `h :`.
We use these equalities to elaborate the right-hand-side of a `match` alternative.
-/
private def withEqs (discrs : Array Discr) (patterns : List Pattern) (k : Array Expr → TermElabM α) : TermElabM α := do
go 0 patterns #[]
where
go (i : Nat) (ps : List Pattern) (eqs : Array Expr) : TermElabM α := do
match ps with
| [] => k eqs
| p::ps =>
if h : i < discrs.size then
let discr := discrs.get ⟨i, h⟩
if let some h := discr.h? then
withLocalDeclD h.getId (← mkEqHEq discr.expr (← p.toExpr)) fun eq => do
addTermInfo' h eq (isBinder := true)
go (i+1) ps (eqs.push eq)
else
go (i+1) ps eqs
else
k eqs
/--
Elaborate the `match` alternative `alt` using the given `matchType`.
The array `toClear` contains variables that must be cleared before elaborating the `rhs` because
they have been generalized/refined.
-/
private def elabMatchAltView (discrs : Array Discr) (alt : MatchAltView) (matchType : Expr) (toClear : Array FVarId) : ExceptT PatternElabException TermElabM (AltLHS × Expr) := withRef alt.ref do
withoutAuxDiscrs matchType do
let (patternVars, alt) ← collectPatternVars alt
trace[Elab.match] "patternVars: {patternVars}"
withPatternVars patternVars fun patternVarDecls => do
withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType =>
withEqs discrs altLHS.patterns fun eqs =>
withLocalInstances altLHS.fvarDecls do
trace[Elab.match] "elabMatchAltView: {matchType}"
-- connect match-generalized pattern fvars, which are a suffix of `latLHS.fvarDecls`,
-- to their original fvars (independently of whether they were cleared successfully) in the info tree
for (fvar, baseId) in altLHS.fvarDecls.toArray.reverse.zip toClear.reverse do
pushInfoLeaf <| .ofFVarAliasInfo { id := fvar.fvarId, baseId }
let matchType ← instantiateMVars matchType
-- If `matchType` is of the form `@m ...`, we create a new metavariable with the current scope.
-- This improves the effectiveness of the `isDefEq` default approximations
let matchType' ← if matchType.getAppFn.isMVar then mkFreshTypeMVar else pure matchType
withToClear toClear matchType' do
let rhs ← elabTermEnsuringType alt.rhs matchType'
-- We use all approximations to ensure the auxiliary type is defeq to the original one.
unless (← fullApproxDefEq <| isDefEq matchType' matchType) do
throwError "type mistmatch, alternative {← mkHasTypeButIsExpectedMsg matchType' matchType}"
let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr ++ eqs
let rhs ← if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs
trace[Elab.match] "rhs: {rhs}"
return (altLHS, rhs)
/--
Collect problematic index for the "discriminant refinement feature". This method is invoked
when we detect a type mismatch at a pattern #`idx` of some alternative. -/
private partial def getIndexToInclude? (discr : Expr) (pathToIndex : List Nat) : TermElabM (Option Expr) := do
go (← inferType discr) pathToIndex |>.run
where
go (e : Expr) (path : List Nat) : OptionT MetaM Expr := do
match path with
| [] => return e
| i::path =>
let e ← whnfD e
guard <| e.isApp && i < e.getAppNumArgs
go (e.getArg! i) path
structure GeneralizeResult where
discrs : Array Discr
/-- `FVarId`s of the variables that have been generalized. We store them to clear after in each branch. -/
toClear : Array FVarId := #[]
matchType : Expr
altViews : Array MatchAltView
refined : Bool := false
/--
"Generalize" variables that depend on the discriminants.
Remarks and limitations:
- We currently do not generalize let-decls.
- We abort generalization if the new `matchType` is type incorrect.
- Only discriminants that are free variables are considered during specialization.
- We "generalize" by adding new discriminants and pattern variables. We do not "clear" the generalized variables,
but they become inaccessible since they are shadowed by the patterns variables. We assume this is ok since
this is the exact behavior users would get if they had written it by hand. Recall there is no `clear` in term mode.
-/
private def generalize (discrs : Array Discr) (matchType : Expr) (altViews : Array MatchAltView) (generalizing? : Option Bool) : TermElabM GeneralizeResult := do
let gen := if let some g := generalizing? then g else true
if !gen then
return { discrs, matchType, altViews }
else
let discrExprs := discrs.map (·.expr)
/- let-decls are currently being ignored by the generalizer. -/
let ysFVarIds ← getFVarsToGeneralize discrExprs (ignoreLetDecls := true)
if ysFVarIds.isEmpty then
return { discrs, matchType, altViews }
else
let ys := ysFVarIds.map mkFVar
let matchType' ← forallBoundedTelescope matchType discrs.size fun ds type => do
let type ← mkForallFVars ys type
let (discrs', ds') := Array.unzip <| Array.zip discrExprs ds |>.filter fun (di, _) => di.isFVar
let type := type.replaceFVars discrs' ds'
mkForallFVars ds type
if (← isTypeCorrect matchType') then
let discrs := discrs ++ ys.map fun y => { expr := y : Discr }
let altViews ← altViews.mapM fun altView => do
let patternVars ← getPatternsVars altView.patterns
-- We traverse backwards because we want to keep the most recent names.
-- For example, if `ys` contains `#[h, h]`, we want to make sure `mkFreshUsername is applied to the first `h`,
-- since it is already shadowed by the second.
let ysUserNames ← ys.foldrM (init := #[]) fun ys ysUserNames => do
let yDecl ← ys.fvarId!.getDecl
let mut yUserName := yDecl.userName
if ysUserNames.contains yUserName then
yUserName ← mkFreshUserName yUserName
-- Explicitly provided pattern variables shadow `y`
else if patternVars.any fun x => x.getId == yUserName then
yUserName ← mkFreshUserName yUserName
return ysUserNames.push yUserName
let ysIds ← ysUserNames.reverse.mapM fun n => return mkIdentFrom (← getRef) n
return { altView with patterns := altView.patterns ++ ysIds }
return { discrs, toClear := ysFVarIds, matchType := matchType', altViews, refined := true }
else
return { discrs, matchType, altViews }
private partial def elabMatchAltViews (generalizing? : Option Bool) (discrs : Array Discr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Discr × Expr × Array (AltLHS × Expr) × Bool) := do
loop discrs #[] matchType altViews none
where
/--
"Discriminant refinement" main loop.
`first?` contains the first error message we found before updated the `discrs`. -/
loop (discrs : Array Discr) (toClear : Array FVarId) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState × Exception))
: TermElabM (Array Discr × Expr × Array (AltLHS × Expr) × Bool) := do
let s ← saveState
let { discrs := discrs', toClear := toClear', matchType := matchType', altViews := altViews', refined } ← generalize discrs matchType altViews generalizing?
match (← altViews'.mapM (fun altView => elabMatchAltView discrs' altView matchType' (toClear ++ toClear')) |>.run) with
| Except.ok alts => return (discrs', matchType', alts, first?.isSome || refined)
| Except.error { patternIdx := patternIdx, pathToIndex := pathToIndex, ex := ex } =>
let discr := discrs[patternIdx]!
let some index ← getIndexToInclude? discr.expr pathToIndex
| throwEx (← updateFirst first? ex)
trace[Elab.match] "index to include: {index}"
if (← discrs.anyM fun discr => isDefEq discr.expr index) then
throwEx (← updateFirst first? ex)
let first ← updateFirst first? ex
s.restore (restoreInfo := true)
let indices ← collectDeps #[index] (discrs.map (·.expr))
let matchType ← try
updateMatchType indices matchType
catch _ => throwEx first
let ref ← getRef
trace[Elab.match] "new indices to add as discriminants: {indices}"
let wildcards ← indices.mapM fun index => do
if index.isFVar then
let localDecl ← index.fvarId!.getDecl
if localDecl.userName.hasMacroScopes then
return mkHole ref
else
let id := mkIdentFrom ref localDecl.userName
`(?$id)
else
return mkHole ref
let altViews := altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns }
let indDiscrs ← indices.mapM fun i => do
match discr.h? with
| none => return { expr := i : Discr }
| some h =>
-- If the discriminant that introduced this index is annotated with `h : discr`, then we should annotate the new discriminant too.
let h := mkIdentFrom h (← mkFreshUserName `h)
return { expr := i, h? := h : Discr }
let discrs := indDiscrs ++ discrs
let indexFVarIds := indices.filterMap fun | .fvar fvarId .. => some fvarId | _ => none
loop discrs (toClear ++ indexFVarIds) matchType altViews first
throwEx {α} (p : SavedState × Exception) : TermElabM α := do
p.1.restore (restoreInfo := true); throw p.2
updateFirst (first? : Option (SavedState × Exception)) (ex : Exception) : TermElabM (SavedState × Exception) := do
match first? with
| none => return (← saveState, ex)
| some first => return first
containsFVar (es : Array Expr) (fvarId : FVarId) : Bool :=
es.any fun e => e.isFVar && e.fvarId! == fvarId
/-- Update `indices` by including any free variable `x` s.t.
- Type of some `discr` depends on `x`.
- Type of `x` depends on some free variable in `indices`.
If we don't include these extra variables in indices, then
`updateMatchType` will generate a type incorrect term.
For example, suppose `discr` contains `h : @HEq α a α b`, and
`indices` is `#[α, b]`, and `matchType` is `@HEq α a α b → B`.
`updateMatchType indices matchType` produces the type
`(α' : Type) → (b : α') → @HEq α' a α' b → B` which is type incorrect
because we have `a : α`.
The method `collectDeps` will include `a` into `indices`.
This method does not handle dependencies among non-free variables.
We rely on the type checking method `check` at `updateMatchType`.
Remark: `indices : Array Expr` does not need to be an array anymore.
We should cleanup this code, and use `index : Expr` instead.
-/
collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do
let mut s : CollectFVars.State := {}
for discr in discrs do
s := collectFVars s (← instantiateMVars (← inferType discr))
let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar
let indicesFVar := indicesFVar.map Expr.fvarId!
let mut toAdd := #[]
for fvarId in s.fvarSet.toList do
unless containsFVar discrs fvarId || containsFVar indices fvarId do
let localDecl ← fvarId.getDecl
for indexFVarId in indicesFVar do
if (← localDeclDependsOn localDecl indexFVarId) then
toAdd := toAdd.push fvarId
let indicesFVar ← sortFVarIds (indicesFVar ++ toAdd)
return indicesFVar.map mkFVar ++ indicesNonFVar
updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do
let matchType ← indices.foldrM (init := matchType) fun index matchType => do
let indexType ← inferType index
let matchTypeBody ← kabstract matchType index
let userName ← mkUserNameFor index
return Lean.mkForall userName BinderInfo.default indexType matchTypeBody
check matchType
return matchType
def mkMatcher (input : Meta.Match.MkMatcherInput) : TermElabM MatcherResult :=
Meta.Match.mkMatcher input
register_builtin_option match.ignoreUnusedAlts : Bool := {
defValue := false
descr := "if true, do not generate error if an alternative is not used"
}
def reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do
unless result.counterExamples.isEmpty do
withHeadRefOnly <| logError m!"missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}"
return ()
unless match.ignoreUnusedAlts.get (← getOptions) || result.unusedAltIdxs.isEmpty do
let mut i := 0
for alt in altLHSS do
if result.unusedAltIdxs.contains i then
withRef alt.ref do
logError "redundant alternative"
i := i + 1
/--
If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]`
Otherwise, return none.
-/
private def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do
assert! altLHSS.length == rhss.size
match altLHSS with
| [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] =>
/- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/
match rhss[0]! with
| Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b
| _ => return none
| _ => return none
private def elabMatchAux (generalizing? : Option Bool) (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptMotive : Syntax) (expectedType : Expr)
: TermElabM Expr := do
let mut generalizing? := generalizing?
if !matchOptMotive.isNone then
if generalizing? == some true then
throwError "the '(generalizing := true)' parameter is not supported when the 'match' motive is explicitly provided"
generalizing? := some false
let (discrs, matchType, altLHSS, isDep, rhss) ← commitIfDidNotPostpone do
let ⟨discrs, matchType, isDep, altViews⟩ ← elabMatchTypeAndDiscrs discrStxs matchOptMotive altViews expectedType
let matchAlts ← liftMacroM <| expandMacrosInPatterns altViews
trace[Elab.match] "matchType: {matchType}"
let (discrs, matchType, alts, refined) ← elabMatchAltViews generalizing? discrs matchType matchAlts
let isDep := isDep || refined
/-
We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be
able to elaborate examples such as:
```
def f (x : Nat) : Option Nat := none
def g (xs : List (Nat × Nat)) : IO Unit :=
xs.forM fun x =>
match f x.fst with
| _ => pure ()
```
If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because
the type of `x` is only available after we proces the last argument of `List.forM`.
We apply pending default types to make sure we can process examples such as
```
let (a, b) := (0, 0)
```
-/
synthesizeSyntheticMVarsUsingDefault
let rhss := alts.map Prod.snd
let matchType ← instantiateMVars matchType
let altLHSS ← alts.toList.mapM fun alt => do
let altLHS ← Match.instantiateAltLHSMVars alt.1
/- Remark: we try to postpone before throwing an error.
The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed.
The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here.
Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here.
```
def bad (ps : Array (Nat × Nat)) : Array (Nat × Nat) :=
(ps.filter fun (p : Prod _ _) =>
match p with
| (x, y) => x == 0)
++
ps
```
When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet
because `Array.filter` has type `{α : Type u_1} → (α → Bool) → (as : Array α) → optParam Nat 0 → optParam Nat (Array.size as) → Array α`
However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`.
-/
withRef altLHS.ref do
for d in altLHS.fvarDecls do
if d.hasExprMVar then
tryPostpone
withExistingLocalDecls altLHS.fvarDecls do
runPendingTacticsAt d.type
if (← instantiateMVars d.type).hasExprMVar then
throwMVarError m!"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}"
for p in altLHS.patterns do
if (← Match.instantiatePatternMVars p).hasExprMVar then
tryPostpone
withExistingLocalDecls altLHS.fvarDecls do
throwMVarError m!"invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}"
pure altLHS
return (discrs, matchType, altLHSS, isDep, rhss)
if let some r ← if isDep then pure none else isMatchUnit? altLHSS rhss then
return r
else
let numDiscrs := discrs.size
let matcherName ← mkAuxName `match
let matcherResult ← mkMatcher { matcherName, matchType, discrInfos := discrs.map fun discr => { hName? := discr.h?.map (·.getId) }, lhss := altLHSS }
reportMatcherResultErrors altLHSS matcherResult
matcherResult.addMatcher
let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType
let r := mkApp matcherResult.matcher motive
let r := mkAppN r (discrs.map (·.expr))
let r := mkAppN r rhss
trace[Elab.match] "result: {r}"
return r
-- leading_parser "match " >> optional generalizingParam >> optional motive >> sepBy1 matchDiscr ", " >> " with " >> ppDedent matchAlts
private def getDiscrs (matchStx : Syntax) : Array Syntax :=
matchStx[3].getSepArgs
private def getMatchOptMotive (matchStx : Syntax) : Syntax :=
matchStx[2]
open TSyntax.Compat in
private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) :=
let matchOptMotive := getMatchOptMotive matchStx
if matchOptMotive.isNone then do
let discrs := getDiscrs matchStx
let allLocal ← discrs.allM fun discr => Option.isSome <$> isAtomicDiscr? discr[1]
if allLocal then
return none
else
-- We use `foundFVars` to make sure the discriminants are distinct variables.
-- See: code for computing "matchType" at `elabMatchTypeAndDiscrs`
let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) (foundFVars : FVarIdSet) := do
match discrs with
| [] =>
let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", ")
pure (matchStx.setArg 3 discrs)
| discr :: discrs =>
-- Recall that
-- matchDiscr := leading_parser optional (ident >> ":") >> termParser
let term := discr[1]
let addAux : TermElabM Syntax := withFreshMacroScope do
let d ← mkAuxDiscr
unless isAuxDiscrName d.getId do -- Use assertion?
throwError "unexpected internal auxiliary discriminant name"
let discrNew := discr.setArg 1 d
let r ← loop discrs (discrsNew.push discrNew) foundFVars
`(let $d := $term; $r)
match (← isAtomicDiscr? term) with
| some x => if x.isFVar then loop discrs (discrsNew.push discr) (foundFVars.insert x.fvarId!) else addAux
| none => addAux
return some (← loop discrs.toList #[] {})
else
-- We do not pull non atomic discriminants when match type is provided explicitly by the user
return none
private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do
tryPostponeIfNoneOrMVar expectedType?
match expectedType? with
| some expectedType => pure expectedType
| none => mkFreshTypeMVar
private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do
-- We don't wait for the discriminants types when match type is provided by user
if getMatchOptMotive matchStx |>.isNone then
let discrs := getDiscrs matchStx
for discr in discrs do
let term := discr[1]
match (← isAtomicDiscr? term) with
| none => throwErrorAt discr "unexpected discriminant" -- see `expandNonAtomicDiscrs?
| some d =>
let dType ← inferType d
trace[Elab.match] "discr {d} : {dType}"
tryPostponeIfMVar dType
/--
We (try to) elaborate a `match` only when the expected type is available.
If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type
of a discriminant is not available. That is, it is of the form `(?m ...)`.
We use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables.
This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances.
Suppose, we are trying to elaborate
```
match g x with
| ... => ...
```
`expandNonAtomicDiscrs?` converts it intro
```
let _discr := g x
match _discr with
| ... => ...
```
Thus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`.
Note that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`.
This elaboration technique is needed to elaborate terms such as:
```lean
xs.filter fun (a, b) => a > b
```
which are syntax sugar for
```lean
List.filter (fun p => match p with | (a, b) => a > b) xs
```
When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet.
-/
private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
tryPostponeIfNoneOrMVar expectedType?
tryPostponeIfDiscrTypeIsMVar matchStx
match expectedType? with
| some expectedType => return expectedType
| none => mkFreshTypeMVar
/--
```
leading_parser "match " >> optional generalizingParam >> optional motive >> sepBy1 matchDiscr ", " >> " with " >> ppDedent matchAlts
```
Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`.
-/
private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
let expectedType ← waitExpectedTypeAndDiscrs stx expectedType?
let discrStxs := (getDiscrs stx).map fun d => d
let gen? := getMatchGeneralizing? stx
let altViews := getMatchAlts stx
let matchOptMotive := getMatchOptMotive stx
elabMatchAux gen? discrStxs altViews matchOptMotive expectedType
private def isPatternVar (stx : Syntax) : TermElabM Bool := do
match (← resolveId? stx "pattern") with
| none => return isAtomicIdent stx
| some f => match f with
| Expr.const fName _ =>
match (← getEnv).find? fName with
| some (ConstantInfo.ctorInfo _) => return false
| some _ => return !hasMatchPatternAttribute (← getEnv) fName
| _ => return isAtomicIdent stx
| _ => return isAtomicIdent stx
where
isAtomicIdent (stx : Syntax) : Bool :=
stx.isIdent && stx.getId.eraseMacroScopes.isAtomic
@[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => do
match stx with
| `(match $discr:term with | $y:ident => $rhs) =>
if (← isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType?
| _ => elabMatchDefault stx expectedType?
where
elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
match (← liftMacroM <| expandMatchAlts? stx) with
| some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?
| none =>
match (← expandNonAtomicDiscrs? stx) with
| some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?
| none =>
let discrs := getDiscrs stx
let matchOptMotive := getMatchOptMotive stx
if !matchOptMotive.isNone && discrs.any fun d => !d[0].isNone then
throwErrorAt matchOptMotive "match motive should not be provided when discriminants with equality proofs are used"
elabMatchCore stx expectedType?
builtin_initialize
registerTraceClass `Elab.match
-- leading_parser:leadPrec "nomatch " >> termParser
@[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => do
match stx with
| `(nomatch $discrExpr) =>
match (← isLocalIdent? discrExpr) with
| some _ =>
let expectedType ← waitExpectedType expectedType?
let discr := mkNode ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr]
elabMatchAux none #[discr] #[] mkNullNode expectedType
| _ =>
let d ← mkAuxDiscr
let stxNew ← `(let $d := $discrExpr; nomatch $d)
withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?
| _ => throwUnsupportedSyntax
end Lean.Elab.Term
|
ceffa6988621e11197f9a300e3d16c767bd90748 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/smt/prove.lean | f1677779e10d28be848b7032f5c6fadd6119c098 | [] | 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 | 82 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
namespace Mathlib
|
3dbb1a4cf3ca5ad15c187bce2481ea13117fe2a3 | 439bc6c3e74a118aa51df633b8e1f24415804d86 | /types.lean | 3616b3adb62f8bea592d9ca9132e6ba6dcfd8de2 | [] | no_license | jcommelin/lt2019_slides | 4ca498db02b5187c5778c21b985126d52d260696 | 3234cd92920d3d4321cc2cef78b48e5fa55be413 | refs/heads/master | 1,586,718,101,957 | 1,546,930,855,000 | 1,546,930,855,000 | 162,697,592 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 136 | lean | instance types : large_category (Type u) :=
{ hom := λ a b, (a → b),
id := λ a, id,
comp := λ _ _ _ f g, g ∘ f }
|
b1d95ed83e1a89ebf2fe2e6ea384773428d2f4ab | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2022/logic/sheet5.lean | 699e8263fcd6570bd1e098e249d7b65475deed1e | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 1,414 | lean | /-
Copyright (c) 2022 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Kevin Buzzard
-/
import tactic -- imports all the Lean tactics
/-!
# Logic in Lean, example sheet 5 : "iff" (`↔`)
We learn about how to manipulate `P ↔ Q` in Lean.
## Tactics
You'll need to know about the tactics from the previous sheets,
and also the following two new tactics:
* `refl`
* `rw`
### The `refl` tactic
If your goal is `P ↔ P` then `refl,` will solve it.
### The `rw` tactic
If `h : P ↔ Q` is a hypothesis, you can decompose it
using `cases h with hPQ hQP,`. However, if you keep
it around then you can do `rw h,` which changes all `P`s in the goal to `Q`s.
Variant: `rw h at h2,` will change all `P`s to `Q`s in hypothesis `h2`.
-/
variables (P Q R S : Prop)
example : P ↔ P :=
begin
sorry
end
example : (P ↔ Q) → (Q ↔ P) :=
begin
sorry
end
example : (P ↔ Q) ↔ (Q ↔ P) :=
begin
sorry
end
example : (P ↔ Q) → (Q ↔ R) → (P ↔ R) :=
begin
sorry
end
example : P ∧ Q ↔ Q ∧ P :=
begin
sorry
end
example : ((P ∧ Q) ∧ R) ↔ (P ∧ (Q ∧ R)) :=
begin
sorry
end
example : P ↔ (P ∧ true) :=
begin
sorry
end
example : false ↔ (P ∧ false) :=
begin
sorry
end
example : (P ↔ Q) → (R ↔ S) → (P ∧ R ↔ Q ∧ S) :=
begin
sorry
end
example : ¬ (P ↔ ¬ P) :=
begin
sorry,
end
|
e1aab482d85b8e32a9e5e47b60491a66f8efaf82 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/computability/DFA.lean | b5006e4745c4545f0b70c091e8ab3d08bc94a493 | [
"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 | 4,621 | lean | /-
Copyright (c) 2020 Fox Thomson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Fox Thomson
-/
import data.fintype.basic
import computability.language
import tactic.norm_num
/-!
# Deterministic Finite Automata
This file contains the definition of a Deterministic Finite Automaton (DFA), a state machine which
determines whether a string (implemented as a list over an arbitrary alphabet) is in a regular set
in linear time.
Note that this definition allows for Automaton with infinite states, a `fintype` instance must be
supplied for true DFA's.
-/
universes u v
/-- A DFA is a set of states (`σ`), a transition function from state to state labelled by the
alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`). -/
structure DFA (α : Type u) (σ : Type v) :=
(step : σ → α → σ)
(start : σ)
(accept : set σ)
namespace DFA
variables {α : Type u} {σ : Type v} (M : DFA α σ)
instance [inhabited σ] : inhabited (DFA α σ) :=
⟨DFA.mk (λ _ _, default σ) (default σ) ∅⟩
/-- `M.eval_from s x` evaluates `M` with input `x` starting from the state `s`. -/
def eval_from (start : σ) : list α → σ :=
list.foldl M.step start
/-- `M.eval x` evaluates `M` with input `x` starting from the state `M.start`. -/
def eval := M.eval_from M.start
/-- `M.accepts` is the language of `x` such that `M.eval x` is an accept state. -/
def accepts : language α :=
λ x, M.eval x ∈ M.accept
lemma mem_accepts (x : list α) : x ∈ M.accepts ↔ M.eval_from M.start x ∈ M.accept := by refl
lemma eval_from_of_append (start : σ) (x y : list α) :
M.eval_from start (x ++ y) = M.eval_from (M.eval_from start x) y :=
x.foldl_append _ _ y
lemma eval_from_split [fintype σ] {x : list α} {s t : σ} (hlen : fintype.card σ ≤ x.length)
(hx : M.eval_from s x = t) :
∃ q a b c,
x = a ++ b ++ c ∧
a.length + b.length ≤ fintype.card σ ∧
b ≠ [] ∧
M.eval_from s a = q ∧
M.eval_from q b = q ∧
M.eval_from q c = t :=
begin
obtain ⟨n, m, hneq, heq⟩ := fintype.exists_ne_map_eq_of_card_lt
(λ n : fin (fintype.card σ + 1), M.eval_from s (x.take n)) (by norm_num),
wlog hle : (n : ℕ) ≤ m using n m,
have hlt : (n : ℕ) < m := (ne.le_iff_lt hneq).mp hle,
have hm : (m : ℕ) ≤ fintype.card σ := fin.is_le m,
dsimp at heq,
refine ⟨M.eval_from s ((x.take m).take n), (x.take m).take n, (x.take m).drop n, x.drop m,
_, _, _, by refl, _⟩,
{ rw [list.take_append_drop, list.take_append_drop] },
{ simp only [list.length_drop, list.length_take],
rw [min_eq_left (hm.trans hlen), min_eq_left hle, add_sub_cancel_of_le hle],
exact hm },
{ intro h,
have hlen' := congr_arg list.length h,
simp only [list.length_drop, list.length, list.length_take] at hlen',
rw [min_eq_left, nat.sub_eq_zero_iff_le] at hlen',
{ apply hneq,
apply le_antisymm,
assumption' },
exact hm.trans hlen, },
have hq :
M.eval_from (M.eval_from s ((x.take m).take n)) ((x.take m).drop n) =
M.eval_from s ((x.take m).take n),
{ rw [list.take_take, min_eq_left hle, ←eval_from_of_append, heq, ←min_eq_left hle,
←list.take_take, min_eq_left hle, list.take_append_drop] },
use hq,
rwa [←hq, ←eval_from_of_append, ←eval_from_of_append, ←list.append_assoc, list.take_append_drop,
list.take_append_drop]
end
lemma eval_from_of_pow {x y : list α} {s : σ} (hx : M.eval_from s x = s)
(hy : y ∈ @language.star α {x}) : M.eval_from s y = s :=
begin
rw language.mem_star at hy,
rcases hy with ⟨ S, rfl, hS ⟩,
induction S with a S ih,
{ refl },
{ have ha := hS a (list.mem_cons_self _ _),
rw set.mem_singleton_iff at ha,
rw [list.join, eval_from_of_append, ha, hx],
apply ih,
intros z hz,
exact hS z (list.mem_cons_of_mem a hz) }
end
lemma pumping_lemma [fintype σ] {x : list α} (hx : x ∈ M.accepts)
(hlen : fintype.card σ ≤ list.length x) :
∃ a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ fintype.card σ ∧ b ≠ [] ∧
{a} * language.star {b} * {c} ≤ M.accepts :=
begin
obtain ⟨_, a, b, c, hx, hlen, hnil, rfl, hb, hc⟩ := M.eval_from_split hlen rfl,
use [a, b, c, hx, hlen, hnil],
intros y hy,
rw language.mem_mul at hy,
rcases hy with ⟨ ab, c', hab, hc', rfl ⟩,
rw language.mem_mul at hab,
rcases hab with ⟨ a', b', ha', hb', rfl ⟩,
rw set.mem_singleton_iff at ha' hc',
substs ha' hc',
have h := M.eval_from_of_pow hb hb',
rwa [mem_accepts, eval_from_of_append, eval_from_of_append, h, hc]
end
end DFA
|
9e37b17783452b0c800df5823d38fee1a0329b1d | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/ring_theory/derivation.lean | 7a97554d6916f3d79d40a5682a8bf791286486e9 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 8,057 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Nicolò Cavalleri.
-/
import algebra.lie_algebra
import ring_theory.algebra_tower
/-!
# Derivations
This file defines derivation. A derivation `D` from the `R`-algebra `A` to the `A`-module `M` is an
`R`-linear map that satisfy the Leibniz rule `D (a * b) = a * D b + D a * b`.
## Notation
The notation `⁅D1, D2⁆` is used for the commutator of two derivations.
TODO: this file is just a stub to go on with some PRs in the geometry section. It only
implements the definition of derivations in commutative algebra. This will soon change: as soon
as bimodules will be there in mathlib I will change this file to take into account the
non-commutative case. Any development on the theory of derivations is discouraged until the
definitive definition of derivation will be implemented.
-/
open algebra ring_hom
/-- `D : derivation R A M` is an `R`-linear map from `A` to `M` that satisfies the `leibniz`
equality.
TODO: update this when bimodules are defined. -/
@[protect_proj]
structure derivation (R : Type*) (A : Type*) [comm_semiring R] [comm_semiring A]
[algebra R A] (M : Type*) [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M]
[is_scalar_tower R A M]
extends A →ₗ[R] M :=
(leibniz' (a b : A) : to_fun (a * b) = a • to_fun b + b • to_fun a)
namespace derivation
section
variables {R : Type*} [comm_semiring R]
variables {A : Type*} [comm_semiring A] [algebra R A]
variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M]
variables [is_scalar_tower R A M]
variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A)
instance : has_coe_to_fun (derivation R A M) := ⟨_, λ D, D.to_linear_map.to_fun⟩
instance has_coe_to_linear_map : has_coe (derivation R A M) (A →ₗ[R] M) :=
⟨λ D, D.to_linear_map⟩
@[simp] lemma to_fun_eq_coe : D.to_fun = ⇑D := rfl
@[simp, norm_cast]
lemma coe_fn_coe (f : derivation R A M) :
⇑(f : A →ₗ[R] M) = f := rfl
lemma coe_injective (H : ⇑D1 = D2) : D1 = D2 :=
by { cases D1, cases D2, congr', exact linear_map.coe_inj H }
@[ext] theorem ext (H : ∀ a, D1 a = D2 a) : D1 = D2 :=
coe_injective $ funext H
@[simp] lemma map_add : D (a + b) = D a + D b := is_add_hom.map_add D a b
@[simp] lemma map_zero : D 0 = 0 := is_add_monoid_hom.map_zero D
@[simp] lemma map_smul : D (r • a) = r • D a := linear_map.map_smul D r a
@[simp] lemma leibniz : D (a * b) = a • D b + b • D a := D.leibniz' _ _
@[simp] lemma map_one_eq_zero : D 1 = 0 :=
begin
have h : D 1 = D (1 * 1) := by rw mul_one,
rw [leibniz D 1 1, one_smul] at h,
exact eq_zero_of_left_cancel_add_self h,
end
@[simp] lemma map_algebra_map : D (algebra_map R A r) = 0 :=
by rw [←mul_one r, ring_hom.map_mul, map_one, ←smul_def, map_smul, map_one_eq_zero, smul_zero]
instance : has_zero (derivation R A M) :=
⟨⟨(0 : A →ₗ[R] M), λ a b, by simp only [add_zero, linear_map.zero_apply,
linear_map.to_fun_eq_coe, smul_zero]⟩⟩
instance : inhabited (derivation R A M) := ⟨0⟩
instance : add_comm_monoid (derivation R A M) :=
{ add := λ D1 D2, ⟨D1 + D2, λ a b, by { simp only [leibniz, linear_map.add_apply,
linear_map.to_fun_eq_coe, coe_fn_coe, smul_add], cc }⟩,
add_assoc := λ D E F, ext $ λ a, add_assoc _ _ _,
zero_add := λ D, ext $ λ a, zero_add _,
add_zero := λ D, ext $ λ a, add_zero _,
add_comm := λ D E, ext $ λ a, add_comm _ _,
..derivation.has_zero }
@[simp] lemma add_apply : (D1 + D2) a = D1 a + D2 a := rfl
@[priority 100]
instance derivation.Rsemimodule : semimodule R (derivation R A M) :=
{ smul := λ r D, ⟨r • D, λ a b, by simp only [linear_map.smul_apply, leibniz,
linear_map.to_fun_eq_coe, smul_algebra_smul_comm, coe_fn_coe, smul_add, add_comm],⟩,
mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _,
one_smul := λ D, ext $ λ b, one_smul _ _,
smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _,
smul_zero := λ a, ext $ λ b, smul_zero _,
add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _,
zero_smul := λ D, ext $ λ b, zero_smul _ _ }
@[simp] lemma smul_to_linear_map_coe : ↑(r • D) = (r • D : A →ₗ[R] M) := rfl
@[simp] lemma Rsmul_apply : (r • D) a = r • D a := rfl
instance : semimodule A (derivation R A M) :=
{ smul := λ a D, ⟨⟨λ b, a • D b,
λ a1 a2, by rw [D.map_add, smul_add],
λ a1 a2, by rw [D.map_smul, smul_algebra_smul_comm]⟩,
λ b c, by { dsimp, simp only [smul_add, leibniz, smul_comm, add_comm] }⟩,
mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _,
one_smul := λ D, ext $ λ b, one_smul A _,
smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _,
smul_zero := λ a, ext $ λ b, smul_zero _,
add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _,
zero_smul := λ D, ext $ λ b, zero_smul A _ }
@[simp] lemma smul_apply : (a • D) b = a • D b := rfl
instance : is_scalar_tower R A (derivation R A M) :=
⟨λ x y z, ext (λ a, smul_assoc _ _ _)⟩
end
section
variables {R : Type*} [comm_ring R]
variables {A : Type*} [comm_ring A] [algebra R A]
section
variables {M : Type*} [add_comm_group M] [module A M] [module R M] [is_scalar_tower R A M]
variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A)
@[simp] lemma map_neg : D (-a) = -D a := linear_map.map_neg D a
@[simp] lemma map_sub : D (a - b) = D a - D b := linear_map.map_sub D a b
instance : add_comm_group (derivation R A M) :=
{ neg := λ D, ⟨-D, λ a b, by simp only [linear_map.neg_apply, smul_neg, neg_add_rev, leibniz,
linear_map.to_fun_eq_coe, coe_fn_coe, add_comm]⟩,
add_left_neg := λ D, ext $ λ a, add_left_neg _,
..derivation.add_comm_monoid }
end
section lie_structures
/-! # Lie structures -/
variables (D : derivation R A A) {D1 D2 : derivation R A A} (r : R) (a b : A)
open ring_commutator
/-- The commutator of derivations is again a derivation. -/
def commutator (D1 D2 : derivation R A A) : derivation R A A :=
⟨⁅D1, D2⁆, λ a b, by {simp only [commutator, map_add, id.smul_eq_mul, linear_map.mul_app,
leibniz, linear_map.to_fun_eq_coe, coe_fn_coe, linear_map.sub_apply], ring }⟩
instance : has_bracket (derivation R A A) := ⟨derivation.commutator⟩
@[simp] lemma commutator_coe_linear_map : ↑⁅D1, D2⁆ = (⁅D1, D2⁆ : A →ₗ[R] A) := rfl
lemma commutator_apply : ⁅D1, D2⁆ a = D1 (D2 a) - D2 (D1 a) := rfl
instance : lie_ring (derivation R A A) :=
{ add_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring },
lie_add := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring },
lie_self := λ d, by { ext a, simp only [commutator_apply, add_apply, map_add], ring },
jacobi := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_sub], ring } }
instance : lie_algebra R (derivation R A A) :=
{ lie_smul := λ r d e, by { ext a, simp only [commutator_apply, map_smul, smul_sub, Rsmul_apply]},
..derivation.Rsemimodule }
end lie_structures
end
end derivation
section comp_der
namespace linear_map
variables {R : Type*} [comm_semiring R]
variables {A : Type*} [comm_semiring A] [algebra R A]
variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M]
variables {N : Type*} [add_cancel_comm_monoid N] [semimodule A N] [semimodule R N]
variables [is_scalar_tower R A M] [is_scalar_tower R A N]
/-- The composition of a linear map and a derivation is a derivation. -/
def comp_der (f : M →ₗ[A] N) (D : derivation R A M) : derivation R A N :=
{ to_fun := λ a, f (D a),
map_add' := λ a1 a2, by rw [D.map_add, f.map_add],
map_smul' := λ r a, by rw [derivation.map_smul, map_smul_eq_smul_map],
leibniz' := λ a b, by simp only [derivation.leibniz, linear_map.map_smul, linear_map.map_add, add_comm] }
@[simp] lemma comp_der_apply (f : M →ₗ[A] N) (D : derivation R A M) (a : A) :
f.comp_der D a = f (D a) := rfl
end linear_map
end comp_der
|
0d4b09df7114a687099c05e59d498e551204a7db | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/univ1.lean | b4c32cc0073a9c2eafaea03adbb3c8142c788de4 | [
"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 | 650 | lean | import logic
namespace S1
axiom I : Type
definition F (X : Type) : Type := (X → Prop) → Prop
axiom unfoldd.{l} : I.{l} → F I.{l}
axiom foldd.{l} : F I.{l} → I.{l}
axiom iso1 : ∀x, foldd (unfoldd x) = x
end S1
namespace S2
universe u
axiom I : Type.{u}
definition F (X : Type) : Type := (X → Prop) → Prop
axiom unfoldd : I → F I
axiom foldd : F I → I
axiom iso1 : ∀x, foldd (unfoldd x) = x
end S2
namespace S3
section
hypothesis I : Type
definition F (X : Type) : Type := (X → Prop) → Prop
hypothesis unfoldd : I → F I
hypothesis foldd : F I → I
hypothesis iso1 : ∀x, foldd (unfoldd x) = x
end
end S3
|
455b91854eec813bd13ebf2ce1be79af2cf40a69 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/tactic/core.lean | 4935948bd14f8c64b267f9255df39ccc8c1706b1 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 72,673 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import data.dlist.basic category.basic meta.expr meta.rb_map data.bool
tactic.lean_core_docs tactic.derive_inhabited
universe variable u
instance : has_lt pos :=
{ lt := λ x y, (x.line, x.column) < (y.line, y.column) }
namespace expr
open tactic
attribute [derive has_reflect] binder_info
attribute [derive decidable_eq] binder_info congr_arg_kind
/-- Given an expr `α` representing a type with numeral structure,
`of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (α : expr) : ℕ → tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some α, none])
(λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else
do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
/-- Given an expr `α` representing a type with numeral structure,
`of_int α n` creates the `α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (α : expr) : ℤ → tactic expr
| (n : ℕ) := expr.of_nat α n
| -[1+ n] := do
e ← expr.of_nat α (n+1),
tactic.mk_app ``has_neg.neg [e]
/-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local
constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (λarg i:expr, do
t ← infer_type arg,
sort l ← infer_type t,
return $ if arg.occurs i ∨ l ≠ level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/
meta def traverse {m : Type → Type u} [applicative m]
{elab elab' : bool} (f : expr elab → m (expr elab')) :
expr elab → m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app e₀ e₁) := app <$> f e₀ <*> f e₁
| (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁
| (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁
| (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂
| (macro mac es) := macro mac <$> list.traverse f es
/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,
with initial value `a`. -/
meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α
| x e := prod.snd <$> (state_t.run (e.traverse $ λ e',
(get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _)
end expr
namespace interaction_monad
open result
variables {σ : Type} {α : Type u}
/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.read` in core.
meta def get_state : interaction_monad σ σ :=
λ state, success state state
/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.write` in core.
meta def set_state (state : σ) : interaction_monad σ unit :=
λ _, success () state
/--
`run_with_state state tac` applies `tac` to the given state `state` and returns the result,
subsequently restoring the original state.
If `tac` fails, then `run_with_state` does too.
-/
meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α :=
λ s, match tac state with
| success val _ := success val s
| exception fn pos _ := exception fn pos s
end
end interaction_monad
namespace lean.parser
open lean interaction_monad.result
/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the
current line. -/
meta def emit_command_here (str : string) : lean.parser string :=
do (_, left) ← with_input command_like str,
return left
/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in
source code. -/
meta def emit_code_here : string → lean.parser unit
| str := do left ← emit_command_here str,
if left.length = 0 then return ()
else emit_code_here left
end lean.parser
namespace format
/-- `join' [a,b,c]` produces the format object `abc`.
It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/
meta def join' (xs : list format) : format :=
xs.foldl compose nil
/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,
where `.` represents `format.join`. -/
meta def intercalate (x : format) : list format → format :=
join' ∘ list.intersperse x
/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`
the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`
each line break is decided independently -/
meta def soft_break : format :=
group line
end format
section format
open format
/-- format a `list` by separating elements with `soft_break` instead of `line` -/
meta def list.to_line_wrap_format {α : Type u} [has_to_format α] : list α → format
| [] := to_fmt "[]"
| xs := to_fmt "[" ++ group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) ++ to_fmt "]"
end format
namespace tactic
open function
/-- `mk_local_pisn e n` instantiates the first `n` variables of a pi expression `e`,
and returns the new local constants along with the instantiated expression. Fails if `e` does
not begin with at least `n` pi binders. -/
meta def mk_local_pisn : expr → nat → tactic (list expr × expr)
| (expr.pi n bi d b) (c + 1) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pisn (b.instantiate_var p) c,
return ((p :: ps), r)
| e 0 := return ([], e)
| _ _ := failed
-- TODO: move to `declaration` namespace in `meta/expr.lean`
/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named
`ls`, type `t`, and body `e`. -/
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this
to the environment as a theorem with name `n` and universe parameters `ls`. -/
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :
tactic expr :=
do ((), body) ← solve_aux type tac,
body ← instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ expr.const n $ ls.map level.param
/-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`.
This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare
situations the latter will fail but the former will succeed. -/
meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α :=
mk_app ``id [e] >>= eval_expr α
/-- `mk_fresh_name` returns identifiers starting with underscores,
which are not legal when emitted by tactic programs. `mk_user_fresh_name`
turns the useful source of random names provided by `mk_fresh_name` into
names which are usable by tactic programs.
The returned name has four components which are all strings. -/
meta def mk_user_fresh_name : tactic name :=
do nm ← mk_fresh_name,
return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__
/-- `has_attribute' attr_name decl_name` checks whether `decl_name` has attribute `attr_name`. -/
meta def has_attribute' (attr_name decl_name : name) : tactic bool :=
succeeds (has_attribute attr_name decl_name)
/-- Checks whether the name is a simp lemma -/
meta def is_simp_lemma : name → tactic bool :=
has_attribute' `simp
/-- Checks whether the name is an instance. -/
meta def is_instance : name → tactic bool :=
has_attribute' `instance
/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.
Covers all declarations from the current file. -/
meta def local_decls : tactic (name_map declaration) :=
do e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s, if environment.in_current_file' e d.to_name
then s.insert d.to_name d else s),
pure xs
/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/
meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n :=
let nm' := nm.append_suffix ("_" ++ to_string n) in
if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'
/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it
returns that, otherwise it tries `nm_2`, `nm_3`, ... -/
meta def get_unused_decl_name (nm : name) : tactic name :=
get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm
/--
Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type`
but with universe params updated to match the fresh universe metavariables in `e`.
This should have the same effect as just
```lean
do e ← mk_const d.to_name,
t ← infer_type e,
return (e, t)
```
but is hopefully faster.
-/
meta def decl_mk_const (d : declaration) : tactic (expr × expr) :=
do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ,
let e : expr := expr.const d.to_name (prod.snd <$> subst),
return (e, d.type.instantiate_univ_params subst)
/-- `mk_local n` creates a dummy local variable with name `n`.
The type of this local constant is a constant with name `n`, so it is very unlikely to be
a meaningful expression. -/
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with pi binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``pis [a, b] `(f a b)`` will return the expression
`Π (a : Ta) (b : Tb), f a b`. -/
meta def pis : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with lambda binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``lambdas [a, b] `(f a b)`` will return the expression
`λ (a : Ta) (b : Tb), f a b`. -/
meta def lambdas : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,
`y : ty x` and `z : tz x y`, creates an expression of sigma type:
`⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`.
-/
meta def mk_psigma : list expr → tactic expr
| [] := mk_const ``punit
| [x@(expr.local_const _ _ _ _)] := pure x
| (x@(expr.local_const _ _ _ _) :: xs) :=
do y ← mk_psigma xs,
α ← infer_type x,
β ← infer_type y,
t ← lambdas [x] β >>= instantiate_mvars,
r ← mk_mapp ``psigma.mk [α,t],
pure $ r x y
| _ := fail "mk_psigma expects a list of local constants"
/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`
times and uses `ns` to name the resulting variables. Returns a triple: list of new variables,
remaining term and unused variable names.
-/
meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name)
| 0 e hs ns := return (hs.reverse, e, ns)
| (n + 1) e hs ns := do
t ← infer_type e,
if t.is_app_of `eq then return (hs.reverse, e, ns)
else do
[(_, [h, h'], _)] ← cases_core e (ns.take 1),
elim_gen_prod n h' (h :: hs) (ns.drop 1)
private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[(_, [h], _), (_, [h'], _)] ← induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose
type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`.
-/
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') ← elim_gen_sum_aux n e [],
gs ← get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
/-- Given `elab_def`, a tactic to solve the current goal,
`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it
to close the goal. If `trusted` is false, it will be a meta definition. -/
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt ← list.map expr.to_implicit_local_const <$> local_context,
t ← target,
(eqns,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
/-- Attempts to close the goal with `dec_trivial`. -/
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion. -/
meta def retrieve {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
result.exception
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/
meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
/--
Given a tactic `tac` that takes an expression
and returns a new expression and a proof of equality,
use that tactic to change the type of the hypotheses listed in `hs`,
as well as the goal if `tgt = tt`.
Returns `tt` if any types were successfully changed.
-/
meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) :
tactic bool :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
succeeds $ do
(new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified ← succeeds $ do {
guard tgt,
(new_t, pr) ← target >>= tac,
replace_target new_t pr },
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
/-- `revert_after e` reverts all local constants after local constant `e`. -/
meta def revert_after (e : expr) : tactic ℕ := do
l ← local_context,
[pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}",
let l := l.drop pos.succ, -- all local hypotheses after `e`
revert_lst l
/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant
with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.
`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the
goal, in which case it just calls `assert`.
In contrast to `generalize` it already introduces the generalized variable. -/
meta def generalize' (e : expr) (n : name) : tactic expr :=
(generalize e n >> intro1) <|> note n none e
/-! ### Various tactics related to local definitions (local constants of the form `x : α := t`)
We call `t` the value of `x`. -/
/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined
locally using a `let` expression. Otherwise it fails. -/
meta def local_def_value (e : expr) : tactic expr :=
pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad.
tactic.unsafe.type_context.run $ do
lctx <- tactic.unsafe.type_context.get_local_context,
some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |
tactic.unsafe.type_context.fail format!"No such hypothesis {s}.",
some let_val <- return ldecl.value |
tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.",
return let_val
/-- `revert_deps e` reverts all the hypotheses that depend on one of the local
constants `e`, including the local definitions that have `e` in their definition.
This fixes a bug in `revert_kdeps` that does not revert local definitions for which `e` only
appears in the definition. -/
/- We cannot implement it as `revert e >> intro1`, because that would change the local constant in
the context. -/
meta def revert_deps (e : expr) : tactic ℕ := do
n ← revert_kdeps e,
l ← local_context,
[pos] ← return $ l.indexes_of e,
let l := l.drop pos.succ, -- local hypotheses after `e`
ls ← l.mfilter $ λ e', try_core (local_def_value e') >>= λ o, return $ o.elim ff $ λ e'',
e''.has_local_constant e,
n' ← revert_lst ls,
return $ n + n'
/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form
`e : α := t`) and otherwise fails. -/
meta def is_local_def (e : expr) : tactic unit :=
retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip
/-- `clear_value e` clears the body of the local definition `e`, changing it into a regular
hypothesis. A hypothesis `e : α := t` is changed to `e : α`.
This tactic is called `clearbody` in Coq. -/
meta def clear_value (e : expr) : tactic unit := do
n ← revert_after e,
is_local_def e <|>
pp e >>= λ s, fail format!"Cannot clear the body of {s}. It is not a local definition.",
let nm := e.local_pp_name,
(generalize' e nm >> clear e) <|>
fail format!"Cannot clear the body of {nm}. The resulting goal is not type correct.",
intron n
/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,
`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting
expression and a proof of equality. -/
meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) :
tactic (expr × expr) :=
prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg
/-- Caches unary type classes on a type `α : Type.{univ}`. -/
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
/-- Creates an `instance_cache` for the type `α`. -/
meta def mk_instance_cache (α : expr) : tactic instance_cache :=
do u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, mk_name_map⟩
namespace instance_cache
/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of
`n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance
via type class resolution, and updates the cache. -/
meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e ← mk_app n [c.α] >>= mk_instance,
return (⟨c.α, c.univ, c.inst.insert n e⟩, e)
end
open expr
/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,
`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/
meta def append_typeclasses : expr → instance_cache → list expr →
tactic (instance_cache × list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) ← c.get n, return (c, p :: l)
| _ c l := return (c, l)
/-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`.
-/
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) :=
do d ← get_decl n,
(c, l) ← append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.α :: l))
end instance_cache
private meta def get_expl_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of the given (Pi-)type. -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of the given function. -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
/-- Auxilliary defintion for `get_pi_binders`. -/
meta def get_pi_binders_aux : list binder → expr → tactic (list binder × expr)
| es (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
let new_b := expr.instantiate_var b l,
get_pi_binders_aux (⟨n, bi, d⟩::es) new_b
| es e := return (es, e)
/-- Get the binders and target of a pi-type. Instantiates bound variables by
local constants. Cf. `pi_binders` in `meta.expr` (which produces open terms).
See also `mk_local_pis` in `init.core.tactic` which does almost the same. -/
meta def get_pi_binders : expr → tactic (list binder × expr) | e :=
do (es, e) ← get_pi_binders_aux [] e, return (es.reverse, e)
/-- Auxilliary definition for `get_pi_binders_dep`. -/
meta def get_pi_binders_dep_aux : ℕ → expr → tactic (list (ℕ × binder) × expr)
| n (expr.pi nm bi d b) :=
do l ← mk_local' nm bi d,
(ls, r) ← get_pi_binders_dep_aux (n+1) (expr.instantiate_var b l),
return (if b.has_var then ls else (n, ⟨nm, bi, d⟩)::ls, r)
| n e := return ([], e)
/-- A variant of `get_pi_binders` that only returns the binders that do not occur in later
arguments or in the target. Also returns the argument position of each returned binder. -/
meta def get_pi_binders_dep : expr → tactic (list (ℕ × binder) × expr) :=
get_pi_binders_dep_aux 0
/-- A variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) :
tactic (expr × list expr) :=
focus1 $
do h' ← assert h p,
[g₀,g₁] ← get_goals,
set_goals [g₀], tac₀,
gs ← get_goals,
set_goals [g₁],
return (h', gs)
/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
/-- When `struct_n` is the name of a structure type,
`subobject_names struct_n` returns two lists of names `(instances, fields)`.
The names in `instances` are the projections from `struct_n` to the structures that it extends
(assuming it was defined with `old_structure_cmd false`).
The names in `fields` are the standard fields of `struct_n`. -/
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
[c] ← pure $ env.constructors_of struct_n | fail "too many constructors",
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
(_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= mk_local_pis,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure
named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name
of the projection is `prefix.name`. -/
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
/--
Return a list of all type classes which can be instantiated
for the given expression.
-/
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (λ n,
succeeds $ mk_app n [e] >>= mk_instance)
open nat
/-- Create a list of `n` fresh metavariables. -/
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/-- Returns the only goal, or fails if there isn't just one goal. -/
meta def get_goal : tactic expr :=
do gs ← get_goals,
match gs with
| [a] := return a
| [] := fail "there are no goals"
| _ := fail "there are too many goals"
end
/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/-- `apply_list l`: try to apply the tactics in the list `l` on the first goal, and
fail if none succeeds -/
meta def apply_list_expr : list expr → tactic unit
| [] := fail "no matching rule"
| (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t
/-- constructs a list of expressions given a list of p-expressions, as follows:
- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it
- if the p-expression is a user attribute, add all the theorems with this attribute
to the list.-/
meta def build_list_expr_for_apply : list pexpr → tactic (list expr)
| [] := return []
| (h::t) := do
tail ← build_list_expr_for_apply t,
a ← i_to_expr_for_apply h,
(do l ← attribute.get_instances (expr.const_name a),
m ← list.mmap mk_const l,
return (m.append tail))
<|> return (a::tail)
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times -/
meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit :=
do l ← build_list_expr_for_apply hs,
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l)
/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local
context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.
Fails if there is nothing named `h` in the local context. -/
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' ← get_local h,
p ← to_expr p,
note h none p,
clear h'
/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``
or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an
`iff`, returns an expression with the `iff` converted to either the forwards or backwards
implication, as requested. -/
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0)
| _ f := none
/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/
meta def iff_mp_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mp ty (λ_, e)
/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/
meta def iff_mpr_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mpr ty (λ_, e)
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the forward implication. -/
meta def iff_mp (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the reverse implication. -/
meta def iff_mpr (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/--
Attempts to apply `e`, and if that fails, if `e` is an `iff`,
try applying both directions separately.
-/
meta def apply_iff (e : expr) : tactic (list (name × expr)) :=
let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in
ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)
/--
Configuration options for `apply_any`:
* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.
* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.
* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.
-/
meta structure apply_any_opt :=
(use_symmetry : bool := tt)
(use_exfalso : bool := tt)
(apply : expr → tactic (list (name × expr)) := tactic.apply)
/--
This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,
and evaluates these as thunks before trying to apply them.
We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.
-/
meta def apply_any_thunk
(lemmas : list (tactic expr))
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
do
let modes := [skip]
++ (if opt.use_symmetry then [symmetry] else [])
++ (if opt.use_exfalso then [exfalso] else []),
modes.any_of (λ m, do m,
lemmas.any_of (λ H, H >>= opt.apply >> tac)) <|>
fail "apply_any tactic failed; no lemma could be applied"
/--
`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.
`apply_any lemmas opt` allows control over how lemmas are applied.
`opt` has fields:
* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)
* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)
* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).
`apply_any lemmas tac` calls the tactic `tac` after a successful application.
Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange
recursive invocations of `apply_any`.
-/
meta def apply_any
(lemmas : list expr)
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
apply_any_thunk (lemmas.map pure) opt tac
/-- Try to apply a hypothesis from the local context to the goal. -/
meta def apply_assumption : tactic unit :=
local_context >>= apply_any
/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails
if this is not a definitional equality.
`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`
by reverting `h`, changing the goal, and reintroducing hypotheses. -/
meta def change_core (e : expr) : option expr → tactic unit
| none := tactic.change e
| (some h) :=
do num_reverted : ℕ ← revert h,
expr.pi n bi d b ← target,
tactic.change $ expr.pi n bi e b,
intron num_reverted
/--
`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,
assuming `olde` and `newe` are defeq when elaborated.
-/
meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=
do h ← get_local hyp,
tp ← infer_type h,
olde ← to_expr olde, newe ← to_expr newe,
let repl_tp := tp.replace (λ a n, if a = olde then some newe else none),
change_core repl_tp (some h)
/-- Returns a list of all metavariables in the current partial proof. This can differ from
the list of goals, since the goals can be manually edited. -/
meta def metavariables : tactic (list expr) :=
expr.list_meta_vars <$> result
/-- Fail if the target contains a metavariable. -/
meta def no_mvars_in_target : tactic unit :=
expr.has_meta_var <$> target >>= guardb ∘ bnot
/-- Succeeds only if the current goal is a proposition. -/
meta def propositional_goal : tactic unit :=
do g :: _ ← get_goals,
is_proof g >>= guardb
/-- Succeeds only if we can construct an instance showing the
current goal is a subsingleton type. -/
meta def subsingleton_goal : tactic unit :=
do g :: _ ← get_goals,
ty ← infer_type g >>= instantiate_mvars,
to_expr ``(subsingleton %%ty) >>= mk_instance >> skip
/--
Succeeds only if the current goal is "terminal",
in the sense that no other goals depend on it
(except possibly through shared metavariables; see `independent_goal`).
-/
meta def terminal_goal : tactic unit :=
propositional_goal <|> subsingleton_goal <|>
do g₀ :: _ ← get_goals,
mvars ← (λ L, list.erase L g₀) <$> metavariables,
mvars.mmap' $ λ g, do
t ← infer_type g >>= instantiate_mvars,
d ← kdepends_on t g₀,
monad.whenb d $
pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.")
/--
Succeeds only if the current goal is "independent", in the sense
that no other goals depend on it, even through shared meta-variables.
-/
meta def independent_goal : tactic unit :=
no_mvars_in_target >> terminal_goal
/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,
it only unfolds reducible definitions, so it sometimes fails faster. -/
meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible
variable {α : Type}
private meta def iterate_aux (t : tactic α) : list α → tactic (list α)
| L := (do r ← t, iterate_aux (r :: L)) <|> return L
/-- Apply a tactic as many times as possible, collecting the results in a list. -/
meta def iterate' (t : tactic α) : tactic (list α) :=
list.reverse <$> iterate_aux t []
/-- Apply a tactic as many times as possible, collecting the results in a list.
Fail if the tactic does not succeed at least once. -/
meta def iterate1 (t : tactic α) : tactic (α × list α) :=
do r ← decorate_ex "iterate1 failed: tactic did not succeed" t,
L ← iterate' t,
return (r, L)
/-- Introduces one or more variables and returns the new local constants.
Fails if `intro` cannot be applied. -/
meta def intros1 : tactic (list expr) :=
iterate1 intro1 >>= λ p, return (p.1 :: p.2)
/-- `successes` invokes each tactic in turn, returning the list of successful results. -/
meta def successes (tactics : list (tactic α)) : tactic (list α) :=
list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t))
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results,
and reverting to the original `tactic_state`.
-/
-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.
meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) :=
λ s, result.success
(tactics.map $
λ t : tactic α,
match t s with
| result.success a s' := [a]
| _ := []
end).join s
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results sorted by
the value produced by a subsequent execution of the `sort_by` tactic,
and reverting to the original `tactic_state`.
-/
meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) :
tactic (list α) :=
λ s, result.success
(((tactics.map $
λ t : tactic α,
match (do a ← t, n ← sort_by, return (a, n)) s with
| result.success a s' := [a]
| _ := []
end).join.qsort (λ p q : α × ℕ, p.2 < q.2)).map (prod.fst)) s
/-- Return target after instantiating metavars and whnf. -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
/--
Just like `split`, `fsplit` applies the constructor when the type of the target is
an inductive data type with one constructor.
However it does not reorder goals or invoke `auto_param` tactics.
-/
-- FIXME check if we can remove `auto_param := ff`
meta def fsplit : tactic unit :=
do [c] ← target' >>= get_constructors_for |
fail "fsplit tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip
run_cmd add_interactive [`fsplit]
add_tactic_doc
{ name := "fsplit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fsplit],
tags := ["logic", "goal management"] }
/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`
succeeds, clears the old hypothesis. -/
meta def injections_and_clear : tactic unit :=
do l ← local_context,
results ← successes $ l.map $ λ e, injection e >> clear e,
when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis")
run_cmd add_interactive [`injections_and_clear]
add_tactic_doc
{ name := "injections_and_clear",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injections_and_clear],
tags := ["context management"] }
/-- Calls `cases` on every local hypothesis, succeeding if
it succeeds on at least one hypothesis. -/
meta def case_bash : tactic unit :=
do l ← local_context,
r ← successes (l.reverse.map (λ h, cases h >> skip)),
when (r.empty) failed
/--
`note_anon t v`, given a proof `v : t`,
adds `h : t` to the current context, where the name `h` is fresh.
`note_anon none v` will infer the type `t` from `v`.
-/
-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.
meta def note_anon (t : option expr) (v : expr) : tactic expr :=
do h ← get_unused_name `h none,
note h t v
/-- `find_local t` returns a local constant with type t, or fails if none exists. -/
meta def find_local (t : pexpr) : tactic expr :=
do t' ← to_expr t,
prod.snd <$> solve_aux t' assumption
/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values
of the previous local constants. `l` is a list of local constants and their values. -/
meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do
let lc := l.map prod.fst,
let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)),
t ← target,
new_goal ← mk_meta_var (t.pis lc),
old::other_goals ← get_goals,
set_goals (old :: new_goal :: other_goals),
exact ((new_goal.mk_app lc).instantiate_locals lm),
return ()
/-- Like `mk_local_pis` but translating into weak head normal form before checking if it is a `Π`.
-/
meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do
(expr.pi n bi d b) ← whnf e | return ([], e),
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
/-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g`. -/
meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do
t ← infer_type h,
(ctxt, t) ← mk_local_pis_whnf t,
`(@Exists %%α %%p) ← whnf t transparency.all |
fail "expected a term of the shape ∀xs, ∃a, p xs a",
α_t ← infer_type α,
expr.sort u ← whnf α_t transparency.all,
value ← mk_local_def data (α.pis ctxt),
t' ← head_beta (p.app (value.mk_app ctxt)),
spec ← mk_local_def spec (t'.pis ctxt),
dependent_pose_core [
(value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt),
(spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)],
try (tactic.clear h),
intro1,
intro1
/-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`,
and a final hypothesis on `p as`. -/
meta def choose : expr → list name → tactic unit
| h [] := fail "expect list of variables"
| h [n] := do
cnt ← revert h,
intro n,
intron (cnt - 1),
return ()
| h (n::ns) := do
v ← get_unused_name >>= choose1 h n,
choose v ns
/--
Instantiates metavariables that appear in the current goal.
-/
meta def instantiate_mvars_in_target : tactic unit :=
target >>= instantiate_mvars >>= change
/--
Instantiates metavariables in all goals.
-/
meta def instantiate_mvars_in_goals : tactic unit :=
all_goals $ instantiate_mvars_in_target
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {α} (t : tactic α) : tactic α
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/-- Similar to `mk_local_pis` but make meta variables instead of
local constants. -/
meta def mk_meta_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_meta_var d,
(ps, r) ← mk_meta_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
/--
Hole command used to fill in a structure's field when specifying an instance.
In the following:
```lean
instance : monad id :=
{! !}
```
invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under
construction.") produces:
```lean
instance : monad id :=
{ map := _,
map_const := _,
pure := _,
seq := _,
seq_left := _,
seq_right := _,
bind := _ }
```
-/
@[hole_command] meta def instance_stub : hole_command :=
{ name := "Instance Stub",
descr := "Generate a skeleton for the structure under construction.",
action := λ _,
do tgt ← target >>= whnf,
let cl := tgt.get_app_fn.const_name,
env ← get_env,
fs ← expanded_field_list cl,
let fs := fs.map prod.snd,
let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"),
let out := format.to_string format!"{{ {fs} }",
return [(out,"")] }
add_tactic_doc
{ name := "instance_stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.instance_stub],
tags := ["instances"] }
/-- Like `resolve_name` except when the list of goals is
empty. In that situation `resolve_name` fails whereas
`resolve_name'` simply proceeds on a dummy goal -/
meta def resolve_name' (n : name) : tactic pexpr :=
do [] ← get_goals | resolve_name n,
g ← mk_mvar,
set_goals [g],
resolve_name n <* set_goals []
private meta def strip_prefix' (n : name) : list string → name → tactic name
| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous
| s (name.mk_string a p) :=
do let n' := s.foldl (flip name.mk_string) name.anonymous,
do { n'' ← tactic.resolve_constant n',
if n'' = n
then pure n'
else strip_prefix' (a :: s) p }
<|> strip_prefix' (a :: s) p
| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n
/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/
meta def strip_prefix : name → tactic name
| n@(name.mk_string a a_1) :=
if (`_private).is_prefix_of n
then let n' := n.update_prefix name.anonymous in
n' <$ resolve_name' n' <|> pure n
else strip_prefix' n [a] a_1
| n := pure n
/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/
meta def mk_patterns (t : expr) : tactic (list format) :=
do let cl := t.get_app_fn.const_name,
env ← get_env,
let fs := env.constructors_of cl,
fs.mmap $ λ f,
do { (vs,_) ← mk_const f >>= infer_type >>= mk_local_pis,
let vs := vs.filter (λ v, v.is_default_local),
vs ← vs.mmap (λ v,
do v' ← get_unused_name v.local_pp_name,
pose v' none `(()),
pure v' ),
vs.mmap' $ λ v, get_local v >>= clear,
let args := list.intersperse (" " : format) $ vs.map to_fmt,
f ← strip_prefix f,
if args.empty
then pure $ format!"| {f} := _\n"
else pure format!"| ({f} {format.join args}) := _\n" }
/--
Hole command used to generate a `match` expression.
In the following:
```lean
meta def foo (e : expr) : tactic unit :=
{! e !}
```
invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression")
produces:
```lean
meta def foo (e : expr) : tactic unit :=
match e with
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
end
```
-/
@[hole_command] meta def match_stub : hole_command :=
{ name := "Match Stub",
descr := "Generate a list of equations for a `match` expression.",
action := λ es,
do [e] ← pure es | fail "expecting one expression",
e ← to_expr e,
t ← infer_type e >>= whnf,
fs ← mk_patterns t,
e ← pp e,
let out := format.to_string format!"match {e} with\n{format.join fs}end\n",
return [(out,"")] }
add_tactic_doc
{ name := "Match Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.match_stub],
tags := ["pattern matching"] }
/--
Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition")
in the following:
```lean
meta def foo : {! expr → tactic unit !} -- `:=` is omitted
```
produces:
```lean
meta def foo : expr → tactic unit
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
A similar result can be obtained by invoking "Equations Stub" on the following:
```lean
meta def foo : expr → tactic unit := -- do not forget to write `:=`!!
{! !}
```
```lean
meta def foo : expr → tactic unit := -- don't forget to erase `:=`!!
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
-/
@[hole_command] meta def eqn_stub : hole_command :=
{ name := "Equations Stub",
descr := "Generate a list of equations for a recursive definition.",
action := λ es,
do t ← match es with
| [t] := to_expr t
| [] := target
| _ := fail "expecting one type"
end,
e ← whnf t,
(v :: _,_) ← mk_local_pis e | fail "expecting a Pi-type",
t' ← infer_type v,
fs ← mk_patterns t',
t ← pp t,
let out :=
if es.empty then
format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}"
else format.to_string format!"{t}\n{format.join fs}",
return [(out,"")] }
add_tactic_doc
{ name := "Equations Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.eqn_stub],
tags := ["pattern matching"] }
/--
This command lists the constructors that can be used to satisfy the expected type.
Invoking "List Constructors" ("Show the list of constructors of the expected type")
in the following hole:
```lean
def foo : ℤ ⊕ ℕ :=
{! !}
```
produces:
```lean
def foo : ℤ ⊕ ℕ :=
{! sum.inl, sum.inr !}
```
and will display:
```lean
sum.inl : ℤ → ℤ ⊕ ℕ
sum.inr : ℕ → ℤ ⊕ ℕ
```
-/
@[hole_command] meta def list_constructors_hole : hole_command :=
{ name := "List Constructors",
descr := "Show the list of constructors of the expected type.",
action := λ es,
do t ← target >>= whnf,
(_,t) ← mk_local_pis t,
let cl := t.get_app_fn.const_name,
let args := t.get_app_args,
env ← get_env,
let cs := env.constructors_of cl,
ts ← cs.mmap $ λ c,
do { e ← mk_const c,
t ← infer_type (e.mk_app args) >>= pp,
c ← strip_prefix c,
pure format!"\n{c} : {t}\n" },
fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt),
let out := format.to_string format!"{{! {fs} !}",
trace (format.join ts).to_string,
return [(out,"")] }
add_tactic_doc
{ name := "List Constructors",
category := doc_category.hole_cmd,
decl_names := [`tactic.list_constructors_hole],
tags := ["goal information"] }
/-- Makes the declaration `classical.prop_decidable` available to type class inference.
This asserts that all propositions are decidable, but does not have computational content. -/
meta def classical : tactic unit :=
do h ← get_unused_name `_inst,
mk_const `classical.prop_decidable >>= note h none,
reset_instance_cache
open expr
/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,
returns the expression `f ∘ g ∘ h`. -/
meta def mk_comp (v : expr) : expr → tactic expr
| (app f e) :=
if e = v then pure f
else do
guard (¬ v.occurs f) <|> fail "bad guard",
e' ← mk_comp e >>= instantiate_mvars,
f ← instantiate_mvars f,
mk_mapp ``function.comp [none,none,none,f,e']
| e :=
do guard (e = v),
t ← infer_type e,
mk_mapp ``id [t]
/--
From a lemma of the shape `∀ x, f (g x) = h x`
derive an auxiliary lemma of the form `f ∘ g = h`
for reasoning about higher-order functions.
-/
meta def mk_higher_order_type : expr → tactic expr
| (pi n bi d b@(pi _ _ _ _)) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'
| (pi n bi d b) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(l,r) ← match_eq b' <|> fail format!"not an equality {b'}",
l' ← mk_comp v l,
r' ← mk_comp v r,
mk_app ``eq [l',r']
| e := failed
open lean.parser interactive.types
/-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`.
It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.
-/
@[user_attribute]
meta def higher_order_attr : user_attribute unit (option name) :=
{ name := `higher_order,
parser := optional ident,
descr :=
"From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the
form `f ∘ g = h` for reasoning about higher-order functions.",
after_set := some $ λ lmm _ _,
do env ← get_env,
decl ← env.get lmm,
let num := decl.univ_params.length,
let lvls := (list.iota num).map (`l).append_after,
let l : expr := expr.const lmm $ lvls.map level.param,
t ← infer_type l >>= instantiate_mvars,
t' ← mk_higher_order_type t,
(_,pr) ← solve_aux t' $ do {
intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },
pr ← instantiate_mvars pr,
lmm' ← higher_order_attr.get_param lmm,
lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,
add_decl $ declaration.thm lmm' lvls t' (pure pr),
copy_attribute `simp lmm lmm',
copy_attribute `functor_norm lmm lmm' }
add_tactic_doc
{ name := "higher_order",
category := doc_category.attr,
decl_names := [`tactic.higher_order_attr],
tags := ["lemma derivation"] }
attribute [higher_order map_comp_pure] map_pure
/--
Use `refine` to partially discharge the goal,
or call `fconstructor` and try again.
-/
private meta def use_aux (h : pexpr) : tactic unit :=
(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)
/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations
at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to
the expected type.
```lean
example : ∃ x : ℤ, x = x :=
by tactic.use ``(42)
```
See the doc string for `tactic.interactive.use` for more information.
-/
protected meta def use (l : list pexpr) : tactic unit :=
focus1 $ seq (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}")
instantiate_mvars_in_target
/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the
local context. -/
meta def clear_aux_decl_aux : list expr → tactic unit
| [] := skip
| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l
/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/
meta def clear_aux_decl : tactic unit :=
local_context >>= clear_aux_decl_aux
/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)
finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/
meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr)
| vs e (pi n bi d b) :=
do { v ← mk_meta_var d,
apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>
(e arg, vs) <$ unify d t
| vs e _ := failed
/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/
meta def apply_at (e h : expr) : tactic unit :=
do ht ← infer_type h,
et ← infer_type e,
(h', gs') ← apply_at_aux h ht [] e et,
note h.local_pp_name none h',
clear h,
gs' ← gs'.mfilter is_assigned,
(g :: gs) ← get_goals,
set_goals (g :: gs' ++ gs)
/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/
meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=
do tgt ← infer_type h,
env ← get_env,
let r := get_app_fn tgt,
match env.symm_for (const_name r) with
| (some symm) := do s ← mk_const symm,
apply_at s h
| none := fail "symmetry tactic failed, target is not a relation application with the expected property."
end
precedence `setup_tactic_parser`:0
/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing
interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.
It does *not* use the `namespace` command, so it will typically be used after
`namespace tactic.interactive`.
-/
@[user_command]
meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") :
lean.parser unit :=
emit_code_here "
open lean
open lean.parser
open interactive interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many .
"
/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if
`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/
meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α :=
λ s, match tac s with
| (result.success r s') := (finalizer >> pure r) s'
| (result.exception msg p s') := (finalizer >> result.exception msg p) s'
end
/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/
meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s :=
let msg (_ : unit) : format := match msg with
| some msg := add_msg ++ format.line ++ msg ()
| none := add_msg
end in
result.exception msg p s
| ok := ok
end
/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,
returns the error message. -/
meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.
-/
meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit :=
do x ← retrieve_or_report_error t,
match x with
| (sum.inl _) := skip
| (sum.inr msg) := if p msg then skip else fail msg
end
add_tactic_doc
{ name := "setup_tactic_parser",
category := doc_category.cmd,
decl_names := [`tactic.setup_tactic_parser_cmd],
tags := ["parsing", "notation"] }
/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message
of `t`. -/
meta def trace_error (msg : string) (t : tactic α) : tactic α
| s := match t s with
| (result.success r s') := result.success r s'
| (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s'
| (result.exception none p s') := result.exception none p s'
end
/--
``trace_if_enabled `n msg`` traces the message `msg`
only if tracing is enabled for the name `n`.
Create new names registered for tracing with `declare_trace n`.
Then use `set_option trace.n true/false` to enable or disable tracing for `n`.
-/
meta def trace_if_enabled
(n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit :=
when_tracing n (trace msg)
/--
``trace_state_if_enabled `n msg`` prints the tactic state,
preceded by the optional string `msg`,
only if tracing is enabled for the name `n`.
-/
meta def trace_state_if_enabled
(n : name) (msg : string := "") : tactic unit :=
when_tracing n ((if msg = "" then skip else trace msg) >> trace_state)
/--
This combinator is for testing purposes. It succeeds if `t` fails with message `msg`,
and fails otherwise.
-/
meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit :=
λ s, match t s with
| (interaction_monad.result.exception msg' _ s') :=
let expected_msg := (msg'.iget ()).to_string in
if msg = expected_msg then result.success () s
else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s
end
/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the
initial goals and returns the goals `tac` ended on. -/
meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) :=
do gs' ← get_goals,
set_goals gs,
finally (prod.mk <$> tac <*> get_goals) (set_goals gs')
/-- like `with_local_goals` but discards the resulting goals -/
meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α :=
prod.fst <$> with_local_goals gs tac
/-- Representation of a proof goal that lends itself to comparison. The
following goal:
```lean
l₀ : T,
l₁ : T
⊢ ∀ v : T, foo
```
is represented as
```
(2, ∀ l₀ l₁ v : T, foo)
```
The number 2 indicates that first the two bound variables of the
`∀` are actually local constant. Comparing two such goals with `=`
rather than `=ₐ` or `is_def_eq` tells us that proof script should
not see the difference between the two.
-/
meta def packaged_goal := ℕ × expr
/-- proof state made of multiple `goal` meant for comparing
the result of running different tactics -/
meta def proof_state := list packaged_goal
meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩
meta instance proof_state.inhabited : inhabited proof_state :=
(infer_instance : inhabited (list packaged_goal))
/-- create a `packaged_goal` corresponding to the current goal -/
meta def get_packaged_goal : tactic packaged_goal := do
ls ← local_context,
tgt ← target >>= instantiate_mvars,
tgt ← pis ls tgt,
pure (ls.length, tgt)
/-- `goal_of_mvar g`, with `g` a meta variable, creates a
`packaged_goal` corresponding to `g` interpretted as a proof goal -/
meta def goal_of_mvar (g : expr) : tactic packaged_goal :=
with_local_goals' [g] get_packaged_goal
/-- `get_proof_state` lists the user visible goal for each goal
of the current state and for each goal, abstracts all of the
meta variables of the other gaols.
This produces a list of goals in the form of `ℕ × expr` where
the `expr` encodes the following proof state:
```lean
2 goals
l₁ : t₁,
l₂ : t₂,
l₃ : t₃
⊢ tgt₁
⊢ tgt₂
```
as
```lean
[ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁),
(0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ]
```
with 2 goals, the first 2 bound variables encode the meta variable
of all the goals, the next 3 (in the first goal) and 0 (in the second goal)
are the local constants.
This representation allows us to compare goals and proof states while
ignoring information like the unique name of local constants and
the equality or difference of meta variables that encode the same goal.
-/
meta def get_proof_state : tactic proof_state :=
do gs ← get_goals,
gs.mmap $ λ g, do
⟨n,g⟩ ← goal_of_mvar g,
g ← gs.mfoldl (λ g v, do
g ← kabstract g v reducible ff,
pure $ pi `goal binder_info.default `(true) g ) g,
pure (n,g)
/--
Run `tac` in a disposable proof state and return the state.
See `proof_state`, `goal` and `get_proof_state`.
-/
meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) :=
try_core $ retrieve $ tac >> get_proof_state
open lean interactive
/-- A type alias for `tactic format`, standing for "pretty print format". -/
meta def pformat := tactic format
/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/
meta def pformat.mk (fmt : format) : pformat := pure fmt
/-- an alias for `pp`. -/
meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat :=
pp x
meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=
⟨ id ⟩
meta instance : has_append pformat :=
⟨ λ x y, (++) <$> x <*> y ⟩
meta instance tactic.has_to_tactic_format [has_to_tactic_format α] :
has_to_tactic_format (tactic α) :=
⟨ λ x, x >>= to_pfmt ⟩
private meta def parse_pformat : string → list char → parser pexpr
| acc [] := pure ``(to_pfmt %%(reflect acc))
| acc ('\n'::s) :=
do f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)
| acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s
| acc ('{'::s) :=
do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string,
'}'::s ← return s.to_list | fail "'}' expected",
f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)
| acc (c::s) := parse_pformat (acc.str c) s
reserve prefix `pformat! `:100
/-- See `format!` in `init/meta/interactive_base.lean`.
The main differences are that `pp` is called instead of `to_fmt` and that we can use
arguments of type `tactic α` in the quotations.
Now, consider the following:
```lean
e ← to_expr ``(3 + 7),
trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`
trace pformat!"{e}" -- outputs `3 + 7`
```
The difference is significant. And now, the following is expressible:
```lean
e ← to_expr ``(3 + 7),
trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ`
```
See also: `trace!` and `fail!`
-/
@[user_notation]
meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr :=
do e ← parse_pformat "" s.to_list,
return ``(%%e : pformat)
reserve prefix `fail! `:100
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= fail)
reserve prefix `trace! `:100
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= trace)
/-- A hackish way to get the `src` directory of mathlib. -/
meta def get_mathlib_dir : tactic string :=
do e ← get_env,
s ← e.decl_olean `tactic.reset_instance_cache,
return $ s.popn_back 17
/-- Checks whether a declaration with the given name is declared in mathlib.
If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,
since it is expensive to execute `get_mathlib_dir` many times. -/
meta def is_in_mathlib (n : name) : tactic bool :=
do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n
/--
Runs a tactic by name.
If it is a `tactic string`, return whatever string it returns.
If it is a `tactic unit`, return the name.
(This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.)
-/
meta def name_to_tactic (n : name) : tactic string :=
do d ← get_decl n,
e ← mk_const n,
let t := d.type,
if (t =ₐ `(tactic unit)) then
(eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n))
else if (t =ₐ `(tactic string)) then
(eval_expr (tactic string) e) >>= (λ t, t)
else fail!"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`"
/-- auxiliary function for apply_under_pis -/
private meta def apply_under_pis_aux (func arg : pexpr) : ℕ → expr → pexpr
| n (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_pis_aux (n+1) bd)
| n _ :=
let vars := ((list.range n).reverse.map (@expr.var ff)),
bd := vars.foldl expr.app arg.mk_explicit in
func bd
/--
Assumes `pi_expr` is of the form `Π x1 ... xn, _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=
apply_under_pis_aux func arg 0 pi_expr
/--
Tries to derive instances by unfolding the newly introduced type and applying type class resolution.
For example,
```lean
@[derive ring] def new_int : Type := ℤ
```
adds an instance `ring new_int`, defined to be the instance of `ring ℤ` found by `apply_instance`.
Multiple instances can be added with `@[derive [ring, module ℝ]]`.
This derive handler applies only to declarations made using `def`, and will fail on such a
declaration if it is unable to derive an instance. It is run with higher priority than the built-in
handlers, which will fail on `def`s.
-/
@[derive_handler, priority 2000] meta def delta_instance : derive_handler :=
λ cls new_decl_name,
do env ← get_env,
if env.is_inductive new_decl_name then return ff else
do new_decl_type ← declaration.type <$> get_decl new_decl_name,
new_decl_pexpr ← resolve_name new_decl_name,
tgt ← to_expr $ apply_under_pis cls new_decl_pexpr new_decl_type,
(_, inst) ← solve_aux tgt
(intros >> reset_instance_cache >> delta_target [new_decl_name] >> apply_instance >> done),
inst ← instantiate_mvars inst,
tgt ← instantiate_mvars tgt,
nm ← get_unused_decl_name $ new_decl_name ++
match cls with
-- the postfix is needed because we can't protect this name. using nm.last directly can
-- conflict with open namespaces
| (expr.const nm _) := (nm.last ++ "_1" : string)
| _ := "inst"
end,
add_decl $ mk_definition nm inst.collect_univ_params tgt inst,
set_basic_attribute `instance nm tt,
return tt
/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.
`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a
declaration named `m` can be found. -/
meta def find_private_decl (n : name) (fr : option name) : tactic name :=
do env ← get_env,
fn ← option_t.run (do
fr ← option_t.mk (return fr),
d ← monad_lift $ get_decl fr,
option_t.mk (return $ env.decl_olean d.to_name) ),
let p : string → bool :=
match fn with
| (some fn) := λ x, fn = x
| none := λ _, tt
end,
let xs := env.decl_filter_map (λ d,
do fn ← env.decl_olean d.to_name,
guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n),
pure d.to_name),
match xs with
| [n] := pure n
| [] := fail "no such private found"
| _ := fail "many matches found"
end
open lean.parser interactive
/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`
and creates a local notation to refer to it.
`import_private foo` looks for `foo` in all imported files.
When possible, make `foo` non-private rather than using this feature.
-/
@[user_command]
meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit :=
do n ← ident,
fr ← optional (tk "from" *> ident),
n ← find_private_decl n fr,
c ← resolve_constant n,
d ← get_decl n,
let c := @expr.const tt c d.univ_levels,
new_n ← new_aux_decl_name,
add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,
let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}",
emit_command_here $ new_not,
skip .
add_tactic_doc
{ name := "import_private",
category := doc_category.cmd,
decl_names := [`tactic.import_private_cmd],
tags := ["renaming"] }
/--
The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`.
Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.
`mk_simp_attribute simp_name none` will use a default description.
Appending the command with `with attr1 attr2 ...` will include all declarations tagged with
`attr1`, `attr2`, ... in the new simp set.
This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string
to the attribute that is defined. If you need to create a simp set in a file where this command is
not available, you should use
```lean
run_cmd mk_simp_attr `simp_name
run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here"
```
-/
@[user_command]
meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit :=
do n ← ident,
d ← parser.pexpr,
d ← to_expr ``(%%d : option string),
descr ← eval_expr (option string) d,
with_list ← types.with_ident_list <|> return [],
mk_simp_attr n with_list,
add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n
add_tactic_doc
{ name := "mk_simp_attribute",
category := doc_category.cmd,
decl_names := [`tactic.mk_simp_attribute_cmd],
tags := ["simplification"] }
end tactic
|
6ecb4e7e4de10356f8c5ad2b4856c0196cc93f14 | 66a6486e19b71391cc438afee5f081a4257564ec | /homotopy/wedge.hlean | 2e306967acd46a33f284ac1505af118eab420765 | [
"Apache-2.0"
] | permissive | spiceghello/Spectral | c8ccd1e32d4b6a9132ccee20fcba44b477cd0331 | 20023aa3de27c22ab9f9b4a177f5a1efdec2b19f | refs/heads/master | 1,611,263,374,078 | 1,523,349,717,000 | 1,523,349,717,000 | 92,312,239 | 0 | 0 | null | 1,495,642,470,000 | 1,495,642,470,000 | null | UTF-8 | Lean | false | false | 3,171 | hlean | -- Authors: Floris van Doorn
import homotopy.wedge
open wedge pushout eq prod sum pointed equiv is_equiv unit lift bool option
namespace wedge
variable (A : Type*)
variables {A}
definition add_point_of_wedge_pbool [unfold 2]
(x : A ∨ pbool) : A₊ :=
begin
induction x with a b,
{ exact some a },
{ induction b, exact some pt, exact none },
{ reflexivity }
end
definition wedge_pbool_of_add_point [unfold 2]
(x : A₊) : A ∨ pbool :=
begin
induction x with a,
{ exact inr tt },
{ exact inl a }
end
variables (A)
definition wedge_pbool_equiv_add_point [constructor] :
A ∨ pbool ≃ A₊ :=
equiv.MK add_point_of_wedge_pbool wedge_pbool_of_add_point
abstract begin
intro x, induction x,
{ reflexivity },
{ reflexivity }
end end
abstract begin
intro x, induction x with a b,
{ reflexivity },
{ induction b, exact wedge.glue, reflexivity },
{ apply eq_pathover_id_right,
refine ap_compose wedge_pbool_of_add_point _ _ ⬝ ap02 _ !elim_glue ⬝ph _,
exact square_of_eq idp }
end end
definition wedge_flip' [unfold 3] {A B : Type*} (x : A ∨ B) : B ∨ A :=
begin
induction x,
{ exact inr a },
{ exact inl a },
{ exact (glue ⋆)⁻¹ }
end
definition wedge_flip [constructor] (A B : Type*) : A ∨ B →* B ∨ A :=
pmap.mk wedge_flip' (glue ⋆)⁻¹
definition wedge_flip'_wedge_flip' [unfold 3] {A B : Type*} (x : A ∨ B) : wedge_flip' (wedge_flip' x) = x :=
begin
induction x,
{ reflexivity },
{ reflexivity },
{ apply eq_pathover_id_right,
apply hdeg_square,
exact ap_compose wedge_flip' _ _ ⬝ ap02 _ !elim_glue ⬝ !ap_inv ⬝ !elim_glue⁻² ⬝ !inv_inv }
end
definition wedge_flip_wedge_flip (A B : Type*) :
wedge_flip B A ∘* wedge_flip A B ~* pid (A ∨ B) :=
phomotopy.mk wedge_flip'_wedge_flip'
proof (whisker_right _ (!ap_inv ⬝ !wedge.elim_glue⁻²) ⬝ !con.left_inv)⁻¹ qed
definition wedge_comm [constructor] (A B : Type*) : A ∨ B ≃* B ∨ A :=
begin
fapply pequiv.MK,
{ exact wedge_flip A B },
{ exact wedge_flip B A },
{ exact wedge_flip_wedge_flip A B },
{ exact wedge_flip_wedge_flip B A }
end
-- TODO: wedge is associative
definition wedge_shift [unfold 3] {A B C : Type*} (x : (A ∨ B) ∨ C) : (A ∨ (B ∨ C)) :=
begin
induction x with l,
induction l with a,
exact inl a,
exact inr (inl a),
exact (glue ⋆),
exact inr (inr a),
-- exact elim_glue _ _ _,
exact sorry
end
definition wedge_pequiv [constructor] {A A' B B' : Type*} (a : A ≃* A') (b : B ≃* B') : A ∨ B ≃* A' ∨ B' :=
begin
fapply pequiv_of_equiv,
exact pushout.equiv !pconst !pconst !pconst !pconst !pequiv.refl a b (λdummy, respect_pt a) (λdummy, respect_pt b),
exact ap pushout.inl (respect_pt a)
end
definition plift_wedge.{u v} (A B : Type*) : plift.{u v} (A ∨ B) ≃* plift.{u v} A ∨ plift.{u v} B :=
calc plift.{u v} (A ∨ B) ≃* A ∨ B : by exact !pequiv_plift⁻¹ᵉ*
... ≃* plift.{u v} A ∨ plift.{u v} B : by exact wedge_pequiv !pequiv_plift !pequiv_plift
end wedge
|
9ebded2f496c762b2b650881931dbbd5f0b481af | 302b541ac2e998a523ae04da7673fd0932ded126 | /tests/bench/list.lean | 638b200d0af2750352f9bdcea8b36918a0039d74 | [] | no_license | mattweingarten/lambdapure | 4aeff69e8e3b8e78ea3c0a2b9b61770ef5a689b1 | f920a4ad78e6b1e3651f30bf8445c9105dfa03a8 | refs/heads/master | 1,680,665,168,790 | 1,618,420,180,000 | 1,618,420,180,000 | 310,816,264 | 2 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 648 | lean |
set_option trace.compiler.ir.init true
inductive L
| Nil
| Cons : Nat -> L -> L
open L
instance : Inhabited L := ⟨Nil⟩
def map : (Nat -> Nat) -> L -> L
| f, Nil => Nil
| f, Cons n l => Cons (f n) (map f l)
def add_one (x:Nat) := x + 1
def map_with_one : (Nat -> Nat -> Nat) -> L -> L
| f,Nil => Nil
| f,Cons n l => map (f 1) (Cons n l)
partial def make' : Nat -> Nat -> L
| n,d =>
if d = 0 then Cons n Nil
else Cons (n-d) (make' n (d -1))
def make (n : Nat) : L := make' n n
def sum : L -> Nat
| Cons x l => x + (sum l)
| Nil => 0
unsafe def main : List String → IO UInt32
| _ =>
pure 0
|
81272adbe3b02624f64dc06d79ec58a9f1f153ee | 4376c25f060c13471bb89cdb12aeac1d53e53876 | /src/espaces-metriques/custom/seq_continuity.lean | d360484ef1526e369fe44886e5a6406f610f0d8f | [
"MIT"
] | permissive | RaitoBezarius/projet-maths-lean | 8fa7df563d64c256561ab71893c523fc1424b85c | 42356e980e021a20c3468f5ca1639fec01bb934f | refs/heads/master | 1,613,002,128,339 | 1,589,289,282,000 | 1,589,289,282,000 | 244,431,534 | 0 | 1 | MIT | 1,584,312,574,000 | 1,583,169,883,000 | TeX | UTF-8 | Lean | false | false | 1,533 | lean | import .defs
import .sequences
open espace_metrique
open_locale classical
section suites
variables {X:Type} [espace_metrique X]
variables {Y:Type} [espace_metrique Y]
variables {Z:Type} [espace_metrique Z]
-- Définir la continuité séquentielle --/
-- f est continue en L si pour tout (x_n) ∈ ℝ^ℕ convergente de limite L, (f(x_n))_n est convergente de limite f(L).
def seq_continue_en_l (f: X → Y) (L: X) := ∀ (x: ℕ → X), converge x L → converge (suite_image f x) (f L)
def seq_continue (f: X → Y) := ∀ L : X, seq_continue_en_l f L
/-- On démontre que la continuité séquentielle est stable par composition --/
-- On démontre la composition des suites images.
theorem comp_suite_image (f: X → Y) (g: Y → Z) (x: ℕ → X): suite_image g (suite_image f x) = suite_image (g ∘ f) x :=
begin
ext,
repeat {rw suite_image},
end
-- On se ramène à la continuité séquentielle en un point.
theorem comp_seq_continue_ponctuel (f : X → Y) (g : Y → Z) (l: X):
seq_continue_en_l f l ∧ seq_continue_en_l g (f l)
→ seq_continue_en_l (g ∘ f) l := begin
intros H x x_cv,
cases H with Hf Hg,
have := Hg (suite_image f x) (Hf x x_cv),
conv at this {
congr,
rw comp_suite_image f g x,
skip,
skip,
},
exact this,
end
theorem comp_seq_continue (f:X → Y) (g:Y → Z):
seq_continue f ∧ seq_continue g → seq_continue (g ∘ f):=
begin
intro H,
intro l,
apply comp_seq_continue_ponctuel,
cases H with Hf Hg,
split,
exact Hf l,
exact Hg (f l),
end
end suites |
49ed8f31ec6a94911b820de6786b07e9299b9977 | e21db629d2e37a833531fdcb0b37ce4d71825408 | /src/use_cases/assign_mcl/proof1.lean | 3d46c750dd9667127e21fb1a81fa62220aae38c8 | [] | no_license | fischerman/GPU-transformation-verifier | 614a28cb4606a05a0eb27e8d4eab999f4f5ea60c | 75a5016f05382738ff93ce5859c4cfa47ccb63c1 | refs/heads/master | 1,586,985,789,300 | 1,579,290,514,000 | 1,579,290,514,000 | 165,031,073 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,466 | lean | /- import mcl
import mcl_rhl
import parlang
import syncablep
import use_cases.assign_mcl
import use_cases.assign_mcl.def
open mcl
open mcl.mclk
open mcl.rhl
open parlang
open parlang.state
open parlang.thread_state
open assign_mcl
namespace assign_mcl
namespace proof1
lemma store_access_elim_idx {sig : signature} {n n_idx} {s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} {var} {idx : vector (expression sig type.int) n_idx}
{t} {h₄ : ((sig.val var).type).dim = n_idx} {h₃ : type_of (sig.val var) = t } {f} {t : fin n} {i : mcl_address sig} {ac₁ : vector bool n} {updates}
(h₂ : i.2.to_list ≠ (idx.map ((eval (((map_active_threads ac₁ (compute_list updates) s).threads).nth t).tlocal))).to_list)
(h₁ : i ∉ accesses (vector.nth ((map_active_threads ac₁ (f ∘ compute_list updates) s).threads) t)) :
i ∉ accesses (vector.nth ((map_active_threads ac₁ (f ∘ (thread_state.tlocal_to_shared var idx h₃ h₄) ∘ compute_list updates) s).threads) t) := begin
sorry,
end
lemma store_access_elim_idx' {sig : signature} {n n_idx} {s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} {var} {idx : vector (expression sig type.int) n_idx}
{t} {h₄ : ((sig.val var).type).dim = n_idx} {h₃ : type_of (sig.val var) = t } {t : fin n} {i : mcl_address sig} {ac₁ : vector bool n} {updates}
(h₂ : i.2.to_list ≠ (idx.map ((eval (((map_active_threads ac₁ (compute_list updates) s).threads).nth t).tlocal ))).to_list)
(h₁ : i ∉ accesses (vector.nth (s.threads) t)) :
i ∉ accesses (vector.nth ((map_active_threads ac₁ ((thread_state.tlocal_to_shared var idx h₃ h₄) ∘ compute_list updates) s).threads) t) := begin
sorry,
end
lemma store_store_success {sig : signature} {i : mcl_address sig} {updates} {ts : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)}
{dim} {idx : vector (expression sig type.int) dim} {var t} {h₁ : type_of (sig.val var) = t} {h₂ : ((sig.val var).type).dim = dim}
{f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} :
i = ⟨var, vector_mpr h₂ (idx.map (eval (compute_list updates ts).tlocal))⟩ → i ∈ ((f ∘ thread_state.tlocal_to_shared var idx h₁ h₂ ∘ compute_list updates) ts).stores := by sorry
/-- Stores can be skipped if the variable name does not match. Does not work for idx -/
lemma store_store_skip_name {sig : signature} {i : mcl_address sig} {updates} {ts : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)}
{dim} {idx : vector (expression sig type.int) dim} {var t} {h₁ : type_of (sig.val var) = t} {h₂ : ((sig.val var).type).dim = dim}
{f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} :
i ∈ ((f ∘ compute_list updates) ts).stores → i ∈ ((f ∘ thread_state.tlocal_to_shared var idx h₁ h₂ ∘ compute_list updates) ts).stores := by sorry
lemma access_init {sig₁ sig₂ : signature} {P : memory (parlang_mcl_shared sig₁) → memory (parlang_mcl_shared sig₂) → Prop}
{f₁ : memory (parlang_mcl_shared sig₁) → ℕ} {f₂ : memory (parlang_mcl_shared sig₂) → ℕ} {m₁ : memory (parlang_mcl_shared sig₁)} {m₂ : memory (parlang_mcl_shared sig₂)}
{n₁} {s₁ : state n₁ (memory $ parlang_mcl_tlocal sig₁) (parlang_mcl_shared sig₁)} {ac₁ : vector bool n₁} {n₂} {s₂ : state n₂ (memory $ parlang_mcl_tlocal sig₂) (parlang_mcl_shared sig₂)} {ac₂ : vector bool n₂} {t} {i} :
initial_kernel_assertion mcl_init mcl_init P f₁ f₂ m₁ m₂ n₁ s₁ ac₁ n₂ s₂ ac₂ → i ∉ accesses (vector.nth (s₁.threads) t) := begin
sorry
end
-- question: should we limit ourselfs to shared scope here?
/-- generic array access for cases-distinction. Covers all accesses with the same variable name and the right number of dimensions -/
structure array_access (sig : signature) (var : string) (i : mcl_address sig) : Prop :=
(var_eq : i.1 = var)
(idx_len : i.2.length = (sig.val var).type.dim)
-- (bound : list.forall₂ nat.lt i.2 (sig var).type.sizes.to_list)
/-- An extension of array_access. Restricts itself to arrays with one dimension and that index being less than n. n is usually used for the numer of threads to create a 1-to-1 mapping from threads to elements. Without shifting thread n stores to element n -/
structure array_access_tid_to_idx (sig : signature) (var : string) (i : mcl_address sig) (n : ℕ) extends array_access sig var i : Prop :=
(one_dim : i.2.length = 1)
(idx_1_lt_n : i.2.nth ⟨0, begin rw [var_eq, ←idx_len, one_dim], exact lt_zero_one end⟩ < n)
/-- Returns the thread identifier, which performs the store -/
def array_access_tid_to_idx.storing_tid {sig : signature} {var : string} {i : mcl_address sig} {n} (a : array_access_tid_to_idx sig var i n) :
fin n := ⟨i.2.nth ⟨0, begin rw [a.to_array_access.var_eq, ← a.to_array_access.idx_len, a.one_dim], exact lt_zero_one end⟩, a.idx_1_lt_n⟩
instance forall₂_decidable {α : Type} [decidable_eq α] (l₁ : list α) (l₂ : list α) : decidable (list.forall₂ eq l₁ l₂) := begin
induction l₁ generalizing l₂,
case list.nil {
cases l₂,
case list.nil {
exact is_true (list.forall₂.nil)
},
case list.cons {
exact is_false (begin
intro h,
cases h,
end)
}
},
case list.cons {
cases l₂,
case list.nil {
exact is_false (begin
intro h,
cases h,
end)
},
case list.cons {
specialize l₁_ih l₂_tl,
admit,
-- by_cases h : l₁_hd = l₂_hd ∧ list.forall₂ eq l₁_tl l₂_tl,
-- {
-- exact is_true (begin
-- apply list.forall₂.cons,
-- exact h,
-- apply l₁_ih,
-- end)
-- }
}
}
end
instance {sig var i} : decidable (array_access sig var i) :=
if var_eq : i.1 = var then
if idx_len : i.2.length = (sig.val var).type.dim then is_true ⟨var_eq, idx_len⟩
-- if bound : list.forall₂ eq i.2 (sig var).type.sizes.to_list then is_true ⟨var_eq, idx_len, bound⟩
-- else is_false (assume h : array_access sig var i, bound (array_access.bound h))
else is_false (assume h : array_access sig var i, idx_len (array_access.idx_len h))
else is_false (assume h : array_access sig var i, var_eq (array_access.var_eq h))
instance ll {sig var i n} : decidable (array_access_tid_to_idx sig var i n) := sorry
lemma store_shared_success {sig : signature} {i : mcl_address sig} {updates}
{dim} {idx : vector (expression sig type.int) dim} {var₁ var₂ t} {h₁ : type_of (sig.val var₂) = t} {h₂}
{ts : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)}
{f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} (a : array_access sig var₁ i) (h : var₁ = var₂) : ((
f ∘
thread_state.tlocal_to_shared var₂ idx h₁ h₂ ∘
compute_list updates)
ts
).shared i = (begin simp [parlang_mcl_shared, signature.lean_type_of, lean_type_of], rw a.var_eq, rw h, exact ((compute_list updates ts).tlocal.get ⟨var₂, vector_mpr h₂ $ idx.map (eval (compute_list updates ts).tlocal)⟩) end) := sorry
lemma store_shared_skip {sig : signature} {i : mcl_address sig} {updates}
{dim} {idx : vector (expression sig type.int) dim} {var₁ var₂ t} {h₁ : type_of (sig.val var₂) = t} {h₂}
{ts : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)}
{f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} (a : array_access sig var₁ i) (h : var₁ ≠ var₂) : ((
f ∘
thread_state.tlocal_to_shared var₂ idx h₁ h₂ ∘
compute_list updates)
ts
).shared i = ((f ∘ compute_list updates) ts).shared i := sorry
def memory_array_update_tid {sig : signature} {n} (var) (s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) (expr : expression sig (type_of (sig.val var))) (m : memory (parlang_mcl_shared sig)) :=
((list.range_fin n).foldl (λ (m : parlang.memory (parlang_mcl_shared sig)) i, m.update ⟨var, eq.mpr sorry v[i]⟩ (eval (s.threads.nth i).tlocal expr))) m
lemma memory_array_update_tid_skip {sig : signature} {n} {var₁ var₂} {s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)}
{expr : expression sig (type_of (sig.val var₂))} {m : memory (parlang_mcl_shared sig)} {i} (a : array_access sig var₁ i) (h : var₁ ≠ var₂) :
(memory_array_update_tid var₂ s expr m) i = m i := begin
cases i,
have : i_fst = var₁ := a.var_eq,
admit,
-- induction on n
-- show non-interference on memory.update
end
lemma memory_array_update_tid_success {sig : signature} {n} {var₁ var₂} {s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)}
{expr : expression sig (type_of (sig.val var₂))} {m : memory (parlang_mcl_shared sig)} {i} (a : array_access_tid_to_idx sig var₁ i n) (h : var₁ = var₂) :
(memory_array_update_tid var₂ s expr m) i = eval (s.threads.nth ⟨_, a.idx_1_lt_n⟩).tlocal (by rw a.to_array_access.var_eq; rw h; exact expr) := begin
admit,
end
structure array_access_oob (sig : signature) (var : string) (i : mcl_address sig) (n : ℕ) : Prop :=
(var_eq: i.1 = var) (idx_len : i.2.length = (sig.val var).type.dim) (one_dim : i.2.length = 1)
(oob: ¬i.2.nth ⟨0, begin rw [var_eq, ←idx_len, one_dim], exact lt_zero_one end⟩ < n)
instance bet {sig var i n} : decidable (array_access_oob sig var i n) := sorry
lemma array_access_false {sig : signature} {n i var} : ¬array_access_tid_to_idx sig var i n →
i.1 ≠ var ∨ i.2.length ≠ (sig.val var).type.dim ∨
i.2.length ≠ 1 ∨ array_access_oob sig var i n := begin
intro h,
by_cases var_eq: i.fst = var, swap, {
left,
trivial,
},
by_cases idx_len : vector.length (i.snd) = ((sig.val var).type).dim, swap, {
right, left,
trivial,
},
by_cases one_dim : vector.length (i.snd) = 1, swap, {
right, right, left,
trivial,
},
by_cases array_access_oob sig var i n, {
right, right, right,
assumption,
}, {
have : i.2.nth ⟨0, begin rw [var_eq, ←idx_len, one_dim], exact lt_zero_one end⟩ < n := begin
by_contra oob,
have : array_access_oob sig var i n := ⟨var_eq, idx_len, one_dim, oob⟩,
contradiction,
end,
have : array_access_tid_to_idx sig var i n := ⟨⟨var_eq, idx_len⟩, one_dim, this⟩,
contradiction,
}
end
-- this approach is like computing both programs and comparing their output
-- this is a fairly naive approach, another approach would be to show that their behavior is equal (based on the fact that we have to show equality)
/--
Show
-/
lemma assign_rel : mclp_rel eq p₁ p₂ eq := begin
apply rel_mclk_to_mclp,
apply skip_right.mpr,
apply rhl.seq,
swap,
apply skip_left_after.mpr,
apply skip_right.mpr,
apply rhl.seq,
swap,
-- break it down into individual proofs
apply add_skip_left.mpr,
apply rhl.seq,
swap,
{
apply shared_assign_right,
},{
apply shared_assign_right,
}, {
apply shared_assign_left,
},
apply shared_assign_left',
intros _ _ _ _ _ _ h,
cases h with m₁ h,
cases h with m₂ h,
simp,
have : n₁ = n₂ := begin
sorry
end,
subst this,
have hseq : s₁ = s₂ := begin
sorry
end,
-- the proof obligation in the form of a map thread on syncable is the simple version because we never consider threads to change active state (here all threads are always active)
-- the two updates store indepedently because "a" ≠ "b"
-- the two updates read indepedently because they both depend on the same state (AFAIK they could still be swaped because the state is fixed)
apply exists.intro (memory_array_update_tid "b" s₁ (read_tid + (expression.literal_int 1 (by refl))) (memory_array_update_tid "a" s₁ read_tid m₁)),
-- split up the proof for the individual memories
split, {
have : thread_state.update_shared_vars_for_expr read_tid = id := by refl,
rw this,
have : thread_state.update_shared_vars_for_expr (read_tid + (expression.literal_int 1 (show type_of (sig.val "b") = type_of (sig.val "b"), by refl))) = id := by refl,
rw this,
simp,
-- put maps in store
-- todo we could distinct cases
-- store stores the same value as update
-- update changes the value of an index of store
-- update can be ignored
-- rw ← function.comp.assoc,
-- rw ← function.comp.assoc,
-- rw thread_state_map,
-- rw ← function.comp.assoc,
-- rw thread_state_map',
-- rw function.comp.assoc,
-- rw function.comp.assoc,
-- rw syncable_remove_map,
have hbni : list.all (vector.to_list v[read_tid]) (bnot ∘ expr_reads "b") = tt := by refl,
have hani : list.all (vector.to_list v[read_tid]) (bnot ∘ expr_reads "a") = tt := by refl,
have hani' : expr_reads "a" read_tid = ff := by refl,
have hbni' : expr_reads "b" read_tid = ff := by refl,
have hbni'' : expr_reads "b" (read_tid + expression.literal_int 1 p₁._proof_5) = ff := by refl,
have hani'' : expr_reads "a" (read_tid + expression.literal_int 1 p₁._proof_5) = ff := by refl,
-- resolve get and update (the result should only be mcl_init, literals and memory (in case of loads))
-- simp [state_get_update_success _ _ _ _ _, eval_update_ignore' hbni, eval_update_ignore' hani, eval_update_ignore hani'', eval_update_ignore hbni''],
-- conv {
-- congr,
-- congr,
-- skip,
-- congr,
-- congr,
-- funext,
-- rw vector.map_single,
-- rw vector.to_list,
-- rw eval_update_ignore hbni',
-- rw eval_update_ignore hani',
-- skip,
-- congr,
-- funext,
-- rw vector.map_single,
-- rw vector.to_list,
-- rw eval_update_ignore hani',
-- },
intro,
-- handle all addresses from array "a"
by_cases ha : array_access_tid_to_idx sig "a" i n₁, {
-- choose that we have a store
right,
use ha.storing_tid,
repeat { rw compute_to_compute_list },
split,
{
-- find the correct store instruction which performs the write
rw map_active_threads_nth_ac, {
rw initial_kernel_assertion_left_thread_state h,
apply store_store_success,
apply address_eq,
swap,
{
apply ha.var_eq,
}, {
rw vector.map_single,
cases i,
cases ha,
cases ha__to_array_access,
simp at ha__to_array_access_var_eq,
simp at ha__to_array_access_idx_len,
dedup,
subst ha__to_array_access_var_eq_1,
rw ← vector.eq_one,
refl,
}
}, {
-- thread is active
apply all_threads_active_nth,
exact h.left_all_threads_active,
}
},
split,
{
-- proof that the value at i is the same in the resulting memory
rw map_active_threads_nth_ac (all_threads_active_nth h.left_all_threads_active _),
rw memory_array_update_tid_skip ha.to_array_access,
swap, {
intro heq,
cases heq,
},
rw memory_array_update_tid_success ha,
swap, {
refl,
},
rw store_shared_success ha.to_array_access,
swap, {
refl
},
rw initial_kernel_assertion_left_thread_state h,
sorry, -- proof that the value is the same
}, {
-- proof that all other threads t' don't access i
intros t' hneqtt',
-- handle store to "a"
apply store_access_elim_idx, {
apply list_neq_elem 0,
swap, {
rw vector.length_list,
rw ha.one_dim,
exact lt_zero_one,
}, {
rw list_nth_vector,
rw list_nth_vector,
rw vector.nth_map,
rw map_active_threads_nth_ac,
rw initial_kernel_assertion_left_thread_state h,
exact fin.fin_eq hneqtt',
sorry, -- todo thread is actives
}, {
rw vector.length_list,
rw vector.length,
exact lt_zero_one,
}
}, {
-- handle store to "b"
rw function.comp.assoc,
rw compute_list_merge,
apply store_access_elim_idx', {
apply list_neq_elem 0,
swap, {
rw vector.length_list,
rw ha.one_dim,
exact lt_zero_one,
}, {
rw list_nth_vector,
rw list_nth_vector,
rw vector.nth_map,
rw map_active_threads_nth_ac,
rw initial_kernel_assertion_left_thread_state h,
exact fin.fin_eq hneqtt',
sorry, -- todo thread is actives
}, {
sorry, -- todo prove length through map and stuff
}
}, {
-- initial state does not access any i
apply access_init h,
}
}
}
},
-- handle all addresses from array "b"
by_cases hb : array_access_tid_to_idx sig "b" i n₁, {
-- choose that we have a store
right,
use hb.storing_tid,
repeat { rw compute_to_compute_list },
split,
{
-- find the correct store instruction which performs the write
rw map_active_threads_nth_ac, {
rw initial_kernel_assertion_left_thread_state h,
apply store_store_skip_name,
rw function.comp.assoc,
rw compute_list_merge,
rw ← function.left_id (thread_state.tlocal_to_shared _ _ _ _ ∘ _),
apply store_store_success,
apply address_eq,
swap,
{
apply hb.var_eq,
}, {
rw vector.map_single,
cases i,
cases hb,
cases hb__to_array_access,
simp at hb__to_array_access_var_eq,
simp at hb__to_array_access_idx_len,
dedup,
subst hb__to_array_access_var_eq_1,
rw ← vector.eq_one,
refl,
}
}, {
-- thread is active
apply all_threads_active_nth,
exact h.left_all_threads_active,
}
},
split,
{
-- proof that the value at i is the same in the resulting memory
rw map_active_threads_nth_ac (all_threads_active_nth h.left_all_threads_active _),
rw memory_array_update_tid_success hb,
swap, {
refl,
},
rw store_shared_skip hb.to_array_access,
swap, {
intro heq,
cases heq,
},
rw initial_kernel_assertion_left_thread_state h,
rw function.comp.assoc,
rw compute_list_merge,
rw ← function.left_id (thread_state.tlocal_to_shared _ _ _ _ ∘ _),
rw store_shared_success hb.to_array_access,
swap, {
refl
},
sorry, -- proof that the value is the same
}, {
-- proof that all other threads t' don't access i
-- the order is defined by the program, we approach them similar to the proof for "a"
intros t' hneqtt',
-- handle store to "a"
apply store_access_elim_idx, {
apply list_neq_elem 0,
swap, {
rw vector.length_list,
rw hb.one_dim,
exact lt_zero_one,
}, {
rw list_nth_vector,
rw list_nth_vector,
rw vector.nth_map,
rw map_active_threads_nth_ac,
rw initial_kernel_assertion_left_thread_state h,
exact fin.fin_eq hneqtt',
sorry, -- todo thread is actives
}, {
rw vector.length_list,
rw vector.length,
exact lt_zero_one,
}
}, {
-- handle store to "b"
rw function.comp.assoc,
rw compute_list_merge,
apply store_access_elim_idx', {
apply list_neq_elem 0,
swap, {
rw vector.length_list,
rw hb.one_dim,
exact lt_zero_one,
}, {
rw list_nth_vector,
rw list_nth_vector,
rw vector.nth_map,
rw map_active_threads_nth_ac,
rw initial_kernel_assertion_left_thread_state h,
exact fin.fin_eq hneqtt',
sorry, -- todo thread is actives
}, {
sorry, -- todo prove length through map and stuff
}
}, {
-- initial state does not access any i
apply access_init h,
}
}
}
},
-- no thread stores in addresses which are not "a" or "b"
left,
intro t,
split,
{
repeat { rw compute_to_compute_list },
apply thread_state.store_accesses,
by_cases i.fst = "a", {
have : _ := array_access_false ha,
sorry,
-- apply store_access_elim_idx, {
-- }
},
by_cases i.fst = "b", {
sorry,
},
sorry,
},
-- TODO: handle all remaining addresses but "a"
sorry,
}, {
sorry,
}
end
end proof1
end assign_mcl -/ |
edbf03c3675387d610061940016d4efc8f658a06 | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/category_theory/endomorphism.lean | f811a7f36823c751706878194902dd1166e4022f | [
"Apache-2.0"
] | permissive | keeferrowan/mathlib | f2818da875dbc7780830d09bd4c526b0764a4e50 | aad2dfc40e8e6a7e258287a7c1580318e865817e | refs/heads/master | 1,661,736,426,952 | 1,590,438,032,000 | 1,590,438,032,000 | 266,892,663 | 0 | 0 | Apache-2.0 | 1,590,445,835,000 | 1,590,445,835,000 | null | UTF-8 | Lean | false | false | 2,818 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Scott Morrison, Simon Hudon
Definition and basic properties of endomorphisms and automorphisms of an object in a category.
-/
import category_theory.category
import category_theory.groupoid
import data.equiv.mul_add
universes v v' u u'
namespace category_theory
/-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with `function.comp`, not with `category.comp`. -/
def End {C : Type u} [𝒞_struct : category_struct.{v} C] (X : C) := X ⟶ X
namespace End
section struct
variables {C : Type u} [𝒞_struct : category_struct.{v} C] (X : C)
include 𝒞_struct
instance has_one : has_one (End X) := ⟨𝟙 X⟩
/-- Multiplication of endomorphisms agrees with `function.comp`, not `category_struct.comp`. -/
instance has_mul : has_mul (End X) := ⟨λ x y, y ≫ x⟩
variable {X}
@[simp] lemma one_def : (1 : End X) = 𝟙 X := rfl
@[simp] lemma mul_def (xs ys : End X) : xs * ys = ys ≫ xs := rfl
end struct
/-- Endomorphisms of an object form a monoid -/
instance monoid {C : Type u} [category.{v} C] {X : C} : monoid (End X) :=
{ mul_one := category.id_comp,
one_mul := category.comp_id,
mul_assoc := λ x y z, (category.assoc z y x).symm,
..End.has_mul X, ..End.has_one X }
/-- In a groupoid, endomorphisms form a group -/
instance group {C : Type u} [groupoid.{v} C] (X : C) : group (End X) :=
{ mul_left_inv := groupoid.comp_inv, inv := groupoid.inv, ..End.monoid }
end End
variables {C : Type u} [category.{v} C] (X : C)
def Aut (X : C) := X ≅ X
attribute [ext Aut] iso.ext
namespace Aut
instance : group (Aut X) :=
by refine { one := iso.refl X,
inv := iso.symm,
mul := flip iso.trans, .. } ; dunfold flip; obviously
/--
Units in the monoid of endomorphisms of an object
are (multiplicatively) equivalent to automorphisms of that object.
-/
def units_End_equiv_Aut : units (End X) ≃* Aut X :=
{ to_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
inv_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
left_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
right_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
map_mul' := λ f g, by rcases f; rcases g; refl }
end Aut
namespace functor
variables {D : Type u'} [category.{v'} D] (f : C ⥤ D) (X)
/-- `f.map` as a monoid hom between endomorphism monoids. -/
def map_End : End X →* End (f.obj X) :=
{ to_fun := functor.map f,
map_mul' := λ x y, f.map_comp y x,
map_one' := f.map_id X }
/-- `f.map_iso` as a group hom between automorphism groups. -/
def map_Aut : Aut X →* Aut (f.obj X) :=
{ to_fun := f.map_iso,
map_mul' := λ x y, f.map_iso_trans y x,
map_one' := f.map_iso_refl X }
end functor
end category_theory
|
5e3fabf1c67eb4ef1ceab752e215c82d4d6603ae | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/finmap_auto.lean | 40b46e1231a8c92cce5d5c957ca129ec92555c06 | [] | 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 | 22,736 | lean | /-
Copyright (c) 2018 Sean Leather. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sean Leather, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.list.alist
import Mathlib.data.finset.basic
import Mathlib.data.pfun
import Mathlib.PostPort
universes u v l u_1 w
namespace Mathlib
/-!
# Finite maps over `multiset`
-/
/-! ### multisets of sigma types-/
namespace multiset
/-- Multiset of keys of an association multiset. -/
def keys {α : Type u} {β : α → Type v} (s : multiset (sigma β)) : multiset α := map sigma.fst s
@[simp] theorem coe_keys {α : Type u} {β : α → Type v} {l : List (sigma β)} :
keys ↑l = ↑(list.keys l) :=
rfl
/-- `nodupkeys s` means that `s` has no duplicate keys. -/
def nodupkeys {α : Type u} {β : α → Type v} (s : multiset (sigma β)) :=
quot.lift_on s list.nodupkeys sorry
@[simp] theorem coe_nodupkeys {α : Type u} {β : α → Type v} {l : List (sigma β)} :
nodupkeys ↑l ↔ list.nodupkeys l :=
iff.rfl
end multiset
/-! ### finmap -/
/-- `finmap β` is the type of finite maps over a multiset. It is effectively
a quotient of `alist β` by permutation of the underlying list. -/
structure finmap {α : Type u} (β : α → Type v) where
entries : multiset (sigma β)
nodupkeys : multiset.nodupkeys entries
/-- The quotient map from `alist` to `finmap`. -/
def alist.to_finmap {α : Type u} {β : α → Type v} (s : alist β) : finmap β :=
finmap.mk (↑(alist.entries s)) (alist.nodupkeys s)
theorem alist.to_finmap_eq {α : Type u} {β : α → Type v} {s₁ : alist β} {s₂ : alist β} :
alist.to_finmap s₁ = alist.to_finmap s₂ ↔ alist.entries s₁ ~ alist.entries s₂ :=
sorry
@[simp] theorem alist.to_finmap_entries {α : Type u} {β : α → Type v} (s : alist β) :
finmap.entries (alist.to_finmap s) = ↑(alist.entries s) :=
rfl
/-- Given `l : list (sigma β)`, create a term of type `finmap β` by removing
entries with duplicate keys. -/
def list.to_finmap {α : Type u} {β : α → Type v} [DecidableEq α] (s : List (sigma β)) : finmap β :=
alist.to_finmap (list.to_alist s)
namespace finmap
/-! ### lifting from alist -/
/-- Lift a permutation-respecting function on `alist` to `finmap`. -/
def lift_on {α : Type u} {β : α → Type v} {γ : Type u_1} (s : finmap β) (f : alist β → γ)
(H : ∀ (a b : alist β), alist.entries a ~ alist.entries b → f a = f b) : γ :=
roption.get
(quotient.lift_on (entries s)
(fun (l : List (sigma β)) =>
roption.mk (list.nodupkeys l) fun (nd : list.nodupkeys l) => f (alist.mk l nd))
sorry)
sorry
@[simp] theorem lift_on_to_finmap {α : Type u} {β : α → Type v} {γ : Type u_1} (s : alist β)
(f : alist β → γ) (H : ∀ (a b : alist β), alist.entries a ~ alist.entries b → f a = f b) :
lift_on (alist.to_finmap s) f H = f s :=
alist.cases_on s
fun (s_entries : List (sigma β)) (s_nodupkeys : list.nodupkeys s_entries) =>
Eq.refl (lift_on (alist.to_finmap (alist.mk s_entries s_nodupkeys)) f H)
/-- Lift a permutation-respecting function on 2 `alist`s to 2 `finmap`s. -/
def lift_on₂ {α : Type u} {β : α → Type v} {γ : Type u_1} (s₁ : finmap β) (s₂ : finmap β)
(f : alist β → alist β → γ)
(H :
∀ (a₁ b₁ a₂ b₂ : alist β),
alist.entries a₁ ~ alist.entries a₂ →
alist.entries b₁ ~ alist.entries b₂ → f a₁ b₁ = f a₂ b₂) :
γ :=
lift_on s₁ (fun (l₁ : alist β) => lift_on s₂ (f l₁) sorry) sorry
@[simp] theorem lift_on₂_to_finmap {α : Type u} {β : α → Type v} {γ : Type u_1} (s₁ : alist β)
(s₂ : alist β) (f : alist β → alist β → γ)
(H :
∀ (a₁ b₁ a₂ b₂ : alist β),
alist.entries a₁ ~ alist.entries a₂ →
alist.entries b₁ ~ alist.entries b₂ → f a₁ b₁ = f a₂ b₂) :
lift_on₂ (alist.to_finmap s₁) (alist.to_finmap s₂) f H = f s₁ s₂ :=
sorry
/-! ### induction -/
theorem induction_on {α : Type u} {β : α → Type v} {C : finmap β → Prop} (s : finmap β)
(H : ∀ (a : alist β), C (alist.to_finmap a)) : C s :=
sorry
theorem induction_on₂ {α : Type u} {β : α → Type v} {C : finmap β → finmap β → Prop} (s₁ : finmap β)
(s₂ : finmap β) (H : ∀ (a₁ a₂ : alist β), C (alist.to_finmap a₁) (alist.to_finmap a₂)) :
C s₁ s₂ :=
induction_on s₁ fun (l₁ : alist β) => induction_on s₂ fun (l₂ : alist β) => H l₁ l₂
theorem induction_on₃ {α : Type u} {β : α → Type v} {C : finmap β → finmap β → finmap β → Prop}
(s₁ : finmap β) (s₂ : finmap β) (s₃ : finmap β)
(H : ∀ (a₁ a₂ a₃ : alist β), C (alist.to_finmap a₁) (alist.to_finmap a₂) (alist.to_finmap a₃)) :
C s₁ s₂ s₃ :=
induction_on₂ s₁ s₂ fun (l₁ l₂ : alist β) => induction_on s₃ fun (l₃ : alist β) => H l₁ l₂ l₃
/-! ### extensionality -/
theorem ext {α : Type u} {β : α → Type v} {s : finmap β} {t : finmap β} :
entries s = entries t → s = t :=
sorry
@[simp] theorem ext_iff {α : Type u} {β : α → Type v} {s : finmap β} {t : finmap β} :
entries s = entries t ↔ s = t :=
{ mp := ext, mpr := congr_arg fun {s : finmap β} => entries s }
/-! ### mem -/
/-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/
protected instance has_mem {α : Type u} {β : α → Type v} : has_mem α (finmap β) :=
has_mem.mk fun (a : α) (s : finmap β) => a ∈ multiset.keys (entries s)
theorem mem_def {α : Type u} {β : α → Type v} {a : α} {s : finmap β} :
a ∈ s ↔ a ∈ multiset.keys (entries s) :=
iff.rfl
@[simp] theorem mem_to_finmap {α : Type u} {β : α → Type v} {a : α} {s : alist β} :
a ∈ alist.to_finmap s ↔ a ∈ s :=
iff.rfl
/-! ### keys -/
/-- The set of keys of a finite map. -/
def keys {α : Type u} {β : α → Type v} (s : finmap β) : finset α :=
finset.mk (multiset.keys (entries s)) sorry
@[simp] theorem keys_val {α : Type u} {β : α → Type v} (s : alist β) :
finset.val (keys (alist.to_finmap s)) = ↑(alist.keys s) :=
rfl
@[simp] theorem keys_ext {α : Type u} {β : α → Type v} {s₁ : alist β} {s₂ : alist β} :
keys (alist.to_finmap s₁) = keys (alist.to_finmap s₂) ↔ alist.keys s₁ ~ alist.keys s₂ :=
sorry
theorem mem_keys {α : Type u} {β : α → Type v} {a : α} {s : finmap β} : a ∈ keys s ↔ a ∈ s :=
induction_on s fun (s : alist β) => alist.mem_keys
/-! ### empty -/
/-- The empty map. -/
protected instance has_emptyc {α : Type u} {β : α → Type v} : has_emptyc (finmap β) :=
has_emptyc.mk (mk 0 list.nodupkeys_nil)
protected instance inhabited {α : Type u} {β : α → Type v} : Inhabited (finmap β) :=
{ default := ∅ }
@[simp] theorem empty_to_finmap {α : Type u} {β : α → Type v} : alist.to_finmap ∅ = ∅ := rfl
@[simp] theorem to_finmap_nil {α : Type u} {β : α → Type v} [DecidableEq α] :
list.to_finmap [] = ∅ :=
rfl
theorem not_mem_empty {α : Type u} {β : α → Type v} {a : α} : ¬a ∈ ∅ := multiset.not_mem_zero a
@[simp] theorem keys_empty {α : Type u} {β : α → Type v} : keys ∅ = ∅ := rfl
/-! ### singleton -/
/-- The singleton map. -/
def singleton {α : Type u} {β : α → Type v} (a : α) (b : β a) : finmap β :=
alist.to_finmap (alist.singleton a b)
@[simp] theorem keys_singleton {α : Type u} {β : α → Type v} (a : α) (b : β a) :
keys (singleton a b) = singleton a :=
rfl
@[simp] theorem mem_singleton {α : Type u} {β : α → Type v} (x : α) (y : α) (b : β y) :
x ∈ singleton y b ↔ x = y :=
sorry
protected instance has_decidable_eq {α : Type u} {β : α → Type v} [DecidableEq α]
[(a : α) → DecidableEq (β a)] : DecidableEq (finmap β) :=
sorry
/-! ### lookup -/
/-- Look up the value associated to a key in a map. -/
def lookup {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : finmap β) : Option (β a) :=
lift_on s (alist.lookup a) sorry
@[simp] theorem lookup_to_finmap {α : Type u} {β : α → Type v} [DecidableEq α] (a : α)
(s : alist β) : lookup a (alist.to_finmap s) = alist.lookup a s :=
rfl
@[simp] theorem lookup_list_to_finmap {α : Type u} {β : α → Type v} [DecidableEq α] (a : α)
(s : List (sigma β)) : lookup a (list.to_finmap s) = list.lookup a s :=
sorry
@[simp] theorem lookup_empty {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) :
lookup a ∅ = none :=
rfl
theorem lookup_is_some {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s : finmap β} :
↥(option.is_some (lookup a s)) ↔ a ∈ s :=
induction_on s fun (s : alist β) => alist.lookup_is_some
theorem lookup_eq_none {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s : finmap β} :
lookup a s = none ↔ ¬a ∈ s :=
induction_on s fun (s : alist β) => alist.lookup_eq_none
@[simp] theorem lookup_singleton_eq {α : Type u} {β : α → Type v} [DecidableEq α] {a : α}
{b : β a} : lookup a (singleton a b) = some b :=
sorry
protected instance has_mem.mem.decidable {α : Type u} {β : α → Type v} [DecidableEq α] (a : α)
(s : finmap β) : Decidable (a ∈ s) :=
decidable_of_iff ↥(option.is_some (lookup a s)) sorry
theorem mem_iff {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s : finmap β} :
a ∈ s ↔ ∃ (b : β a), lookup a s = some b :=
induction_on s
fun (s : alist β) =>
iff.trans list.mem_keys
(exists_congr fun (b : β a) => iff.symm (list.mem_lookup_iff (alist.nodupkeys s)))
theorem mem_of_lookup_eq_some {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a}
{s : finmap β} (h : lookup a s = some b) : a ∈ s :=
iff.mpr mem_iff (Exists.intro b h)
theorem ext_lookup {α : Type u} {β : α → Type v} [DecidableEq α] {s₁ : finmap β} {s₂ : finmap β} :
(∀ (x : α), lookup x s₁ = lookup x s₂) → s₁ = s₂ :=
sorry
/-! ### replace -/
/-- Replace a key with a given value in a finite map.
If the key is not present it does nothing. -/
def replace {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a) (s : finmap β) :
finmap β :=
lift_on s (fun (t : alist β) => alist.to_finmap (alist.replace a b t)) sorry
@[simp] theorem replace_to_finmap {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a)
(s : alist β) : replace a b (alist.to_finmap s) = alist.to_finmap (alist.replace a b s) :=
sorry
@[simp] theorem keys_replace {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a)
(s : finmap β) : keys (replace a b s) = keys s :=
sorry
@[simp] theorem mem_replace {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α} {b : β a}
{s : finmap β} : a' ∈ replace a b s ↔ a' ∈ s :=
sorry
/-! ### foldl -/
/-- Fold a commutative function over the key-value pairs in the map -/
def foldl {α : Type u} {β : α → Type v} {δ : Type w} (f : δ → (a : α) → β a → δ)
(H :
∀ (d : δ) (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂),
f (f d a₁ b₁) a₂ b₂ = f (f d a₂ b₂) a₁ b₁)
(d : δ) (m : finmap β) : δ :=
multiset.foldl (fun (d : δ) (s : sigma β) => f d (sigma.fst s) (sigma.snd s)) sorry d (entries m)
/-- `any f s` returns `tt` iff there exists a value `v` in `s` such that `f v = tt`. -/
def any {α : Type u} {β : α → Type v} (f : (x : α) → β x → Bool) (s : finmap β) : Bool :=
foldl (fun (x : Bool) (y : α) (z : β y) => to_bool (↥x ∨ ↥(f y z))) sorry false s
/-- `all f s` returns `tt` iff `f v = tt` for all values `v` in `s`. -/
def all {α : Type u} {β : α → Type v} (f : (x : α) → β x → Bool) (s : finmap β) : Bool :=
foldl (fun (x : Bool) (y : α) (z : β y) => to_bool (↥x ∧ ↥(f y z))) sorry false s
/-! ### erase -/
/-- Erase a key from the map. If the key is not present it does nothing. -/
def erase {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : finmap β) : finmap β :=
lift_on s (fun (t : alist β) => alist.to_finmap (alist.erase a t)) sorry
@[simp] theorem erase_to_finmap {α : Type u} {β : α → Type v} [DecidableEq α] (a : α)
(s : alist β) : erase a (alist.to_finmap s) = alist.to_finmap (alist.erase a s) :=
sorry
@[simp] theorem keys_erase_to_finset {α : Type u} {β : α → Type v} [DecidableEq α] (a : α)
(s : alist β) :
keys (alist.to_finmap (alist.erase a s)) = finset.erase (keys (alist.to_finmap s)) a :=
sorry
@[simp] theorem keys_erase {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : finmap β) :
keys (erase a s) = finset.erase (keys s) a :=
sorry
@[simp] theorem mem_erase {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α}
{s : finmap β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s :=
sorry
theorem not_mem_erase_self {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s : finmap β} :
¬a ∈ erase a s :=
eq.mpr (id (Eq._oldrec (Eq.refl (¬a ∈ erase a s)) (propext mem_erase)))
(eq.mpr (id (Eq._oldrec (Eq.refl (¬(a ≠ a ∧ a ∈ s))) (propext not_and_distrib)))
(eq.mpr (id (Eq._oldrec (Eq.refl (¬a ≠ a ∨ ¬a ∈ s)) (propext not_not))) (Or.inl (Eq.refl a))))
@[simp] theorem lookup_erase {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : finmap β) :
lookup a (erase a s) = none :=
induction_on s (alist.lookup_erase a)
@[simp] theorem lookup_erase_ne {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α}
{s : finmap β} (h : a ≠ a') : lookup a (erase a' s) = lookup a s :=
induction_on s fun (s : alist β) => alist.lookup_erase_ne h
theorem erase_erase {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α} {s : finmap β} :
erase a (erase a' s) = erase a' (erase a s) :=
sorry
/-! ### sdiff -/
/-- `sdiff s s'` consists of all key-value pairs from `s` and `s'` where the keys are in `s` or
`s'` but not both. -/
def sdiff {α : Type u} {β : α → Type v} [DecidableEq α] (s : finmap β) (s' : finmap β) : finmap β :=
foldl (fun (s : finmap β) (x : α) (_x : β x) => erase x s) sorry s s'
protected instance has_sdiff {α : Type u} {β : α → Type v} [DecidableEq α] : has_sdiff (finmap β) :=
has_sdiff.mk sdiff
/-! ### insert -/
/-- Insert a key-value pair into a finite map, replacing any existing pair with
the same key. -/
def insert {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a) (s : finmap β) :
finmap β :=
lift_on s (fun (t : alist β) => alist.to_finmap (alist.insert a b t)) sorry
@[simp] theorem insert_to_finmap {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a)
(s : alist β) : insert a b (alist.to_finmap s) = alist.to_finmap (alist.insert a b s) :=
sorry
theorem insert_entries_of_neg {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a}
{s : finmap β} : ¬a ∈ s → entries (insert a b s) = sigma.mk a b ::ₘ entries s :=
sorry
@[simp] theorem mem_insert {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α}
{b' : β a'} {s : finmap β} : a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s :=
induction_on s alist.mem_insert
@[simp] theorem lookup_insert {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a}
(s : finmap β) : lookup a (insert a b s) = some b :=
sorry
@[simp] theorem lookup_insert_of_ne {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α}
{b : β a} (s : finmap β) (h : a' ≠ a) : lookup a' (insert a b s) = lookup a' s :=
sorry
@[simp] theorem insert_insert {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a}
{b' : β a} (s : finmap β) : insert a b' (insert a b s) = insert a b' s :=
sorry
theorem insert_insert_of_ne {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {a' : α} {b : β a}
{b' : β a'} (s : finmap β) (h : a ≠ a') :
insert a' b' (insert a b s) = insert a b (insert a' b' s) :=
sorry
theorem to_finmap_cons {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a)
(xs : List (sigma β)) : list.to_finmap (sigma.mk a b :: xs) = insert a b (list.to_finmap xs) :=
rfl
theorem mem_list_to_finmap {α : Type u} {β : α → Type v} [DecidableEq α] (a : α)
(xs : List (sigma β)) : a ∈ list.to_finmap xs ↔ ∃ (b : β a), sigma.mk a b ∈ xs :=
sorry
@[simp] theorem insert_singleton_eq {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a}
{b' : β a} : insert a b (singleton a b') = singleton a b :=
sorry
/-! ### extract -/
/-- Erase a key from the map, and return the corresponding value, if found. -/
def extract {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (s : finmap β) :
Option (β a) × finmap β :=
lift_on s (fun (t : alist β) => prod.map id alist.to_finmap (alist.extract a t)) sorry
@[simp] theorem extract_eq_lookup_erase {α : Type u} {β : α → Type v} [DecidableEq α] (a : α)
(s : finmap β) : extract a s = (lookup a s, erase a s) :=
sorry
/-! ### union -/
/-- `s₁ ∪ s₂` is the key-based union of two finite maps. It is left-biased: if
there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/
def union {α : Type u} {β : α → Type v} [DecidableEq α] (s₁ : finmap β) (s₂ : finmap β) :
finmap β :=
lift_on₂ s₁ s₂ (fun (s₁ s₂ : alist β) => alist.to_finmap (s₁ ∪ s₂)) sorry
protected instance has_union {α : Type u} {β : α → Type v} [DecidableEq α] : has_union (finmap β) :=
has_union.mk union
@[simp] theorem mem_union {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {s₁ : finmap β}
{s₂ : finmap β} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ :=
induction_on₂ s₁ s₂ fun (_x _x_1 : alist β) => alist.mem_union
@[simp] theorem union_to_finmap {α : Type u} {β : α → Type v} [DecidableEq α] (s₁ : alist β)
(s₂ : alist β) : alist.to_finmap s₁ ∪ alist.to_finmap s₂ = alist.to_finmap (s₁ ∪ s₂) :=
sorry
theorem keys_union {α : Type u} {β : α → Type v} [DecidableEq α] {s₁ : finmap β} {s₂ : finmap β} :
keys (s₁ ∪ s₂) = keys s₁ ∪ keys s₂ :=
sorry
@[simp] theorem lookup_union_left {α : Type u} {β : α → Type v} [DecidableEq α] {a : α}
{s₁ : finmap β} {s₂ : finmap β} : a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ :=
induction_on₂ s₁ s₂ fun (s₁ s₂ : alist β) => alist.lookup_union_left
@[simp] theorem lookup_union_right {α : Type u} {β : α → Type v} [DecidableEq α] {a : α}
{s₁ : finmap β} {s₂ : finmap β} : ¬a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ :=
induction_on₂ s₁ s₂ fun (s₁ s₂ : alist β) => alist.lookup_union_right
theorem lookup_union_left_of_not_in {α : Type u} {β : α → Type v} [DecidableEq α] {a : α}
{s₁ : finmap β} {s₂ : finmap β} (h : ¬a ∈ s₂) : lookup a (s₁ ∪ s₂) = lookup a s₁ :=
sorry
@[simp] theorem mem_lookup_union {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a}
{s₁ : finmap β} {s₂ : finmap β} :
b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ ¬a ∈ s₁ ∧ b ∈ lookup a s₂ :=
induction_on₂ s₁ s₂ fun (s₁ s₂ : alist β) => alist.mem_lookup_union
theorem mem_lookup_union_middle {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a}
{s₁ : finmap β} {s₂ : finmap β} {s₃ : finmap β} :
b ∈ lookup a (s₁ ∪ s₃) → ¬a ∈ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) :=
induction_on₃ s₁ s₂ s₃ fun (s₁ s₂ s₃ : alist β) => alist.mem_lookup_union_middle
theorem insert_union {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} {s₁ : finmap β}
{s₂ : finmap β} : insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ :=
sorry
theorem union_assoc {α : Type u} {β : α → Type v} [DecidableEq α] {s₁ : finmap β} {s₂ : finmap β}
{s₃ : finmap β} : s₁ ∪ s₂ ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) :=
sorry
@[simp] theorem empty_union {α : Type u} {β : α → Type v} [DecidableEq α] {s₁ : finmap β} :
∅ ∪ s₁ = s₁ :=
sorry
@[simp] theorem union_empty {α : Type u} {β : α → Type v} [DecidableEq α] {s₁ : finmap β} :
s₁ ∪ ∅ = s₁ :=
sorry
theorem erase_union_singleton {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a)
(s : finmap β) (h : lookup a s = some b) : erase a s ∪ singleton a b = s :=
sorry
/-! ### disjoint -/
/-- `disjoint s₁ s₂` holds if `s₁` and `s₂` have no keys in common. -/
def disjoint {α : Type u} {β : α → Type v} (s₁ : finmap β) (s₂ : finmap β) :=
∀ (x : α), x ∈ s₁ → ¬x ∈ s₂
theorem disjoint_empty {α : Type u} {β : α → Type v} (x : finmap β) : disjoint ∅ x :=
fun (x_1 : α) (H : x_1 ∈ ∅) (ᾰ : x_1 ∈ x) => false.dcases_on (fun (H : x_1 ∈ ∅) => False) H
theorem disjoint.symm {α : Type u} {β : α → Type v} (x : finmap β) (y : finmap β)
(h : disjoint x y) : disjoint y x :=
fun (p : α) (hy : p ∈ y) (hx : p ∈ x) => h p hx hy
theorem disjoint.symm_iff {α : Type u} {β : α → Type v} (x : finmap β) (y : finmap β) :
disjoint x y ↔ disjoint y x :=
{ mp := disjoint.symm x y, mpr := disjoint.symm y x }
protected instance disjoint.decidable_rel {α : Type u} {β : α → Type v} [DecidableEq α] :
DecidableRel disjoint :=
fun (x y : finmap β) => id multiset.decidable_dforall_multiset
theorem disjoint_union_left {α : Type u} {β : α → Type v} [DecidableEq α] (x : finmap β)
(y : finmap β) (z : finmap β) : disjoint (x ∪ y) z ↔ disjoint x z ∧ disjoint y z :=
sorry
theorem disjoint_union_right {α : Type u} {β : α → Type v} [DecidableEq α] (x : finmap β)
(y : finmap β) (z : finmap β) : disjoint x (y ∪ z) ↔ disjoint x y ∧ disjoint x z :=
sorry
theorem union_comm_of_disjoint {α : Type u} {β : α → Type v} [DecidableEq α] {s₁ : finmap β}
{s₂ : finmap β} : disjoint s₁ s₂ → s₁ ∪ s₂ = s₂ ∪ s₁ :=
sorry
theorem union_cancel {α : Type u} {β : α → Type v} [DecidableEq α] {s₁ : finmap β} {s₂ : finmap β}
{s₃ : finmap β} (h : disjoint s₁ s₃) (h' : disjoint s₂ s₃) : s₁ ∪ s₃ = s₂ ∪ s₃ ↔ s₁ = s₂ :=
sorry
end Mathlib |
c7a70f7d16fe4c348d6baebd9cb700988ee0805f | 8e6cad62ec62c6c348e5faaa3c3f2079012bdd69 | /src/data/polynomial/monomial.lean | 2d7df719a3ca894aac2c8765d8948f0bfb6328a1 | [
"Apache-2.0"
] | permissive | benjamindavidson/mathlib | 8cc81c865aa8e7cf4462245f58d35ae9a56b150d | fad44b9f670670d87c8e25ff9cdf63af87ad731e | refs/heads/master | 1,679,545,578,362 | 1,615,343,014,000 | 1,615,343,014,000 | 312,926,983 | 0 | 0 | Apache-2.0 | 1,615,360,301,000 | 1,605,399,418,000 | Lean | UTF-8 | Lean | false | false | 3,116 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import data.polynomial.basic
/-!
# Univariate monomials
Preparatory lemmas for degree_basic.
-/
noncomputable theory
open finsupp
namespace polynomial
universes u
variables {R : Type u} {a b : R} {m n : ℕ}
variables [semiring R] {p q r : polynomial R}
/--
`C a` is the constant polynomial `a`.
`C` is provided as a ring homomorphism.
-/
def C : R →+* polynomial R := add_monoid_algebra.single_zero_ring_hom
@[simp] lemma monomial_zero_left (a : R) : monomial 0 a = C a := rfl
lemma C_0 : C (0 : R) = 0 := single_zero
lemma C_1 : C (1 : R) = 1 := rfl
lemma C_mul : C (a * b) = C a * C b := C.map_mul a b
lemma C_add : C (a + b) = C a + C b := C.map_add a b
@[simp] lemma C_bit0 : C (bit0 a) = bit0 (C a) := C_add
@[simp] lemma C_bit1 : C (bit1 a) = bit1 (C a) := by simp [bit1, C_bit0]
lemma C_pow : C (a ^ n) = C a ^ n := C.map_pow a n
@[simp]
lemma C_eq_nat_cast (n : ℕ) : C (n : R) = (n : polynomial R) :=
C.map_nat_cast n
@[simp]
lemma sum_C_index {a} {β} [add_comm_monoid β] {f : ℕ → R → β} (h : f 0 0 = 0) :
(C a).sum f = f 0 a :=
sum_single_index h
lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 :=
by { convert coeff_monomial using 2, simp [eq_comm], }
@[simp] lemma coeff_C_zero : coeff (C a) 0 = a := coeff_monomial
lemma coeff_C_ne_zero (h : n ≠ 0) : (C a).coeff n = 0 :=
by rw [coeff_C, if_neg h]
theorem nontrivial.of_polynomial_ne (h : p ≠ q) : nontrivial R :=
⟨⟨0, 1, λ h01 : 0 = 1, h $
by rw [← mul_one p, ← mul_one q, ← C_1, ← h01, C_0, mul_zero, mul_zero] ⟩⟩
lemma single_eq_C_mul_X : ∀{n}, monomial n a = C a * X^n
| 0 := (mul_one _).symm
| (n+1) :=
calc monomial (n + 1) a = monomial n a * X : by { rw [X, monomial_mul_monomial, mul_one], }
... = (C a * X^n) * X : by rw [single_eq_C_mul_X]
... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one]
@[simp] lemma C_inj : C a = C b ↔ a = b :=
⟨λ h, coeff_C_zero.symm.trans (h.symm ▸ coeff_C_zero), congr_arg C⟩
@[simp] lemma C_eq_zero : C a = 0 ↔ a = 0 :=
calc C a = 0 ↔ C a = C 0 : by rw C_0
... ↔ a = 0 : C_inj
instance [nontrivial R] : infinite (polynomial R) :=
infinite.of_injective (λ i, monomial i 1)
begin
intros m n h,
have := (single_eq_single_iff _ _ _ _).mp h,
simpa only [and_true, eq_self_iff_true, or_false, one_ne_zero, and_self],
end
lemma monomial_eq_smul_X {n} : monomial n (a : R) = a • X^n :=
calc monomial n a = monomial n (a * 1) : by simp
... = a • monomial n 1 : (smul_single' _ _ _).symm
... = a • X^n : by rw X_pow_eq_monomial
lemma ring_hom_ext {S} [semiring S] {f g : polynomial R →+* S}
(h₁ : ∀ a, f (C a) = g (C a)) (h₂ : f X = g X) : f = g :=
by { ext, exacts [h₁ _, h₂] }
@[ext] lemma ring_hom_ext' {S} [semiring S] {f g : polynomial R →+* S}
(h₁ : f.comp C = g.comp C) (h₂ : f X = g X) : f = g :=
ring_hom_ext (ring_hom.congr_fun h₁) h₂
end polynomial
|
77a50f20fd2862a1b31e39b82fc8e7d2c70d63f7 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/escape_id.lean | cd2ac0907207135d7f9e233967b375afedfca8ed | [
"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 | 224 | lean | def «def» := 1
#check «def»
#check def.equations._eqn_1
def «[ ]» := 1
#check «[ ]»
#check «[»
def a.«b.c» := 1
#check a.«b.c»
#check a.b.c
#check «a.b.c»
#check [1].«length»
#check ««»
#check «
»
|
7f071c4309d60823ab1903175434e77b5d879839 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/linear_algebra/affine_space/affine_map.lean | bb3fa4390f21f503a7102745d78f2faa11d07237 | [
"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 | 23,589 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import algebra.add_torsor
import data.set.intervals.unordered_interval
import linear_algebra.affine_space.basic
import linear_algebra.bilinear_map
import linear_algebra.pi
import linear_algebra.prod
import tactic.abel
/-!
# Affine maps
This file defines affine maps.
## Main definitions
* `affine_map` is the type of affine maps between two affine spaces with the same ring `k`. Various
basic examples of affine maps are defined, including `const`, `id`, `line_map` and `homothety`.
## Notations
* `P1 →ᵃ[k] P2` is a notation for `affine_map k P1 P2`;
* `affine_space V P`: a localized notation for `add_torsor V P` defined in
`linear_algebra.affine_space.basic`.
## Implementation notes
`out_param` is used in the definition of `[add_torsor V P]` to make `V` an implicit argument
(deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes
using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an
explicit argument rather than implied by `P` or `V`.
This file only provides purely algebraic definitions and results. Those depending on analysis or
topology are defined elsewhere; see `analysis.normed_space.add_torsor` and
`topology.algebra.affine`.
## References
* https://en.wikipedia.org/wiki/Affine_space
* https://en.wikipedia.org/wiki/Principal_homogeneous_space
-/
open_locale affine
/-- An `affine_map k P1 P2` (notation: `P1 →ᵃ[k] P2`) is a map from `P1` to `P2` that
induces a corresponding linear map from `V1` to `V2`. -/
structure affine_map (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*)
[ring k]
[add_comm_group V1] [module k V1] [affine_space V1 P1]
[add_comm_group V2] [module k V2] [affine_space V2 P2] :=
(to_fun : P1 → P2)
(linear : V1 →ₗ[k] V2)
(map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear v +ᵥ to_fun p)
notation P1 ` →ᵃ[`:25 k:25 `] `:0 P2:0 := affine_map k P1 P2
instance (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*)
[ring k]
[add_comm_group V1] [module k V1] [affine_space V1 P1]
[add_comm_group V2] [module k V2] [affine_space V2 P2]:
has_coe_to_fun (P1 →ᵃ[k] P2) (λ _, P1 → P2) := ⟨affine_map.to_fun⟩
namespace linear_map
variables {k : Type*} {V₁ : Type*} {V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁]
[add_comm_group V₂] [module k V₂] (f : V₁ →ₗ[k] V₂)
/-- Reinterpret a linear map as an affine map. -/
def to_affine_map : V₁ →ᵃ[k] V₂ :=
{ to_fun := f,
linear := f,
map_vadd' := λ p v, f.map_add v p }
@[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl
@[simp] lemma to_affine_map_linear : f.to_affine_map.linear = f := rfl
end linear_map
namespace affine_map
variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*}
{V3 : Type*} {P3 : Type*} {V4 : Type*} {P4 : Type*} [ring k]
[add_comm_group V1] [module k V1] [affine_space V1 P1]
[add_comm_group V2] [module k V2] [affine_space V2 P2]
[add_comm_group V3] [module k V3] [affine_space V3 P3]
[add_comm_group V4] [module k V4] [affine_space V4 P4]
include V1 V2
/-- Constructing an affine map and coercing back to a function
produces the same map. -/
@[simp] lemma coe_mk (f : P1 → P2) (linear add) :
((mk f linear add : P1 →ᵃ[k] P2) : P1 → P2) = f := rfl
/-- `to_fun` is the same as the result of coercing to a function. -/
@[simp] lemma to_fun_eq_coe (f : P1 →ᵃ[k] P2) : f.to_fun = ⇑f := rfl
/-- An affine map on the result of adding a vector to a point produces
the same result as the linear map applied to that vector, added to the
affine map applied to that point. -/
@[simp] lemma map_vadd (f : P1 →ᵃ[k] P2) (p : P1) (v : V1) :
f (v +ᵥ p) = f.linear v +ᵥ f p := f.map_vadd' p v
/-- The linear map on the result of subtracting two points is the
result of subtracting the result of the affine map on those two
points. -/
@[simp] lemma linear_map_vsub (f : P1 →ᵃ[k] P2) (p1 p2 : P1) :
f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 :=
by conv_rhs { rw [←vsub_vadd p1 p2, map_vadd, vadd_vsub] }
/-- Two affine maps are equal if they coerce to the same function. -/
@[ext] lemma ext {f g : P1 →ᵃ[k] P2} (h : ∀ p, f p = g p) : f = g :=
begin
rcases f with ⟨f, f_linear, f_add⟩,
rcases g with ⟨g, g_linear, g_add⟩,
obtain rfl : f = g := funext h,
congr' with v,
cases (add_torsor.nonempty : nonempty P1) with p,
apply vadd_right_cancel (f p),
erw [← f_add, ← g_add]
end
lemma ext_iff {f g : P1 →ᵃ[k] P2} : f = g ↔ ∀ p, f p = g p := ⟨λ h p, h ▸ rfl, ext⟩
lemma coe_fn_injective : @function.injective (P1 →ᵃ[k] P2) (P1 → P2) coe_fn :=
λ f g H, ext $ congr_fun H
protected lemma congr_arg (f : P1 →ᵃ[k] P2) {x y : P1} (h : x = y) : f x = f y :=
congr_arg _ h
protected lemma congr_fun {f g : P1 →ᵃ[k] P2} (h : f = g) (x : P1) : f x = g x :=
h ▸ rfl
variables (k P1)
/-- Constant function as an `affine_map`. -/
def const (p : P2) : P1 →ᵃ[k] P2 :=
{ to_fun := function.const P1 p,
linear := 0,
map_vadd' := λ p v, by simp }
@[simp] lemma coe_const (p : P2) : ⇑(const k P1 p) = function.const P1 p := rfl
@[simp] lemma const_linear (p : P2) : (const k P1 p).linear = 0 := rfl
variables {k P1}
lemma linear_eq_zero_iff_exists_const (f : P1 →ᵃ[k] P2) :
f.linear = 0 ↔ ∃ q, f = const k P1 q :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ use f (classical.arbitrary P1),
ext,
rw [coe_const, function.const_apply, ← @vsub_eq_zero_iff_eq V2, ← f.linear_map_vsub, h,
linear_map.zero_apply], },
{ rcases h with ⟨q, rfl⟩,
exact const_linear k P1 q, },
end
instance nonempty : nonempty (P1 →ᵃ[k] P2) :=
(add_torsor.nonempty : nonempty P2).elim $ λ p, ⟨const k P1 p⟩
/-- Construct an affine map by verifying the relation between the map and its linear part at one
base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and
a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/
def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) :
P1 →ᵃ[k] P2 :=
{ to_fun := f,
linear := f',
map_vadd' := λ p' v, by rw [h, h p', vadd_vsub_assoc, f'.map_add, vadd_vadd] }
@[simp] lemma coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f := rfl
@[simp] lemma mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' := rfl
section has_scalar
variables {R : Type*} [monoid R] [distrib_mul_action R V2] [smul_comm_class k R V2]
/-- The space of affine maps to a module inherits an `R`-action from the action on its codomain. -/
instance : mul_action R (P1 →ᵃ[k] V2) :=
{ smul := λ c f, ⟨c • f, c • f.linear, λ p v, by simp [smul_add]⟩,
one_smul := λ f, ext $ λ p, one_smul _ _,
mul_smul := λ c₁ c₂ f, ext $ λ p, mul_smul _ _ _ }
@[simp, norm_cast] lemma coe_smul (c : R) (f : P1 →ᵃ[k] V2) : ⇑(c • f) = c • f := rfl
@[simp] lemma smul_linear (t : R) (f : P1 →ᵃ[k] V2) : (t • f).linear = t • f.linear := rfl
instance [distrib_mul_action Rᵐᵒᵖ V2] [is_central_scalar R V2] :
is_central_scalar R (P1 →ᵃ[k] V2) :=
{ op_smul_eq_smul := λ r x, ext $ λ _, op_smul_eq_smul _ _ }
end has_scalar
instance : has_zero (P1 →ᵃ[k] V2) := { zero := ⟨0, 0, λ p v, (zero_vadd _ _).symm⟩ }
instance : has_add (P1 →ᵃ[k] V2) :=
{ add := λ f g, ⟨f + g, f.linear + g.linear, λ p v, by simp [add_add_add_comm]⟩ }
instance : has_sub (P1 →ᵃ[k] V2) :=
{ sub := λ f g, ⟨f - g, f.linear - g.linear, λ p v, by simp [sub_add_sub_comm]⟩ }
instance : has_neg (P1 →ᵃ[k] V2) := { neg := λ f, ⟨-f, -f.linear, λ p v, by simp [add_comm]⟩ }
@[simp, norm_cast] lemma coe_zero : ⇑(0 : P1 →ᵃ[k] V2) = 0 := rfl
@[simp, norm_cast] lemma coe_add (f g : P1 →ᵃ[k] V2) : ⇑(f + g) = f + g := rfl
@[simp, norm_cast] lemma coe_neg (f : P1 →ᵃ[k] V2) : ⇑(-f) = -f := rfl
@[simp, norm_cast] lemma coe_sub (f g : P1 →ᵃ[k] V2) : ⇑(f - g) = f - g := rfl
@[simp] lemma zero_linear : (0 : P1 →ᵃ[k] V2).linear = 0 := rfl
@[simp] lemma add_linear (f g : P1 →ᵃ[k] V2) : (f + g).linear = f.linear + g.linear := rfl
@[simp] lemma sub_linear (f g : P1 →ᵃ[k] V2) : (f - g).linear = f.linear - g.linear := rfl
@[simp] lemma neg_linear (f : P1 →ᵃ[k] V2) : (-f).linear = -f.linear := rfl
/-- The set of affine maps to a vector space is an additive commutative group. -/
instance : add_comm_group (P1 →ᵃ[k] V2) :=
coe_fn_injective.add_comm_group _
coe_zero coe_add coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _)
/-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine maps
from `P1` to the vector space `V2` corresponding to `P2`. -/
instance : affine_space (P1 →ᵃ[k] V2) (P1 →ᵃ[k] P2) :=
{ vadd := λ f g, ⟨λ p, f p +ᵥ g p, f.linear + g.linear, λ p v,
by simp [vadd_vadd, add_right_comm]⟩,
zero_vadd := λ f, ext $ λ p, zero_vadd _ (f p),
add_vadd := λ f₁ f₂ f₃, ext $ λ p, add_vadd (f₁ p) (f₂ p) (f₃ p),
vsub := λ f g, ⟨λ p, f p -ᵥ g p, f.linear - g.linear, λ p v,
by simp [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, sub_add_eq_add_sub]⟩,
vsub_vadd' := λ f g, ext $ λ p, vsub_vadd (f p) (g p),
vadd_vsub' := λ f g, ext $ λ p, vadd_vsub (f p) (g p) }
@[simp] lemma vadd_apply (f : P1 →ᵃ[k] V2) (g : P1 →ᵃ[k] P2) (p : P1) :
(f +ᵥ g) p = f p +ᵥ g p :=
rfl
@[simp] lemma vsub_apply (f g : P1 →ᵃ[k] P2) (p : P1) :
(f -ᵥ g : P1 →ᵃ[k] V2) p = f p -ᵥ g p :=
rfl
/-- `prod.fst` as an `affine_map`. -/
def fst : (P1 × P2) →ᵃ[k] P1 :=
{ to_fun := prod.fst,
linear := linear_map.fst k V1 V2,
map_vadd' := λ _ _, rfl }
@[simp] lemma coe_fst : ⇑(fst : (P1 × P2) →ᵃ[k] P1) = prod.fst := rfl
@[simp] lemma fst_linear : (fst : (P1 × P2) →ᵃ[k] P1).linear = linear_map.fst k V1 V2 := rfl
/-- `prod.snd` as an `affine_map`. -/
def snd : (P1 × P2) →ᵃ[k] P2 :=
{ to_fun := prod.snd,
linear := linear_map.snd k V1 V2,
map_vadd' := λ _ _, rfl }
@[simp] lemma coe_snd : ⇑(snd : (P1 × P2) →ᵃ[k] P2) = prod.snd := rfl
@[simp] lemma snd_linear : (snd : (P1 × P2) →ᵃ[k] P2).linear = linear_map.snd k V1 V2 := rfl
variables (k P1)
omit V2
/-- Identity map as an affine map. -/
def id : P1 →ᵃ[k] P1 :=
{ to_fun := id,
linear := linear_map.id,
map_vadd' := λ p v, rfl }
/-- The identity affine map acts as the identity. -/
@[simp] lemma coe_id : ⇑(id k P1) = _root_.id := rfl
@[simp] lemma id_linear : (id k P1).linear = linear_map.id := rfl
variable {P1}
/-- The identity affine map acts as the identity. -/
lemma id_apply (p : P1) : id k P1 p = p := rfl
variables {k P1}
instance : inhabited (P1 →ᵃ[k] P1) := ⟨id k P1⟩
include V2 V3
/-- Composition of affine maps. -/
def comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : P1 →ᵃ[k] P3 :=
{ to_fun := f ∘ g,
linear := f.linear.comp g.linear,
map_vadd' := begin
intros p v,
rw [function.comp_app, g.map_vadd, f.map_vadd],
refl
end }
/-- Composition of affine maps acts as applying the two functions. -/
@[simp] lemma coe_comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) :
⇑(f.comp g) = f ∘ g := rfl
/-- Composition of affine maps acts as applying the two functions. -/
lemma comp_apply (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) (p : P1) :
f.comp g p = f (g p) := rfl
omit V3
@[simp] lemma comp_id (f : P1 →ᵃ[k] P2) : f.comp (id k P1) = f := ext $ λ p, rfl
@[simp] lemma id_comp (f : P1 →ᵃ[k] P2) : (id k P2).comp f = f := ext $ λ p, rfl
include V3 V4
lemma comp_assoc (f₃₄ : P3 →ᵃ[k] P4) (f₂₃ : P2 →ᵃ[k] P3) (f₁₂ : P1 →ᵃ[k] P2) :
(f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) :=
rfl
omit V2 V3 V4
instance : monoid (P1 →ᵃ[k] P1) :=
{ one := id k P1,
mul := comp,
one_mul := id_comp,
mul_one := comp_id,
mul_assoc := comp_assoc }
@[simp] lemma coe_mul (f g : P1 →ᵃ[k] P1) : ⇑(f * g) = f ∘ g := rfl
@[simp] lemma coe_one : ⇑(1 : P1 →ᵃ[k] P1) = _root_.id := rfl
/-- `affine_map.linear` on endomorphisms is a `monoid_hom`. -/
@[simps] def linear_hom : (P1 →ᵃ[k] P1) →* (V1 →ₗ[k] V1) :=
{ to_fun := linear,
map_one' := rfl,
map_mul' := λ _ _, rfl }
include V2
@[simp] lemma injective_iff_linear_injective (f : P1 →ᵃ[k] P2) :
function.injective f.linear ↔ function.injective f :=
begin
obtain ⟨p⟩ := (infer_instance : nonempty P1),
have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p),
{ ext v, simp [f.map_vadd, vadd_vsub_assoc], },
rw [h, equiv.comp_injective, equiv.injective_comp],
end
@[simp] lemma surjective_iff_linear_surjective (f : P1 →ᵃ[k] P2) :
function.surjective f.linear ↔ function.surjective f :=
begin
obtain ⟨p⟩ := (infer_instance : nonempty P1),
have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p),
{ ext v, simp [f.map_vadd, vadd_vsub_assoc], },
rw [h, equiv.comp_surjective, equiv.surjective_comp],
end
lemma image_vsub_image {s t : set P1} (f : P1 →ᵃ[k] P2) :
(f '' s) -ᵥ (f '' t) = f.linear '' (s -ᵥ t) :=
begin
ext v,
simp only [set.mem_vsub, set.mem_image, exists_exists_and_eq_and, exists_and_distrib_left,
← f.linear_map_vsub],
split,
{ rintros ⟨x, hx, y, hy, hv⟩,
exact ⟨x -ᵥ y, ⟨x, hx, y, hy, rfl⟩, hv⟩, },
{ rintros ⟨-, ⟨x, hx, y, hy, rfl⟩, rfl⟩,
exact ⟨x, hx, y, hy, rfl⟩, },
end
omit V2
/-! ### Definition of `affine_map.line_map` and lemmas about it -/
/-- The affine map from `k` to `P1` sending `0` to `p₀` and `1` to `p₁`. -/
def line_map (p₀ p₁ : P1) : k →ᵃ[k] P1 :=
((linear_map.id : k →ₗ[k] k).smul_right (p₁ -ᵥ p₀)).to_affine_map +ᵥ const k k p₀
lemma coe_line_map (p₀ p₁ : P1) : (line_map p₀ p₁ : k → P1) = λ c, c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl
lemma line_map_apply (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c = c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl
lemma line_map_apply_module' (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = c • (p₁ - p₀) + p₀ := rfl
lemma line_map_apply_module (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = (1 - c) • p₀ + c • p₁ :=
by simp [line_map_apply_module', smul_sub, sub_smul]; abel
omit V1
lemma line_map_apply_ring' (a b c : k) : line_map a b c = c * (b - a) + a :=
rfl
lemma line_map_apply_ring (a b c : k) : line_map a b c = (1 - c) * a + c * b :=
line_map_apply_module a b c
include V1
lemma line_map_vadd_apply (p : P1) (v : V1) (c : k) :
line_map p (v +ᵥ p) c = c • v +ᵥ p :=
by rw [line_map_apply, vadd_vsub]
@[simp] lemma line_map_linear (p₀ p₁ : P1) :
(line_map p₀ p₁ : k →ᵃ[k] P1).linear = linear_map.id.smul_right (p₁ -ᵥ p₀) :=
add_zero _
lemma line_map_same_apply (p : P1) (c : k) : line_map p p c = p := by simp [line_map_apply]
@[simp] lemma line_map_same (p : P1) : line_map p p = const k k p :=
ext $ line_map_same_apply p
@[simp] lemma line_map_apply_zero (p₀ p₁ : P1) : line_map p₀ p₁ (0:k) = p₀ :=
by simp [line_map_apply]
@[simp] lemma line_map_apply_one (p₀ p₁ : P1) : line_map p₀ p₁ (1:k) = p₁ :=
by simp [line_map_apply]
include V2
@[simp] lemma apply_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) (c : k) :
f (line_map p₀ p₁ c) = line_map (f p₀) (f p₁) c :=
by simp [line_map_apply]
@[simp] lemma comp_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) :
f.comp (line_map p₀ p₁) = line_map (f p₀) (f p₁) :=
ext $ f.apply_line_map p₀ p₁
@[simp] lemma fst_line_map (p₀ p₁ : P1 × P2) (c : k) :
(line_map p₀ p₁ c).1 = line_map p₀.1 p₁.1 c :=
fst.apply_line_map p₀ p₁ c
@[simp] lemma snd_line_map (p₀ p₁ : P1 × P2) (c : k) :
(line_map p₀ p₁ c).2 = line_map p₀.2 p₁.2 c :=
snd.apply_line_map p₀ p₁ c
omit V2
lemma line_map_symm (p₀ p₁ : P1) :
line_map p₀ p₁ = (line_map p₁ p₀).comp (line_map (1:k) (0:k)) :=
by { rw [comp_line_map], simp }
lemma line_map_apply_one_sub (p₀ p₁ : P1) (c : k) :
line_map p₀ p₁ (1 - c) = line_map p₁ p₀ c :=
by { rw [line_map_symm p₀, comp_apply], congr, simp [line_map_apply] }
@[simp] lemma line_map_vsub_left (p₀ p₁ : P1) (c : k) :
line_map p₀ p₁ c -ᵥ p₀ = c • (p₁ -ᵥ p₀) :=
vadd_vsub _ _
@[simp] lemma left_vsub_line_map (p₀ p₁ : P1) (c : k) :
p₀ -ᵥ line_map p₀ p₁ c = c • (p₀ -ᵥ p₁) :=
by rw [← neg_vsub_eq_vsub_rev, line_map_vsub_left, ← smul_neg, neg_vsub_eq_vsub_rev]
@[simp] lemma line_map_vsub_right (p₀ p₁ : P1) (c : k) :
line_map p₀ p₁ c -ᵥ p₁ = (1 - c) • (p₀ -ᵥ p₁) :=
by rw [← line_map_apply_one_sub, line_map_vsub_left]
@[simp] lemma right_vsub_line_map (p₀ p₁ : P1) (c : k) :
p₁ -ᵥ line_map p₀ p₁ c = (1 - c) • (p₁ -ᵥ p₀) :=
by rw [← line_map_apply_one_sub, left_vsub_line_map]
lemma line_map_vadd_line_map (v₁ v₂ : V1) (p₁ p₂ : P1) (c : k) :
line_map v₁ v₂ c +ᵥ line_map p₁ p₂ c = line_map (v₁ +ᵥ p₁) (v₂ +ᵥ p₂) c :=
((fst : V1 × P1 →ᵃ[k] V1) +ᵥ snd).apply_line_map (v₁, p₁) (v₂, p₂) c
lemma line_map_vsub_line_map (p₁ p₂ p₃ p₄ : P1) (c : k) :
line_map p₁ p₂ c -ᵥ line_map p₃ p₄ c = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₄) c :=
-- Why Lean fails to find this instance without a hint?
by letI : affine_space (V1 × V1) (P1 × P1) := prod.add_torsor; exact
((fst : P1 × P1 →ᵃ[k] P1) -ᵥ (snd : P1 × P1 →ᵃ[k] P1)).apply_line_map (_, _) (_, _) c
/-- Decomposition of an affine map in the special case when the point space and vector space
are the same. -/
lemma decomp (f : V1 →ᵃ[k] V2) : (f : V1 → V2) = f.linear + (λ z, f 0) :=
begin
ext x,
calc
f x = f.linear x +ᵥ f 0 : by simp [← f.map_vadd]
... = (f.linear.to_fun + λ (z : V1), f 0) x : by simp
end
/-- Decomposition of an affine map in the special case when the point space and vector space
are the same. -/
lemma decomp' (f : V1 →ᵃ[k] V2) : (f.linear : V1 → V2) = f - (λ z, f 0) :=
by rw decomp ; simp only [linear_map.map_zero, pi.add_apply, add_sub_cancel, zero_add]
omit V1
lemma image_interval {k : Type*} [linear_ordered_field k] (f : k →ᵃ[k] k)
(a b : k) :
f '' set.interval a b = set.interval (f a) (f b) :=
begin
have : ⇑f = (λ x, x + f 0) ∘ λ x, x * (f 1 - f 0),
{ ext x,
change f x = x • (f 1 -ᵥ f 0) +ᵥ f 0,
rw [← f.linear_map_vsub, ← f.linear.map_smul, ← f.map_vadd],
simp only [vsub_eq_sub, add_zero, mul_one, vadd_eq_add, sub_zero, smul_eq_mul] },
rw [this, set.image_comp],
simp only [set.image_add_const_interval, set.image_mul_const_interval]
end
section
variables {ι : Type*} {V : Π i : ι, Type*} {P : Π i : ι, Type*} [Π i, add_comm_group (V i)]
[Π i, module k (V i)] [Π i, add_torsor (V i) (P i)]
include V
/-- Evaluation at a point as an affine map. -/
def proj (i : ι) : (Π i : ι, P i) →ᵃ[k] P i :=
{ to_fun := λ f, f i,
linear := @linear_map.proj k ι _ V _ _ i,
map_vadd' := λ p v, rfl }
@[simp] lemma proj_apply (i : ι) (f : Π i, P i) : @proj k _ ι V P _ _ _ i f = f i := rfl
@[simp] lemma proj_linear (i : ι) :
(@proj k _ ι V P _ _ _ i).linear = @linear_map.proj k ι _ V _ _ i := rfl
lemma pi_line_map_apply (f g : Π i, P i) (c : k) (i : ι) :
line_map f g c i = line_map (f i) (g i) c :=
(proj i : (Π i, P i) →ᵃ[k] P i).apply_line_map f g c
end
end affine_map
namespace affine_map
variables {R k V1 P1 V2 : Type*}
section ring
variables [ring k] [add_comm_group V1] [affine_space V1 P1] [add_comm_group V2]
variables [module k V1] [module k V2]
include V1
section distrib_mul_action
variables [monoid R] [distrib_mul_action R V2] [smul_comm_class k R V2]
/-- The space of affine maps to a module inherits an `R`-action from the action on its codomain. -/
instance : distrib_mul_action R (P1 →ᵃ[k] V2) :=
{ smul_add := λ c f g, ext $ λ p, smul_add _ _ _,
smul_zero := λ c, ext $ λ p, smul_zero _ }
end distrib_mul_action
section module
variables [semiring R] [module R V2] [smul_comm_class k R V2]
/-- The space of affine maps taking values in an `R`-module is an `R`-module. -/
instance : module R (P1 →ᵃ[k] V2) :=
{ smul := (•),
add_smul := λ c₁ c₂ f, ext $ λ p, add_smul _ _ _,
zero_smul := λ f, ext $ λ p, zero_smul _ _,
.. affine_map.distrib_mul_action }
variables (R)
/-- The space of affine maps between two modules is linearly equivalent to the product of the
domain with the space of linear maps, by taking the value of the affine map at `(0 : V1)` and the
linear part.
See note [bundled maps over different rings]-/
@[simps] def to_const_prod_linear_map : (V1 →ᵃ[k] V2) ≃ₗ[R] V2 × (V1 →ₗ[k] V2) :=
{ to_fun := λ f, ⟨f 0, f.linear⟩,
inv_fun := λ p, p.2.to_affine_map + const k V1 p.1,
left_inv := λ f, by { ext, rw f.decomp, simp, },
right_inv := by { rintros ⟨v, f⟩, ext; simp, },
map_add' := by simp,
map_smul' := by simp, }
end module
end ring
section comm_ring
variables [comm_ring k] [add_comm_group V1] [affine_space V1 P1] [add_comm_group V2]
variables [module k V1] [module k V2]
include V1
/-- `homothety c r` is the homothety (also known as dilation) about `c` with scale factor `r`. -/
def homothety (c : P1) (r : k) : P1 →ᵃ[k] P1 :=
r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c
lemma homothety_def (c : P1) (r : k) :
homothety c r = r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c :=
rfl
lemma homothety_apply (c : P1) (r : k) (p : P1) : homothety c r p = r • (p -ᵥ c : V1) +ᵥ c := rfl
lemma homothety_eq_line_map (c : P1) (r : k) (p : P1) : homothety c r p = line_map c p r := rfl
@[simp] lemma homothety_one (c : P1) : homothety c (1:k) = id k P1 :=
by { ext p, simp [homothety_apply] }
@[simp] lemma homothety_apply_same (c : P1) (r : k) : homothety c r c = c := line_map_same_apply c r
lemma homothety_mul_apply (c : P1) (r₁ r₂ : k) (p : P1) :
homothety c (r₁ * r₂) p = homothety c r₁ (homothety c r₂ p) :=
by simp [homothety_apply, mul_smul]
lemma homothety_mul (c : P1) (r₁ r₂ : k) :
homothety c (r₁ * r₂) = (homothety c r₁).comp (homothety c r₂) :=
ext $ homothety_mul_apply c r₁ r₂
@[simp] lemma homothety_zero (c : P1) : homothety c (0:k) = const k P1 c :=
by { ext p, simp [homothety_apply] }
@[simp] lemma homothety_add (c : P1) (r₁ r₂ : k) :
homothety c (r₁ + r₂) = r₁ • (id k P1 -ᵥ const k P1 c) +ᵥ homothety c r₂ :=
by simp only [homothety_def, add_smul, vadd_vadd]
/-- `homothety` as a multiplicative monoid homomorphism. -/
def homothety_hom (c : P1) : k →* P1 →ᵃ[k] P1 :=
⟨homothety c, homothety_one c, homothety_mul c⟩
@[simp] lemma coe_homothety_hom (c : P1) : ⇑(homothety_hom c : k →* _) = homothety c := rfl
/-- `homothety` as an affine map. -/
def homothety_affine (c : P1) : k →ᵃ[k] (P1 →ᵃ[k] P1) :=
⟨homothety c, (linear_map.lsmul k _).flip (id k P1 -ᵥ const k P1 c),
function.swap (homothety_add c)⟩
@[simp] lemma coe_homothety_affine (c : P1) :
⇑(homothety_affine c : k →ᵃ[k] _) = homothety c :=
rfl
end comm_ring
end affine_map
|
3ff09151bd0f968a9e29a5bf83a820ab478eaaac | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/bench/rbmap.lean | 6699ad97df7abd97222174edffaf5194b981d92c | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 2,902 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Option.Basic
import Init.Data.List.BasicAux
import Init.Data.String
import Init.System.IO
universe u v w w'
inductive color
| Red | Black
inductive Tree
| Leaf {} : Tree
| Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree
variable {σ : Type w}
open color Nat Tree
def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ
| Leaf, b => b
| Node _ l k v r, b => fold f r (f k v (fold f l b))
@[inline]
def balance1 : Nat → Bool → Tree → Tree → Tree
| kv, vv, t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t)
| kv, vv, t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t)
| kv, vv, t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t
| _, _, _, _ => Leaf
@[inline]
def balance2 : Tree → Nat → Bool → Tree → Tree
| t, kv, vv, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂)
| t, kv, vv, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂)
| t, kv, vv, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r)
| _, _, _, _ => Leaf
def isRed : Tree → Bool
| Node Red _ _ _ _ => true
| _ => false
def ins : Tree → Nat → Bool → Tree
| Leaf, kx, vx => Node Red Leaf kx vx Leaf
| Node Red a ky vy b, kx, vx =>
(if kx < ky then Node Red (ins a kx vx) ky vy b
else if kx = ky then Node Red a kx vx b
else Node Red a ky vy (ins b kx vx))
| Node Black a ky vy b, kx, vx =>
if kx < ky then
(if isRed a then balance1 ky vy b (ins a kx vx)
else Node Black (ins a kx vx) ky vy b)
else if kx = ky then Node Black a kx vx b
else if isRed b then balance2 a ky vy (ins b kx vx)
else Node Black a ky vy (ins b kx vx)
def setBlack : Tree → Tree
| Node _ l k v r => Node Black l k v r
| e => e
def insert (t : Tree) (k : Nat) (v : Bool) : Tree :=
if isRed t then setBlack (ins t k v)
else ins t k v
def mkMapAux : Nat → Tree → Tree
| 0, m => m
| n+1, m => mkMapAux n (insert m n (n % 10 = 0))
def mkMap (n : Nat) :=
mkMapAux n Leaf
def main (xs : List String) : IO UInt32 :=
let m := mkMap xs.head!.toNat!;
let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0;
IO.println (toString v) *>
pure 0
|
1e677b17332b56c96a7b53439144c72b7d4575e2 | d796eac6dc113f68ec6fc0579c13e8eae2bdef6c | /Resources/Code/Category+Theory-Github-Topic/monoidal-categories-reboot/src/monoidal_categories_reboot/rigid_monoidal_category.lean | 6a990e14fe11d5a20f51f161e3da2c7f2b06179c | [
"Apache-2.0"
] | permissive | paddlelaw/functional-discipline-content-cats | 5a7e13e8adedd96b94f66b0b3cbf1847bc86d7f6 | d93b7aa849b343c384cec40c73ee84a9300004e8 | refs/heads/master | 1,675,541,859,508 | 1,607,251,766,000 | 1,607,251,766,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,526 | lean | -- Copyright (c) 2018 Michael Jendrusch. All rights reserved.
import .monoidal_category
import .braided_monoidal_category
universes v u
namespace category_theory.monoidal
open monoidal_category
class right_duality {C : Sort u} (A A' : C) [monoidal_category.{v} C] :=
(right_unit : tensor_unit C ⟶ A ⊗ A')
(right_counit : A' ⊗ A ⟶ tensor_unit C)
(triangle_right_1' : ((𝟙 A') ⊗ right_unit) ≫ (associator A' A A').inv ≫ (right_counit ⊗ (𝟙 A'))
= (right_unitor A').hom ≫ (left_unitor A').inv
. obviously)
(triangle_right_2' : (right_unit ⊗ (𝟙 A)) ≫ (associator A A' A).hom ≫ ((𝟙 A) ⊗ right_counit)
= (left_unitor A).hom ≫ (right_unitor A).inv
. obviously)
class left_duality {C : Sort u} (A A' : C) [monoidal_category.{v} C] :=
(left_unit : tensor_unit C ⟶ A' ⊗ A)
(left_counit : A ⊗ A' ⟶ tensor_unit C)
(triangle_left_1' : ((𝟙 A) ⊗ left_unit) ≫ (associator A A' A).inv ≫ (left_counit ⊗ (𝟙 A))
= (right_unitor A).hom ≫ (left_unitor A).inv
. obviously)
(triangle_left_2' : (left_unit ⊗ (𝟙 A')) ≫ (associator A' A A').hom ≫ ((𝟙 A') ⊗ left_counit)
= (left_unitor A').hom ≫ (right_unitor A').inv
. obviously)
class duality {C : Sort u} (A A' : C) [braided_monoidal_category.{v} C]
extends right_duality.{v} A A', left_duality.{v} A A'
def self_duality {C : Sort u} (A : C) [braided_monoidal_category.{v} C] :=
duality A A
-- Hmmm, constructivity/universe issues here:
class right_rigid (C : Type u) [monoidal_category.{v+1} C] :=
(right_rigidity' : Π X : C, Σ X' : C, right_duality X X')
class left_rigid (C : Type u) [monoidal_category.{v+1} C] :=
(left_rigidity' : Π X : C, Σ X' : C, left_duality X X')
class rigid (C : Type u) [monoidal_category.{v+1} C]
extends right_rigid.{v} C, left_rigid.{v} C
class self_dual (C : Sort u) [braided_monoidal_category.{v} C] :=
(self_duality' : Π X : C, self_duality X)
def compact_closed (C : Type u) [symmetric_monoidal_category.{v+1} C] :=
rigid.{v} C
section
open self_dual
open left_duality
instance rigid_of_self_dual
(C : Type u)
[braided_monoidal_category.{v+1} C]
[𝒟 : self_dual.{v+1} C] : rigid.{v} C :=
{ left_rigidity' := λ X : C, sigma.mk X (self_duality' X).to_left_duality,
right_rigidity' := λ X : C, sigma.mk X (self_duality' X).to_right_duality }
end
end category_theory.monoidal
|
c78d5914a9603deb84a4d4db7b5b946e03479b25 | e38e95b38a38a99ecfa1255822e78e4b26f65bb0 | /src/certigrad/kl.lean | bb800cef0c638f33589174ddbf195d81a8f2568c | [
"Apache-2.0"
] | permissive | ColaDrill/certigrad | fefb1be3670adccd3bed2f3faf57507f156fd501 | fe288251f623ac7152e5ce555f1cd9d3a20203c2 | refs/heads/master | 1,593,297,324,250 | 1,499,903,753,000 | 1,499,903,753,000 | 97,075,797 | 1 | 0 | null | 1,499,916,210,000 | 1,499,916,210,000 | null | UTF-8 | Lean | false | false | 26,965 | lean | /-
Copyright (c) 2017 Daniel Selsam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Daniel Selsam
Certified graph transformation that integrates out a specific KL divergence term.
-/
import .util .tensor .compute_grad .graph .tactics .predicates .lemmas .env .expected_value .ops
namespace certigrad
open list
def integrate_mvn_iso_kl (eloss : ID) : list node → list node
| [] := []
| (⟨(z, .(shape)), [(μ, .(shape)), (σ, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(el, []), [(μ', .(shape')), (σ', .(shape')), (z', .(shape'))], operator.det (det.op.mvn_iso_empirical_kl shape')⟩
::nodes) :=
(⟨(el, []), [⟨μ, shape⟩, ⟨σ, shape⟩], operator.det (ops.mvn_iso_kl shape)⟩
::⟨(z, shape), [⟨μ, shape⟩, ⟨σ, shape⟩], operator.rand (rand.op.mvn_iso shape)⟩
::nodes)
| (⟨(z, .(shape)), [(μ, .(shape)), (σ, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩ :: nodes) :=
⟨(z, shape), [(μ, shape), (σ, shape)], operator.rand (rand.op.mvn_iso shape)⟩ :: integrate_mvn_iso_kl nodes
| (n::nodes) := n :: integrate_mvn_iso_kl nodes
def integrate_mvn_iso_kl_pre (eloss : ID) : list node → env → Prop
-- EQ1
| [] _ := true
-- EQ2 (a)
| (⟨(rname, rshape), [], operator.det op⟩::nodes) inputs :=
integrate_mvn_iso_kl_pre nodes (env.insert (rname, rshape) (op^.f (env.get_ks [] inputs)) inputs)
-- EQ2 (b)
| (⟨(rname, rshape), [], operator.rand op⟩::nodes) inputs := false
-- EQ3 (a)
| (⟨(rname, rshape), [(pname, pshape)], operator.det op⟩::nodes) inputs :=
integrate_mvn_iso_kl_pre nodes (env.insert (rname, rshape) (op^.f (env.get_ks [(pname, pshape)] inputs)) inputs)
-- EQ3 (b)
| (⟨(rname, rshape), [(pname, pshape)], operator.rand op⟩::nodes) inputs := false
-- EQ4
| (⟨(rname, rshape), [(pname₁, pshape₁), (pname₂, pshape₂)], operator.det op⟩::nodes) inputs :=
integrate_mvn_iso_kl_pre nodes (env.insert (rname, rshape) (op^.f (env.get_ks [(pname₁, pshape₁), (pname₂, pshape₂)] inputs)) inputs)
-- EQ5
| [⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩] inputs := false
-- EQ6
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), [], op⟩::nodes) inputs := false
-- EQ7
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), [(pname₃, shape₃)], op⟩::nodes) inputs := false
-- EQ8
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), [(pname₃, shape₃), (pname₄, shape₄)], op⟩::nodes) inputs := false
-- EQ9
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), [(pname₃, shape₃), (pname₄, shape₄), (pname₅, shape₅)], operator.det (det.op.mk _ _ _ _ _ _ _)⟩::nodes) inputs := false
-- EQ10
| (⟨(z, .(shape)), [(μ, .(shape)), (σ, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(el, []), [(μ', .(shape')), (σ', .(shape')), (z', .(shape'))], operator.det (det.op.mvn_iso_empirical_kl shape')⟩
::nodes) inputs :=
(μ = μ' ∧ σ = σ' ∧ z = z' ∧ shape = shape' ∧ eloss = el ∧ σ ≠ μ)
∧ ((¬ env.has_key (eloss, []) inputs) ∧ (eloss, []) ∉ (z, shape) :: map node.ref nodes ∧ 0 < env.get (σ, shape) inputs ∧ ∀ (y : T shape), all_parents_in_env (env.insert (z, shape) y inputs) nodes)
-- EQ11
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), [(pname₃, shape₃), (pname₄, shape₄), (pname₅, shape₅)], operator.rand op⟩::nodes) inputs := false
-- EQ12
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), ((pname₃, shape₃)::(pname₄, shape₄)::(pname₅, shape₅)::parent::parents), op⟩::nodes) inputs := false
-- EQ13
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, (shape₂ :: shapes₂)), parents, op⟩::nodes) inputs := false
-- EQ14 (a)
| (⟨(rname₂, shape₂), ((pname₃, shape₃)::(pname₄, shape₄)::parent::parents), operator.det op⟩::nodes) inputs :=
integrate_mvn_iso_kl_pre nodes (env.insert (rname₂, shape₂) (op^.f $ env.get_ks ((pname₃, shape₃)::(pname₄, shape₄)::parent::parents) inputs) inputs)
-- EQ14 (b)
| (⟨(rname₂, shape₂), ((pname₃, shape₃)::(pname₄, shape₄)::parent::parents), operator.rand op⟩::nodes) inputs := false
theorem integrate_mvn_iso_kl_correct (eloss : ID) (costs : list ID) :
∀ (nodes : list node) (inputs : env),
eloss ∉ costs →
integrate_mvn_iso_kl_pre eloss nodes inputs →
uniq_ids nodes inputs →
all_parents_in_env inputs nodes →
pdfs_exist_at nodes inputs →
is_gintegrable (λ m, ⟦sum_costs m (eloss::costs)⟧) inputs (integrate_mvn_iso_kl eloss nodes) dvec.head →
is_gintegrable (λ m, ⟦sum_costs m (eloss::costs)⟧) inputs nodes dvec.head →
E (graph.to_dist (λ env₀, ⟦sum_costs env₀ (eloss::costs)⟧) inputs (integrate_mvn_iso_kl eloss nodes)) dvec.head
=
E (graph.to_dist (λ env₀, ⟦sum_costs env₀ (eloss::costs)⟧) inputs nodes) dvec.head
-- EQ1
| [] _ _ _ _ _ _ _ _ := rfl
-- EQ2 (a)
| (⟨(rname, rshape), [], operator.det op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint :=
begin
dunfold graph.to_dist operator.to_dist integrate_mvn_iso_kl,
dunfold integrate_mvn_iso_kl_pre at H_pre,
simp [E.E_bind, E.E_ret],
assertv H_pre_next : integrate_mvn_iso_kl_pre eloss nodes (env.insert (rname, rshape) (op^.f (env.get_ks nil inputs)) inputs) := H_pre,
assertv H_ps_in_env_next : all_parents_in_env (env.insert (rname, rshape) (op^.f (env.get_ks nil inputs)) inputs) nodes := H_ps_in_env^.right _,
exact (integrate_mvn_iso_kl_correct _ _ H_eloss_not_cost H_pre_next (H_uids^.right _) H_ps_in_env_next H_pdfs_exist_at H_kl_gint H_gint)
end
-- EQ2 (b)
| (⟨(rname, rshape), [], operator.rand op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint := false.rec _ H_pre
-- EQ3 (a)
| (⟨(rname, rshape), [(pname, pshape)], operator.det op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint :=
begin
dunfold graph.to_dist operator.to_dist integrate_mvn_iso_kl,
dunfold integrate_mvn_iso_kl_pre at H_pre,
simp [E.E_bind, E.E_ret],
assertv H_pre_next : integrate_mvn_iso_kl_pre eloss nodes (env.insert (rname, rshape) (op^.f (env.get_ks [(pname, pshape)] inputs)) inputs) := H_pre,
assertv H_ps_in_env_next : all_parents_in_env (env.insert (rname, rshape) (op^.f (env.get_ks [(pname, pshape)] inputs)) inputs) nodes := H_ps_in_env^.right _,
exact (integrate_mvn_iso_kl_correct _ _ H_eloss_not_cost H_pre_next (H_uids^.right _) H_ps_in_env_next H_pdfs_exist_at H_kl_gint H_gint)
end
-- EQ3 (b)
| (⟨(rname, rshape), [(pname, pshape)], operator.rand op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint := false.rec _ H_pre
-- EQ4
| (⟨(rname, rshape), [(pname₁, pshape₁), (pname₂, pshape₂)], operator.det op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint :=
begin
dunfold graph.to_dist operator.to_dist integrate_mvn_iso_kl,
dunfold integrate_mvn_iso_kl_pre at H_pre,
simp [E.E_bind, E.E_ret],
assertv H_pre_next : integrate_mvn_iso_kl_pre eloss nodes (env.insert (rname, rshape) (op^.f (env.get_ks [(pname₁, pshape₁), (pname₂, pshape₂)] inputs)) inputs) := H_pre,
assertv H_ps_in_env_next : all_parents_in_env (env.insert (rname, rshape) (op^.f (env.get_ks [(pname₁, pshape₁), (pname₂, pshape₂)] inputs)) inputs) nodes := H_ps_in_env^.right _,
exact (integrate_mvn_iso_kl_correct _ _ H_eloss_not_cost H_pre_next (H_uids^.right _) H_ps_in_env_next H_pdfs_exist_at H_kl_gint H_gint)
end
-- EQ5
| [⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩] inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint := false.rec _ H_pre
-- EQ6
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), [], op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint := false.rec _ H_pre
-- EQ7
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), [(pname₃, shape₃)], op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint := false.rec _ H_pre
-- EQ8
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), [(pname₃, shape₃), (pname₄, shape₄)], op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint := false.rec _ H_pre
-- EQ9
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), [(pname₃, shape₃), (pname₄, shape₄), (pname₅, shape₅)], operator.det (det.op.mk _ _ _ _ _ _ _)⟩::nodes) inputs
H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint := false.rec _ H_pre
-- EQ10
| (⟨(z, .(shape)), [(μ, .(shape)), (σ, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(el, []), [(μ', .(shape')), (σ', .(shape')), (z', .(shape'))], operator.det (det.op.mvn_iso_empirical_kl shape')⟩
::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint :=
begin
assertv H_ok : μ = μ' ∧ σ = σ' ∧ z = z' ∧ shape = shape' ∧ eloss = el ∧ σ ≠ μ := H_pre^.left,
cases H_ok with H_μ H_ok, subst H_μ,
cases H_ok with H_σ H_ok, subst H_σ,
cases H_ok with H_z H_ok, subst H_z,
cases H_ok with H_shape H_ok, subst H_shape,
cases H_ok with H_eloss_eq_el H_σ_neq_μ, subst H_eloss_eq_el,
dunfold graph.to_dist operator.to_dist dvec.head integrate_mvn_iso_kl,
simp [E.E_bind, E.E_ret],
dunfold dvec.head, dsimp,
assertv H_μ_in : env.has_key (μ, shape) inputs := H_ps_in_env^.left (μ, shape) (mem_cons_self _ _),
assertv H_σ_in : env.has_key (σ, shape) inputs := H_ps_in_env^.left (σ, shape) (mem_cons_of_mem _ (mem_cons_self _ _)),
assertv H_z_nin : ¬ env.has_key (z, shape) inputs := H_uids^.left,
assertv H_eloss_nin : ¬ env.has_key (eloss, []) inputs := H_pre^.right^.left,
assertv H_μ_neq_z : (μ, shape) ≠ (z, shape) := env_in_nin_ne H_μ_in H_z_nin,
assertv H_σ_neq_z : (σ, shape) ≠ (z, shape) := env_in_nin_ne H_σ_in H_z_nin,
assertv H_μ_neq_eloss : (μ, shape) ≠ (eloss, []) := env_in_nin_ne H_μ_in H_eloss_nin,
assertv H_σ_neq_eloss : (σ, shape) ≠ (eloss, []) := env_in_nin_ne H_σ_in H_eloss_nin,
assertv H_eloss_neq_z : (eloss, []) ≠ (z, shape) := ne_of_not_mem_cons H_pre^.right^.right^.left,
assertv H_eloss_nin_nodes : (eloss, []) ∉ map node.ref nodes := not_mem_of_not_mem_cons H_pre^.right^.right^.left,
dunfold env.get_ks,
tactic.dget_dinsert,
dunfold det.op.f ops.mvn_iso_kl ops.mvn_iso_kl.f dvec.head dvec.head2 dvec.head3,
-- TODO(dhs): unbelievable that this won't unfold det.op.f
-- I tried simp as well
-- I copy-pasted to a new file (to avoid the 45 second delay) and all variants worked
dsimp [det.op.f, ops.mvn_iso_kl.f, dvec.head, dvec.head2, dvec.head3],
-- TODO(dhs): I think this is a bug in LEAN. (z, shape) and (eloss, []) are in the type of the last argument.
simp only [λ (x : dvec T [shape]),
@env.insert_insert_flip (z, shape) (eloss, []) x^.head
(T.mvn_iso_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape))
inputs (ne.symm H_eloss_neq_z)],
-- Two steps:
-- 1. Split out eloss, and prove that it equals the lookup val
-- 2. For RHS, use eloss not appearing to remove them both
dunfold det.op.f ops.mvn_iso_kl ops.mvn_iso_kl.f dvec.head dvec.head2 dvec.head3,
dunfold sum_costs map sumr,
-- Step 1
definev k₁ : env → ℝ := λ (m : env), env.get (eloss, @nil ℕ) m,
definev k₂ : env → ℝ := λ (m : env), sumr (map (λ (cost : ID), env.get (cost, @nil ℕ) m) costs),
definev m_lhs_k_add : dvec T [shape] → env := λ (x : dvec T [shape]), env.insert (eloss, @nil ℕ) (T.mvn_iso_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape))
(env.insert (z, shape) (dvec.head x) inputs),
assert H_lhs_kint₁ : ∀ (x : dvec T [shape]), is_gintegrable (λ m, ⟦k₁ m⟧) (m_lhs_k_add x) nodes dvec.head,
{ dsimp [is_gintegrable, integrate_mvn_iso_kl, dvec.head] at H_kl_gint, dsimp, intro x,
cases x with xx x xxx xnil, cases xnil,
simp only [λ a1 a2 a3, @env.insert_insert_flip (eloss, []) (z, shape) a1 a2 a3 H_eloss_neq_z],
simp only [det.op.f, ops.mvn_iso_kl, ops.mvn_iso_kl.f, dvec.head, env.get_ks, sum_costs] at H_kl_gint,
dunfold sumr map at H_kl_gint,
exact (iff.mpr (is_gintegrable_k_add _ _ _ _) (H_kl_gint^.right x))^.left
},
assert H_lhs_kint₂ : ∀ (x : dvec T [shape]), is_gintegrable (λ m, ⟦k₂ m⟧) (m_lhs_k_add x) nodes dvec.head,
{ dsimp [is_gintegrable, integrate_mvn_iso_kl, dvec.head] at H_kl_gint, dsimp, intro x,
cases x with xx x xxx xnil, cases xnil,
simp only [λ a1 a2 a3, @env.insert_insert_flip (eloss, []) (z, shape) a1 a2 a3 H_eloss_neq_z],
simp only [det.op.f, ops.mvn_iso_kl, ops.mvn_iso_kl.f, dvec.head, env.get_ks, sum_costs] at H_kl_gint,
dunfold sumr map at H_kl_gint,
exact (iff.mpr (is_gintegrable_k_add _ _ _ _) (H_kl_gint^.right x))^.right },
simp only [(λ (x : dvec T [shape]), E.E_k_add k₁ k₂ (m_lhs_k_add x) nodes (H_lhs_kint₁ x) (H_lhs_kint₂ x))],
clear H_lhs_kint₁ H_lhs_kint₂,
definev m_rhs_k_add : dvec T [shape] → env := λ x, env.insert (eloss, @nil ℕ)
(T.mvn_iso_empirical_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape) (dvec.head x))
(env.insert (z, shape) (dvec.head x) inputs),
assert H_rhs_kint₁ : ∀ (x : dvec T [shape]), is_gintegrable (λ m, ⟦k₁ m⟧) (m_rhs_k_add x) nodes dvec.head,
{ dsimp [is_gintegrable, integrate_mvn_iso_kl, dvec.head] at H_gint, dsimp, intro x,
cases x with xx x xxx xnil, cases xnil,
simp only [det.op.f, dvec.head, env.get_ks, sum_costs] at H_gint,
tactic.dget_dinsert_at `H_gint,
dunfold sumr map dvec.head dvec.head2 dvec.head3 at H_gint,
exact (iff.mpr (is_gintegrable_k_add _ _ _ _) (H_gint^.right x))^.left },
assert H_rhs_kint₂ : ∀ (x : dvec T [shape]), is_gintegrable (λ m, ⟦k₂ m⟧) (m_rhs_k_add x) nodes dvec.head,
{ dsimp [is_gintegrable, integrate_mvn_iso_kl, dvec.head] at H_gint, dsimp, intro x,
cases x with xx x xxx xnil, cases xnil,
simp only [det.op.f, dvec.head, env.get_ks, sum_costs] at H_gint,
tactic.dget_dinsert_at `H_gint,
dunfold sumr map dvec.head dvec.head2 dvec.head3 at H_gint,
exact (iff.mpr (is_gintegrable_k_add _ _ _ _) (H_gint^.right x))^.right },
simp only [(λ (x : dvec T [shape]), E.E_k_add k₁ k₂ (m_rhs_k_add x) nodes (H_rhs_kint₁ x) (H_rhs_kint₂ x))],
clear H_rhs_kint₁ H_rhs_kint₂,
pose d_base := sprog.prim (rand.op.mvn_iso shape) ⟦env.get (μ, shape) inputs, env.get (σ, shape) inputs⟧,
pose lhs_f₁ := λ x, E (graph.to_dist (λ (m : env), ⟦k₁ m⟧) (m_lhs_k_add x) nodes) dvec.head,
pose lhs_f₂ := λ x, E (graph.to_dist (λ (m : env), ⟦k₂ m⟧) (m_lhs_k_add x) nodes) dvec.head,
assert H_E_kl_add :
∀ x, E (graph.to_dist (λ (m : env),
⟦env.get (eloss, @nil ℕ) m + sumr (map (λ (cost : ID), (env.get (cost, @nil ℕ) m : ℝ)) costs)⟧)
(env.insert (z, shape) x
(env.insert (eloss, @nil ℕ) (T.mvn_iso_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape)) inputs))
nodes)
dvec.head
=
E (graph.to_dist (λ (m : env), ⟦k₁ m⟧)
(env.insert (z, shape) x
(env.insert (eloss, @nil ℕ) (T.mvn_iso_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape)) inputs))
nodes)
dvec.head
+
E (graph.to_dist (λ (m : env), ⟦k₂ m⟧)
(env.insert (z, shape) x
(env.insert (eloss, @nil ℕ) (T.mvn_iso_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape)) inputs))
nodes)
dvec.head,
{ intro x,
exact E.E_k_add k₁ k₂ _ _ (iff.mpr (is_gintegrable_k_add _ _ _ _) (H_kl_gint^.right x))^.left (iff.mpr (is_gintegrable_k_add _ _ _ _) (H_kl_gint^.right x))^.right },
assert H_lhs_eint₁ : E.is_eintegrable d_base lhs_f₁,
{
dsimp [E.is_eintegrable, dvec.head],
dsimp [integrate_mvn_iso_kl, is_gintegrable] at H_kl_gint,
simp only [λ a1 a2 a3, @env.insert_insert_flip (eloss, []) (z, shape) a1 a2 a3 H_eloss_neq_z],
simp only [det.op.f, ops.mvn_iso_kl, p1, p2, ops.mvn_iso_kl.f, dvec.head, env.get_ks, sum_costs] at H_kl_gint,
dunfold det.op.f ops.mvn_iso_kl p1 p2 ops.mvn_iso_kl.f dvec.head env.get_ks sum_costs at H_kl_gint,
tactic.dget_dinsert_at `H_kl_gint,
dunfold det.op.f ops.mvn_iso_kl ops.mvn_iso_kl.f sumr map dvec.head dvec.head2 dvec.head3 at H_kl_gint,
simp only [H_E_kl_add] at H_kl_gint,
exact (iff.mpr (T.is_integrable_add_middle _ _ _) H_kl_gint^.left)^.left
},
assert H_lhs_eint₂ : E.is_eintegrable d_base lhs_f₂,
{
dsimp [E.is_eintegrable, dvec.head],
dsimp [integrate_mvn_iso_kl, is_gintegrable] at H_kl_gint,
simp only [λ a1 a2 a3, @env.insert_insert_flip (eloss, []) (z, shape) a1 a2 a3 H_eloss_neq_z],
simp only [det.op.f, ops.mvn_iso_kl, p1, p2, ops.mvn_iso_kl.f, dvec.head, env.get_ks, sum_costs] at H_kl_gint,
dunfold det.op.f ops.mvn_iso_kl p1 p2 ops.mvn_iso_kl.f dvec.head env.get_ks sum_costs at H_kl_gint,
tactic.dget_dinsert_at `H_kl_gint,
dunfold sumr map dvec.head dvec.head2 dvec.head3 at H_kl_gint,
simp only [H_E_kl_add] at H_kl_gint,
exact (iff.mpr (T.is_integrable_add_middle _ _ _) H_kl_gint^.left)^.right
},
erw E.E_add d_base lhs_f₁ lhs_f₂ H_lhs_eint₁ H_lhs_eint₂,
pose rhs_f₁ := λ x, E (graph.to_dist (λ (m : env), ⟦k₁ m⟧) (m_rhs_k_add x) nodes) dvec.head,
pose rhs_f₂ := λ x, E (graph.to_dist (λ (m : env), ⟦k₂ m⟧) (m_rhs_k_add x) nodes) dvec.head,
dsimp [graph.to_dist, operator.to_dist, is_gintegrable, integrate_mvn_iso_kl, dvec.head] at H_gint,
simp only [E.E_bind, E.E_ret, det.op.f, dvec.head, env.get_ks, sum_costs] at H_gint,
tactic.dget_dinsert_at `H_gint,
assert H_E_add : ∀ x,
E
(graph.to_dist
(λ (m : env), ⟦(env.get (eloss, @nil ℕ) m : ℝ) + sumr (map (λ (cost : ID), (env.get (cost, @nil ℕ) m : ℝ)) costs)⟧)
(env.insert (eloss, @nil ℕ)
(T.mvn_iso_empirical_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape) x)
(env.insert (z, shape) x inputs))
nodes)
dvec.head
=
E
(graph.to_dist
(λ (m : env), ⟦k₁ m⟧)
(env.insert (eloss, @nil ℕ)
(T.mvn_iso_empirical_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape) x)
(env.insert (z, shape) x inputs))
nodes)
dvec.head
+
E
(graph.to_dist
(λ (m : env), ⟦k₂ m⟧)
(env.insert (eloss, @nil ℕ)
(T.mvn_iso_empirical_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape) x)
(env.insert (z, shape) x inputs))
nodes)
dvec.head,
{
intro x,
exact E.E_k_add k₁ k₂ _ _ (iff.mpr (is_gintegrable_k_add _ _ _ _) (H_gint^.right x))^.left (iff.mpr (is_gintegrable_k_add _ _ _ _) (H_gint^.right x))^.right
},
assert H_rhs_eint₁ : E.is_eintegrable d_base rhs_f₁,
{
dsimp [E.is_eintegrable, dvec.head],
dunfold sumr map dvec.head dvec.head2 dvec.head3 at H_gint,
simp only [H_E_add] at H_gint,
exact (iff.mpr (T.is_integrable_add_middle _ _ _) H_gint^.left)^.left
},
assert H_rhs_eint₂ : E.is_eintegrable d_base rhs_f₂,
{
dsimp [E.is_eintegrable, dvec.head],
dunfold sumr map dvec.head dvec.head2 dvec.head3 at H_gint,
simp only [H_E_add] at H_gint,
exact (iff.mpr (T.is_integrable_add_middle _ _ _) H_gint^.left)^.right
},
erw E.E_add d_base rhs_f₁ rhs_f₂ H_rhs_eint₁ H_rhs_eint₂,
clear integrate_mvn_iso_kl_correct,
assert H_term₁_lhs :
∀ (x : dvec T [shape]),
E (graph.to_dist (λ (m : env), ⟦(λ (m : env), env.get (eloss, []) m) m⟧)
(env.insert (eloss, []) (T.mvn_iso_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape))
(env.insert (z, shape) (dvec.head x) inputs))
nodes)
dvec.head
=
T.mvn_iso_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape),
{ intro x, apply (E.E_of_lookup H_eloss_nin_nodes),
dsimp [pdfs_exist_at] at H_pdfs_exist_at,
dsimp [all_parents_in_env] at H_ps_in_env,
exact (pdfs_exist_at_ignore (H_pre^.right^.right^.right^.right _) (env_not_has_key_insert H_eloss_neq_z H_eloss_nin) H_eloss_nin_nodes (H_pdfs_exist_at^.right _))
},
assert H_term₁_rhs :
∀ (x : dvec T [shape]),
E (graph.to_dist (λ (m : env), ⟦(λ (m : env), env.get (eloss, @nil ℕ) m) m⟧)
(env.insert (eloss, @nil ℕ)
(T.mvn_iso_empirical_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape) (dvec.head x))
(env.insert (z, shape) (dvec.head x) inputs))
nodes)
dvec.head
=
T.mvn_iso_empirical_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape) (dvec.head x),
{ intro x, apply (E.E_of_lookup H_eloss_nin_nodes),
dsimp [pdfs_exist_at] at H_pdfs_exist_at,
dsimp [all_parents_in_env] at H_ps_in_env,
exact (pdfs_exist_at_ignore (H_pre^.right^.right^.right^.right _) (env_not_has_key_insert H_eloss_neq_z H_eloss_nin) H_eloss_nin_nodes (H_pdfs_exist_at^.right _))
},
assert H_term₁ :
E (sprog.prim (rand.op.mvn_iso shape) ⟦env.get (μ, shape) inputs, env.get (σ, shape) inputs⟧)
(λ (x : dvec T [shape]),
E
(graph.to_dist (λ (m : env), ⟦(λ (m : env), env.get (eloss, @nil ℕ) m) m⟧)
(env.insert (eloss, @nil ℕ) (T.mvn_iso_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape))
(env.insert (z, shape) (dvec.head x) inputs))
nodes)
dvec.head)
=
E (sprog.prim (rand.op.mvn_iso shape) ⟦env.get (μ, shape) inputs, env.get (σ, shape) inputs⟧)
(λ (x : dvec T [shape]),
E (graph.to_dist (λ (m : env), ⟦(λ (m : env), env.get (eloss, @nil ℕ) m) m⟧)
(env.insert (eloss, @nil ℕ)
(T.mvn_iso_empirical_kl (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape) (dvec.head x))
(env.insert (z, shape) (dvec.head x) inputs))
nodes)
dvec.head),
{
simp [H_term₁_lhs, H_term₁_rhs],
dunfold E T.dintegral dvec.head rand.op.pdf dvec.head2 dvec.head3,
dsimp,
dunfold dvec.head,
erw T.integral_fscale,
erw (@T.mvn_iso_kl_identity shape (env.get (μ, shape) inputs) (env.get (σ, shape) inputs) H_pre^.right^.right^.right^.left),
assertv H_pdf_1 : ∫ (λ (x : T shape), T.mvn_iso_pdf (env.get (μ, shape) inputs : T shape) (env.get (σ, shape) inputs : T shape) x) = 1 :=
T.mvn_iso_pdf_int1 _ _ H_pre^.right^.right^.right^.left,
delta rand.pdf.mvn_iso,
dsimp,
rw H_pdf_1,
rw T.one_smul
},
erw H_term₁, clear H_term₁, apply congr_arg,
apply congr_arg, apply funext, intro x,
assertv H_ps_in_env : all_parents_in_env (env.insert (z, shape) x^.head inputs) nodes := by apply H_pre^.right^.right^.right^.right,
dsimp,
erw (to_dist_congr_insert H_ps_in_env (env_not_has_key_insert H_eloss_neq_z H_eloss_nin) H_eloss_nin_nodes H_eloss_not_cost),
erw (to_dist_congr_insert H_ps_in_env (env_not_has_key_insert H_eloss_neq_z H_eloss_nin) H_eloss_nin_nodes H_eloss_not_cost)
end
-- EQ11
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), [(pname₃, shape₃), (pname₄, shape₄), (pname₅, shape₅)], operator.rand op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint := false.rec _ H_pre
-- EQ12
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, []), ((pname₃, shape₃)::(pname₄, shape₄)::(pname₅, shape₅)::parent::parents), op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint := false.rec _ H_pre
-- EQ13
| (⟨(rname, .(shape)), [(pname₁, .(shape)), (pname₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩
::⟨(rname₂, (shape₂ :: shapes₂)), parents, op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint := false.rec _ H_pre
-- EQ14 (a)
| (⟨(rname₂, shape₂), ((pname₃, shape₃)::(pname₄, shape₄)::parent::parents), operator.det op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint :=
begin
dunfold graph.to_dist operator.to_dist integrate_mvn_iso_kl,
dunfold integrate_mvn_iso_kl_pre at H_pre,
rw [E.E_bind, E.E_bind],
simp [E.E_ret],
definev next_inputs : env := env.insert (rname₂, shape₂) (op^.f (env.get_ks ((pname₃, shape₃)::(pname₄, shape₄)::parent::parents) inputs)) inputs,
definev next_nodes : list node := nodes,
assertv H_pre_next : integrate_mvn_iso_kl_pre eloss next_nodes next_inputs := H_pre,
assertv H_ps_in_env_next : all_parents_in_env next_inputs next_nodes := H_ps_in_env^.right _,
exact (integrate_mvn_iso_kl_correct _ _ H_eloss_not_cost H_pre_next (H_uids^.right _) H_ps_in_env_next H_pdfs_exist_at H_kl_gint H_gint)
end
-- EQ14 (b)
| (⟨(rname₂, shape₂), ((pname₃, shape₃)::(pname₄, shape₄)::parent::parents), operator.rand op⟩::nodes) inputs H_eloss_not_cost H_pre H_uids H_ps_in_env H_pdfs_exist_at H_kl_gint H_gint := false.rec _ H_pre
-- More useful API
def integrate_kl_pre : graph → env → Prop
| g m := integrate_mvn_iso_kl_pre g^.costs^.head g^.nodes m
def integrate_kl : graph → graph
| g := ⟨integrate_mvn_iso_kl g^.costs^.head g^.nodes, g^.costs, g^.targets, g^.inputs⟩
end certigrad
|
92895ca26484a09ed45f851fc16e2c0dd3aad82e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/mixfix.lean | 7ec7410ba9664c7ac58a137e0c12d0d20d0d1db3 | [
"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 | 234 | lean |
infix:65 " +' " => Add.add
infix:70 " *' " => Mul.mul
infixr:30 " OR " => Or
prefix:40 "NOT " => Not
theorem ex (a b c d : Nat) (p : Prop) : (NOT p OR a = b*'c +' c*'a OR a = b *' c) = (¬ p ∨ a = b*c + c*a ∨ a = b * c) :=
rfl
|
1d560e31806693e4e2703c78d4aac78d40a52402 | 33340b3a23ca62ef3c8a7f6a2d4e14c07c6d3354 | /dot_prod.lean | 8d69c6bfaa958a98cd7bc2c3d1d183f02530c14a | [] | no_license | lclem/cooper | 79554e72ced343c64fed24b2d892d24bf9447dfe | 812afc6b158821f2e7dac9c91d3b6123c7a19faf | refs/heads/master | 1,607,554,257,488 | 1,578,694,133,000 | 1,578,694,133,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,445 | lean | import .list .num
namespace int
open list
def dot_prod : list int → list int → int
| [] [] := 0
| [] (_::_) := 0
| (_::_) [] := 0
| (a1::as1) (a2::as2) :=
(a1 * a2) + dot_prod as1 as2
def map_neg_dot_prod :
∀ {as1 as2 : list int}, dot_prod (map_neg as1) as2 = -(dot_prod as1 as2)
| [] [] := begin simp [map_neg, dot_prod] end
| [] (_::_) := begin simp [map_neg, dot_prod] end
| (_::_) [] := begin simp [map_neg, dot_prod] end
| (a1::as1) (a2::as2) :=
begin
simp [map_neg, dot_prod],
rw (@map_neg_dot_prod as1 as2).symm,
simp [map_neg],
end
lemma nil_dot_prod :
∀ {as}, dot_prod [] as = 0
| [] := rfl
| (a::as) := rfl
lemma dot_prod_nil :
∀ {as}, dot_prod as [] = 0
| [] := rfl
| (a::as) := rfl
lemma cons_dot_prod_cons_eq {a1 a2 as1 as2} :
dot_prod (a1::as1) (a2::as2) = (a1 * a2) + dot_prod as1 as2 := rfl
lemma comp_add_dot_prod :
∀ (as1 as2 as3 : list int),
dot_prod (comp_add as1 as2) as3 = (dot_prod as1 as3) + (dot_prod as2 as3)
| [] as2 as3 :=
begin simp [dot_prod, nil_comp_add, nil_dot_prod] end
| as1 [] as3 :=
begin simp [dot_prod, comp_add_nil, nil_dot_prod] end
| as1 as2 [] :=
begin repeat {rewrite dot_prod_nil}, simp end
| (a1::as1) (a2::as2) (a3::as3) :=
begin simp [dot_prod, comp_add, comp_add_dot_prod, add_mul] end
lemma comp_sub_dot_prod :
∀ (as1 as2 as3 : list int),
dot_prod (comp_sub as1 as2) as3 = (dot_prod as1 as3) - (dot_prod as2 as3)
| [] as2 as3 :=
begin simp [dot_prod, nil_comp_sub, map_neg_dot_prod, nil_dot_prod] end
| as1 [] as3 :=
begin simp [dot_prod, comp_sub_nil, nil_dot_prod] end
| as1 as2 [] :=
begin repeat {rewrite dot_prod_nil}, simp end
| (a1::as1) (a2::as2) (a3::as3) :=
begin simp [dot_prod, comp_sub, comp_sub_dot_prod, add_mul] end
lemma map_mul_dot_prod {a : int} :
∀ {as1 as2}, dot_prod (map_mul a as1) as2 = a * (dot_prod as1 as2)
| [] as2 :=
begin simp [map_mul, nil_dot_prod] end
| as1 [] :=
begin
repeat {rewrite dot_prod_nil},
rewrite _root_.mul_zero a,
end
| (a1::as1) (a2::as2) :=
begin
unfold map_mul, simp, repeat {rewrite cons_dot_prod_cons_eq},
have h := @map_mul_dot_prod as1 as2, unfold map_mul at h,
rewrite h, rewrite mul_add, simp, rewrite mul_assoc
end
end int
namespace znum
open list
def dot_prod : list znum → list znum → znum
| [] [] := 0
| [] (_::_) := 0
| (_::_) [] := 0
| (a1::as1) (a2::as2) :=
(a1 * a2) + dot_prod as1 as2
def map_neg_dot_prod :
∀ {as1 as2 : list znum}, dot_prod (map_neg as1) as2 = -(dot_prod as1 as2)
| [] [] := begin simp [map_neg, dot_prod] end
| [] (_::_) := begin simp [map_neg, dot_prod] end
| (_::_) [] := begin simp [map_neg, dot_prod] end
| (a1::as1) (a2::as2) :=
begin
simp [map_neg, dot_prod],
rw (@map_neg_dot_prod as1 as2).symm,
simp [map_neg],
end
@[simp] lemma nil_dot_prod :
∀ {as}, dot_prod [] as = 0
| [] := rfl
| (a::as) := rfl
@[simp] lemma dot_prod_nil :
∀ {as}, dot_prod as [] = 0
| [] := rfl
| (a::as) := rfl
lemma cons_dot_prod_cons_eq {a1 a2 as1 as2} :
dot_prod (a1::as1) (a2::as2) = (a1 * a2) + dot_prod as1 as2 := rfl
lemma comp_add_dot_prod :
∀ (as1 as2 as3 : list znum),
dot_prod (comp_add as1 as2) as3 = (dot_prod as1 as3) + (dot_prod as2 as3)
| [] as2 as3 :=
begin
rewrite nil_comp_add,
rewrite nil_dot_prod, simp
end
| as1 [] as3 :=
begin
rewrite comp_add_nil,
rewrite nil_dot_prod, simp
end
| as1 as2 [] :=
begin repeat {rewrite dot_prod_nil}, simp end
| (a1::as1) (a2::as2) (a3::as3) :=
begin simp [dot_prod, comp_add, comp_add_dot_prod, add_mul] end
lemma comp_sub_dot_prod :
∀ (as1 as2 as3 : list znum),
dot_prod (comp_sub as1 as2) as3 = (dot_prod as1 as3) - (dot_prod as2 as3)
| [] as2 as3 :=
begin simp [dot_prod, nil_comp_sub, map_neg_dot_prod, nil_dot_prod] end
| as1 [] as3 :=
begin simp [dot_prod, comp_sub_nil, nil_dot_prod] end
| as1 as2 [] :=
begin repeat {rewrite dot_prod_nil}, simp end
| (a1::as1) (a2::as2) (a3::as3) :=
begin simp [dot_prod, comp_sub, comp_sub_dot_prod, add_mul] end
lemma map_mul_dot_prod {a : znum} :
∀ {as1 as2}, dot_prod (map_mul a as1) as2 = a * (dot_prod as1 as2)
| [] as2 :=
begin
unfold map_mul, simp,
repeat {rewrite nil_dot_prod}
end
| as1 [] :=
begin
repeat {rewrite dot_prod_nil},
rewrite mul_zero
end
| (a1::as1) (a2::as2) :=
begin
unfold map_mul, simp, repeat {rewrite cons_dot_prod_cons_eq},
have h := @map_mul_dot_prod as1 as2, unfold map_mul at h,
rewrite h, rewrite mul_add, simp, rewrite mul_assoc
end
lemma dot_prod_to_int' :
∀ {zs1 zs2 : list znum},
(dot_prod zs1 zs2).to_int = int.dot_prod (map to_int zs1) (map to_int zs2)
| [] [] := rfl
| [] (a2::as2) := begin simp [nil_dot_prod, map], refl end
| (a1::as1) [] := begin simp [dot_prod_nil, map], refl end
| (a1::as1) (a2::as2) :=
begin
simp [int.cons_dot_prod_cons_eq, znum.cons_dot_prod_cons_eq,
dot_prod_to_int', to_int, int.to_znum],
have h := @dot_prod_to_int' as1 as2, simp [to_int] at h, rw h,
end
lemma dot_prod_to_int :
∀ {zs1 zs2 : list znum},
↑(dot_prod zs1 zs2) = int.dot_prod (map to_int zs1) (map to_int zs2) :=
@dot_prod_to_int'
lemma dot_prod_eq_of_forall_mem_zero :
∀ {zs1 zs2}, (∀ z ∈ zs1, z = (0 : znum)) → dot_prod zs1 zs2 = 0
| [] zs2 _ := nil_dot_prod
| (z1::zs1) zs2 h :=
begin
cases zs2, apply dot_prod_nil,
simp [dot_prod], have hrw := (h z1 (or.inl rfl)),
subst hrw, simp, apply dot_prod_eq_of_forall_mem_zero,
apply forall_mem_of_forall_mem_cons h
end
end znum
namespace num
open list
def dot_prod : list num → list num → num
| [] [] := 0
| [] (_::_) := 0
| (_::_) [] := 0
| (a1::as1) (a2::as2) :=
(a1 * a2) + dot_prod as1 as2
@[simp] lemma nil_dot_prod :
∀ {as}, dot_prod [] as = 0
| [] := rfl
| (a::as) := rfl
@[simp] lemma dot_prod_nil :
∀ {as}, dot_prod as [] = 0
| [] := rfl
| (a::as) := rfl
lemma comp_add_dot_prod :
∀ (as1 as2 as3 : list num),
dot_prod (comp_add as1 as2) as3 = (dot_prod as1 as3) + (dot_prod as2 as3)
| [] as2 as3 :=
begin
rewrite nil_comp_add,
rewrite nil_dot_prod, simp
end
| as1 [] as3 :=
begin
rewrite comp_add_nil,
rewrite nil_dot_prod, simp
end
| as1 as2 [] :=
begin repeat {rewrite dot_prod_nil}, simp end
| (a1::as1) (a2::as2) (a3::as3) :=
begin
simp [dot_prod, comp_add, comp_add_dot_prod as1 as2 as3, add_mul]
end
lemma cons_dot_prod_cons_eq {a1 a2 as1 as2} :
dot_prod (a1::as1) (a2::as2) = (a1 * a2) + dot_prod as1 as2 := rfl
lemma dot_prod_to_znum' :
∀ {ns1 ns2 : list num},
(dot_prod ns1 ns2).to_znum = znum.dot_prod (map to_znum ns1) (map to_znum ns2)
| [] [] := rfl
| [] (a2::as2) := begin simp [nil_dot_prod, map], refl end
| (a1::as1) [] := begin simp [dot_prod_nil, map], refl end
| (a1::as1) (a2::as2) :=
begin
simp [num.cons_dot_prod_cons_eq, znum.cons_dot_prod_cons_eq,
dot_prod_to_znum', num.mul_to_znum'],
end
lemma map_mul_dot_prod {a : num} :
∀ {as1 as2}, dot_prod (map_mul a as1) as2 = a * (dot_prod as1 as2)
| [] as2 := begin simp [map_mul] end
| as1 [] := begin simp [map_mul] end
| (a1::as1) (a2::as2) :=
begin
unfold map_mul, simp, repeat {rewrite cons_dot_prod_cons_eq},
have h := @map_mul_dot_prod as1 as2, unfold map_mul at h,
rewrite h, rewrite mul_add, simp, rewrite mul_assoc
end
end num |
270b63e512601155608b8f665b162467a6e28594 | 4f065978c49388d188224610d9984673079f7d91 | /Sym.lean | 0ef363bfc8f6ce05c992c55b34f81e08e2274e57 | [] | no_license | kckennylau/Lean | b323103f52706304907adcfaee6f5cb8095d4a33 | 907d0a4d2bd8f23785abd6142ad53d308c54fdcb | refs/heads/master | 1,624,623,720,653 | 1,563,901,820,000 | 1,563,901,820,000 | 109,506,702 | 3 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 37,760 | lean | import data.fintype data.equiv.basic group_theory.subgroup
namespace list
@[simp] lemma length_attach {α} (L : list α) :
L.attach.length = L.length :=
length_pmap
@[simp] lemma nth_le_attach {α} (L : list α) (i) (H : i < L.attach.length) :
(L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) :=
calc (L.attach.nth_le i H).1
= (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map'
... = L.nth_le i _ : by congr; apply attach_map_val
@[simp] lemma nth_le_range {n} (i) (H : i < (range n).length) :
nth_le (range n) i H = i :=
option.some.inj $ by rw [← nth_le_nth _, nth_range (by simpa using H)]
attribute [simp] length_of_fn
attribute [simp] nth_le_of_fn
-- Congratulations, I proved that two things which have
-- equally few lemmas are equal.
theorem of_fn_eq_pmap {α n} {f : fin n → α} :
of_fn f = pmap (λ i hi, f ⟨i, hi⟩) (range n) (λ _, mem_range.1) :=
by rw [pmap_eq_map_attach]; from ext_le (by simp)
(λ i hi1 hi2, by simp at hi1; simp [nth_le_of_fn f ⟨i, hi1⟩])
theorem nodup_of_fn {α n} {f : fin n → α} (hf : function.injective f) :
nodup (of_fn f) :=
by rw of_fn_eq_pmap; from nodup_pmap
(λ _ _ _ _ H, fin.veq_of_eq $ hf H) (nodup_range n)
end list
section fin
variables {m n : ℕ}
def fin_zero_elim {C : Sort*} : fin 0 → C :=
λ x, false.elim $ nat.not_lt_zero x.1 x.2
def fin_sum : (fin m ⊕ fin n) ≃ fin (m + n) :=
{ to_fun := λ x, sum.rec_on x
(λ y, ⟨y.1, nat.lt_of_lt_of_le y.2 $ nat.le_add_right m n⟩)
(λ y, ⟨m + y.1, nat.add_lt_add_left y.2 m⟩),
inv_fun := λ x, if H : x.1 < m
then sum.inl ⟨x.1, H⟩
else sum.inr ⟨x.1 - m, nat.lt_of_add_lt_add_left $
show m + (x.1 - m) < m + n,
from (nat.add_sub_of_le $ le_of_not_gt H).symm ▸ x.2⟩,
left_inv := λ x, sum.cases_on x
(λ y, by simp [y.2]; from fin.eq_of_veq rfl)
(λ y, have H : ¬m + y.val < m, by simp [nat.zero_le],
by simp [H, nat.add_sub_cancel_left];
from fin.eq_of_veq rfl),
right_inv := λ x, begin
by_cases H : x.1 < m,
{ dsimp; rw [dif_pos H]; simp,
exact fin.eq_of_veq rfl },
{ dsimp; rw [dif_neg H]; simp,
apply fin.eq_of_veq; simp,
rw [nat.add_sub_of_le (le_of_not_gt H)] }
end }
def fin_prod : (fin m × fin n) ≃ fin (m * n) :=
{ to_fun := λ x, ⟨x.2.1 + n * x.1.1, calc
x.2.1 + n * x.1.1 + 1
= x.1.1 * n + x.2.1 + 1 : by ac_refl
... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _
... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _
... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩,
inv_fun := λ x, have H : n > 0,
from nat.pos_of_ne_zero $ λ H,
nat.not_lt_zero x.1 $ by subst H; from x.2,
(⟨x.1 / n, (nat.div_lt_iff_lt_mul _ _ H).2 x.2⟩,
⟨x.1 % n, nat.mod_lt _ H⟩),
left_inv := λ ⟨x, y⟩, have H : n > 0,
from nat.pos_of_ne_zero $ λ H,
nat.not_lt_zero y.1 $ H ▸ y.2,
prod.ext
(fin.eq_of_veq $ calc
(y.1 + n * x.1) / n
= y.1 / n + x.1 : nat.add_mul_div_left _ _ H
... = 0 + x.1 : by rw nat.div_eq_of_lt y.2
... = x.1 : nat.zero_add x.1)
(fin.eq_of_veq $ calc
(y.1 + n * x.1) % n
= y.1 % n : nat.add_mul_mod_self_left _ _ _
... = y.1 : nat.mod_eq_of_lt y.2),
right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ }
@[simp] lemma fin.raise_val (k : fin n) :
k.raise.val = k.val :=
rfl
def fin.fall : Π i : fin (n+1), i.1 < n → fin n :=
λ i h, ⟨i.1, h⟩
@[simp] lemma fin.fall_val (k : fin (n+1)) (H : k.1 < n) :
(k.fall H).val = k.val :=
rfl
def fin.descend (pivot : fin (n+1)) : Π i : fin (n+1), i ≠ pivot → fin n :=
λ i H, if h : i.1 < pivot.1
then i.fall (lt_of_lt_of_le h $ nat.le_of_lt_succ pivot.2)
else i.pred (λ H1, H $ by subst H1;
replace h := nat.eq_zero_of_le_zero (le_of_not_gt h);
from fin.eq_of_veq h.symm)
def fin.ascend (pivot : fin (n+1)) : Π i : fin n, fin (n+1) :=
λ i, if i.1 < pivot.1 then i.raise else i.succ
theorem fin.ascend_ne (pivot : fin (n+1)) (i : fin n) :
pivot.ascend i ≠ pivot :=
λ H, begin
unfold fin.ascend at H,
split_ifs at H;
rw ← H at h;
simp [lt_irrefl, nat.lt_succ_self] at h;
cc
end
@[simp] lemma fin.ascend_descend (pivot i : fin (n+1))
(H : i ≠ pivot) : pivot.ascend (pivot.descend i H) = i :=
begin
unfold fin.descend fin.ascend,
split_ifs with H1 H2 H3; apply fin.eq_of_veq; simp at *,
{ cases pivot with p hp,
cases i with i hi,
cases i with i, { simp at * },
exfalso, apply H, apply fin.eq_of_veq,
apply le_antisymm, { apply nat.succ_le_of_lt H2 },
simpa using H1 },
{ cases pivot with p hp,
cases i with i hi,
cases i with i,
{ exfalso, apply H, apply fin.eq_of_veq, symmetry,
apply nat.eq_zero_of_le_zero H2 },
refl }
end
@[simp] lemma fin.descend_ascend (pivot : fin (n+1))
(i : fin n) (H : pivot.ascend i ≠ pivot) :
pivot.descend (pivot.ascend i) H = i :=
begin
unfold fin.descend fin.ascend,
apply fin.eq_of_veq,
by_cases h : i.val < pivot.val,
{ simp [h] },
{ unfold ite dite,
cases nat.decidable_lt ((ite (i.val < pivot.val) (fin.raise i) (fin.succ i)).val) (pivot.val) with h1 h1,
{ simp,
cases nat.decidable_lt (i.val) (pivot.val),
{ simp },
{ cc } },
{ simp,
cases nat.decidable_lt (i.val) (pivot.val) with h2 h2,
{ simp [h2] at h1,
simp at *,
exfalso, apply lt_asymm (nat.lt_succ_self i.1),
apply lt_of_lt_of_le h1 h },
{ simp } } }
end
@[simp] lemma fin.succ_pred (i : fin (n+1)) (H : i ≠ 0) :
(i.pred H).succ = i :=
begin
apply fin.eq_of_veq,
cases i with i hi,
cases i,
{ exfalso, apply H, apply fin.eq_of_veq, refl },
refl
end
@[simp] lemma fin.pred_succ (i : fin n) (H : i.succ ≠ 0) :
i.succ.pred H = i :=
by cases i; refl
instance : decidable_linear_order (fin n) :=
{ lt_iff_le_not_le := λ i j, nat.lt_iff_le_not_le,
le_refl := λ ⟨i, hi⟩, nat.le_refl i,
le_trans := λ ⟨i, hi⟩ ⟨j, hj⟩ ⟨k, hk⟩ hij hjk, nat.le_trans hij hjk,
le_antisymm := λ ⟨i, hi⟩ ⟨j, hj⟩ hij hji, fin.eq_of_veq $ nat.le_antisymm hij hji,
le_total := λ ⟨i, hi⟩ ⟨j, hj⟩, or.cases_on (@nat.le_total i j) or.inl or.inr,
decidable_le := fin.decidable_le,
.. fin.has_le, .. fin.has_lt }
instance : preorder (fin n) :=
by apply_instance
end fin
section miscellaneous
theorem nat.pred_eq_of_eq_succ {m n : ℕ}
(H : m = n.succ) : m.pred = n :=
by simp [H]
@[simp] lemma equiv.symm_apply_eq {α β} {e : α ≃ β} {x y} :
e.symm x = y ↔ x = e y :=
⟨λ H, by simp [H.symm], λ H, by simp [H]⟩
theorem finset.lt_wf {α} [decidable_eq α] :
well_founded (@has_lt.lt (finset α) _) :=
have H : subrelation (@has_lt.lt (finset α) _)
(inv_image (<) finset.card),
from λ x y hxy, finset.card_lt_card hxy,
subrelation.wf H $ inv_image.wf _ $ nat.lt_wf
def finset.min' {α} [decidable_linear_order α]
(S : finset α) (H : S ≠ ∅) : α :=
@option.get _ S.min $
let ⟨k, hk⟩ := finset.exists_mem_of_ne_empty H in
let ⟨b, hb⟩ := finset.min_of_mem hk in by simp at hb; simp [hb]
theorem finset.min'_mem {α} [decidable_linear_order α]
(S : finset α) (H : S ≠ ∅) : S.min' H ∈ S :=
finset.mem_of_min $ by simp [finset.min']
theorem finset.min'_le {α} [decidable_linear_order α]
(S : finset α) (H : S ≠ ∅)
(x) (H2 : x ∈ S) : S.min' H ≤ x :=
finset.le_min_of_mem H2 $ option.get_mem _
theorem finset.le_min' {α} [decidable_linear_order α]
(S : finset α) (H : S ≠ ∅)
(x) (H2 : ∀ y ∈ S, x ≤ y) : x ≤ S.min' H :=
H2 _ $ finset.min'_mem _ _
def finset.max' {α} [decidable_linear_order α]
(S : finset α) (H : S ≠ ∅) : α :=
@option.get _ S.max $
let ⟨k, hk⟩ := finset.exists_mem_of_ne_empty H in
let ⟨b, hb⟩ := finset.max_of_mem hk in by simp at hb; simp [hb]
theorem finset.max'_mem {α} [decidable_linear_order α]
(S : finset α) (H : S ≠ ∅) : S.max' H ∈ S :=
finset.mem_of_max $ by simp [finset.max']
theorem finset.le_max' {α} [decidable_linear_order α]
(S : finset α) (H : S ≠ ∅)
(x) (H2 : x ∈ S) : x ≤ S.max' H :=
finset.le_max_of_mem H2 $ option.get_mem _
theorem finset.max'_le {α} [decidable_linear_order α]
(S : finset α) (H : S ≠ ∅)
(x) (H2 : ∀ y ∈ S, y ≤ x) : S.max' H ≤ x :=
H2 _ $ finset.max'_mem _ _
theorem finset.min'_lt_max' {α} [decidable_linear_order α]
(S : finset α) (H : S ≠ ∅) {i j}
(H1 : i ∈ S) (H2 : j ∈ S) (H3 : i ≠ j) :
S.min' H < S.max' H :=
begin
rcases lt_trichotomy i j with H4 | H4 | H4,
{ have H5 := finset.min'_le S H i H1,
have H6 := finset.le_max' S H j H2,
apply lt_of_le_of_lt H5,
apply lt_of_lt_of_le H4 H6 },
{ cc },
{ have H5 := finset.min'_le S H j H2,
have H6 := finset.le_max' S H i H1,
apply lt_of_le_of_lt H5,
apply lt_of_lt_of_le H4 H6 }
end
end miscellaneous
variable (n : ℕ)
def Sym : Type :=
equiv.perm (fin n)
instance : has_coe_to_fun (Sym n) :=
equiv.has_coe_to_fun
@[extensionality] theorem Sym.ext (σ τ : Sym n)
(H : ∀ i, σ i = τ i) : σ = τ :=
equiv.ext _ _ H
theorem Sym.ext_iff (σ τ : Sym n) :
σ = τ ↔ ∀ i, σ i = τ i :=
⟨λ H i, H ▸ rfl, Sym.ext _ _ _⟩
instance : decidable_eq (Sym n) :=
λ σ τ, decidable_of_iff' _ (Sym.ext_iff _ _ _)
instance : group (Sym n) :=
equiv.perm_group
variable {n}
section perm
def Sym.to_list (σ : Sym n) : list (fin n) :=
list.of_fn σ
theorem Sym.to_list_perm (σ : Sym n) :
σ.to_list ~ list.of_fn (1 : Sym n) :=
(list.perm_ext
(list.nodup_of_fn $ σ.bijective.1)
(list.nodup_of_fn $ (1 : Sym n).bijective.1)).2 $ λ f,
by rw [list.of_fn_eq_pmap, list.of_fn_eq_pmap, list.mem_pmap, list.mem_pmap]; from
⟨λ _, ⟨f.1, by simp [f.2], fin.eq_of_veq rfl⟩,
λ _, ⟨(σ⁻¹ f).1, by simp [(σ⁻¹ f).2], by convert equiv.apply_inverse_apply σ f;
from congr_arg _ (fin.eq_of_veq rfl)⟩⟩
def list.to_sym (L : list (fin n))
(HL : L ~ list.of_fn (1 : Sym n)) : Sym n :=
{ to_fun := λ f, list.nth_le L f.1 $
by rw [list.perm_length HL, list.length_of_fn]; from f.2,
inv_fun := λ f, ⟨list.index_of f L,
begin
convert list.index_of_lt_length.2 _,
{ rw [list.perm_length HL, list.length_of_fn] },
{ rw [list.mem_of_perm HL, list.mem_iff_nth_le],
refine ⟨f.1, _, _⟩,
{ rw list.length_of_fn,
exact f.2 },
{ apply list.nth_le_of_fn } }
end⟩,
left_inv := λ f, fin.eq_of_veq $ list.nth_le_index_of
((list.perm_nodup HL).2 $ list.nodup_of_fn $ λ _ _, id) _ _,
right_inv := λ f, list.index_of_nth_le $ list.index_of_lt_length.2 $
(list.mem_of_perm HL).2 $ list.mem_iff_nth_le.2 $
⟨f.1, by rw list.length_of_fn; from f.2,
list.nth_le_of_fn _ _⟩ }
@[simp] lemma list.to_sym_apply (L : list (fin n))
(HL : L ~ list.of_fn (1 : Sym n)) (i) :
(L.to_sym HL) i = L.nth_le i.1 (by simp [list.perm_length HL, i.2]) :=
rfl
@[simp] lemma Sym.to_list_to_sym (σ : Sym n) :
σ.to_list.to_sym σ.to_list_perm = σ :=
Sym.ext _ _ _ $ λ i, fin.eq_of_veq $ by simp [Sym.to_list]
end perm
namespace Sym
def equiv_0 : Sym 0 ≃ fin (0:ℕ).fact :=
{ to_fun := λ _, ⟨0, dec_trivial⟩,
inv_fun := λ _, 1,
left_inv := λ _, ext _ _ _ $ λ ⟨n, H⟩, by cases H,
right_inv := λ ⟨n, H⟩, fin.eq_of_veq $
by cases H with H1 H1; [refl, cases H1] }
def descend (σ : Sym (n+1)) : Sym n :=
{ to_fun := λ i, (σ 0).descend (σ i.succ)
(λ H, by cases i; from nat.no_confusion
(fin.veq_of_eq (σ.bijective.1 H))),
inv_fun := λ i, (σ.symm ((σ 0).ascend i)).pred $ λ H,
fin.ascend_ne (σ 0) i $ by simpa using H,
left_inv := λ i, fin.eq_of_veq $ by dsimp; rw [fin.pred_val];
apply nat.pred_eq_of_eq_succ; rw [← fin.succ_val];
apply fin.veq_of_eq; simp,
right_inv := λ i, fin.eq_of_veq $ by simp }
def ascend (σ : Sym n) (k : fin (n+1)) : Sym (n+1) :=
{ to_fun := λ i, if H : i = 0 then k
else k.ascend $ σ $ i.pred H,
inv_fun := λ i, if H : i = k then 0
else (σ.symm $ k.descend i H).succ,
left_inv := λ i, fin.eq_of_veq $ begin
dsimp,
by_cases h1 : i = 0,
{ simp [h1] },
{ rw [dif_neg h1],
rw [dif_neg (fin.ascend_ne k (σ (i.pred h1)))],
simp }
end,
right_inv := λ i, fin.eq_of_veq $ begin
dsimp,
by_cases h1 : i = k,
{ simp [h1] },
{ rw [dif_neg h1, dif_neg], { simp },
intro H,
replace H := fin.veq_of_eq H,
simp at H,
exact nat.no_confusion H }
end }
@[simp] lemma descend_ascend (σ : Sym n) (k : fin (n+1)) :
descend (ascend σ k) = σ :=
begin
ext i,
dsimp [ascend, descend],
have H : i.succ ≠ 0,
{ intro H,
replace H := fin.veq_of_eq H,
simp at H, injections },
simp [H]
end
def equiv_succ (ih : Sym n ≃ fin n.fact) :
Sym (n+1) ≃ (fin (n+1) × fin n.fact) :=
{ to_fun := λ σ, (σ 0, ih $ descend σ),
inv_fun := λ F, ascend (ih.symm F.2) F.1,
left_inv := λ σ, ext _ _ _ $ λ i, begin
dsimp, rw [equiv.inverse_apply_apply ih],
dsimp [descend, ascend],
split_ifs, {subst h},
simp
end,
right_inv := λ F, prod.ext
(fin.eq_of_veq $ by dsimp [ascend]; simp) $
fin.eq_of_veq $ by simp }
protected def equiv : Sym n ≃ fin n.fact :=
nat.rec_on n equiv_0 $ λ n ih,
calc Sym (n+1)
≃ (fin (n+1) × fin n.fact) : equiv_succ ih
... ≃ fin (n+1).fact : fin_prod
instance : fintype (Sym n) :=
fintype.of_equiv _ Sym.equiv.symm
theorem card : fintype.card (Sym n) = nat.fact n :=
(fintype.of_equiv_card Sym.equiv.symm).trans $
fintype.card_fin _
theorem Cayley (α : Type*) [group α] [fintype α] :
∃ f : α → Sym (fintype.card α), function.injective f ∧ is_group_hom f :=
nonempty.rec_on (fintype.card_eq.1 $ fintype.card_fin $ fintype.card α) $ λ φ,
⟨λ x, ⟨λ i, φ.symm (x * φ i), λ i, φ.symm (x⁻¹ * φ i),
λ i, by simp, λ i, by simp⟩,
λ x y H, have H1 : _ := congr_fun (equiv.mk.inj H).1 (φ.symm 1), by simpa using H1,
⟨λ x y, ext _ _ _ $ λ i, by simp [mul_assoc]⟩⟩
@[simp] lemma mul_apply (σ τ : Sym n) (i : fin n) :
(σ * τ) i = σ (τ i) :=
rfl
@[simp] lemma one_apply (i : fin n) :
(1 : Sym n) i = i :=
rfl
@[simp] lemma inv_apply (σ : Sym n) (i : fin n) :
σ⁻¹ i = σ.symm i :=
rfl
def swap (i j : fin n) : Sym n :=
{ to_fun := λ k, if k = i then j
else if k = j then i else k,
inv_fun := λ k, if k = i then j
else if k = j then i else k,
left_inv := λ k, by dsimp; split_ifs; cc,
right_inv := λ k, by dsimp; split_ifs; cc }
@[simp] lemma swap_left (i j : fin n) :
swap i j i = j :=
by dsimp [swap]; cc
@[simp] lemma swap_right (i j : fin n) :
swap i j j = i :=
by dsimp [swap]; split_ifs; cc
@[simp] lemma swap_mul_self (i j : fin n) :
swap i j * swap i j = 1 :=
ext _ _ _ $ λ k, by dsimp [swap]; split_ifs; cc
theorem swap_comm (i j : fin n) :
swap i j = swap j i :=
ext _ _ _ $ λ k, by dsimp [swap]; split_ifs; cc
theorem swap_canonical (i j : fin n)
(H1 H2 : ({i, j} : finset (fin n)) ≠ ∅) :
swap (finset.min' _ H1) (finset.max' _ H2) = swap i j :=
begin
have H3 := finset.min'_mem _ H1,
have H4 : finset.min' _ H1 = j ∨ finset.min' _ H1 = i,
{ simpa using H3 },
have H5 := finset.max'_mem _ H2,
have H6 : finset.max' _ H2 = j ∨ finset.max' _ H2 = i,
{ simpa using H5 },
cases H4; cases H6,
{ rw [H4, H6],
have H7 := finset.min'_le _ H1 i (by simp),
have H8 := finset.le_max' _ H2 i (by simp),
rw H4 at H7, rw H6 at H8,
have H9 := le_antisymm H7 H8,
subst H9 },
{ rw [H4, H6, swap_comm] },
{ rw [H4, H6] },
{ rw [H4, H6],
have H7 := finset.min'_le _ H1 j (by simp),
have H8 := finset.le_max' _ H2 j (by simp),
rw H4 at H7, rw H6 at H8,
have H9 := le_antisymm H7 H8,
subst H9 }
end
@[simp] theorem swap_self (i : fin n) :
swap i i = 1 :=
ext _ _ _ $ λ k, by dsimp [swap]; split_ifs; cc
def support (σ : Sym n) : finset (fin n) :=
finset.filter (λ i, σ i ≠ i) finset.univ
theorem support_def {σ : Sym n} {i : fin n} :
i ∈ σ.support ↔ σ i ≠ i :=
⟨λ H, (finset.mem_filter.1 H).2, λ H, finset.mem_filter.2 ⟨finset.mem_univ _, H⟩⟩
def support_choice (σ : Sym n) (H : σ.support ≠ ∅) :
{ i // i ∈ σ.support } :=
⟨σ.support.min' H, finset.min'_mem _ _⟩
theorem support_swap {i j : fin n} (H : i ≠ j) :
(swap i j).support = {i, j} :=
begin
ext k, split,
{ intro H1,
simp [support_def, swap] at H1,
split_ifs at H1 with h1 h2 h3 h4,
{ subst h1, simp },
{ subst h2, simp },
cc },
{ intro H1,
simp at H1,
cases H1 with H1 H1;
subst H1;
simp [support_def, swap, H.symm, H] }
end
theorem support_swap_mul {σ : Sym n} {i : fin n}
(H : i ∈ σ.support) : (swap (σ i) i * σ).support < σ.support :=
begin
split,
{ intros j h1,
simp [support_def, swap] at *,
split_ifs at h1,
{ intro h2, rw ← h2 at h, subst h, cc },
{ cc },
{ cc } },
intro H1,
specialize H1 H,
simp [support_def, swap] at H1,
apply H1
end
@[simp] lemma support_one : support (1 : Sym n) = ∅ :=
finset.eq_empty_of_forall_not_mem $ λ i H,
support_def.1 H rfl
variable (n)
@[derive decidable_eq]
structure step : Type :=
(fst : fin n)
(snd : fin n)
(lt : fst < snd)
variable {n}
instance step.fintype : fintype (step n) :=
@fintype.of_surjective { i : fin n × fin n // i.1 < i.2 } _ _ _
(λ i, (⟨i.1.1, i.1.2, i.2⟩ : step n)) $ λ s,
⟨⟨(s.1, s.2), s.3⟩, by cases s; refl⟩
instance : has_mem (fin n) (step n) :=
⟨λ i s, i = s.1 ∨ i = s.2⟩
@[extensionality] theorem step.ext (s t : step n)
(H1 : s.1 = t.1) (H2 : s.2 = t.2) : s = t :=
by cases s; cases t; congr; assumption
def step.mk' (i j : fin n) (H : i ≠ j) : step n :=
if h : i < j then ⟨i, j, h⟩ else
⟨j, i, (eq_or_lt_of_not_lt h).resolve_left H⟩
def step.eval (s : step n) : Sym n :=
swap s.1 s.2
@[simp] lemma step.eval_mul_self (s : step n) :
s.eval * s.eval = 1 :=
by simp [step.eval]
@[simp] lemma step.eval_mk' (i j : fin n) (H : i ≠ j) :
(step.mk' i j H).eval = swap i j :=
by unfold step.mk'; split_ifs; simp [step.eval, swap_comm]
theorem choice.aux (σ : Sym n)
(H : ∃ i j, i ≠ j ∧ σ = swap i j) :
σ.support ≠ ∅ :=
let ⟨i, j, h1, h2⟩ := H in by
refine finset.ne_empty_of_mem (_ : j ∈ σ.support);
rw [h2, support_swap h1];
apply finset.mem_insert_self
def choice (σ : Sym n)
(H : ∃ i j, i ≠ j ∧ σ = swap i j) : step n :=
{ fst := σ.support.min' $ choice.aux _ H,
snd := σ.support.max' $ choice.aux _ H,
lt := by rcases H with ⟨i, j, h1, h2⟩; subst h2; dsimp;
refine finset.min'_lt_max' _ _ _ _ h1;
simp [support_swap h1] }
theorem eval_choice (σ : Sym n)
(H : ∃ i j, i ≠ j ∧ σ = swap i j) :
(σ.choice H).eval = σ :=
begin
rcases H with ⟨i, j, h1, h2⟩,
subst h2, unfold step.eval choice, dsimp,
convert swap_canonical i j _ _;
simp [support_swap h1]
end
theorem choice_eval (s : step n)
(H : ∃ i j, i ≠ j ∧ s.eval = swap i j) :
s.eval.choice H = s :=
begin
ext; dsimp [step.eval, choice],
{ apply le_antisymm,
{ apply finset.min'_le,
simp [support_swap (ne_of_lt s.3)] },
{ apply finset.le_min',
intros y h1,
simp [support_swap (ne_of_lt s.3)] at h1,
cases h1; subst h1,
apply le_of_lt s.3 } },
{ apply le_antisymm,
{ apply finset.max'_le,
intros y h1,
simp [support_swap (ne_of_lt s.3)] at h1,
cases h1; subst h1,
apply le_of_lt s.3 },
{ apply finset.le_max',
simp [support_swap (ne_of_lt s.3)] } }
end
def list_step.aux : has_well_founded (Sym n) :=
{ r := inv_image (<) support,
wf := inv_image.wf _ finset.lt_wf }
local attribute [instance] list_step.aux
attribute [elab_as_eliminator] well_founded.fix
attribute [elab_as_eliminator] well_founded.induction
def list_step (σ : Sym n) : list (step n) :=
by refine well_founded.fix list_step.aux.wf _ σ; from
λ σ ih, if H : σ.support = ∅ then []
else let ⟨i, hi⟩ := σ.support_choice H in
step.mk' (σ i) i (support_def.1 hi)
:: ih (swap (σ i) i * σ) (support_swap_mul hi)
@[simp] lemma list_step_prod (σ : Sym n) :
(σ.list_step.map step.eval).prod = σ :=
well_founded.induction list_step.aux.wf σ $ λ σ ih,
begin
dsimp [list_step],
rw [well_founded.fix_eq],
split_ifs,
{ ext, by_contra H,
suffices : i ∈ (∅ : finset (fin n)),
{ simp at this, cc },
rw [← h, support_def],
exact mt eq.symm H },
cases support_choice σ h with i hi,
unfold list_step._match_1,
specialize ih _ (support_swap_mul hi),
dsimp [list_step] at ih,
rw [list.map_cons, list.prod_cons, ih, ← mul_assoc],
rw [step.eval_mk', swap_mul_self, one_mul]
end
theorem mem_step_iff_mem_support (s : step n) (i : fin n) :
i ∈ s ↔ i ∈ s.eval.support :=
begin
unfold step.eval,
simp [support_swap (ne_of_lt s.3)],
rw [or_comm], refl
end
theorem support_eq_of_mul_eq_one {σ τ : Sym n} (H : σ * τ = 1) :
σ.support = τ.support :=
begin
ext i, simp [support_def, not_iff_not],
rw [eq_comm, iff.comm],
convert equiv.symm_apply_eq,
symmetry,
rw [equiv.symm_apply_eq, ← mul_apply, H, one_apply],
end
theorem of_mem_mul_support {σ τ : Sym n} {i}
(H : i ∈ (σ * τ).support) :
i ∈ σ.support ∨ i ∈ τ.support :=
by_contradiction $ λ H2,
by simp [support_def, not_or_distrib] at H H2;
simp [H2] at H; cc
theorem of_not_mem_mul_support {σ τ : Sym n} {i}
(H : i ∉ (σ * τ).support) :
i ∈ σ.support ↔ i ∈ τ.support :=
begin
simp [support_def] at H ⊢,
split,
{ intros H2 H3, rw H3 at H, cc },
{ intros H2 H3, rw ← H3 at H,
replace H := σ.bijective.1 H,
rw H3 at H, cc }
end
theorem not_mem_mul_support {σ τ : Sym n} {i}
(H1 : i ∉ σ.support) (H2 : i ∉ τ.support) :
i ∉ (σ * τ).support :=
begin
simp [support_def] at H1 H2 ⊢,
rw [H2, H1]
end
@[simp] lemma mem_mk' {i j k : fin n} (H : i ≠ j) :
k ∈ step.mk' i j H ↔ k = i ∨ k = j :=
begin
unfold step.mk',
split_ifs,
{ refl },
{ apply or_comm }
end
-- (ab)(cd) = (cd)(ab)
theorem sgn_aux5 (s t : step n)
(H1 : s.1 ≠ t.1) (H2 : s.1 ≠ t.2)
(H3 : s.2 ≠ t.1) (H4 : s.2 ≠ t.2) :
s.eval * t.eval = t.eval * s.eval :=
begin
have := ne_of_lt s.3,
have := ne_of_lt t.3,
dsimp [step.eval, swap], ext k,
dsimp at *,
split_ifs; cc
end
-- (ab)(ac) = (bc)(ab)
theorem sgn_aux4a (s t : step n)
(H1 : s.1 = t.1) (H4 : s.2 ≠ t.2) :
s.eval * t.eval = (step.mk' s.2 t.2 H4).eval * s.eval :=
begin
have := ne_of_lt s.3,
have := ne_of_lt t.3,
unfold step.eval step.mk',
simp [swap], ext k,
dsimp at *,
split_ifs; cc
end
-- (ab)(ca) = (cb)(ab)
theorem sgn_aux4b (s t : step n) (H1 : s.1 = t.2)
(H2 : t.1 < s.2) :
s.eval * t.eval = (⟨t.1, s.2, H2⟩ : step n).eval * s.eval :=
begin
have := ne_of_lt s.3,
have := ne_of_lt t.3,
have := ne_of_lt H2,
dsimp [step.eval, swap], ext k,
dsimp at *,
split_ifs; cc
end
-- (ab)(ac) = (ac)(bc)
theorem sgn_aux4c (s t : step n)
(H1 : s.1 = t.1) (H4 : s.2 ≠ t.2) :
s.eval * t.eval = t.eval * (step.mk' s.2 t.2 H4).eval :=
begin
have := ne_of_lt s.3,
have := ne_of_lt t.3,
unfold step.eval step.mk',
simp [swap], ext k,
dsimp at *,
split_ifs; cc
end
-- (ab)(ca) = (ca)(cb)
theorem sgn_aux4d (s t : step n)
(H1 : s.1 = t.2) (H4 : t.1 < s.2) :
s.eval * t.eval = t.eval * (⟨t.1, s.2, H4⟩ : step n).eval :=
begin
have := ne_of_lt s.3,
have := ne_of_lt t.3,
have := ne_of_lt H4,
simp [step.eval, swap], ext k,
dsimp at *,
split_ifs; cc
end
-- (ab)(bc) = (bc)(ac)
theorem sgn_aux3a (s t : step n) (H1 : s.2 = t.1)
(H2 : s.1 < t.2) :
s.eval * t.eval = t.eval * (⟨s.1, t.2, H2⟩ : step n).eval :=
begin
have := ne_of_lt s.3,
have := ne_of_lt t.3,
have := ne_of_lt H2,
dsimp [step.eval, swap], ext k,
dsimp at *,
split_ifs; cc
end
-- (ab)(cb) = (cb)(ac)
theorem sgn_aux3b (s t : step n) (H1 : s.2 = t.2)
(H2 : s.1 ≠ t.1) :
s.eval * t.eval = t.eval * (step.mk' s.1 t.1 H2).eval :=
begin
have := ne_of_lt s.3,
have := ne_of_lt t.3,
unfold step.eval step.mk',
simp [swap], ext k,
dsimp at *,
split_ifs; cc
end
-- (ab)(bc) = (ac)(ab)
theorem sgn_aux3c (s t : step n) (H1 : s.2 = t.1)
(H2 : s.1 < t.2) :
s.eval * t.eval = (⟨s.1, t.2, H2⟩ : step n).eval * s.eval :=
begin
have := ne_of_lt s.3,
have := ne_of_lt t.3,
have := ne_of_lt H2,
dsimp [step.eval, swap], ext k,
dsimp at *,
split_ifs; cc
end
-- (ab)(cb) = (ac)(ab)
theorem sgn_aux3d (s t : step n) (H1 : s.2 = t.2)
(H2 : s.1 ≠ t.1) :
s.eval * t.eval = (step.mk' s.1 t.1 H2).eval * s.eval :=
begin
have := ne_of_lt s.3,
have := ne_of_lt t.3,
unfold step.eval step.mk',
simp [swap], ext k,
dsimp at *,
split_ifs; cc
end
theorem sgn_aux2 (s t : step n) (i) (H : i ∈ s) :
s = t ∨ ∃ s' t' : step n, s.eval * t.eval = s'.eval * t'.eval
∧ i ∉ s' ∧ i ∈ t' :=
begin
cases H with H H; subst H,
{ by_cases H2 : s.1 = t.1,
{ by_cases H3 : s.2 = t.2,
{ left, ext; assumption },
right, -- (ab)(ac) = (bc)(ab)
refine ⟨step.mk' s.2 t.2 H3, s, _, _⟩,
{ exact sgn_aux4a _ _ H2 _ },
rw [mem_mk'],
exact ⟨λ H, or.cases_on H
(ne_of_lt s.3) (H2.symm ▸ (ne_of_lt t.3)),
or.inl rfl⟩ },
right,
by_cases H3 : s.1 = t.2,
{ -- (ab)(ca) = (cb)(ab)
have H4 : t.1 < s.2 := lt_trans t.3 (H3 ▸ s.3),
refine ⟨⟨t.1, s.2, H4⟩, s, _, _⟩,
{ exact sgn_aux4b _ _ H3 _ },
exact ⟨λ H, or.cases_on H
H2 (ne_of_lt s.3),
or.inl rfl⟩ },
by_cases H4 : s.2 = t.1,
{ -- (ab)(bc) = (bc)(ac)
have H5 : s.1 < t.2 := lt_trans s.3 (H4.symm ▸ t.3),
refine ⟨t, ⟨s.1, t.2, H5⟩, _, _⟩,
{ exact sgn_aux3a _ _ H4 _ },
exact ⟨λ H, or.cases_on H
H2 (ne_of_lt H5),
or.inl rfl⟩ },
by_cases H5 : s.2 = t.2,
{ -- (ab)(cb) = (cb)(ac)
refine ⟨t, step.mk' s.1 t.1 H2, _, _⟩,
{ exact sgn_aux3b _ _ H5 _ },
exact ⟨λ H, or.cases_on H
H2 H3,
by simp⟩ },
-- (ab)(cd) = (cd)(ab)
refine ⟨t, s, _, _⟩,
{ exact sgn_aux5 _ _ H2 H3 H4 H5 },
exact ⟨λ H, or.cases_on H
H2 H3,
or.inl rfl⟩ },
by_cases H2 : s.1 = t.1,
{ by_cases H3 : s.2 = t.2,
{ left, ext; assumption },
right, -- (ab)(ac) = (ac)(bc)
refine ⟨t, step.mk' s.2 t.2 H3, _, _⟩,
{ exact sgn_aux4c _ _ H2 _ },
rw [mem_mk'],
exact ⟨λ H, or.cases_on H
(H2 ▸ ne_of_gt s.3) H3,
or.inl rfl⟩ },
right,
by_cases H3 : s.1 = t.2,
{ -- (ab)(ca) = (ca)(cb)
have H4 : t.1 < s.2 := lt_trans t.3 (H3 ▸ s.3),
refine ⟨t, ⟨t.1, s.2, H4⟩, _, _⟩,
{ exact sgn_aux4d _ _ H3 _ },
exact ⟨λ H, or.cases_on H
(ne_of_gt H4) (H3 ▸ ne_of_gt s.3),
or.inr rfl⟩ },
by_cases H4 : s.2 = t.1,
{ -- (ab)(bc) = (ac)(ab)
have H5 : s.1 < t.2 := lt_trans s.3 (H4.symm ▸ t.3),
refine ⟨⟨s.1, t.2, H5⟩, s, _, _⟩,
{ exact sgn_aux3c _ _ H4 _ },
exact ⟨λ H, or.cases_on H
(ne_of_gt s.3) (H4.symm ▸ ne_of_lt t.3),
or.inr rfl⟩ },
by_cases H5 : s.2 = t.2,
{ -- (ab)(cb) = (ac)(ab)
refine ⟨step.mk' s.1 t.1 H2, s, _, _⟩,
{ exact sgn_aux3d _ _ H5 _ },
rw [mem_mk'],
exact ⟨λ H, or.cases_on H
(ne_of_gt s.3) (H5.symm ▸ ne_of_gt t.3),
or.inr rfl⟩ },
refine ⟨t, s, _, _⟩,
{ exact sgn_aux5 _ _ H2 H3 H4 H5 },
exact ⟨λ H, or.cases_on H
H4 H5,
or.inr rfl⟩
end
theorem sgn_aux (L1 : list (step n)) (s : step n) (L2 : list (step n)) (i : fin n)
(H1 : (L1.map step.eval).prod * s.eval * (L2.map step.eval).prod = 1)
(H2 : i ∈ s) (H3 : i ∉ (L1.map step.eval).prod.support) :
∃ (L : list (step n)),
(L.map step.eval).prod = 1
∧ L.length + 2 = L1.length + 1 + L2.length :=
begin
induction L2 with hd tl ih generalizing L1 s,
{ simp at H1,
simp [mem_step_iff_mem_support] at H2,
rw support_eq_of_mul_eq_one H1 at H3,
cc },
simp [mul_assoc] at H1,
simp [mem_step_iff_mem_support] at H2,
have H4 := H3,
rw [support_eq_of_mul_eq_one H1] at H4,
replace H4 := of_not_mem_mul_support H4,
replace H4 := H4.1 H2,
rw [← mem_step_iff_mem_support] at H2,
rcases sgn_aux2 s hd i H2 with H5 | ⟨s', t', H5, H6, H7⟩,
{ subst H5,
rw [← mul_assoc s.eval, step.eval_mul_self, one_mul] at H1,
rw [← list.prod_append, ← list.map_append] at H1,
refine ⟨_, H1, _⟩,
simp, unfold bit0, ac_refl },
specialize ih (L1 ++ [s']) t' _ H7 _,
rcases ih with ⟨L, H8, H9⟩,
refine ⟨L, H8, _⟩,
{ simp [H9] },
{ simp at H5 ⊢,
rw [mul_assoc (L1.map step.eval).prod, ← H5],
simpa [mul_assoc] using H1 },
simpa using not_mem_mul_support H3 _,
simpa [mem_step_iff_mem_support] using H6
end
theorem length_even_of_prod_one (L : list (step n))
(H : (L.map step.eval).prod = 1) :
L.length % 2 = 0 :=
begin
generalize H1 : L.length = k,
revert L,
apply nat.strong_induction_on k,
intros k ih L H H1,
cases k with k, { refl },
cases k with k,
{ exfalso,
rw list.length_eq_one at H1,
cases H1 with s H2,
subst H2,
replace H := congr_arg support H,
simp [step.eval, support_swap (ne_of_lt s.3)] at H,
exact H },
cases L with hd tl, { simp at H1, injections },
rcases sgn_aux [] hd tl hd.1 _ (or.inl rfl) _ with ⟨L, H2, H3⟩,
specialize ih k _ L H2 _,
change (k + 2) % 2 = 0,
{ rw [nat.add_mod_right, ih] },
{ constructor, constructor },
{ simp at H1 H3,
rw ← H3 at H1,
exact nat.succ_inj (nat.succ_inj H1) },
{ simpa using H },
simp
end
theorem length_mod_two_eq (L1 L2 : list (step n))
(H : (L1.map step.eval).prod = (L2.map step.eval).prod) :
L1.length % 2 = L2.length % 2 :=
have H1 : (L2.map step.eval).reverse.prod = (L2.map step.eval).prod⁻¹,
from list.rec_on L2 (by simp) $ λ hd tl ih,
by simp [ih, eq_inv_iff_mul_eq_one],
have H2 : _,
from length_even_of_prod_one (L1 ++ L2.reverse) $
by simp [H1, H],
have H3 : 2 ∣ L1.length + L2.length,
by simpa [nat.dvd_iff_mod_eq_zero] using H2,
calc L1.length % 2
= (L1.length + L2.length + L2.length) % 2 :
by rw [add_assoc, ← mul_two, nat.add_mul_mod_self_right]
... = L2.length % 2 :
by cases H3 with k H4; rw [H4, add_comm, nat.add_mul_mod_self_left]
end Sym
@[derive decidable_eq]
inductive mu2 : Type
| plus_one : mu2
| minus_one : mu2
namespace mu2
definition neg : mu2 → mu2
| plus_one := minus_one
| minus_one := plus_one
instance : has_one mu2 := ⟨plus_one⟩
instance : has_neg mu2 := ⟨neg⟩
instance : comm_group mu2 :=
{ mul := λ x y, mu2.rec_on x (mu2.rec_on y 1 (-1)) (mu2.rec_on y (-1) 1),
mul_assoc := λ x y z, by cases x; cases y; cases z; refl,
mul_one := λ x, by cases x; refl,
one_mul := λ x, by cases x; refl,
inv := id,
mul_left_inv := λ x, by cases x; refl,
mul_comm := λ x y, by cases x; cases y; refl,
.. mu2.has_one }
instance : fintype mu2 :=
{ elems := {1, -1},
complete := λ x, mu2.cases_on x (or.inr $ or.inl rfl) (or.inl rfl) }
theorem card : fintype.card mu2 = 2 :=
rfl
theorem neg_one_pow {n} : (-1 : mu2) ^ n = (-1 : mu2) ^ (n%2) :=
have H : (-1 : mu2) ^ 2 = 1, from rfl,
by rw [← nat.mod_add_div n 2, pow_add, pow_mul, H, one_pow, mul_one, nat.mod_add_div n 2]
@[simp] lemma mul_self_eq_one (x : mu2) : x * x = 1 :=
by cases x; refl
@[simp] lemma inv_eq_self (x : mu2) : x⁻¹ = x :=
rfl
@[simp] protected lemma mul_neg_one (x : mu2) : x * -1 = -x :=
by cases x; refl
@[simp] protected lemma neg_one_mul (x : mu2) : -1 * x = -x :=
by cases x; refl
@[simp] lemma neg_mul_self (x : mu2) : -x * x = -1 :=
by cases x; refl
@[simp] lemma mul_neg (x y : mu2) : x * -y = -x * y :=
by cases x; cases y; refl
end mu2
namespace Sym
def sgn (σ : Sym n) : mu2 :=
(-1) ^ σ.list_step.length
instance sgn.is_group_hom : is_group_hom (@sgn n) :=
begin
constructor,
intros σ τ,
unfold sgn,
rw [← pow_add, ← list.length_append],
rw [mu2.neg_one_pow, eq_comm, mu2.neg_one_pow],
refine congr_arg _ _,
apply length_mod_two_eq,
simp
end
@[simp] lemma sgn_step (s : step n) :
sgn s.eval = -1 :=
suffices s.eval.list_step.length % 2 = [s].length % 2,
by unfold sgn; rw [mu2.neg_one_pow, this]; refl,
length_mod_two_eq _ _ $ by simp
@[simp] lemma sgn_mul (σ τ : Sym n) :
sgn (σ * τ) = sgn σ * sgn τ :=
is_group_hom.mul sgn _ _
@[simp] lemma sgn_one :
sgn (1 : Sym n) = 1 :=
is_group_hom.one sgn
@[simp] lemma sgn_inv (σ : Sym n) :
sgn σ⁻¹ = sgn σ :=
is_group_hom.inv sgn _
def eq_sgn_aux4 (s t : step n) : Sym n :=
swap (swap s.1 t.1 s.2) t.2 * swap s.1 t.1
theorem eq_sgn_aux3 (s t : step n) :
eq_sgn_aux4 s t s.1 = t.1 :=
begin
dsimp [eq_sgn_aux4, swap],
have := ne_of_lt s.3,
have := ne_of_lt t.3,
simp, split_ifs; cc
end
theorem eq_sgn_aux2 (s t : step n) :
eq_sgn_aux4 s t s.2 = t.2 :=
begin
dsimp [eq_sgn_aux4, swap],
simp
end
theorem eq_sgn_aux (s t : step n) :
eq_sgn_aux4 s t * s.eval * (eq_sgn_aux4 s t)⁻¹ = t.eval :=
begin
ext k,
by_cases H1 : k = t.1,
{ subst H1,
dsimp [step.eval],
simp [equiv.symm_apply_eq.2 (eq_sgn_aux3 s t).symm, eq_sgn_aux2] },
by_cases H2 : k = t.2,
{ subst H2,
dsimp [step.eval],
simp [equiv.symm_apply_eq.2 (eq_sgn_aux2 s t).symm, eq_sgn_aux3] },
dsimp [step.eval, swap],
simp [H1, H2, eq_sgn_aux2, eq_sgn_aux3]
end
theorem eq_sgn (f : Sym n → mu2) [is_group_hom f]
(s : step n) (H1 : f s.eval = -1) (σ : Sym n) :
f σ = sgn σ :=
begin
have H2 : ∀ t : step n, f t.eval = -1,
{ intro t,
rw [← eq_sgn_aux s t],
simp [is_group_hom.mul f, is_group_hom.inv f, H1] },
have H3 := list_step_prod σ,
revert H3, generalize : list_step σ = L, intro H3, subst H3,
induction L with hd tl ih, { simp [is_group_hom.one f] },
simp [is_group_hom.mul f, ih, H2]
end
section inversions
def step.map (s : step n) (σ : Sym n) : step n :=
step.mk' (σ s.1) (σ s.2) $ λ H, ne_of_lt s.3 $
σ.bijective.1 H
@[simp] lemma step.map_map_inv (s : step n) (σ : Sym n) :
(s.map σ).map σ⁻¹ = s :=
begin
unfold step.map step.mk',
by_cases H1 : σ s.1 < σ s.2,
{ rw [dif_pos H1], dsimp,
rw dif_pos, ext; simp,
simp [s.3] },
rw [dif_neg H1], dsimp,
rw dif_neg, ext; simp,
simp [le_of_lt s.3]
end
@[simp] lemma step.map_inv_map (s : step n) (σ : Sym n) :
(s.map σ⁻¹).map σ = s :=
by simpa using step.map_map_inv s σ⁻¹
def inversion (σ : Sym n) (s : step n) : mu2 :=
if σ s.1 > σ s.2 then -1 else 1
def inversions (σ : Sym n) : mu2 :=
finset.prod finset.univ $ inversion σ
theorem inversion_mul (σ τ : Sym n) (s : step n) :
inversion (σ * τ) s = inversion σ (s.map τ) * inversion τ s :=
begin
unfold inversion step.map step.mk',
split_ifs with h1 h2 h3 h3 h4 h4 h2 h3 h3 h4 h4; try { refl },
{ exfalso, apply lt_asymm h2 h3 },
{ exfalso, apply lt_asymm h1 h3 },
{ simp at *, exfalso,
exact ne_of_lt s.3 (τ.bijective.1 $ le_antisymm h4 h2) },
{ exfalso, apply lt_asymm h2 h3 },
{ simp at *, exfalso,
exact ne_of_lt s.3 (τ.bijective.1 $ le_antisymm h4 h2) },
{ simp at *, exfalso,
exact ne_of_lt s.3 (τ.bijective.1 $ σ.bijective.1 $ le_antisymm h1 h3) }
end
instance : is_group_hom (@inversions n) :=
⟨λ σ τ, calc
inversions (σ * τ)
= finset.prod finset.univ (inversion (σ * τ)) : rfl
... = finset.prod finset.univ (λ s : step n,
inversion σ (s.map τ) * inversion τ s) :
congr_arg _ $ funext $ inversion_mul σ τ
... = finset.prod finset.univ (λ s : step n,
inversion σ (s.map τ)) * inversions τ :
finset.prod_mul_distrib
... = finset.prod finset.univ (inversion σ) * inversions τ :
congr_arg (λ z, z * inversions τ) $ finset.prod_bij
(λ s _, step.map s τ) (λ _ _, finset.mem_univ _) (λ _ _, rfl)
(λ s t _ _ H, by simpa using congr_arg (λ z, step.map z τ⁻¹) H)
(λ s _, ⟨s.map τ⁻¹, finset.mem_univ _, by simp⟩)⟩
variable (n)
def step01 : step (n+2) :=
⟨⟨0, nat.zero_lt_succ _⟩, ⟨1, nat.succ_lt_succ $ nat.zero_lt_succ _⟩, dec_trivial⟩
variable {n}
theorem inversions_step01 : inversions (step01 n).eval = -1 :=
show _ = finset.prod {step01 n} (inversion (step01 n).eval), from
eq.symm $ finset.prod_subset (finset.subset_univ _) $ λ s _ H1, begin
unfold inversion step.eval swap step01; dsimp at *, rw if_neg,
by_cases H2 : s.1.1 = 0,
{ rw [if_pos, if_neg, if_neg],
{ intro H3,
replace H3 := nat.le_of_lt_succ H3,
replace H3 := nat.eq_zero_of_le_zero H3,
exact ne_of_lt s.3 (fin.eq_of_veq $ H2.trans H3.symm) },
{ intro H3, apply H1, simp, ext, exact fin.eq_of_veq H2, exact H3 },
{ exact ne_of_gt (H2 ▸ s.3 : s.2.1 > 0), },
{ exact fin.eq_of_veq H2 } },
by_cases H3 : s.1.1 = 1,
{ rw [if_neg, if_pos], exact nat.not_lt_zero _,
exact fin.eq_of_veq H3, exact mt fin.veq_of_eq H2 },
rw [if_neg, if_neg, if_neg, if_neg],
{ exact lt_asymm s.3 },
{ intro H4, have H5 := s.3, rw H4 at H5,
replace H5 := nat.le_of_lt_succ H5,
replace H5 := nat.eq_zero_of_le_zero H5,
cc },
{ intro H4, have H5 := s.3, rw H4 at H5,
cases H5 },
{ exact mt fin.veq_of_eq H3 },
{ exact mt fin.veq_of_eq H2 }
end
theorem inversions_eq_sgn : ∀ σ : Sym n, inversions σ = sgn σ :=
nat.cases_on n dec_trivial $ λ n,
nat.cases_on n dec_trivial $ λ n σ,
eq_sgn inversions (step01 n) inversions_step01 σ
end inversions
end Sym
variable (n)
def Alt : Type :=
is_group_hom.ker (@Sym.sgn n)
instance : group (Alt n) :=
by unfold Alt; apply_instance
|
3bb35cc5eeaefd962f4101fd6b4bc19262f2daa1 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/adjunction/lifting.lean | d1b70e8462e1a59a07be249eced74e002f0e3dc4 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 11,790 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.limits.shapes.equalizers
import category_theory.limits.shapes.reflexive
import category_theory.monad.adjunction
import category_theory.monad.coequalizer
/-!
# Adjoint lifting
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file gives two constructions for building left adjoints: the adjoint triangle theorem and the
adjoint lifting theorem.
The adjoint triangle theorem says that given a functor `U : B ⥤ C` with a left adjoint `F` such
that `ε_X : FUX ⟶ X` is a regular epi. Then for any category `A` with coequalizers of reflexive
pairs, a functor `R : A ⥤ B` has a left adjoint if (and only if) the composite `R ⋙ U` does.
Note that the condition on `U` regarding `ε_X` is automatically satisfied in the case when `U` is
a monadic functor, giving the corollary: `monadic_adjoint_triangle_lift`, i.e. if `U` is monadic,
`A` has reflexive coequalizers then `R : A ⥤ B` has a left adjoint provided `R ⋙ U` does.
The adjoint lifting theorem says that given a commutative square of functors (up to isomorphism):
Q
A → B
U ↓ ↓ V
C → D
R
where `U` and `V` are monadic and `A` has reflexive coequalizers, then if `R` has a left adjoint
then `Q` has a left adjoint.
## Implementation
It is more convenient to prove this theorem by assuming we are given the explicit adjunction rather
than just a functor known to be a right adjoint. In docstrings, we write `(η, ε)` for the unit
and counit of the adjunction `adj₁ : F ⊣ U` and `(ι, δ)` for the unit and counit of the adjunction
`adj₂ : F' ⊣ R ⋙ U`.
## TODO
Dualise to lift right adjoints through comonads (by reversing 1-cells) and dualise to lift right
adjoints through monads (by reversing 2-cells), and the combination.
## References
* https://ncatlab.org/nlab/show/adjoint+triangle+theorem
* https://ncatlab.org/nlab/show/adjoint+lifting+theorem
* Adjoint Lifting Theorems for Categories of Algebras (PT Johnstone, 1975)
* A unified approach to the lifting of adjoints (AJ Power, 1988)
-/
namespace category_theory
open category limits
universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄
variables {A : Type u₁} {B : Type u₂} {C : Type u₃}
variables [category.{v₁} A] [category.{v₂} B] [category.{v₃} C]
-- Hide implementation details in this namespace
namespace lift_adjoint
variables {U : B ⥤ C} {F : C ⥤ B} (R : A ⥤ B) (F' : C ⥤ A)
variables (adj₁ : F ⊣ U) (adj₂ : F' ⊣ R ⋙ U)
/--
To show that `ε_X` is a coequalizer for `(FUε_X, ε_FUX)`, it suffices to assume it's always a
coequalizer of something (i.e. a regular epi).
-/
def counit_coequalises [∀ (X : B), regular_epi (adj₁.counit.app X)] (X : B) :
is_colimit (cofork.of_π (adj₁.counit.app X) (adj₁.counit_naturality _)) :=
cofork.is_colimit.mk' _ $ λ s,
begin
refine ⟨(regular_epi.desc' (adj₁.counit.app X) s.π _).1, _, _⟩,
{ rw ← cancel_epi (adj₁.counit.app (regular_epi.W (adj₁.counit.app X))),
rw ← adj₁.counit_naturality_assoc,
dsimp only [functor.comp_obj],
rw [← s.condition, ← F.map_comp_assoc, ← U.map_comp, regular_epi.w, U.map_comp,
F.map_comp_assoc, s.condition, ← adj₁.counit_naturality_assoc] },
{ apply (regular_epi.desc' (adj₁.counit.app X) s.π _).2 },
{ intros m hm,
rw ← cancel_epi (adj₁.counit.app X),
apply hm.trans (regular_epi.desc' (adj₁.counit.app X) s.π _).2.symm }
end
include adj₁ adj₂
/--
(Implementation)
To construct the left adjoint, we use the coequalizer of `F' U ε_Y` with the composite
`F' U F U X ⟶ F' U F U R F U' X ⟶ F' U R F' U X ⟶ F' U X`
where the first morphism is `F' U F ι_UX`, the second is `F' U ε_RF'UX`, and the third is `δ_F'UX`.
We will show that this coequalizer exists and that it forms the object map for a left adjoint to
`R`.
-/
def other_map (X) : F'.obj (U.obj (F.obj (U.obj X))) ⟶ F'.obj (U.obj X) :=
F'.map (U.map (F.map (adj₂.unit.app _) ≫ adj₁.counit.app _)) ≫ adj₂.counit.app _
/--
`(F'Uε_X, other_map X)` is a reflexive pair: in particular if `A` has reflexive coequalizers then
it has a coequalizer.
-/
instance (X : B) :
is_reflexive_pair (F'.map (U.map (adj₁.counit.app X))) (other_map _ _ adj₁ adj₂ X) :=
is_reflexive_pair.mk'
(F'.map (adj₁.unit.app (U.obj X)))
(by {rw [← F'.map_comp, adj₁.right_triangle_components], apply F'.map_id })
begin
dsimp [other_map],
rw [← F'.map_comp_assoc, U.map_comp, adj₁.unit_naturality_assoc, adj₁.right_triangle_components,
comp_id, adj₂.left_triangle_components]
end
variables [has_reflexive_coequalizers A]
/--
Construct the object part of the desired left adjoint as the coequalizer of `F'Uε_Y` with
`other_map`.
-/
noncomputable def construct_left_adjoint_obj (Y : B) : A :=
coequalizer (F'.map (U.map (adj₁.counit.app Y))) (other_map _ _ adj₁ adj₂ Y)
/-- The homset equivalence which helps show that `R` is a right adjoint. -/
@[simps {rhs_md := semireducible}]
noncomputable
def construct_left_adjoint_equiv [∀ (X : B), regular_epi (adj₁.counit.app X)] (Y : A) (X : B) :
(construct_left_adjoint_obj _ _ adj₁ adj₂ X ⟶ Y) ≃ (X ⟶ R.obj Y) :=
calc (construct_left_adjoint_obj _ _ adj₁ adj₂ X ⟶ Y)
≃ {f : F'.obj (U.obj X) ⟶ Y //
F'.map (U.map (adj₁.counit.app X)) ≫ f = other_map _ _ adj₁ adj₂ _ ≫ f} :
cofork.is_colimit.hom_iso (colimit.is_colimit _) _
... ≃ {g : U.obj X ⟶ U.obj (R.obj Y) //
U.map (F.map g ≫ adj₁.counit.app _) = U.map (adj₁.counit.app _) ≫ g} :
begin
apply (adj₂.hom_equiv _ _).subtype_equiv _,
intro f,
rw [← (adj₂.hom_equiv _ _).injective.eq_iff, eq_comm, adj₂.hom_equiv_naturality_left,
other_map, assoc, adj₂.hom_equiv_naturality_left, ← adj₂.counit_naturality,
adj₂.hom_equiv_naturality_left, adj₂.hom_equiv_unit,
adj₂.right_triangle_components, comp_id, functor.comp_map, ← U.map_comp, assoc,
← adj₁.counit_naturality, adj₂.hom_equiv_unit, adj₂.hom_equiv_unit, F.map_comp,
assoc],
refl,
end
... ≃ {z : F.obj (U.obj X) ⟶ R.obj Y // _} :
begin
apply (adj₁.hom_equiv _ _).symm.subtype_equiv,
intro g,
rw [← (adj₁.hom_equiv _ _).symm.injective.eq_iff, adj₁.hom_equiv_counit,
adj₁.hom_equiv_counit, adj₁.hom_equiv_counit, F.map_comp, assoc, U.map_comp,
F.map_comp, assoc, adj₁.counit_naturality, adj₁.counit_naturality_assoc],
apply eq_comm,
end
... ≃ (X ⟶ R.obj Y) : (cofork.is_colimit.hom_iso (counit_coequalises adj₁ X) _).symm
/-- Construct the left adjoint to `R`, with object map `construct_left_adjoint_obj`. -/
noncomputable def construct_left_adjoint [∀ (X : B), regular_epi (adj₁.counit.app X)] : B ⥤ A :=
begin
refine adjunction.left_adjoint_of_equiv (λ X Y, construct_left_adjoint_equiv R _ adj₁ adj₂ Y X) _,
intros X Y Y' g h,
rw [construct_left_adjoint_equiv_apply, construct_left_adjoint_equiv_apply, function.comp_app,
function.comp_app, equiv.trans_apply, equiv.trans_apply, equiv.trans_apply, equiv.trans_apply,
equiv.symm_apply_eq, subtype.ext_iff, cofork.is_colimit.hom_iso_natural,
equiv.apply_symm_apply, equiv.subtype_equiv_apply, equiv.subtype_equiv_apply,
equiv.subtype_equiv_apply, equiv.subtype_equiv_apply, subtype.coe_mk, subtype.coe_mk,
subtype.coe_mk, subtype.coe_mk, ← adj₁.hom_equiv_naturality_right_symm,
cofork.is_colimit.hom_iso_natural, adj₂.hom_equiv_naturality_right, functor.comp_map],
end
end lift_adjoint
/--
The adjoint triangle theorem: Suppose `U : B ⥤ C` has a left adjoint `F` such that each counit
`ε_X : FUX ⟶ X` is a regular epimorphism. Then if a category `A` has coequalizers of reflexive
pairs, then a functor `R : A ⥤ B` has a left adjoint if the composite `R ⋙ U` does.
Note the converse is true (with weaker assumptions), by `adjunction.comp`.
See https://ncatlab.org/nlab/show/adjoint+triangle+theorem
-/
noncomputable def adjoint_triangle_lift {U : B ⥤ C} {F : C ⥤ B} (R : A ⥤ B) (adj₁ : F ⊣ U)
[Π (X : B), regular_epi (adj₁.counit.app X)]
[has_reflexive_coequalizers A]
[is_right_adjoint (R ⋙ U)] : is_right_adjoint R :=
{ left := lift_adjoint.construct_left_adjoint R _ adj₁ (adjunction.of_right_adjoint _),
adj := adjunction.adjunction_of_equiv_left _ _ }
/--
If `R ⋙ U` has a left adjoint, the domain of `R` has reflexive coequalizers and `U` is a monadic
functor, then `R` has a left adjoint.
This is a special case of `adjoint_triangle_lift` which is often more useful in practice.
-/
noncomputable def monadic_adjoint_triangle_lift (U : B ⥤ C) [monadic_right_adjoint U] {R : A ⥤ B}
[has_reflexive_coequalizers A]
[is_right_adjoint (R ⋙ U)] :
is_right_adjoint R :=
begin
let R' : A ⥤ _ := R ⋙ monad.comparison (adjunction.of_right_adjoint U),
rsufficesI : is_right_adjoint R',
{ let : is_right_adjoint (R' ⋙ (monad.comparison (adjunction.of_right_adjoint U)).inv),
{ apply_instance },
{ let : R' ⋙ (monad.comparison (adjunction.of_right_adjoint U)).inv ≅ R :=
(iso_whisker_left R (monad.comparison _).as_equivalence.unit_iso.symm : _) ≪≫
R.right_unitor,
exactI adjunction.right_adjoint_of_nat_iso this } },
let : is_right_adjoint (R' ⋙ monad.forget (adjunction.of_right_adjoint U).to_monad) :=
adjunction.right_adjoint_of_nat_iso
(iso_whisker_left R (monad.comparison_forget (adjunction.of_right_adjoint U)).symm : _),
letI : Π X, regular_epi ((monad.adj (adjunction.of_right_adjoint U).to_monad).counit.app X),
{ intro X,
simp only [monad.adj_counit],
exact ⟨_, _, _, _, monad.beck_algebra_coequalizer X⟩ },
exact adjoint_triangle_lift R' (monad.adj _),
end
variables {D : Type u₄}
variables [category.{v₄} D]
/--
Suppose we have a commutative square of functors
Q
A → B
U ↓ ↓ V
C → D
R
where `U` has a left adjoint, `A` has reflexive coequalizers and `V` has a left adjoint such that
each component of the counit is a regular epi.
Then `Q` has a left adjoint if `R` has a left adjoint.
See https://ncatlab.org/nlab/show/adjoint+lifting+theorem
-/
noncomputable def adjoint_square_lift (Q : A ⥤ B) (V : B ⥤ D) (U : A ⥤ C) (R : C ⥤ D)
(comm : U ⋙ R ≅ Q ⋙ V)
[is_right_adjoint U] [is_right_adjoint V] [is_right_adjoint R]
[∀ X, regular_epi ((adjunction.of_right_adjoint V).counit.app X)]
[has_reflexive_coequalizers A] :
is_right_adjoint Q :=
begin
let := adjunction.right_adjoint_of_nat_iso comm,
exactI adjoint_triangle_lift Q (adjunction.of_right_adjoint V),
end
/--
Suppose we have a commutative square of functors
Q
A → B
U ↓ ↓ V
C → D
R
where `U` has a left adjoint, `A` has reflexive coequalizers and `V` is monadic.
Then `Q` has a left adjoint if `R` has a left adjoint.
See https://ncatlab.org/nlab/show/adjoint+lifting+theorem
-/
noncomputable def monadic_adjoint_square_lift (Q : A ⥤ B) (V : B ⥤ D) (U : A ⥤ C) (R : C ⥤ D)
(comm : U ⋙ R ≅ Q ⋙ V)
[is_right_adjoint U] [monadic_right_adjoint V] [is_right_adjoint R]
[has_reflexive_coequalizers A] :
is_right_adjoint Q :=
begin
let := adjunction.right_adjoint_of_nat_iso comm,
exactI monadic_adjoint_triangle_lift V,
end
end category_theory
|
a299f4e0f871708e97fc7c1f9a35b05c8b35283a | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/urysohns_bounded.lean | 1d497be696a06c04ce74854ae581c8c533b3b594 | [
"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 | 2,196 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import topology.urysohns_lemma
import topology.continuous_function.bounded
/-!
# Urysohn's lemma for bounded continuous functions
In this file we reformulate Urysohn's lemma `exists_continuous_zero_one_of_closed` in terms of
bounded continuous functions `X →ᵇ ℝ`. These lemmas live in a separate file because
`topology.continuous_function.bounded` imports too many other files.
## Tags
Urysohn's lemma, normal topological space
-/
open_locale bounded_continuous_function
open set function
/-- Urysohns lemma: if `s` and `t` are two disjoint closed sets in a normal topological space `X`,
then there exists a continuous function `f : X → ℝ` such that
* `f` equals zero on `s`;
* `f` equals one on `t`;
* `0 ≤ f x ≤ 1` for all `x`.
-/
lemma exists_bounded_zero_one_of_closed {X : Type*} [topological_space X] [normal_space X]
{s t : set X} (hs : is_closed s) (ht : is_closed t)
(hd : disjoint s t) :
∃ f : X →ᵇ ℝ, eq_on f 0 s ∧ eq_on f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 :=
let ⟨f, hfs, hft, hf⟩ := exists_continuous_zero_one_of_closed hs ht hd
in ⟨⟨f, 1, λ x y, real.dist_le_of_mem_Icc_01 (hf _) (hf _)⟩, hfs, hft, hf⟩
/-- Urysohns lemma: if `s` and `t` are two disjoint closed sets in a normal topological space `X`,
and `a ≤ b` are two real numbers, then there exists a continuous function `f : X → ℝ` such that
* `f` equals `a` on `s`;
* `f` equals `b` on `t`;
* `a ≤ f x ≤ b` for all `x`.
-/
lemma exists_bounded_mem_Icc_of_closed_of_le {X : Type*} [topological_space X] [normal_space X]
{s t : set X} (hs : is_closed s) (ht : is_closed t) (hd : disjoint s t)
{a b : ℝ} (hle : a ≤ b) :
∃ f : X →ᵇ ℝ, eq_on f (const X a) s ∧ eq_on f (const X b) t ∧ ∀ x, f x ∈ Icc a b :=
let ⟨f, hfs, hft, hf01⟩ := exists_bounded_zero_one_of_closed hs ht hd
in ⟨bounded_continuous_function.const X a + (b - a) • f,
λ x hx, by simp [hfs hx], λ x hx, by simp [hft hx],
λ x, ⟨by dsimp; nlinarith [(hf01 x).1], by dsimp; nlinarith [(hf01 x).2]⟩⟩
|
0fc40979be1107ef260e4925ad04ce98579fd8dd | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/linear_algebra/free_module/rank.lean | d363b6bfd33bb75004ecd93b53bc14f1982629f6 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 4,981 | lean | /-
Copyright (c) 2021 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import linear_algebra.free_module.basic
import linear_algebra.finsupp_vector_space
/-!
# Rank of free modules
This is a basic API for the rank of free modules.
-/
universes u v w
variables (R : Type u) (M : Type v) (N : Type w)
open_locale tensor_product direct_sum big_operators cardinal
open cardinal
namespace module.free
section ring
variables [ring R] [strong_rank_condition R]
variables [add_comm_group M] [module R M] [module.free R M]
variables [add_comm_group N] [module R N] [module.free R N]
/-- The rank of a free module `M` over `R` is the cardinality of `choose_basis_index R M`. -/
lemma rank_eq_card_choose_basis_index : module.rank R M = #(choose_basis_index R M) :=
(choose_basis R M).mk_eq_dim''.symm
/-- The rank of `(ι →₀ R)` is `(# ι).lift`. -/
@[simp] lemma rank_finsupp {ι : Type v} : module.rank R (ι →₀ R) = (# ι).lift :=
by simpa [lift_id', lift_umax] using
(basis.of_repr (linear_equiv.refl _ (ι →₀ R))).mk_eq_dim.symm
/-- If `R` and `ι` lie in the same universe, the rank of `(ι →₀ R)` is `# ι`. -/
lemma rank_finsupp' {ι : Type u} : module.rank R (ι →₀ R) = # ι := by simp
/-- The rank of `M × N` is `(module.rank R M).lift + (module.rank R N).lift`. -/
@[simp] lemma rank_prod :
module.rank R (M × N) = lift.{w v} (module.rank R M) + lift.{v w} (module.rank R N) :=
by simpa [rank_eq_card_choose_basis_index R M, rank_eq_card_choose_basis_index R N,
lift_umax, lift_umax'] using ((choose_basis R M).prod (choose_basis R N)).mk_eq_dim.symm
/-- If `M` and `N` lie in the same universe, the rank of `M × N` is
`(module.rank R M) + (module.rank R N)`. -/
lemma rank_prod' (N : Type v) [add_comm_group N] [module R N] [module.free R N] :
module.rank R (M × N) = (module.rank R M) + (module.rank R N) := by simp
/-- The rank of the direct sum is the sum of the ranks. -/
@[simp] lemma rank_direct_sum {ι : Type v} (M : ι → Type w) [Π (i : ι), add_comm_group (M i)]
[Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] :
module.rank R (⨁ i, M i) = cardinal.sum (λ i, module.rank R (M i)) :=
begin
let B := λ i, choose_basis R (M i),
let b : basis _ R (⨁ i, M i) := dfinsupp.basis (λ i, B i),
simp [← b.mk_eq_dim'', λ i, (B i).mk_eq_dim''],
end
/-- The rank of a finite product is the sum of the ranks. -/
@[simp] lemma rank_pi_fintype {ι : Type v} [fintype ι] {M : ι → Type w}
[Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] :
module.rank R (Π i, M i) = cardinal.sum (λ i, module.rank R (M i)) :=
by { rw [← (direct_sum.linear_equiv_fun_on_fintype _ _ M).dim_eq, rank_direct_sum] }
/-- If `n` and `m` are `fintype`, the rank of `n × m` matrices is `(# n).lift * (# m).lift`. -/
@[simp] lemma rank_matrix (n : Type v) [fintype n] (m : Type w) [fintype m] :
module.rank R (matrix n m R) = (lift.{(max v w u) v} (# n)) * (lift.{(max v w u) w} (# m)) :=
begin
have h := (matrix.std_basis R n m).mk_eq_dim,
rw [← lift_lift.{(max v w u) (max v w)}, lift_inj] at h,
simpa using h.symm,
end
/-- If `n` and `m` are `fintype` that lie in the same universe, the rank of `n × m` matrices is
`(# n * # m).lift`. -/
@[simp] lemma rank_matrix' (n : Type v) [fintype n] (m : Type v) [fintype m] :
module.rank R (matrix n m R) = (# n * # m).lift :=
by rw [rank_matrix, lift_mul, lift_umax]
/-- If `n` and `m` are `fintype` that lie in the same universe as `R`, the rank of `n × m` matrices
is `# n * # m`. -/
@[simp] lemma rank_matrix'' (n : Type u) [fintype n] (m : Type u) [fintype m] :
module.rank R (matrix n m R) = # n * # m := by simp
end ring
section comm_ring
variables [comm_ring R] [strong_rank_condition R]
variables [add_comm_group M] [module R M] [module.free R M]
variables [add_comm_group N] [module R N] [module.free R N]
/-- The rank of `M ⊗[R] N` is `(module.rank R M).lift * (module.rank R N).lift`. -/
@[simp] lemma rank_tensor_product : module.rank R (M ⊗[R] N) = lift.{w v} (module.rank R M) *
lift.{v w} (module.rank R N) :=
begin
let ιM := choose_basis_index R M,
let ιN := choose_basis_index R N,
have h₁ := linear_equiv.lift_dim_eq (tensor_product.congr (repr R M) (repr R N)),
let b : basis (ιM × ιN) R (_ →₀ R) := finsupp.basis_single_one,
rw [linear_equiv.dim_eq (finsupp_tensor_finsupp' R ιM ιN), ← b.mk_eq_dim, mk_prod] at h₁,
rw [lift_inj.1 h₁, rank_eq_card_choose_basis_index R M, rank_eq_card_choose_basis_index R N],
end
/-- If `M` and `N` lie in the same universe, the rank of `M ⊗[R] N` is
`(module.rank R M) * (module.rank R N)`. -/
lemma rank_tensor_product' (N : Type v) [add_comm_group N] [module R N] [module.free R N] :
module.rank R (M ⊗[R] N) = (module.rank R M) * (module.rank R N) := by simp
end comm_ring
end module.free
|
aaa46af23557afd752fc2b1af5e0fdae61c2ea7c | bb31430994044506fa42fd667e2d556327e18dfe | /src/group_theory/group_action/support.lean | bf39f8da16b976aa1a98ca1f162ba8d5fac23939 | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 1,657 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.set.pointwise.smul
/-!
# Support of an element under an action action
Given an action of a group `G` on a type `α`, we say that a set `s : set α` supports an element
`a : α` if, for all `g` that fix `s` pointwise, `g` fixes `a`.
This is crucial in Fourier-Motzkin constructions.
-/
open_locale pointwise
variables {G H α β : Type*}
namespace mul_action
section has_smul
variables (G) [has_smul G α] [has_smul G β]
/-- A set `s` supports `b` if `g • b = b` whenever `g • a = a` for all `a ∈ s`. -/
@[to_additive "A set `s` supports `b` if `g +ᵥ b = b` whenever `g +ᵥ a = a` for all `a ∈ s`."]
def supports (s : set α) (b : β) := ∀ g : G, (∀ ⦃a⦄, a ∈ s → g • a = a) → g • b = b
variables {s t : set α} {a : α} {b : β}
@[to_additive] lemma supports_of_mem (ha : a ∈ s) : supports G s a := λ g h, h ha
variables {G}
@[to_additive] lemma supports.mono (h : s ⊆ t) (hs : supports G s b) : supports G t b :=
λ g hg, hs _ $ λ a ha, hg $ h ha
end has_smul
variables [group H] [has_smul G α] [has_smul G β] [mul_action H α] [has_smul H β]
[smul_comm_class G H β] [smul_comm_class G H α] {s t : set α} {b : β}
-- TODO: This should work without `smul_comm_class`
@[to_additive] lemma supports.smul (g : H) (h : supports G s b) : supports G (g • s) (g • b) :=
begin
rintro g' hg',
rw [smul_comm, h],
rintro a ha,
have := set.ball_image_iff.1 hg' a ha,
rwa [smul_comm, smul_left_cancel_iff] at this,
end
end mul_action
|
af9848ec416ac3c90d67a120e5a463379a247c37 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/group_theory/finiteness.lean | 3c753586285a88259ce8479a105d932fb20a1465 | [
"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 | 8,284 | lean | /-
Copyright (c) 2021 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import data.set.finite
import group_theory.submonoid.operations
import group_theory.subgroup.basic
/-!
# Finitely generated monoids and groups
We define finitely generated monoids and groups. See also `submodule.fg` and `module.finite` for
finitely-generated modules.
## Main definition
* `submonoid.fg S`, `add_submonoid.fg S` : A submonoid `S` is finitely generated.
* `monoid.fg M`, `add_monoid.fg M` : A typeclass indicating a type `M` is finitely generated as a
monoid.
* `subgroup.fg S`, `add_subgroup.fg S` : A subgroup `S` is finitely generated.
* `group.fg M`, `add_group.fg M` : A typeclass indicating a type `M` is finitely generated as a
group.
-/
/-! ### Monoids and submonoids -/
open_locale pointwise
variables {M N : Type*} [monoid M] [add_monoid N]
section submonoid
/-- A submonoid of `M` is finitely generated if it is the closure of a finite subset of `M`. -/
@[to_additive]
def submonoid.fg (P : submonoid M) : Prop := ∃ S : finset M, submonoid.closure ↑S = P
/-- An additive submonoid of `N` is finitely generated if it is the closure of a finite subset of
`M`. -/
add_decl_doc add_submonoid.fg
/-- An equivalent expression of `submonoid.fg` in terms of `set.finite` instead of `finset`. -/
@[to_additive "An equivalent expression of `add_submonoid.fg` in terms of `set.finite` instead of
`finset`."]
lemma submonoid.fg_iff (P : submonoid M) : submonoid.fg P ↔
∃ S : set M, submonoid.closure S = P ∧ S.finite :=
⟨λ ⟨S, hS⟩, ⟨S, hS, finset.finite_to_set S⟩, λ ⟨S, hS, hf⟩, ⟨set.finite.to_finset hf, by simp [hS]⟩⟩
lemma submonoid.fg_iff_add_fg (P : submonoid M) : P.fg ↔ P.to_add_submonoid.fg :=
⟨λ h, let ⟨S, hS, hf⟩ := (submonoid.fg_iff _).1 h in (add_submonoid.fg_iff _).mpr
⟨additive.to_mul ⁻¹' S, by simp [← submonoid.to_add_submonoid_closure, hS], hf⟩,
λ h, let ⟨T, hT, hf⟩ := (add_submonoid.fg_iff _).1 h in (submonoid.fg_iff _).mpr
⟨multiplicative.of_add ⁻¹' T, by simp [← add_submonoid.to_submonoid'_closure, hT], hf⟩⟩
lemma add_submonoid.fg_iff_mul_fg (P : add_submonoid N) : P.fg ↔ P.to_submonoid.fg :=
begin
convert (submonoid.fg_iff_add_fg P.to_submonoid).symm,
exact set_like.ext' rfl
end
end submonoid
section monoid
variables (M N)
/-- A monoid is finitely generated if it is finitely generated as a submonoid of itself. -/
class monoid.fg : Prop := (out : (⊤ : submonoid M).fg)
/-- An additive monoid is finitely generated if it is finitely generated as an additive submonoid of
itself. -/
class add_monoid.fg : Prop := (out : (⊤ : add_submonoid N).fg)
attribute [to_additive] monoid.fg
variables {M N}
lemma monoid.fg_def : monoid.fg M ↔ (⊤ : submonoid M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩
lemma add_monoid.fg_def : add_monoid.fg N ↔ (⊤ : add_submonoid N).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩
/-- An equivalent expression of `monoid.fg` in terms of `set.finite` instead of `finset`. -/
@[to_additive "An equivalent expression of `add_monoid.fg` in terms of `set.finite` instead of
`finset`."]
lemma monoid.fg_iff : monoid.fg M ↔
∃ S : set M, submonoid.closure S = (⊤ : submonoid M) ∧ S.finite :=
⟨λ h, (submonoid.fg_iff ⊤).1 h.out, λ h, ⟨(submonoid.fg_iff ⊤).2 h⟩⟩
lemma monoid.fg_iff_add_fg : monoid.fg M ↔ add_monoid.fg (additive M) :=
⟨λ h, ⟨(submonoid.fg_iff_add_fg ⊤).1 h.out⟩, λ h, ⟨(submonoid.fg_iff_add_fg ⊤).2 h.out⟩⟩
lemma add_monoid.fg_iff_mul_fg : add_monoid.fg N ↔ monoid.fg (multiplicative N) :=
⟨λ h, ⟨(add_submonoid.fg_iff_mul_fg ⊤).1 h.out⟩, λ h, ⟨(add_submonoid.fg_iff_mul_fg ⊤).2 h.out⟩⟩
instance add_monoid.fg_of_monoid_fg [monoid.fg M] : add_monoid.fg (additive M) :=
monoid.fg_iff_add_fg.1 ‹_›
instance monoid.fg_of_add_monoid_fg [add_monoid.fg N] : monoid.fg (multiplicative N) :=
add_monoid.fg_iff_mul_fg.1 ‹_›
end monoid
/-! ### Groups and subgroups -/
variables {G H : Type*} [group G] [add_group H]
section subgroup
/-- A subgroup of `G` is finitely generated if it is the closure of a finite subset of `G`. -/
@[to_additive]
def subgroup.fg (P : subgroup G) : Prop := ∃ S : finset G, subgroup.closure ↑S = P
/-- An additive subgroup of `H` is finitely generated if it is the closure of a finite subset of
`H`. -/
add_decl_doc add_subgroup.fg
/-- An equivalent expression of `subgroup.fg` in terms of `set.finite` instead of `finset`. -/
@[to_additive "An equivalent expression of `add_subgroup.fg` in terms of `set.finite` instead of
`finset`."]
lemma subgroup.fg_iff (P : subgroup G) : subgroup.fg P ↔
∃ S : set G, subgroup.closure S = P ∧ S.finite :=
⟨λ⟨S, hS⟩, ⟨S, hS, finset.finite_to_set S⟩, λ⟨S, hS, hf⟩, ⟨set.finite.to_finset hf, by simp [hS]⟩⟩
/-- A subgroup is finitely generated if and only if it is finitely generated as a submonoid. -/
@[to_additive add_subgroup.fg_iff_add_submonoid.fg "An additive subgroup is finitely generated if
and only if it is finitely generated as an additive submonoid."]
lemma subgroup.fg_iff_submonoid_fg (P : subgroup G) : P.fg ↔ P.to_submonoid.fg :=
begin
split,
{ rintro ⟨S, rfl⟩,
rw submonoid.fg_iff,
refine ⟨S ∪ S⁻¹, _, S.finite_to_set.union S.finite_to_set.inv⟩,
exact (subgroup.closure_to_submonoid _).symm },
{ rintro ⟨S, hS⟩,
refine ⟨S, le_antisymm _ _⟩,
{ rw [subgroup.closure_le, ←subgroup.coe_to_submonoid, ←hS],
exact submonoid.subset_closure },
{ rw [← subgroup.to_submonoid_le, ← hS, submonoid.closure_le],
exact subgroup.subset_closure } }
end
lemma subgroup.fg_iff_add_fg (P : subgroup G) : P.fg ↔ P.to_add_subgroup.fg :=
begin
rw [subgroup.fg_iff_submonoid_fg, add_subgroup.fg_iff_add_submonoid.fg],
exact (subgroup.to_submonoid P).fg_iff_add_fg
end
lemma add_subgroup.fg_iff_mul_fg (P : add_subgroup H) :
P.fg ↔ P.to_subgroup.fg :=
begin
rw [add_subgroup.fg_iff_add_submonoid.fg, subgroup.fg_iff_submonoid_fg],
exact add_submonoid.fg_iff_mul_fg (add_subgroup.to_add_submonoid P)
end
end subgroup
section group
variables (G H)
/-- A group is finitely generated if it is finitely generated as a submonoid of itself. -/
class group.fg : Prop := (out : (⊤ : subgroup G).fg)
/-- An additive group is finitely generated if it is finitely generated as an additive submonoid of
itself. -/
class add_group.fg : Prop := (out : (⊤ : add_subgroup H).fg)
attribute [to_additive] group.fg
variables {G H}
lemma group.fg_def : group.fg G ↔ (⊤ : subgroup G).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩
lemma add_group.fg_def : add_group.fg H ↔ (⊤ : add_subgroup H).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩
/-- An equivalent expression of `group.fg` in terms of `set.finite` instead of `finset`. -/
@[to_additive "An equivalent expression of `add_group.fg` in terms of `set.finite` instead of
`finset`."]
lemma group.fg_iff : group.fg G ↔
∃ S : set G, subgroup.closure S = (⊤ : subgroup G) ∧ S.finite :=
⟨λ h, (subgroup.fg_iff ⊤).1 h.out, λ h, ⟨(subgroup.fg_iff ⊤).2 h⟩⟩
/-- A group is finitely generated if and only if it is finitely generated as a monoid. -/
@[to_additive add_group.fg_iff_add_monoid.fg "An additive group is finitely generated if and only
if it is finitely generated as an additive monoid."]
lemma group.fg_iff_monoid.fg : group.fg G ↔ monoid.fg G :=
⟨λ h, monoid.fg_def.2 $ (subgroup.fg_iff_submonoid_fg ⊤).1 (group.fg_def.1 h),
λ h, group.fg_def.2 $ (subgroup.fg_iff_submonoid_fg ⊤).2 (monoid.fg_def.1 h)⟩
lemma group_fg.iff_add_fg : group.fg G ↔ add_group.fg (additive G) :=
⟨λ h, ⟨(subgroup.fg_iff_add_fg ⊤).1 h.out⟩, λ h, ⟨(subgroup.fg_iff_add_fg ⊤).2 h.out⟩⟩
lemma add_group.fg_iff_mul_fg : add_group.fg H ↔ group.fg (multiplicative H) :=
⟨λ h, ⟨(add_subgroup.fg_iff_mul_fg ⊤).1 h.out⟩, λ h, ⟨(add_subgroup.fg_iff_mul_fg ⊤).2 h.out⟩⟩
instance add_group.fg_of_group_fg [group.fg G] : add_group.fg (additive G) :=
group_fg.iff_add_fg.1 ‹_›
instance group.fg_of_mul_group_fg [add_group.fg H] : group.fg (multiplicative H) :=
add_group.fg_iff_mul_fg.1 ‹_›
end group
|
f3dcff515135dd30796679667603bd8261db97a6 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/type_class_bug.lean | e7d06a706e0d729fc31cbf0d5f5790ca1abc9d21 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 175 | lean | set_option pp.all true
check
(do {
a : nat ← [1],
return a } : list nat )
check
(do {
a : nat ← [1, 2, 3],
b : nat ← [3, 4],
return (a, b) } : list (nat × nat) )
|
5278b07d8191f07523a0b0ee664366bd6935c773 | 0c1546a496eccfb56620165cad015f88d56190c5 | /library/init/meta/rb_map.lean | dffcc578187ed0c2a717ac3fa8fab6f73d2a20e0 | [
"Apache-2.0"
] | permissive | Solertis/lean | 491e0939957486f664498fbfb02546e042699958 | 84188c5aa1673fdf37a082b2de8562dddf53df3f | refs/heads/master | 1,610,174,257,606 | 1,486,263,620,000 | 1,486,263,620,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,848 | 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, Jeremy Avigad
-/
prelude
import init.data.ordering init.function init.meta.name init.meta.format
meta constant {u₁ u₂} rb_map : Type u₁ → Type u₂ → Type (max u₁ u₂)
namespace rb_map
meta constant mk_core {key : Type} (data : Type) : (key → key → ordering) → rb_map key data
meta constant size {key : Type} {data : Type} : rb_map key data → nat
meta constant insert {key : Type} {data : Type} : rb_map key data → key → data → rb_map key data
meta constant erase {key : Type} {data : Type} : rb_map key data → key → rb_map key data
meta constant contains {key : Type} {data : Type} : rb_map key data → key → bool
meta constant find {key : Type} {data : Type} : rb_map key data → key → option data
meta constant min {key : Type} {data : Type} : rb_map key data → option data
meta constant max {key : Type} {data : Type} : rb_map key data → option data
meta constant fold {key : Type} {data : Type} {α :Type} : rb_map key data → α → (key → data → α → α) → α
attribute [inline]
meta def mk (key : Type) [has_ordering key] (data : Type) : rb_map key data :=
mk_core data has_ordering.cmp
open list
meta def of_list {key : Type} {data : Type} [has_ordering key] : list (key × data) → rb_map key data
| [] := mk key data
| ((k, v)::ls) := insert (of_list ls) k v
meta def keys {key : Type} {data : Type} (m : rb_map key data) : list key :=
fold m [] (λk v ks, k :: ks)
meta def values {key : Type} {data : Type} (m : rb_map key data) : list data :=
fold m [] (λk v vs, v :: vs)
meta def to_list {key : Type} {data : Type} (m : rb_map key data) : list (key × data) :=
fold m [] (λk v res, (k, v) :: res)
meta def set_of_list {A} [has_ordering A] : list A → rb_map A unit
| [] := mk _ _
| (x::xs) := insert (set_of_list xs) x ()
meta def map {A B C} [has_ordering A] (f : B → C) (m : rb_map A B) : rb_map A C :=
fold m (mk _ _) (λk v res, insert res k (f v))
meta def for {A B C} [has_ordering A] (m : rb_map A B) (f : B → C) : rb_map A C :=
map f m
meta def filter {A B} [has_ordering A] (m : rb_map A B) (f : B → Prop) [decidable_pred f] :=
fold m (mk _ _) $ λa b m', if f b then insert m' a b else m'
end rb_map
attribute [reducible]
meta def nat_map (data : Type) := rb_map nat data
namespace nat_map
export rb_map (hiding mk)
attribute [inline]
meta def mk (data : Type) : nat_map data :=
rb_map.mk nat data
end nat_map
attribute [reducible]
meta def name_map (data : Type) := rb_map name data
namespace name_map
export rb_map (hiding mk)
attribute [inline]
meta def mk (data : Type) : name_map data :=
rb_map.mk name data
end name_map
open rb_map prod
section
open format
variables {key : Type} {data : Type} [has_to_format key] [has_to_format data]
private meta def format_key_data (k : key) (d : data) (first : bool) : format :=
(if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt k ++ space ++ to_fmt "←" ++ space ++ to_fmt d
meta instance : has_to_format (rb_map key data) :=
⟨λ m, group $ to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ k d p, (fst p ++ format_key_data k d (snd p), ff)))) ++
to_fmt "⟩"⟩
end
section
variables {key : Type} {data : Type} [has_to_string key] [has_to_string data]
private meta def key_data_to_string (k : key) (d : data) (first : bool) : string :=
(if first then "" else ", ") ++ to_string k ++ " ← " ++ to_string d
meta instance : has_to_string (rb_map key data) :=
⟨λ m, "⟨" ++ (fst (fold m ("", tt) (λ k d p, (fst p ++ key_data_to_string k d (snd p), ff)))) ++ "⟩"⟩
end
/- a variant of rb_maps that stores a list of elements for each key.
"find" returns the list of elements in the opposite order that they were inserted. -/
meta def rb_lmap (key : Type) (data : Type) : Type := rb_map key (list data)
namespace rb_lmap
protected meta def mk (key : Type) [has_ordering key] (data : Type) : rb_lmap key data :=
rb_map.mk key (list data)
meta def insert {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) (d : data) :
rb_lmap key data :=
match (rb_map.find rbl k) with
| none := rb_map.insert rbl k [d]
| (some l) := rb_map.insert (rb_map.erase rbl k) k (d :: l)
end
meta def erase {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) :
rb_lmap key data :=
rb_map.erase rbl k
meta def contains {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : bool :=
rb_map.contains rbl k
meta def find {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : list data :=
match (rb_map.find rbl k) with
| none := []
| (some l) := l
end
end rb_lmap
|
5d0b5c5f584952e6fc5b2dd83b29933b6eada0c8 | 47181b4ef986292573c77e09fcb116584d37ea8a | /src/for_mathlib/nat_digits.lean | b553ac3006c591f0045802c3825cdb96fc867ea2 | [
"MIT"
] | permissive | RaitoBezarius/berkovich-spaces | 87662a2bdb0ac0beed26e3338b221e3f12107b78 | 0a49f75a599bcb20333ec86b301f84411f04f7cf | refs/heads/main | 1,690,520,666,912 | 1,629,328,012,000 | 1,629,328,012,000 | 332,238,095 | 4 | 0 | MIT | 1,629,312,085,000 | 1,611,414,506,000 | Lean | UTF-8 | Lean | false | false | 1,728 | lean | import data.nat.digits
import .list
lemma of_digits_eq_sum_map_with_index_aux (b : ℕ) (l : list ℕ) :
(list.zip_with ((λ (i a : ℕ), a * b ^ i) ∘ nat.succ) (list.range l.length) l).sum =
b * (list.zip_with (λ i a, a * b ^ i) (list.range l.length) l).sum :=
begin
suffices : list.zip_with (((λ (i a : ℕ), a * b ^ i) ∘ nat.succ)) (list.range l.length) l =
list.zip_with (λ i a, b * (a * b ^ i)) (list.range l.length) l,
{ simp [this] },
congr,
ext,
simp [pow_succ],
ring
end
lemma of_digits_eq_sum_map_with_index (b: ℕ) (L: list ℕ):
nat.of_digits b L = list.sum (L.map_with_index (λ (i: ℕ) (a: ℕ), a * b ^ i)) :=
begin
rw [list.map_with_index_eq_enum_map, list.enum_eq_zip_range,
list.map_uncurry_zip_eq_zip_with, nat.of_digits_eq_foldr b],
induction L with hd tl hl,
{ simp },
{
norm_cast at hl,
simp [list.range_succ_eq_map, list.zip_with_map_left, of_digits_eq_sum_map_with_index_aux, hl],
}
end
lemma fun_of_digits_eq_fun_of_sum_map_with_index
{α β} [has_lift_t ℕ α]
[semiring α]
(f: α → β) (b: ℕ) (l: list ℕ):
f ((nat.of_digits b l): α) = f (list.sum (l.map_with_index (λ i a, a * (b: α) ^ i))) :=
begin
congr,
rw_mod_cast of_digits_eq_sum_map_with_index,
have := list.sum_hom _ (nat.cast_add_monoid_hom α),
simp at this,
rw [← this, list.map_map_with_index],
end
lemma one_le_of_nonzero_digits_length
(n b: ℕ) (hn: n ≠ 0):
1 ≤ (b.digits n).length :=
begin
induction n with d hd,
exact absurd rfl hn,
cases b,
{ simp },
{
cases b,
{ simp },
{ dsimp [nat.digits],
rw nat.digits_aux,
simp only [list.length, zero_le, le_add_iff_nonneg_left],
}
},
end |
a9391faf174aaf9da1725ae8b8f69a856642b66e | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/ring_theory/graded_algebra/homogeneous_ideal.lean | 02156a1661fa2ab8c1415a148686fd91743bb103 | [
"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 | 21,513 | lean | /-
Copyright (c) 2021 Jujian Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jujian Zhang, Eric Wieser
-/
import ring_theory.ideal.basic
import ring_theory.ideal.operations
import linear_algebra.finsupp
import ring_theory.graded_algebra.basic
/-!
# Homogeneous ideals of a graded algebra
This file defines homogeneous ideals of `graded_ring 𝒜` where `𝒜 : ι → submodule R A` and
operations on them.
## Main definitions
For any `I : ideal A`:
* `ideal.is_homogeneous 𝒜 I`: The property that an ideal is closed under `graded_ring.proj`.
* `homogeneous_ideal 𝒜`: The structure extending ideals which satisfy `ideal.is_homogeneous`
* `ideal.homogeneous_core I 𝒜`: The largest homogeneous ideal smaller than `I`.
* `ideal.homogeneous_hull I 𝒜`: The smallest homogeneous ideal larger than `I`.
## Main statements
* `homogeneous_ideal.complete_lattice`: `ideal.is_homogeneous` is preserved by `⊥`, `⊤`, `⊔`, `⊓`,
`⨆`, `⨅`, and so the subtype of homogeneous ideals inherits a complete lattice structure.
* `ideal.homogeneous_core.gi`: `ideal.homogeneous_core` forms a galois insertion with coercion.
* `ideal.homogeneous_hull.gi`: `ideal.homogeneous_hull` forms a galois insertion with coercion.
## Implementation notes
We introduce `ideal.homogeneous_core'` earlier than might be expected so that we can get access
to `ideal.is_homogeneous.iff_exists` as quickly as possible.
## Tags
graded algebra, homogeneous
-/
open set_like direct_sum set
open_locale big_operators pointwise direct_sum
variables {ι σ R A : Type*}
section homogeneous_def
variables [semiring A]
variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ)
variables [decidable_eq ι] [add_monoid ι] [graded_ring 𝒜]
variable (I : ideal A)
include A
/--An `I : ideal A` is homogeneous if for every `r ∈ I`, all homogeneous components
of `r` are in `I`.-/
def ideal.is_homogeneous : Prop :=
∀ (i : ι) ⦃r : A⦄, r ∈ I → (direct_sum.decompose 𝒜 r i : A) ∈ I
/-- For any `semiring A`, we collect the homogeneous ideals of `A` into a type. -/
structure homogeneous_ideal extends submodule A A :=
(is_homogeneous' : ideal.is_homogeneous 𝒜 to_submodule)
variable {𝒜}
/--Converting a homogeneous ideal to an ideal-/
def homogeneous_ideal.to_ideal (I : homogeneous_ideal 𝒜) : ideal A := I.to_submodule
lemma homogeneous_ideal.is_homogeneous (I : homogeneous_ideal 𝒜) :
I.to_ideal.is_homogeneous 𝒜 := I.is_homogeneous'
lemma homogeneous_ideal.to_ideal_injective :
function.injective (homogeneous_ideal.to_ideal : homogeneous_ideal 𝒜 → ideal A) :=
λ ⟨x, hx⟩ ⟨y, hy⟩ (h : x = y), by simp [h]
instance homogeneous_ideal.set_like : set_like (homogeneous_ideal 𝒜) A :=
{ coe := λ I, I.to_ideal,
coe_injective' := λ I J h, homogeneous_ideal.to_ideal_injective $ set_like.coe_injective h }
@[ext] lemma homogeneous_ideal.ext {I J : homogeneous_ideal 𝒜}
(h : I.to_ideal = J.to_ideal) : I = J := homogeneous_ideal.to_ideal_injective h
@[simp] lemma homogeneous_ideal.mem_iff {I : homogeneous_ideal 𝒜} {x : A} :
x ∈ I.to_ideal ↔ x ∈ I := iff.rfl
end homogeneous_def
section homogeneous_core
variables [semiring A]
variables [set_like σ A] (𝒜 : ι → σ)
variable (I : ideal A)
include A
/-- For any `I : ideal A`, not necessarily homogeneous, `I.homogeneous_core' 𝒜`
is the largest homogeneous ideal of `A` contained in `I`, as an ideal. -/
def ideal.homogeneous_core' (I : ideal A) : ideal A :=
ideal.span (coe '' ((coe : subtype (is_homogeneous 𝒜) → A) ⁻¹' I))
lemma ideal.homogeneous_core'_mono : monotone (ideal.homogeneous_core' 𝒜) :=
λ I J I_le_J, ideal.span_mono $ set.image_subset _ $ λ x, @I_le_J _
lemma ideal.homogeneous_core'_le : I.homogeneous_core' 𝒜 ≤ I :=
ideal.span_le.2 $ image_preimage_subset _ _
end homogeneous_core
section is_homogeneous_ideal_defs
variables [semiring A]
variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ)
variables [decidable_eq ι] [add_monoid ι] [graded_ring 𝒜]
variable (I : ideal A)
include A
lemma ideal.is_homogeneous_iff_forall_subset :
I.is_homogeneous 𝒜 ↔ ∀ i, (I : set A) ⊆ graded_ring.proj 𝒜 i ⁻¹' I :=
iff.rfl
lemma ideal.is_homogeneous_iff_subset_Inter :
I.is_homogeneous 𝒜 ↔ (I : set A) ⊆ ⋂ i, graded_ring.proj 𝒜 i ⁻¹' ↑I :=
subset_Inter_iff.symm
lemma ideal.mul_homogeneous_element_mem_of_mem
{I : ideal A} (r x : A) (hx₁ : is_homogeneous 𝒜 x) (hx₂ : x ∈ I) (j : ι) :
graded_ring.proj 𝒜 j (r * x) ∈ I :=
begin
classical,
rw [←direct_sum.sum_support_decompose 𝒜 r, finset.sum_mul, map_sum],
apply ideal.sum_mem,
intros k hk,
obtain ⟨i, hi⟩ := hx₁,
have mem₁ : (direct_sum.decompose 𝒜 r k : A) * x ∈ 𝒜 (k + i) := graded_monoid.mul_mem
(set_like.coe_mem _) hi,
erw [graded_ring.proj_apply, direct_sum.decompose_of_mem 𝒜 mem₁,
coe_of_apply, set_like.coe_mk],
split_ifs,
{ exact I.mul_mem_left _ hx₂ },
{ exact I.zero_mem },
end
lemma ideal.is_homogeneous_span (s : set A) (h : ∀ x ∈ s, is_homogeneous 𝒜 x) :
(ideal.span s).is_homogeneous 𝒜 :=
begin
rintros i r hr,
rw [ideal.span, finsupp.span_eq_range_total] at hr,
rw linear_map.mem_range at hr,
obtain ⟨s, rfl⟩ := hr,
rw [finsupp.total_apply, finsupp.sum, decompose_sum, dfinsupp.finset_sum_apply,
add_submonoid_class.coe_finset_sum],
refine ideal.sum_mem _ _,
rintros z hz1,
rw [smul_eq_mul],
refine ideal.mul_homogeneous_element_mem_of_mem 𝒜 (s z) z _ _ i,
{ rcases z with ⟨z, hz2⟩,
apply h _ hz2, },
{ exact ideal.subset_span z.2 },
end
/--For any `I : ideal A`, not necessarily homogeneous, `I.homogeneous_core' 𝒜`
is the largest homogeneous ideal of `A` contained in `I`.-/
def ideal.homogeneous_core : homogeneous_ideal 𝒜 :=
⟨ideal.homogeneous_core' 𝒜 I,
ideal.is_homogeneous_span _ _ (λ x h, by { rw [subtype.image_preimage_coe] at h, exact h.2 })⟩
lemma ideal.homogeneous_core_mono : monotone (ideal.homogeneous_core 𝒜) :=
ideal.homogeneous_core'_mono 𝒜
lemma ideal.to_ideal_homogeneous_core_le : (I.homogeneous_core 𝒜).to_ideal ≤ I :=
ideal.homogeneous_core'_le 𝒜 I
variables {𝒜 I}
lemma ideal.mem_homogeneous_core_of_is_homogeneous_of_mem {x : A}
(h : set_like.is_homogeneous 𝒜 x) (hmem : x ∈ I) : x ∈ I.homogeneous_core 𝒜 :=
ideal.subset_span ⟨⟨x, h⟩, hmem, rfl⟩
lemma ideal.is_homogeneous.to_ideal_homogeneous_core_eq_self (h : I.is_homogeneous 𝒜) :
(I.homogeneous_core 𝒜).to_ideal = I :=
begin
apply le_antisymm (I.homogeneous_core'_le 𝒜) _,
intros x hx,
classical,
rw ←direct_sum.sum_support_decompose 𝒜 x,
exact ideal.sum_mem _ (λ j hj, ideal.subset_span ⟨⟨_, is_homogeneous_coe _⟩, h _ hx, rfl⟩)
end
@[simp] lemma homogeneous_ideal.to_ideal_homogeneous_core_eq_self (I : homogeneous_ideal 𝒜) :
I.to_ideal.homogeneous_core 𝒜 = I :=
by ext1; convert ideal.is_homogeneous.to_ideal_homogeneous_core_eq_self I.is_homogeneous
variables (𝒜 I)
lemma ideal.is_homogeneous.iff_eq : I.is_homogeneous 𝒜 ↔ (I.homogeneous_core 𝒜).to_ideal = I :=
⟨ λ hI, hI.to_ideal_homogeneous_core_eq_self,
λ hI, hI ▸ (ideal.homogeneous_core 𝒜 I).2 ⟩
lemma ideal.is_homogeneous.iff_exists :
I.is_homogeneous 𝒜 ↔ ∃ (S : set (homogeneous_submonoid 𝒜)), I = ideal.span (coe '' S) :=
begin
rw [ideal.is_homogeneous.iff_eq, eq_comm],
exact ((set.image_preimage.compose (submodule.gi _ _).gc).exists_eq_l _).symm,
end
end is_homogeneous_ideal_defs
/-! ### Operations
In this section, we show that `ideal.is_homogeneous` is preserved by various notations, then use
these results to provide these notation typeclasses for `homogeneous_ideal`. -/
section operations
section semiring
variables [semiring A] [decidable_eq ι] [add_monoid ι]
variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜]
include A
namespace ideal.is_homogeneous
lemma bot : ideal.is_homogeneous 𝒜 ⊥ := λ i r hr,
begin
simp only [ideal.mem_bot] at hr,
rw [hr, decompose_zero, zero_apply],
apply ideal.zero_mem
end
lemma top : ideal.is_homogeneous 𝒜 ⊤ :=
λ i r hr, by simp only [submodule.mem_top]
variables {𝒜}
lemma inf {I J : ideal A} (HI : I.is_homogeneous 𝒜) (HJ : J.is_homogeneous 𝒜) :
(I ⊓ J).is_homogeneous 𝒜 :=
λ i r hr, ⟨HI _ hr.1, HJ _ hr.2⟩
lemma sup {I J : ideal A} (HI : I.is_homogeneous 𝒜) (HJ : J.is_homogeneous 𝒜) :
(I ⊔ J).is_homogeneous 𝒜 :=
begin
rw iff_exists at HI HJ ⊢,
obtain ⟨⟨s₁, rfl⟩, ⟨s₂, rfl⟩⟩ := ⟨HI, HJ⟩,
refine ⟨s₁ ∪ s₂, _⟩,
rw [set.image_union],
exact (submodule.span_union _ _).symm,
end
protected lemma supr {κ : Sort*} {f : κ → ideal A} (h : ∀ i, (f i).is_homogeneous 𝒜) :
(⨆ i, f i).is_homogeneous 𝒜 :=
begin
simp_rw iff_exists at h ⊢,
choose s hs using h,
refine ⟨⋃ i, s i, _⟩,
simp_rw [set.image_Union, ideal.span_Union],
congr',
exact funext hs,
end
protected lemma infi {κ : Sort*} {f : κ → ideal A} (h : ∀ i, (f i).is_homogeneous 𝒜) :
(⨅ i, f i).is_homogeneous 𝒜 :=
begin
intros i x hx,
simp only [ideal.mem_infi] at ⊢ hx,
exact λ j, h _ _ (hx j),
end
lemma supr₂ {κ : Sort*} {κ' : κ → Sort*} {f : Π i, κ' i → ideal A}
(h : ∀ i j, (f i j).is_homogeneous 𝒜) :
(⨆ i j, f i j).is_homogeneous 𝒜 :=
is_homogeneous.supr $ λ i, is_homogeneous.supr $ h i
lemma infi₂ {κ : Sort*} {κ' : κ → Sort*} {f : Π i, κ' i → ideal A}
(h : ∀ i j, (f i j).is_homogeneous 𝒜) :
(⨅ i j, f i j).is_homogeneous 𝒜 :=
is_homogeneous.infi $ λ i, is_homogeneous.infi $ h i
lemma Sup {ℐ : set (ideal A)} (h : ∀ I ∈ ℐ, ideal.is_homogeneous 𝒜 I) :
(Sup ℐ).is_homogeneous 𝒜 :=
by { rw Sup_eq_supr, exact supr₂ h }
lemma Inf {ℐ : set (ideal A)} (h : ∀ I ∈ ℐ, ideal.is_homogeneous 𝒜 I) :
(Inf ℐ).is_homogeneous 𝒜 :=
by { rw Inf_eq_infi, exact infi₂ h }
end ideal.is_homogeneous
variables {𝒜}
namespace homogeneous_ideal
instance : partial_order (homogeneous_ideal 𝒜) := set_like.partial_order
instance : has_top (homogeneous_ideal 𝒜) := ⟨⟨⊤, ideal.is_homogeneous.top 𝒜⟩⟩
instance : has_bot (homogeneous_ideal 𝒜) := ⟨⟨⊥, ideal.is_homogeneous.bot 𝒜⟩⟩
instance : has_sup (homogeneous_ideal 𝒜) := ⟨λ I J, ⟨_, I.is_homogeneous.sup J.is_homogeneous⟩⟩
instance : has_inf (homogeneous_ideal 𝒜) := ⟨λ I J, ⟨_, I.is_homogeneous.inf J.is_homogeneous⟩⟩
instance : has_Sup (homogeneous_ideal 𝒜) :=
⟨λ S, ⟨⨆ s ∈ S, to_ideal s, ideal.is_homogeneous.supr₂ $ λ s _, s.is_homogeneous⟩⟩
instance : has_Inf (homogeneous_ideal 𝒜) :=
⟨λ S, ⟨⨅ s ∈ S, to_ideal s, ideal.is_homogeneous.infi₂ $ λ s _, s.is_homogeneous⟩⟩
@[simp] lemma coe_top : ((⊤ : homogeneous_ideal 𝒜) : set A) = univ := rfl
@[simp] lemma coe_bot : ((⊥ : homogeneous_ideal 𝒜) : set A) = 0 := rfl
@[simp] lemma coe_sup (I J : homogeneous_ideal 𝒜) : ↑(I ⊔ J) = (I + J : set A) :=
submodule.coe_sup _ _
@[simp] lemma coe_inf (I J : homogeneous_ideal 𝒜) : (↑(I ⊓ J) : set A) = I ∩ J := rfl
@[simp] lemma to_ideal_top : (⊤ : homogeneous_ideal 𝒜).to_ideal = (⊤ : ideal A) := rfl
@[simp] lemma to_ideal_bot : (⊥ : homogeneous_ideal 𝒜).to_ideal = (⊥ : ideal A) := rfl
@[simp] lemma to_ideal_sup (I J : homogeneous_ideal 𝒜) :
(I ⊔ J).to_ideal = I.to_ideal ⊔ J.to_ideal := rfl
@[simp] lemma to_ideal_inf (I J : homogeneous_ideal 𝒜) :
(I ⊓ J).to_ideal = I.to_ideal ⊓ J.to_ideal := rfl
@[simp] lemma to_ideal_Sup (ℐ : set (homogeneous_ideal 𝒜)) :
(Sup ℐ).to_ideal = ⨆ s ∈ ℐ, to_ideal s := rfl
@[simp] lemma to_ideal_Inf (ℐ : set (homogeneous_ideal 𝒜)) :
(Inf ℐ).to_ideal = ⨅ s ∈ ℐ, to_ideal s := rfl
@[simp] lemma to_ideal_supr {κ : Sort*} (s : κ → homogeneous_ideal 𝒜) :
(⨆ i, s i).to_ideal = ⨆ i, (s i).to_ideal :=
by rw [supr, to_ideal_Sup, supr_range]
@[simp] lemma to_ideal_infi {κ : Sort*} (s : κ → homogeneous_ideal 𝒜) :
(⨅ i, s i).to_ideal = ⨅ i, (s i).to_ideal :=
by rw [infi, to_ideal_Inf, infi_range]
@[simp] lemma to_ideal_supr₂ {κ : Sort*} {κ' : κ → Sort*} (s : Π i, κ' i → homogeneous_ideal 𝒜) :
(⨆ i j, s i j).to_ideal = ⨆ i j, (s i j).to_ideal :=
by simp_rw to_ideal_supr
@[simp] lemma to_ideal_infi₂ {κ : Sort*} {κ' : κ → Sort*} (s : Π i, κ' i → homogeneous_ideal 𝒜) :
(⨅ i j, s i j).to_ideal = ⨅ i j, (s i j).to_ideal :=
by simp_rw to_ideal_infi
@[simp] lemma eq_top_iff (I : homogeneous_ideal 𝒜) : I = ⊤ ↔ I.to_ideal = ⊤ :=
to_ideal_injective.eq_iff.symm
@[simp] lemma eq_bot_iff (I : homogeneous_ideal 𝒜) : I = ⊥ ↔ I.to_ideal = ⊥ :=
to_ideal_injective.eq_iff.symm
instance : complete_lattice (homogeneous_ideal 𝒜) :=
to_ideal_injective.complete_lattice _ to_ideal_sup to_ideal_inf to_ideal_Sup to_ideal_Inf
to_ideal_top to_ideal_bot
instance : has_add (homogeneous_ideal 𝒜) := ⟨(⊔)⟩
@[simp] lemma to_ideal_add (I J : homogeneous_ideal 𝒜) :
(I + J).to_ideal = I.to_ideal + J.to_ideal := rfl
instance : inhabited (homogeneous_ideal 𝒜) := { default := ⊥ }
end homogeneous_ideal
end semiring
section comm_semiring
variables [comm_semiring A]
variables [decidable_eq ι] [add_monoid ι]
variables [set_like σ A] [add_submonoid_class σ A] {𝒜 : ι → σ} [graded_ring 𝒜]
variable (I : ideal A)
include A
lemma ideal.is_homogeneous.mul {I J : ideal A}
(HI : I.is_homogeneous 𝒜) (HJ : J.is_homogeneous 𝒜) : (I * J).is_homogeneous 𝒜 :=
begin
rw ideal.is_homogeneous.iff_exists at HI HJ ⊢,
obtain ⟨⟨s₁, rfl⟩, ⟨s₂, rfl⟩⟩ := ⟨HI, HJ⟩,
rw ideal.span_mul_span',
exact ⟨s₁ * s₂, congr_arg _ $ (set.image_mul (homogeneous_submonoid 𝒜).subtype).symm⟩,
end
variables {𝒜}
instance : has_mul (homogeneous_ideal 𝒜) :=
{ mul := λ I J, ⟨I.to_ideal * J.to_ideal, I.is_homogeneous.mul J.is_homogeneous⟩ }
@[simp] lemma homogeneous_ideal.to_ideal_mul (I J : homogeneous_ideal 𝒜) :
(I * J).to_ideal = I.to_ideal * J.to_ideal := rfl
end comm_semiring
end operations
/-! ### Homogeneous core
Note that many results about the homogeneous core came earlier in this file, as they are helpful
for building the lattice structure. -/
section homogeneous_core
open homogeneous_ideal
variables [semiring A] [decidable_eq ι] [add_monoid ι]
variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜]
variable (I : ideal A)
include A
lemma ideal.homogeneous_core.gc : galois_connection to_ideal (ideal.homogeneous_core 𝒜) :=
λ I J, ⟨
λ H, I.to_ideal_homogeneous_core_eq_self ▸ ideal.homogeneous_core_mono 𝒜 H,
λ H, le_trans H (ideal.homogeneous_core'_le _ _)⟩
/--`to_ideal : homogeneous_ideal 𝒜 → ideal A` and `ideal.homogeneous_core 𝒜` forms a galois
coinsertion-/
def ideal.homogeneous_core.gi : galois_coinsertion to_ideal (ideal.homogeneous_core 𝒜) :=
{ choice := λ I HI,
⟨I, le_antisymm (I.to_ideal_homogeneous_core_le 𝒜) HI ▸ homogeneous_ideal.is_homogeneous _⟩,
gc := ideal.homogeneous_core.gc 𝒜,
u_l_le := λ I, ideal.homogeneous_core'_le _ _,
choice_eq := λ I H, le_antisymm H (I.to_ideal_homogeneous_core_le _) }
lemma ideal.homogeneous_core_eq_Sup :
I.homogeneous_core 𝒜 = Sup {J : homogeneous_ideal 𝒜 | J.to_ideal ≤ I} :=
eq.symm $ is_lub.Sup_eq $ (ideal.homogeneous_core.gc 𝒜).is_greatest_u.is_lub
lemma ideal.homogeneous_core'_eq_Sup :
I.homogeneous_core' 𝒜 = Sup {J : ideal A | J.is_homogeneous 𝒜 ∧ J ≤ I} :=
begin
refine (is_lub.Sup_eq _).symm,
apply is_greatest.is_lub,
have coe_mono : monotone (to_ideal : homogeneous_ideal 𝒜 → ideal A) := λ x y, id,
convert coe_mono.map_is_greatest (ideal.homogeneous_core.gc 𝒜).is_greatest_u using 1,
ext,
rw [mem_image, mem_set_of_eq],
refine ⟨λ hI, ⟨⟨x, hI.1⟩, ⟨hI.2, rfl⟩⟩, by rintro ⟨x, ⟨hx, rfl⟩⟩; exact ⟨x.is_homogeneous, hx⟩⟩,
end
end homogeneous_core
/-! ### Homogeneous hulls -/
section homogeneous_hull
open homogeneous_ideal
variables [semiring A] [decidable_eq ι] [add_monoid ι]
variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜]
variable (I : ideal A)
include A
/--For any `I : ideal A`, not necessarily homogeneous, `I.homogeneous_hull 𝒜` is
the smallest homogeneous ideal containing `I`. -/
def ideal.homogeneous_hull : homogeneous_ideal 𝒜 :=
⟨ideal.span {r : A | ∃ (i : ι) (x : I), (direct_sum.decompose 𝒜 (x : A) i : A) = r}, begin
refine ideal.is_homogeneous_span _ _ (λ x hx, _),
obtain ⟨i, x, rfl⟩ := hx,
apply set_like.is_homogeneous_coe
end⟩
lemma ideal.le_to_ideal_homogeneous_hull :
I ≤ (ideal.homogeneous_hull 𝒜 I).to_ideal :=
begin
intros r hr,
classical,
rw [←direct_sum.sum_support_decompose 𝒜 r],
refine ideal.sum_mem _ _, intros j hj,
apply ideal.subset_span, use j, use ⟨r, hr⟩, refl,
end
lemma ideal.homogeneous_hull_mono : monotone (ideal.homogeneous_hull 𝒜) := λ I J I_le_J,
begin
apply ideal.span_mono,
rintros r ⟨hr1, ⟨x, hx⟩, rfl⟩,
refine ⟨hr1, ⟨⟨x, I_le_J hx⟩, rfl⟩⟩,
end
variables {I 𝒜}
lemma ideal.is_homogeneous.to_ideal_homogeneous_hull_eq_self (h : I.is_homogeneous 𝒜) :
(ideal.homogeneous_hull 𝒜 I).to_ideal = I :=
begin
apply le_antisymm _ (ideal.le_to_ideal_homogeneous_hull _ _),
apply (ideal.span_le).2,
rintros _ ⟨i, x, rfl⟩,
exact h _ x.prop,
end
@[simp] lemma homogeneous_ideal.homogeneous_hull_to_ideal_eq_self (I : homogeneous_ideal 𝒜) :
I.to_ideal.homogeneous_hull 𝒜 = I :=
homogeneous_ideal.to_ideal_injective $ I.is_homogeneous.to_ideal_homogeneous_hull_eq_self
variables (I 𝒜)
lemma ideal.to_ideal_homogeneous_hull_eq_supr :
(I.homogeneous_hull 𝒜).to_ideal = ⨆ i, ideal.span (graded_ring.proj 𝒜 i '' I) :=
begin
rw ←ideal.span_Union,
apply congr_arg ideal.span _,
ext1,
simp only [set.mem_Union, set.mem_image, mem_set_of_eq, graded_ring.proj_apply,
set_like.exists, exists_prop, subtype.coe_mk, set_like.mem_coe],
end
lemma ideal.homogeneous_hull_eq_supr :
(I.homogeneous_hull 𝒜) =
⨆ i, ⟨ideal.span (graded_ring.proj 𝒜 i '' I), ideal.is_homogeneous_span 𝒜 _
(by {rintros _ ⟨x, -, rfl⟩, apply set_like.is_homogeneous_coe})⟩ :=
by { ext1, rw [ideal.to_ideal_homogeneous_hull_eq_supr, to_ideal_supr], refl }
end homogeneous_hull
section galois_connection
open homogeneous_ideal
variables [semiring A] [decidable_eq ι] [add_monoid ι]
variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜]
include A
lemma ideal.homogeneous_hull.gc : galois_connection (ideal.homogeneous_hull 𝒜) to_ideal :=
λ I J, ⟨
le_trans (ideal.le_to_ideal_homogeneous_hull _ _),
λ H, J.homogeneous_hull_to_ideal_eq_self ▸ ideal.homogeneous_hull_mono 𝒜 H⟩
/-- `ideal.homogeneous_hull 𝒜` and `to_ideal : homogeneous_ideal 𝒜 → ideal A` form a galois
insertion-/
def ideal.homogeneous_hull.gi : galois_insertion (ideal.homogeneous_hull 𝒜) to_ideal :=
{ choice := λ I H, ⟨I, le_antisymm H (I.le_to_ideal_homogeneous_hull 𝒜) ▸ is_homogeneous _⟩,
gc := ideal.homogeneous_hull.gc 𝒜,
le_l_u := λ I, ideal.le_to_ideal_homogeneous_hull _ _,
choice_eq := λ I H, le_antisymm (I.le_to_ideal_homogeneous_hull 𝒜) H}
lemma ideal.homogeneous_hull_eq_Inf (I : ideal A) :
ideal.homogeneous_hull 𝒜 I = Inf { J : homogeneous_ideal 𝒜 | I ≤ J.to_ideal } :=
eq.symm $ is_glb.Inf_eq $ (ideal.homogeneous_hull.gc 𝒜).is_least_l.is_glb
end galois_connection
section irrelevant_ideal
variables [semiring A]
variables [decidable_eq ι]
variables [canonically_ordered_add_monoid ι]
variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜]
include A
open graded_ring set_like.graded_monoid direct_sum
/--
For a graded ring `⨁ᵢ 𝒜ᵢ` graded by a `canonically_ordered_add_monoid ι`, the irrelevant ideal
refers to `⨁_{i>0} 𝒜ᵢ`, or equivalently `{a | a₀ = 0}`. This definition is used in `Proj`
construction where `ι` is always `ℕ` so the irrelevant ideal is simply elements with `0` as
0-th coordinate.
# Future work
Here in the definition, `ι` is assumed to be `canonically_ordered_add_monoid`. However, the notion
of irrelevant ideal makes sense in a more general setting by defining it as the ideal of elements
with `0` as i-th coordinate for all `i ≤ 0`, i.e. `{a | ∀ (i : ι), i ≤ 0 → aᵢ = 0}`.
-/
def homogeneous_ideal.irrelevant : homogeneous_ideal 𝒜 :=
⟨(graded_ring.proj_zero_ring_hom 𝒜).ker, λ i r (hr : (decompose 𝒜 r 0 : A) = 0), begin
change (decompose 𝒜 (decompose 𝒜 r _ : A) 0 : A) = 0,
by_cases h : i = 0,
{ rw [h, hr, decompose_zero, zero_apply, zero_mem_class.coe_zero] },
{ rw [decompose_of_mem_ne 𝒜 (set_like.coe_mem _) h] }
end⟩
@[simp] lemma homogeneous_ideal.mem_irrelevant_iff (a : A) :
a ∈ homogeneous_ideal.irrelevant 𝒜 ↔ proj 𝒜 0 a = 0 := iff.rfl
@[simp] lemma homogeneous_ideal.to_ideal_irrelevant :
(homogeneous_ideal.irrelevant 𝒜).to_ideal = (graded_ring.proj_zero_ring_hom 𝒜).ker := rfl
end irrelevant_ideal
|
6550cf86ed7f8aa03853c959b9e9ee94d5b667e5 | 076f5040b63237c6dd928c6401329ed5adcb0e44 | /instructor-notes/2019.10.01.Polymorphism/boxed_test.lean | 289ca2f01ef7dcc237818fc8c6477f7bcea50555 | [] | no_license | kevinsullivan/uva-cs-dm-f19 | 0f123689cf6cb078f263950b18382a7086bf30be | 09a950752884bd7ade4be33e9e89a2c4b1927167 | refs/heads/master | 1,594,771,841,541 | 1,575,853,850,000 | 1,575,853,850,000 | 205,433,890 | 4 | 9 | null | 1,571,592,121,000 | 1,567,188,539,000 | Lean | UTF-8 | Lean | false | false | 341 | lean | import .boxed
open boxed_adt
open boxed_adt.boxed
def b1 : boxed nat := box 3
def b2 : boxed bool := box tt
def b3 : boxed string := box "I love polymorphism"
def b1' := box 3
#check b1'
def b2' := box tt
#check b2'
#reduce unbox b1
#reduce unbox b2
#eval unbox b3
#reduce @unbox nat b1
#reduce @unbox bool b2
#eval @unbox string b3
|
9569ebf2a45e84b64eeaf75fa940bb255cc3ef32 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/rat/defs.lean | 4d46b52bcd7b980bcc46e72b46fcb127e0190764 | [
"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 | 36,454 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.int.basic
import data.nat.gcd
import logic.encodable.basic
/-!
# Basics for the Rational Numbers
## Summary
We define a rational number `q` as a structure `{ num, denom, pos, cop }`, where
- `num` is the numerator of `q`,
- `denom` is the denominator of `q`,
- `pos` is a proof that `denom > 0`, and
- `cop` is a proof `num` and `denom` are coprime.
We then define the integral domain structure on `ℚ` and prove basic lemmas about it.
The definition of the field structure on `ℚ` will be done in `data.rat.basic` once the
`field` class has been defined.
## Main Definitions
- `rat` is the structure encoding `ℚ`.
- `rat.mk n d` constructs a rational number `q = n / d` from `n d : ℤ`.
## Notations
- `/.` is infix notation for `rat.mk`.
## Tags
rat, rationals, field, ℚ, numerator, denominator, num, denom
-/
/-- `rat`, or `ℚ`, is the type of rational numbers. It is defined
as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and
`d` are coprime. This representation is preferred to the quotient
because without periodic reduction, the numerator and denominator can grow
exponentially (for example, adding 1/2 to itself repeatedly). -/
structure rat := mk' ::
(num : ℤ)
(denom : ℕ)
(pos : 0 < denom)
(cop : num.nat_abs.coprime denom)
notation `ℚ` := rat
namespace rat
/-- String representation of a rational numbers, used in `has_repr`, `has_to_string`, and
`has_to_format` instances. -/
protected def repr : ℚ → string
| ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else
_root_.repr n ++ "/" ++ _root_.repr d
instance : has_repr ℚ := ⟨rat.repr⟩
instance : has_to_string ℚ := ⟨rat.repr⟩
meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩
instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // 0 < d ∧ n.nat_abs.coprime d})
⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩,
λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩
/-- Embed an integer as a rational number -/
def of_int (n : ℤ) : ℚ :=
⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩
instance : has_zero ℚ := ⟨of_int 0⟩
instance : has_one ℚ := ⟨of_int 1⟩
instance : inhabited ℚ := ⟨0⟩
lemma ext_iff {p q : ℚ} : p = q ↔ p.num = q.num ∧ p.denom = q.denom :=
by { cases p, cases q, simp }
@[ext] lemma ext {p q : ℚ} (hn : p.num = q.num) (hd : p.denom = q.denom) : p = q :=
rat.ext_iff.mpr ⟨hn, hd⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/
def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ :=
let n' := n.nat_abs, g := n'.gcd d in
⟨n / g, d / g, begin
apply (nat.le_div_iff_mul_le (nat.gcd_pos_of_pos_right _ dpos)).2,
rw one_mul, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _)
end, begin
have : int.nat_abs (n / ↑g) = n' / g,
{ cases int.nat_abs_eq n with e e; rw e, { refl },
rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl },
exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) },
rw this,
exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos)
end⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we
define `n / 0 = 0` by convention. -/
def mk_nat (n : ℤ) (d : ℕ) : ℚ :=
if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩
/-- Form the quotient `n / d` where `n d : ℤ`. -/
def mk : ℤ → ℤ → ℚ
| n (d : ℕ) := mk_nat n d
| n -[1+ d] := mk_pnat (-n) d.succ_pnat
localized "infix (name := rat.mk) ` /. `:70 := rat.mk" in rat
theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d :=
by change n /. d with dite _ _ _; simp [ne_of_gt h]
theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl
@[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl
@[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 :=
begin
cases n with n npos,
simp only [mk_pnat, int.nat_abs_zero, nat.div_self npos, nat.gcd_zero_left, int.zero_div],
refl
end
@[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 :=
by by_cases n = 0; simp [*, mk_nat]
@[simp] theorem zero_mk (n) : 0 /. n = 0 :=
by cases n; simp [mk]
private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a :=
int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b
@[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 :=
begin
refine ⟨λ h, _, by { rintro rfl, simp }⟩,
have : ∀ {a b}, mk_pnat a b = 0 → a = 0,
{ rintro a ⟨b, h⟩ e,
injection e with e,
apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e },
cases b with b; simp only [mk, mk_nat, int.of_nat_eq_coe, dite_eq_left_iff] at h,
{ simp only [mt (congr_arg int.of_nat) b0, not_false_iff, forall_true_left] at h,
exact this h },
{ apply neg_injective, simp [this h] }
end
theorem mk_ne_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b ≠ 0 ↔ a ≠ 0 :=
(mk_eq_zero b0).not
theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0),
a /. b = c /. d ↔ a * d = c * b :=
suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b,
begin
intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hb],
all_goals
{ cases d with d d; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hd],
all_goals { rw this, try {refl} } },
{ change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b,
constructor; intro h; apply neg_injective; simpa [left_distrib, neg_add_eq_iff_eq_add,
eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h },
{ change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ,
constructor; intro h; apply neg_injective; simpa [left_distrib, eq_comm] using h },
{ change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ,
simp [left_distrib, sub_eq_add_neg], cc }
end,
begin
intros, simp [mk_pnat], constructor; intro h,
{ cases h with ha hb,
have ha,
{ have dv := @gcd_abs_dvd_left,
have := int.eq_mul_of_div_eq_right dv ha,
rw ← int.mul_div_assoc _ dv at this,
exact int.eq_mul_of_div_eq_left (dv.mul_left _) this.symm },
have hb,
{ have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b,
have := nat.eq_mul_of_div_eq_right dv hb,
rw ← nat.mul_div_assoc _ dv at this,
exact nat.eq_mul_of_div_eq_left (dv.mul_left _) this.symm },
have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0,
{ refine int.coe_nat_ne_zero.2 (ne_of_gt _),
apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption },
apply mul_right_cancel₀ m0,
simpa [mul_comm, mul_left_comm] using
congr (congr_arg (*) ha.symm) (congr_arg coe hb) },
{ suffices : ∀ a c, a * d = c * b →
a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d,
{ cases this a.nat_abs c.nat_abs
(by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂,
have hs := congr_arg int.sign h,
simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb),
int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs,
conv in a { rw ← int.sign_mul_nat_abs a },
conv in c { rw ← int.sign_mul_nat_abs c },
rw [int.mul_div_assoc, int.mul_div_assoc],
exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩,
all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } },
intros a c h,
suffices bd : b / a.gcd b = d / c.gcd d,
{ refine ⟨_, bd⟩,
apply nat.eq_of_mul_eq_mul_left hb,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd,
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] },
suffices : ∀ {a c : ℕ} (b>0) (d>0),
a * d = c * b → b / a.gcd b ≤ d / c.gcd d,
{ exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) },
intros a c b hb d hd h,
have gb0 := nat.gcd_pos_of_pos_right a hb,
have gd0 := nat.gcd_pos_of_pos_right c hd,
apply nat.le_of_dvd,
apply (nat.le_div_iff_mul_le gd0).2,
simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _),
apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left,
refine ⟨c / c.gcd d, _⟩,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)],
apply congr_arg (/ c.gcd d),
rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] }
end
@[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) :
(a * c) /. (b * c) = a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp },
apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc]
end
@[simp] theorem num_denom : ∀ {a : ℚ}, a.num /. a.denom = a
| ⟨n, d, h, (c:_=1)⟩ := show mk_nat n d = _,
by simp [mk_nat, ne_of_gt h, mk_pnat, c]
theorem num_denom' {n d h c} : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom.symm
theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom'
/-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational
numbers of the form `n /. d` with `0 < d` and coprime `n`, `d`. -/
@[elab_as_eliminator] def {u} num_denom_cases_on {C : ℚ → Sort u}
: ∀ (a : ℚ) (H : ∀ n d, 0 < d → (int.nat_abs n).coprime d → C (n /. d)), C a
| ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c
/-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational
numbers of the form `n /. d` with `d ≠ 0`. -/
@[elab_as_eliminator] def {u} num_denom_cases_on' {C : ℚ → Sort u}
(a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a :=
num_denom_cases_on a $ λ n d h c, H n d h.ne'
theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a :=
begin
cases e : a /. b with n d h c,
rw [rat.num_denom', rat.mk_eq b0
(ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $
c.dvd_of_dvd_mul_right _),
have := congr_arg int.nat_abs e,
simp only [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this]
end
theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b :=
begin
by_cases b0 : b = 0, {simp [b0]},
cases e : a /. b with n d h c,
rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _),
rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp
end
/-- Addition of rational numbers. Use `(+)` instead. -/
protected def add : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_add ℚ := ⟨rat.add⟩
theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ)
(fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂},
f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂)
(f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0)
(a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0)
(H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d),
f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) :
f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d :=
begin
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc,
rw fv,
have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁),
have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂),
exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc))
end
@[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b + c /. d = (a * d + c * b) /. (b * d) :=
begin
apply lift_binop_eq rat.add; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
calc (n₁ * d₂ + n₂ * d₁) * (b * d) =
(n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm]
... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂]
... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm]
end
/-- Negation of rational numbers. Use `-r` instead. -/
protected def neg (r : ℚ) : ℚ :=
⟨-r.num, r.denom, r.pos, by simp [r.cop]⟩
instance : has_neg ℚ := ⟨rat.neg⟩
@[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
show rat.mk' _ _ _ _ = _, rw num_denom',
have d0 := ne_of_gt (int.coe_nat_lt.2 h₁),
apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha,
simp only [neg_mul, congr_arg has_neg.neg h₁]
end
@[simp] lemma mk_neg_denom (n d : ℤ) : n /. -d = -n /. d :=
begin
by_cases hd : d = 0;
simp [rat.mk_eq, hd]
end
/-- Multiplication of rational numbers. Use `(*)` instead. -/
protected def mul : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_mul ℚ := ⟨rat.mul⟩
@[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
(a /. b) * (c /. d) = (a * c) /. (b * d) :=
begin
apply lift_binop_eq rat.mul; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
cc
end
/-- Inverse rational number. Use `r⁻¹` instead. -/
protected def inv : ℚ → ℚ
| ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩
| ⟨0, d, h, c⟩ := 0
| ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩
instance : has_inv ℚ := ⟨rat.inv⟩
instance : has_div ℚ := ⟨λ a b, a * b⁻¹⟩
@[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a :=
begin
by_cases a0 : a = 0, { subst a0, simp, refl },
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha,
refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _,
{ cases n with n; [cases n with n, skip],
{ refl },
{ change int.of_nat n.succ with (n+1:ℕ),
unfold rat.inv, rw num_denom' },
{ unfold rat.inv, rw num_denom', refl } },
have n0 : n ≠ 0,
{ rintro rfl,
rw [rat.zero_mk, mk_eq_zero b0] at ha,
exact a0 ha },
have d0 := ne_of_gt (int.coe_nat_lt.2 h),
have ha := (mk_eq b0 d0).1 ha,
apply (mk_eq n0 a0).2,
cc
end
variables (a b c : ℚ)
protected theorem add_zero : a + 0 = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem zero_add : 0 + a = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem add_comm : a + b = b + a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂]; cc
protected theorem add_assoc : a + b + c = a + (b + c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm, add_assoc]
protected theorem add_left_neg : -a + a = 0 :=
num_denom_cases_on' a $ λ n d h,
by simp [h]
@[simp] lemma mk_zero_one : 0 /. 1 = 0 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
@[simp] lemma mk_one_one : 1 /. 1 = 1 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
@[simp] lemma mk_neg_one_one : (-1) /. 1 = -1 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
protected theorem mul_one : a * 1 = a :=
num_denom_cases_on' a $ λ n d h,
by { rw ← mk_one_one, simp [h, -mk_one_one] }
protected theorem one_mul : 1 * a = a :=
num_denom_cases_on' a $ λ n d h,
by { rw ← mk_one_one, simp [h, -mk_one_one] }
protected theorem mul_comm : a * b = b * a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂, mul_comm]
protected theorem mul_assoc : a * b * c = a * (b * c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm]
protected theorem add_mul : (a + b) * c = a * c + b * c :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero];
refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _;
simp [mul_add, mul_comm, mul_assoc, mul_left_comm]
protected theorem mul_add : a * (b + c) = a * b + a * c :=
by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a]
protected theorem zero_ne_one : 0 ≠ (1:ℚ) :=
by { rw [ne_comm, ← mk_one_one, mk_ne_zero one_ne_zero], exact one_ne_zero }
protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 :=
num_denom_cases_on' a $ λ n d h a0,
have n0 : n ≠ 0, from mt (by { rintro rfl, simp }) a0,
by simpa [h, n0, mul_comm] using @div_mk_div_cancel_left 1 1 _ n0
protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 :=
eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h)
instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance
/-! At this point in the import hierarchy we have not defined the `field` typeclass.
Instead we'll instantiate `comm_ring` and `comm_group_with_zero` at this point.
The `rat.field` instance and any field-specific lemmas can be found in `data.rat.basic`.
-/
instance : comm_ring ℚ :=
{ zero := 0,
add := (+),
neg := has_neg.neg,
one := 1,
mul := (*),
zero_add := rat.zero_add,
add_zero := rat.add_zero,
add_comm := rat.add_comm,
add_assoc := rat.add_assoc,
add_left_neg := rat.add_left_neg,
mul_one := rat.mul_one,
one_mul := rat.one_mul,
mul_comm := rat.mul_comm,
mul_assoc := rat.mul_assoc,
left_distrib := rat.mul_add,
right_distrib := rat.add_mul,
nat_cast := λ n, rat.of_int n,
nat_cast_zero := rfl,
nat_cast_succ := λ n, show of_int _ = of_int _ + 1,
by simp only [of_int_eq_mk, add_def one_ne_zero one_ne_zero, ← mk_one_one]; simp }
instance : comm_group_with_zero ℚ :=
{ zero := 0,
one := 1,
mul := (*),
inv := has_inv.inv,
div := (/),
exists_pair_ne := ⟨0, 1, rat.zero_ne_one⟩,
inv_zero := rfl,
mul_inv_cancel := rat.mul_inv_cancel,
mul_zero := mul_zero,
zero_mul := zero_mul,
.. rat.comm_ring }
instance : is_domain ℚ :=
{ .. rat.comm_group_with_zero,
.. (infer_instance : no_zero_divisors ℚ) }
/- Extra instances to short-circuit type class resolution -/
-- TODO(Mario): this instance slows down data.real.basic
instance : nontrivial ℚ := by apply_instance
--instance : ring ℚ := by apply_instance
instance : comm_semiring ℚ := by apply_instance
instance : semiring ℚ := by apply_instance
instance : add_comm_group ℚ := by apply_instance
instance : add_group ℚ := by apply_instance
instance : add_comm_monoid ℚ := by apply_instance
instance : add_monoid ℚ := by apply_instance
instance : add_left_cancel_semigroup ℚ := by apply_instance
instance : add_right_cancel_semigroup ℚ := by apply_instance
instance : add_comm_semigroup ℚ := by apply_instance
instance : add_semigroup ℚ := by apply_instance
instance : comm_monoid ℚ := by apply_instance
instance : monoid ℚ := by apply_instance
instance : comm_semigroup ℚ := by apply_instance
instance : semigroup ℚ := by apply_instance
theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b - c /. d = (a * d - c * b) /. (b * d) :=
by simp [b0, d0, sub_eq_add_neg]
@[simp] lemma denom_neg_eq_denom (q : ℚ) : (-q).denom = q.denom := rfl
@[simp] lemma num_neg_eq_neg_num (q : ℚ) : (-q).num = -(q.num) := rfl
@[simp] lemma num_zero : rat.num 0 = 0 := rfl
@[simp] lemma denom_zero : rat.denom 0 = 1 := rfl
lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 :=
have q = q.num /. q.denom, from num_denom.symm,
by simpa [hq]
lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 :=
⟨λ _, by simp *, zero_of_num_zero⟩
lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 :=
assume : q.num = 0,
h $ zero_of_num_zero this
@[simp] lemma num_one : (1 : ℚ).num = 1 := rfl
@[simp] lemma denom_one : (1 : ℚ).denom = 1 := rfl
lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 :=
ne_of_gt q.pos
lemma eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.denom = q.num * p.denom :=
begin
conv { to_lhs, rw [← @num_denom p, ← @num_denom q] },
apply rat.mk_eq; rw [← nat.cast_zero, ne, int.coe_nat_eq_coe_nat_iff]; apply denom_ne_zero,
end
lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 :=
assume : n = 0,
hq $ by simpa [this] using hqnd
lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 :=
assume : d = 0,
hq $ by simpa [this] using hqnd
lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 :=
(mk_ne_zero hd).mpr h
lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) :=
have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa,
have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa,
suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom),
by simpa using this,
by simp [mul_def hq' hr', -num_denom]
lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) :=
if hr : r.num = 0 then
have hr' : r = 0, from zero_of_num_zero hr,
by simp *
else
calc q / r = q * r⁻¹ : div_eq_mul_inv q r
... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by simp
... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def
... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr
lemma num_denom_mk {q : ℚ} {n d : ℤ} (hd : d ≠ 0) (qdf : q = n /. d) :
∃ c : ℤ, n = c * q.num ∧ d = c * q.denom :=
begin
obtain rfl|hn := eq_or_ne n 0,
{ simp [qdf] },
have : q.num * d = n * ↑(q.denom),
{ refine (rat.mk_eq _ hd).mp _,
{ exact int.coe_nat_ne_zero.mpr (rat.denom_ne_zero _) },
{ rwa [num_denom] } },
have hqdn : q.num ∣ n,
{ rw qdf, exact rat.num_dvd _ hd },
refine ⟨n / q.num, _, _⟩,
{ rw int.div_mul_cancel hqdn },
{ refine int.eq_mul_div_of_mul_eq_mul_of_dvd_left _ hqdn this,
rw qdf,
exact rat.num_ne_zero_of_ne_zero ((mk_ne_zero hd).mpr hn) }
end
theorem mk_pnat_num (n : ℤ) (d : ℕ+) :
(mk_pnat n d).num = n / nat.gcd n.nat_abs d :=
by cases d; refl
theorem mk_pnat_denom (n : ℤ) (d : ℕ+) :
(mk_pnat n d).denom = d / nat.gcd n.nat_abs d :=
by cases d; refl
lemma num_mk (n d : ℤ) :
(n /. d).num = d.sign * n / n.gcd d :=
begin
rcases d with ((_ | _) | _);
simp [rat.mk, mk_nat, mk_pnat, nat.succ_pnat, int.sign, int.gcd,
-nat.cast_succ, -int.coe_nat_succ, int.zero_div]
end
lemma denom_mk (n d : ℤ) :
(n /. d).denom = if d = 0 then 1 else d.nat_abs / n.gcd d :=
begin
rcases d with ((_ | _) | _);
simp [rat.mk, mk_nat, mk_pnat, nat.succ_pnat, int.sign, int.gcd,
-nat.cast_succ, -int.coe_nat_succ]
end
theorem mk_pnat_denom_dvd (n : ℤ) (d : ℕ+) :
(mk_pnat n d).denom ∣ d.1 :=
begin
rw mk_pnat_denom,
apply nat.div_dvd_of_dvd,
apply nat.gcd_dvd_right
end
theorem add_denom_dvd (q₁ q₂ : ℚ) : (q₁ + q₂).denom ∣ q₁.denom * q₂.denom :=
by { cases q₁, cases q₂, apply mk_pnat_denom_dvd }
theorem mul_denom_dvd (q₁ q₂ : ℚ) : (q₁ * q₂).denom ∣ q₁.denom * q₂.denom :=
by { cases q₁, cases q₂, apply mk_pnat_denom_dvd }
theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num =
(q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) :=
by cases q₁; cases q₂; refl
theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom =
(q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) :=
by cases q₁; cases q₂; refl
theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num :=
by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom :=
by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
lemma add_num_denom (q r : ℚ) : q + r =
((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) :=
have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3,
have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3,
by conv_lhs { rw [←@num_denom q, ←@num_denom r, rat.add_def hqd hrd] };
simp [mul_comm]
section casts
protected lemma add_mk (a b c : ℤ) : (a + b) /. c = a /. c + b /. c :=
if h : c = 0 then by simp [h] else
by { rw [add_def h h, mk_eq h (mul_ne_zero h h)], simp [add_mul, mul_assoc] }
theorem coe_int_eq_mk : ∀ z : ℤ, ↑z = z /. 1
| (n : ℕ) := of_int_eq_mk _
| -[1+ n] := show -(of_int _) = _, by simp [of_int_eq_mk, neg_def, int.neg_succ_of_nat_coe]
theorem mk_eq_div (n d : ℤ) : n /. d = ((n : ℚ) / d) :=
begin
by_cases d0 : d = 0, {simp [d0, div_zero]},
simp [division_def, coe_int_eq_mk, mul_def one_ne_zero d0]
end
lemma mk_mul_mk_cancel {x : ℤ} (hx : x ≠ 0) (n d : ℤ) : (n /. x) * (x /. d) = n /. d :=
begin
by_cases hd : d = 0,
{ rw hd,
simp},
rw [mul_def hx hd, mul_comm x, div_mk_div_cancel_left hx],
end
lemma mk_div_mk_cancel_left {x : ℤ} (hx : x ≠ 0) (n d : ℤ) : (n /. x) / (d /. x) = n /. d :=
by rw [div_eq_mul_inv, inv_def, mk_mul_mk_cancel hx]
lemma mk_div_mk_cancel_right {x : ℤ} (hx : x ≠ 0) (n d : ℤ) : (x /. n) / (x /. d) = d /. n :=
by rw [div_eq_mul_inv, inv_def, mul_comm, mk_mul_mk_cancel hx]
lemma coe_int_div_eq_mk {n d : ℤ} : (n : ℚ) / ↑d = n /. d :=
begin
repeat {rw coe_int_eq_mk},
exact mk_div_mk_cancel_left one_ne_zero n d,
end
@[simp]
theorem num_div_denom (r : ℚ) : (r.num / r.denom : ℚ) = r :=
by rw [← int.cast_coe_nat, ← mk_eq_div, num_denom]
lemma exists_eq_mul_div_num_and_eq_mul_div_denom (n : ℤ) {d : ℤ} (d_ne_zero : d ≠ 0) :
∃ (c : ℤ), n = c * ((n : ℚ) / d).num ∧ (d : ℤ) = c * ((n : ℚ) / d).denom :=
begin
have : ((n : ℚ) / d) = rat.mk n d, by rw [←rat.mk_eq_div],
exact rat.num_denom_mk d_ne_zero this
end
lemma mul_num_denom' (q r : ℚ) :
(q * r).num * q.denom * r.denom = q.num * r.num * (q * r).denom :=
begin
let s := (q.num * r.num) /. (q.denom * r.denom : ℤ),
have hs : (q.denom * r.denom : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.mpr (mul_pos q.pos r.pos),
obtain ⟨c, ⟨c_mul_num, c_mul_denom⟩⟩ :=
exists_eq_mul_div_num_and_eq_mul_div_denom (q.num * r.num) hs,
rw [c_mul_num, mul_assoc, mul_comm],
nth_rewrite 0 c_mul_denom,
repeat {rw mul_assoc},
apply mul_eq_mul_left_iff.2,
rw or_iff_not_imp_right,
intro c_pos,
have h : _ = s := @mul_def q.num q.denom r.num r.denom
(int.coe_nat_ne_zero_iff_pos.mpr q.pos)
(int.coe_nat_ne_zero_iff_pos.mpr r.pos),
rw [num_denom, num_denom] at h,
rw h,
rw mul_comm,
apply rat.eq_iff_mul_eq_mul.mp,
rw ←mk_eq_div,
end
lemma add_num_denom' (q r : ℚ) :
(q + r).num * q.denom * r.denom = (q.num * r.denom + r.num * q.denom) * (q + r).denom :=
begin
let s := mk (q.num * r.denom + r.num * q.denom) (q.denom * r.denom : ℤ),
have hs : (q.denom * r.denom : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.mpr (mul_pos q.pos r.pos),
obtain ⟨c, ⟨c_mul_num, c_mul_denom⟩⟩ := exists_eq_mul_div_num_and_eq_mul_div_denom
(q.num * r.denom + r.num * q.denom) hs,
rw [c_mul_num, mul_assoc, mul_comm],
nth_rewrite 0 c_mul_denom,
repeat {rw mul_assoc},
apply mul_eq_mul_left_iff.2,
rw or_iff_not_imp_right,
intro c_pos,
have h : _ = s := @add_def q.num q.denom r.num r.denom
(int.coe_nat_ne_zero_iff_pos.mpr q.pos)
(int.coe_nat_ne_zero_iff_pos.mpr r.pos),
rw [num_denom, num_denom] at h,
rw h,
rw mul_comm,
apply rat.eq_iff_mul_eq_mul.mp,
rw ←mk_eq_div,
end
lemma substr_num_denom' (q r : ℚ) :
(q - r).num * q.denom * r.denom = (q.num * r.denom - r.num * q.denom) * (q - r).denom :=
by rw [sub_eq_add_neg, sub_eq_add_neg, ←neg_mul, ←num_neg_eq_neg_num, ←denom_neg_eq_denom r,
add_num_denom' q (-r)]
theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z :=
(coe_int_eq_mk z).trans (of_int_eq_mk z).symm
@[simp, norm_cast] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n :=
by rw coe_int_eq_of_int; refl
@[simp, norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 :=
by rw coe_int_eq_of_int; refl
lemma coe_int_num_of_denom_eq_one {q : ℚ} (hq : q.denom = 1) : ↑(q.num) = q :=
by { conv_rhs { rw [←(@num_denom q), hq] }, rw [coe_int_eq_mk], refl }
lemma denom_eq_one_iff (r : ℚ) : r.denom = 1 ↔ ↑r.num = r :=
⟨rat.coe_int_num_of_denom_eq_one, λ h, h ▸ rat.coe_int_denom r.num⟩
instance : can_lift ℚ ℤ :=
⟨coe, λ q, q.denom = 1, λ q hq, ⟨q.num, coe_int_num_of_denom_eq_one hq⟩⟩
theorem coe_nat_eq_mk (n : ℕ) : ↑n = n /. 1 :=
by rw [← int.cast_coe_nat, coe_int_eq_mk]
@[simp, norm_cast] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n :=
by rw [← int.cast_coe_nat, coe_int_num]
@[simp, norm_cast] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 :=
by rw [← int.cast_coe_nat, coe_int_denom]
-- Will be subsumed by `int.coe_inj` after we have defined
-- `linear_ordered_field ℚ` (which implies characteristic zero).
lemma coe_int_inj (m n : ℤ) : (m : ℚ) = n ↔ m = n :=
⟨λ h, by simpa using congr_arg num h, congr_arg _⟩
end casts
lemma inv_def' {q : ℚ} : q⁻¹ = (q.denom : ℚ) / q.num :=
by { conv_lhs { rw ←(@num_denom q) }, cases q, simp [div_num_denom] }
protected lemma inv_neg (q : ℚ) : (-q)⁻¹ = -(q⁻¹) :=
begin
simp only [inv_def'],
cases eq_or_ne (q.num : ℚ) 0 with hq hq;
simp [div_eq_iff, hq]
end
@[simp] lemma mul_denom_eq_num {q : ℚ} : q * q.denom = q.num :=
begin
suffices : mk (q.num) ↑(q.denom) * mk ↑(q.denom) 1 = mk (q.num) 1, by
{ conv { for q [1] { rw ←(@num_denom q) }}, rwa [coe_int_eq_mk, coe_nat_eq_mk] },
have : (q.denom : ℤ) ≠ 0, from ne_of_gt (by exact_mod_cast q.pos),
rw [(rat.mul_def this one_ne_zero), (mul_comm (q.denom : ℤ) 1), (div_mk_div_cancel_left this)]
end
lemma denom_div_cast_eq_one_iff (m n : ℤ) (hn : n ≠ 0) :
((m : ℚ) / n).denom = 1 ↔ n ∣ m :=
begin
replace hn : (n:ℚ) ≠ 0, by rwa [ne.def, ← int.cast_zero, coe_int_inj],
split,
{ intro h,
lift ((m : ℚ) / n) to ℤ using h with k hk,
use k,
rwa [eq_div_iff_mul_eq hn, ← int.cast_mul, mul_comm, eq_comm, coe_int_inj] at hk },
{ rintros ⟨d, rfl⟩,
rw [int.cast_mul, mul_comm, mul_div_cancel _ hn, rat.coe_int_denom] }
end
lemma num_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) :
(a / b : ℚ).num = a :=
begin
lift b to ℕ using le_of_lt hb0,
norm_cast at hb0 h,
rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_num, pnat.mk_coe, h.gcd_eq_one,
int.coe_nat_one, int.div_one]
end
lemma denom_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) :
((a / b : ℚ).denom : ℤ) = b :=
begin
lift b to ℕ using le_of_lt hb0,
norm_cast at hb0 h,
rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_denom, pnat.mk_coe, h.gcd_eq_one,
nat.div_one]
end
lemma div_int_inj {a b c d : ℤ} (hb0 : 0 < b) (hd0 : 0 < d)
(h1 : nat.coprime a.nat_abs b.nat_abs) (h2 : nat.coprime c.nat_abs d.nat_abs)
(h : (a : ℚ) / b = (c : ℚ) / d) : a = c ∧ b = d :=
begin
apply and.intro,
{ rw [← (num_div_eq_of_coprime hb0 h1), h, num_div_eq_of_coprime hd0 h2] },
{ rw [← (denom_div_eq_of_coprime hb0 h1), h, denom_div_eq_of_coprime hd0 h2] }
end
@[norm_cast] lemma coe_int_div_self (n : ℤ) : ((n / n : ℤ) : ℚ) = n / n :=
begin
by_cases hn : n = 0,
{ subst hn, simp only [int.cast_zero, int.zero_div, zero_div] },
{ have : (n : ℚ) ≠ 0, { rwa ← coe_int_inj at hn },
simp only [int.div_self hn, int.cast_one, ne.def, not_false_iff, div_self this] }
end
@[norm_cast] lemma coe_nat_div_self (n : ℕ) : ((n / n : ℕ) : ℚ) = n / n :=
coe_int_div_self n
lemma coe_int_div (a b : ℤ) (h : b ∣ a) : ((a / b : ℤ) : ℚ) = a / b :=
begin
rcases h with ⟨c, rfl⟩,
simp only [mul_comm b, int.mul_div_assoc c (dvd_refl b), int.cast_mul, mul_div_assoc,
coe_int_div_self]
end
lemma coe_nat_div (a b : ℕ) (h : b ∣ a) : ((a / b : ℕ) : ℚ) = a / b :=
begin
rcases h with ⟨c, rfl⟩,
simp only [mul_comm b, nat.mul_div_assoc c (dvd_refl b), nat.cast_mul, mul_div_assoc,
coe_nat_div_self]
end
lemma inv_coe_int_num_of_pos {a : ℤ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 :=
begin
rw [rat.inv_def', rat.coe_int_num, rat.coe_int_denom, nat.cast_one, ←int.cast_one],
apply num_div_eq_of_coprime ha0,
rw int.nat_abs_one,
exact nat.coprime_one_left _,
end
lemma inv_coe_nat_num_of_pos {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 :=
inv_coe_int_num_of_pos (by exact_mod_cast ha0 : 0 < (a : ℤ))
lemma inv_coe_int_denom_of_pos {a : ℤ} (ha0 : 0 < a) : ((a : ℚ)⁻¹.denom : ℤ) = a :=
begin
rw [rat.inv_def', rat.coe_int_num, rat.coe_int_denom, nat.cast_one, ←int.cast_one],
apply denom_div_eq_of_coprime ha0,
rw int.nat_abs_one,
exact nat.coprime_one_left _,
end
lemma inv_coe_nat_denom_of_pos {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.denom = a :=
begin
rw [← int.coe_nat_eq_coe_nat_iff, ← int.cast_coe_nat a, inv_coe_int_denom_of_pos],
rwa [← nat.cast_zero, nat.cast_lt]
end
@[simp] lemma inv_coe_int_num (a : ℤ) : (a : ℚ)⁻¹.num = int.sign a :=
begin
induction a using int.induction_on;
simp [←int.neg_succ_of_nat_coe', int.neg_succ_of_nat_coe, -neg_add_rev, rat.inv_neg,
int.coe_nat_add_one_out, -nat.cast_succ, inv_coe_nat_num_of_pos, -int.cast_neg_succ_of_nat,
@eq_comm ℤ 1, int.sign_eq_one_of_pos]
end
@[simp] lemma inv_coe_nat_num (a : ℕ) : (a : ℚ)⁻¹.num = int.sign a :=
inv_coe_int_num a
@[simp] lemma inv_coe_int_denom (a : ℤ) : (a : ℚ)⁻¹.denom = if a = 0 then 1 else a.nat_abs :=
begin
induction a using int.induction_on;
simp [←int.neg_succ_of_nat_coe', int.neg_succ_of_nat_coe, -neg_add_rev, rat.inv_neg,
int.coe_nat_add_one_out, -nat.cast_succ, inv_coe_nat_denom_of_pos,
-int.cast_neg_succ_of_nat]
end
@[simp] lemma inv_coe_nat_denom (a : ℕ) : (a : ℚ)⁻¹.denom = if a = 0 then 1 else a :=
by simpa using inv_coe_int_denom a
protected lemma «forall» {p : ℚ → Prop} : (∀ r, p r) ↔ ∀ a b : ℤ, p (a / b) :=
⟨λ h _ _, h _,
λ h q, (show q = q.num / q.denom, from by simp [rat.div_num_denom]).symm ▸ (h q.1 q.2)⟩
protected lemma «exists» {p : ℚ → Prop} : (∃ r, p r) ↔ ∃ a b : ℤ, p (a / b) :=
⟨λ ⟨r, hr⟩, ⟨r.num, r.denom, by rwa [← mk_eq_div, num_denom]⟩, λ ⟨a, b, h⟩, ⟨_, h⟩⟩
/-!
### Denominator as `ℕ+`
-/
section pnat_denom
/-- Denominator as `ℕ+`. -/
def pnat_denom (x : ℚ) : ℕ+ := ⟨x.denom, x.pos⟩
@[simp] lemma coe_pnat_denom (x : ℚ) : (x.pnat_denom : ℕ) = x.denom := rfl
@[simp] lemma mk_pnat_pnat_denom_eq (x : ℚ) : mk_pnat x.num x.pnat_denom = x :=
by rw [pnat_denom, mk_pnat_eq, num_denom]
lemma pnat_denom_eq_iff_denom_eq {x : ℚ} {n : ℕ+} : x.pnat_denom = n ↔ x.denom = ↑n :=
subtype.ext_iff
@[simp] lemma pnat_denom_one : (1 : ℚ).pnat_denom = 1 := rfl
@[simp] lemma pnat_denom_zero : (0 : ℚ).pnat_denom = 1 := rfl
end pnat_denom
end rat
|
e4300d7d39f21eba277a00af92bf3e18c6fae2e4 | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Lean/Parser/Module.lean | b7afc0e118d6bfe6a84ed0ee6dc6e7e42b5e1540 | [
"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 | 5,976 | 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, Sebastian Ullrich
-/
import Lean.Message
import Lean.Parser.Command
namespace Lean
namespace Parser
namespace Module
def «prelude» := leading_parser "prelude"
def «import» := leading_parser "import " >> optional "runtime" >> ident
def header := leading_parser optional («prelude» >> ppLine) >> many («import» >> ppLine) >> ppLine
/--
Parser for a Lean module. We never actually run this parser but instead use the imperative definitions below that
return the same syntax tree structure, but add error recovery. Still, it is helpful to have a `Parser` definition
for it in order to auto-generate helpers such as the pretty printer. -/
@[run_builtin_parser_attribute_hooks]
def module := leading_parser header >> many (commandParser >> ppLine >> ppLine)
def updateTokens (tokens : TokenTable) : TokenTable :=
match addParserTokens tokens header.info with
| Except.ok tables => tables
| Except.error _ => unreachable!
end Module
structure ModuleParserState where
pos : String.Pos := 0
recovering : Bool := false
deriving Inhabited
private def mkErrorMessage (c : InputContext) (pos : String.Pos) (errorMsg : String) : Message :=
let pos := c.fileMap.toPosition pos
{ fileName := c.fileName, pos := pos, data := errorMsg }
def parseHeader (inputCtx : InputContext) : IO (Syntax × ModuleParserState × MessageLog) := do
let dummyEnv ← mkEmptyEnvironment
let p := andthenFn whitespace Module.header.fn
let tokens := Module.updateTokens (getTokenTable dummyEnv)
let s := p.run inputCtx { env := dummyEnv, options := {} } tokens (mkParserState inputCtx.input)
let stx := s.stxStack.back
match s.errorMsg with
| some errorMsg =>
let msg := mkErrorMessage inputCtx s.pos (toString errorMsg)
pure (stx, { pos := s.pos, recovering := true }, { : MessageLog }.add msg)
| none =>
pure (stx, { pos := s.pos }, {})
private def mkEOI (pos : String.Pos) : Syntax :=
let atom := mkAtom (SourceInfo.original "".toSubstring pos "".toSubstring pos) ""
mkNode `Lean.Parser.Module.eoi #[atom]
def isEOI (s : Syntax) : Bool :=
s.isOfKind `Lean.Parser.Module.eoi
def isTerminalCommand (s : Syntax) : Bool :=
s.isOfKind ``Command.exit || s.isOfKind ``Command.import
private def consumeInput (inputCtx : InputContext) (pmctx : ParserModuleContext) (pos : String.Pos) : String.Pos :=
let s : ParserState := { cache := initCacheForInput inputCtx.input, pos := pos }
let s := tokenFn [] |>.run inputCtx pmctx (getTokenTable pmctx.env) s
match s.errorMsg with
| some _ => pos + ' '
| none => s.pos
def topLevelCommandParserFn : ParserFn :=
commandParser.fn
partial def parseCommand (inputCtx : InputContext) (pmctx : ParserModuleContext) (mps : ModuleParserState) (messages : MessageLog) : Syntax × ModuleParserState × MessageLog := Id.run do
let mut pos := mps.pos
let mut recovering := mps.recovering
let mut messages := messages
let mut stx := Syntax.missing -- will always be assigned below
repeat
if inputCtx.input.atEnd pos then
stx := mkEOI pos
break
let pos' := pos
let p := andthenFn whitespace topLevelCommandParserFn
let s := p.run inputCtx pmctx (getTokenTable pmctx.env) { cache := initCacheForInput inputCtx.input, pos }
pos := s.pos
if recovering && !s.stxStack.isEmpty && s.stxStack.back.isAntiquot then
-- top-level antiquotation during recovery is most likely remnant from unfinished quotation, ignore
continue
match s.errorMsg with
| none =>
stx := s.stxStack.back
recovering := false
break
| some errorMsg =>
-- advance at least one token to prevent infinite loops
if pos == pos' then
pos := consumeInput inputCtx pmctx pos
/- We ignore commands where `getPos?` is none. This happens only on commands that have a prefix comprised of optional elements.
For example, unification hints start with `optional («scoped» <|> «local»)`.
We claim a syntactically incorrect command containing no token or identifier is irrelevant for intellisense and should be ignored. -/
let ignore := s.stxStack.isEmpty || s.stxStack.back.getPos?.isNone
unless recovering && ignore do
messages := messages.add <| mkErrorMessage inputCtx s.pos (toString errorMsg)
recovering := true
if ignore then
continue
else
stx := s.stxStack.back
break
return (stx, { pos, recovering }, messages)
-- only useful for testing since most Lean files cannot be parsed without elaboration
partial def testParseModuleAux (env : Environment) (inputCtx : InputContext) (s : ModuleParserState) (msgs : MessageLog) (stxs : Array Syntax) : IO (Array Syntax) :=
let rec parse (state : ModuleParserState) (msgs : MessageLog) (stxs : Array Syntax) :=
match parseCommand inputCtx { env := env, options := {} } state msgs with
| (stx, state, msgs) =>
if isEOI stx then
if msgs.isEmpty then
pure stxs
else do
msgs.forM fun msg => msg.toString >>= IO.println
throw (IO.userError "failed to parse file")
else
parse state msgs (stxs.push stx)
parse s msgs stxs
def testParseModule (env : Environment) (fname contents : String) : IO (TSyntax ``Parser.Module.module) := do
let inputCtx := mkInputContext contents fname
let (header, state, messages) ← parseHeader inputCtx
let cmds ← testParseModuleAux env inputCtx state messages #[]
let stx := mkNode `Lean.Parser.Module.module #[header, mkListNode cmds]
pure ⟨stx.raw.updateLeading⟩
def testParseFile (env : Environment) (fname : System.FilePath) : IO (TSyntax ``Parser.Module.module) := do
let contents ← IO.FS.readFile fname
testParseModule env fname.toString contents
end Parser
end Lean
|
724053058d14c5c9ce04fe317138e4ffc7b03cda | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/algebra/module/basic.lean | a44a0898d4ef1b43a4f8b68a49c288ed815be83e | [
"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 | 23,438 | lean | /-
Copyright (c) 2015 Nathaniel Thomas. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro
-/
import group_theory.group_action
import tactic.nth_rewrite
import algebra.group.hom
/-!
# Modules over a ring
In this file we define
* `semimodule R M` : an additive commutative monoid `M` is a `semimodule` over a
`semiring` `R` if for `r : R` and `x : M` their "scalar multiplication `r • x : M` is defined, and
the operation `•` satisfies some natural associativity and distributivity axioms similar to those
on a ring.
* `module R M` : same as `semimodule R M` but assumes that `R` is a `ring` and `M` is an
additive commutative group.
* `vector_space k M` : same as `semimodule k M` and `module k M` but assumes that `k` is a `field`
and `M` is an additive commutative group.
* `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`semimodule`s.
* `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map.
## Implementation notes
* `vector_space` and `module` are abbreviations for `semimodule R M`.
## Tags
semimodule, module, vector space, linear map
-/
open function
open_locale big_operators
universes u u' v w x y z
variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y}
{ι : Type z}
/-- A semimodule is a generalization of vector spaces to a scalar semiring.
It consists of a scalar semiring `R` and an additive monoid of "vectors" `M`,
connected by a "scalar multiplication" operation `r • x : M`
(where `r : R` and `x : M`) with some natural associativity and
distributivity axioms similar to those on a ring. -/
@[protect_proj] class semimodule (R : Type u) (M : Type v) [semiring R]
[add_comm_monoid M] extends distrib_mul_action R M :=
(add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x)
(zero_smul : ∀x : M, (0 : R) • x = 0)
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [semimodule R M] (r s : R) (x y : M)
theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x
variables (R)
@[simp] theorem zero_smul : (0 : R) • x = 0 := semimodule.zero_smul x
theorem two_smul : (2 : R) • x = x + x := by rw [bit0, add_smul, one_smul]
/-- Pullback a `semimodule` structure along an injective additive monoid homomorphism. -/
protected def function.injective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M₂ →+ M)
(hf : injective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) :
semimodule R M₂ :=
{ smul := (•),
add_smul := λ c₁ c₂ x, hf $ by simp only [smul, f.map_add, add_smul],
zero_smul := λ x, hf $ by simp only [smul, zero_smul, f.map_zero],
.. hf.distrib_mul_action f smul }
/-- Pushforward a `semimodule` structure along a surjective additive monoid homomorphism. -/
protected def function.surjective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M →+ M₂)
(hf : surjective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) :
semimodule R M₂ :=
{ smul := (•),
add_smul := λ c₁ c₂ x, by { rcases hf x with ⟨x, rfl⟩,
simp only [add_smul, ← smul, ← f.map_add] },
zero_smul := λ x, by { rcases hf x with ⟨x, rfl⟩, simp only [← f.map_zero, ← smul, zero_smul] },
.. hf.distrib_mul_action f smul }
variable (M)
/-- `(•)` as an `add_monoid_hom`. -/
def smul_add_hom : R →+ M →+ M :=
{ to_fun := const_smul_hom M,
map_zero' := add_monoid_hom.ext $ λ r, by simp,
map_add' := λ x y, add_monoid_hom.ext $ λ r, by simp [add_smul] }
variables {R M}
@[simp] lemma smul_add_hom_apply (r : R) (x : M) :
smul_add_hom R M r x = r • x := rfl
lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : x = 0 :=
by rw [←one_smul R x, ←zero_eq_one, zero_smul]
lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum :=
((smul_add_hom R M).flip x).map_list_sum l
lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum :=
((smul_add_hom R M).flip x).map_multiset_sum l
lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} :
(∑ i in s, f i) • x = (∑ i in s, (f i) • x) :=
((smul_add_hom R M).flip x).map_sum f s
end add_comm_monoid
variables (R)
/-- An `add_comm_monoid` that is a `semimodule` over a `ring` carries a natural `add_comm_group` structure. -/
def semimodule.add_comm_monoid_to_add_comm_group [ring R] [add_comm_monoid M] [semimodule R M] :
add_comm_group M :=
{ neg := λ a, (-1 : R) • a,
add_left_neg := λ a, by {
nth_rewrite 1 ← one_smul _ a,
rw [← add_smul, add_left_neg, zero_smul], },
..(infer_instance : add_comm_monoid M), }
variables {R}
section add_comm_group
variables (R M) [semiring R] [add_comm_group M]
/-- A structure containing most informations as in a semimodule, except the fields `zero_smul`
and `smul_zero`. As these fields can be deduced from the other ones when `M` is an `add_comm_group`,
this provides a way to construct a semimodule structure by checking less properties, in
`semimodule.of_core`. -/
@[nolint has_inhabited_instance]
structure semimodule.core extends has_scalar R M :=
(smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y)
(add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x)
(mul_smul : ∀(r s : R) (x : M), (r * s) • x = r • s • x)
(one_smul : ∀x : M, (1 : R) • x = x)
variables {R M}
/-- Define `semimodule` without proving `zero_smul` and `smul_zero` by using an auxiliary
structure `semimodule.core`, when the underlying space is an `add_comm_group`. -/
def semimodule.of_core (H : semimodule.core R M) : semimodule R M :=
by letI := H.to_has_scalar; exact
{ zero_smul := λ x, (add_monoid_hom.mk' (λ r : R, r • x) (λ r s, H.add_smul r s x)).map_zero,
smul_zero := λ r, (add_monoid_hom.mk' ((•) r) (H.smul_add r)).map_zero,
..H }
end add_comm_group
/--
Modules are defined as an `abbreviation` for semimodules,
if the base semiring is a ring.
(A previous definition made `module` a structure
defined to be `semimodule`.)
This has as advantage that modules are completely transparent
for type class inference, which means that all instances for semimodules
are immediately picked up for modules as well.
A cosmetic disadvantage is that one can not extend modules as such,
in definitions such as `normed_space`.
The solution is to extend `semimodule` instead.
-/
library_note "module definition"
/-- A module is the same as a semimodule, except the scalar semiring is actually
a ring.
This is the traditional generalization of spaces like `ℤ^n`, which have a natural
addition operation and a way to multiply them by elements of a ring, but no multiplication
operation between vectors. -/
abbreviation module (R : Type u) (M : Type v) [ring R] [add_comm_group M] :=
semimodule R M
/--
To prove two module structures on a fixed `add_comm_group` agree,
it suffices to check the scalar multiplications agree.
-/
-- We'll later use this to show `module ℤ M` is a subsingleton.
@[ext]
lemma module_ext {R : Type*} [ring R] {M : Type*} [add_comm_group M] (P Q : module R M)
(w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) :
P = Q :=
begin
unfreezingI { rcases P with ⟨⟨⟨⟨P⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨Q⟩⟩⟩⟩ },
congr,
funext r m,
exact w r m,
all_goals { apply proof_irrel_heq },
end
section module
variables [ring R] [add_comm_group M] [module R M] (r s : R) (x y : M)
@[simp] theorem neg_smul : -r • x = - (r • x) :=
eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul])
variables (R)
theorem neg_one_smul (x : M) : (-1 : R) • x = -x := by simp
variables {R}
theorem sub_smul (r s : R) (y : M) : (r - s) • y = r • y - s • y :=
by simp [add_smul, sub_eq_add_neg]
theorem smul_eq_zero {R E : Type*} [division_ring R] [add_comm_group E] [module R E]
{c : R} {x : E} :
c • x = 0 ↔ c = 0 ∨ x = 0 :=
⟨λ h, or_iff_not_imp_left.2 $ λ hc, (units.mk0 c hc).smul_eq_zero.1 h,
λ h, h.elim (λ hc, hc.symm ▸ zero_smul R x) (λ hx, hx.symm ▸ smul_zero c)⟩
end module
/-- A semimodule over a `subsingleton` semiring is a `subsingleton`. We cannot register this
as an instance because Lean has no way to guess `R`. -/
theorem semimodule.subsingleton (R M : Type*) [semiring R] [subsingleton R] [add_comm_monoid M]
[semimodule R M] :
subsingleton M :=
⟨λ x y, by rw [← one_smul R x, ← one_smul R y, subsingleton.elim (1:R) 0, zero_smul, zero_smul]⟩
@[priority 910] -- see Note [lower instance priority]
instance semiring.to_semimodule [semiring R] : semimodule R R :=
{ smul := (*),
smul_add := mul_add,
add_smul := add_mul,
mul_smul := mul_assoc,
one_smul := one_mul,
zero_smul := zero_mul,
smul_zero := mul_zero }
@[simp] lemma smul_eq_mul [semiring R] {a a' : R} : a • a' = a * a' := rfl
/-- A ring homomorphism `f : R →+* M` defines a module structure by `r • x = f r * x`. -/
def ring_hom.to_semimodule [semiring R] [semiring S] (f : R →+* S) : semimodule R S :=
{ smul := λ r x, f r * x,
smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add],
add_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_add, add_mul],
mul_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_mul, mul_assoc],
one_smul := λ x, show f 1 * x = _, by rw [f.map_one, one_mul],
zero_smul := λ x, show f 0 * x = 0, by rw [f.map_zero, zero_mul],
smul_zero := λ r, mul_zero (f r) }
/-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties
`f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this
property. A bundled version is available with `linear_map`, and should be favored over
`is_linear_map` most of the time. -/
structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w}
[semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂]
(f : M → M₂) : Prop :=
(map_add : ∀ x y, f (x + y) = f x + f y)
(map_smul : ∀ (c : R) x, f (c • x) = c • f x)
set_option old_structure_cmd true
/-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties
`f (x + y) = f x + f y` and `f (c • x) = c • f x`. Elements of `linear_map R M M₂` (available under
the notation `M →ₗ[R] M₂`) are bundled versions of such maps. An unbundled version is available with
the predicate `is_linear_map`, but it should be avoided most of the time. -/
structure linear_map (R : Type u) (M : Type v) (M₂ : Type w)
[semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends add_hom M M₂ :=
(map_smul' : ∀(c : R) x, to_fun (c • x) = c • to_fun x)
/-- The `add_hom` underlying a `linear_map`. -/
add_decl_doc linear_map.to_add_hom
set_option old_structure_cmd false
infixr ` →ₗ `:25 := linear_map _
notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map R M M₂
namespace linear_map
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
section
variables [semimodule R M] [semimodule R M₂]
instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩
@[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) :
((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl
/-- Identity map as a `linear_map` -/
def id : M →ₗ[R] M :=
⟨id, λ _ _, rfl, λ _ _, rfl⟩
lemma id_apply (x : M) :
@id R M _ _ _ x = x := rfl
@[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id :=
by { ext x, refl }
end
section
-- We can infer the module structure implicitly from the linear maps,
-- rather than via typeclass resolution.
variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂}
variables (f g : M →ₗ[R] M₂)
include semimodule_M semimodule_M₂
@[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl
theorem is_linear : is_linear_map R f := ⟨f.2, f.3⟩
variables {f g}
theorem coe_injective : injective (λ f : M →ₗ[R] M₂, show M → M₂, from f) :=
by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr
@[ext] theorem ext (H : ∀ x, f x = g x) : f = g :=
coe_injective $ funext H
lemma coe_fn_congr : Π {x x' : M}, x = x' → f x = f x'
| _ _ rfl := rfl
theorem ext_iff : f = g ↔ ∀ x, f x = g x :=
⟨by { rintro rfl x, refl } , ext⟩
/-- If two linear maps are equal, they are equal at each point. -/
lemma lcongr_fun (h : f = g) (m : M) : f m = g m :=
congr_fun (congr_arg linear_map.to_fun h) m
variables (f g)
@[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y
@[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x
@[simp] lemma map_zero : f 0 = 0 :=
by rw [← zero_smul R, map_smul f 0 0, zero_smul]
instance : is_add_monoid_hom f :=
{ map_add := map_add f,
map_zero := map_zero f }
/-- convert a linear map to an additive map -/
def to_add_monoid_hom : M →+ M₂ :=
{ to_fun := f,
map_zero' := f.map_zero,
map_add' := f.map_add }
@[simp] lemma to_add_monoid_hom_coe :
((f.to_add_monoid_hom) : M → M₂) = f := rfl
@[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} :
f (∑ i in t, g i) = (∑ i in t, f (g i)) :=
f.to_add_monoid_hom.map_sum _ _
theorem to_add_monoid_hom_injective :
function.injective (to_add_monoid_hom : (M →ₗ[R] M₂) → (M →+ M₂)) :=
λ f g h, ext $ add_monoid_hom.congr_fun h
end
section
variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂}
{semimodule_M₃ : semimodule R M₃}
variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂)
/-- Composition of two linear maps is a linear map -/
def comp : M →ₗ[R] M₃ := ⟨f ∘ g, by simp, by simp⟩
@[simp] lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl
@[norm_cast]
lemma comp_coe : (f : M₂ → M₃) ∘ (g : M → M₂) = f.comp g := rfl
end
end add_comm_monoid
section add_comm_group
variables [semiring R] [add_comm_group M] [add_comm_group M₂]
variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂}
variables (f : M →ₗ[R] M₂)
@[simp] lemma map_neg (x : M) : f (- x) = - f x :=
f.to_add_monoid_hom.map_neg x
@[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y :=
f.to_add_monoid_hom.map_sub x y
instance : is_add_group_hom f :=
{ map_add := map_add f}
end add_comm_group
end linear_map
namespace is_linear_map
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂]
variables [semimodule R M] [semimodule R M₂]
include R
/-- Convert an `is_linear_map` predicate to a `linear_map` -/
def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := ⟨f, H.1, H.2⟩
@[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) :
mk' f H x = f x := rfl
lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [semimodule R M] (c : R) :
is_linear_map R (λ (z : M), c • z) :=
begin
refine is_linear_map.mk (smul_add c) _,
intros _ _,
simp only [smul_smul, mul_comm]
end
--TODO: move
lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] (a : M) :
is_linear_map R (λ (c : R), c • a) :=
is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a)
variables {f : M → M₂} (lin : is_linear_map R f)
include M M₂ lin
lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero
end add_comm_monoid
section add_comm_group
variables [semiring R] [add_comm_group M] [add_comm_group M₂]
variables [semimodule R M] [semimodule R M₂]
include R
lemma is_linear_map_neg :
is_linear_map R (λ (z : M), -z) :=
is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm)
variables {f : M → M₂} (lin : is_linear_map R f)
include M M₂ lin
lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x
lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y
end add_comm_group
end is_linear_map
/-- Ring of linear endomorphismsms of a module. -/
abbreviation module.End (R : Type u) (M : Type v)
[semiring R] [add_comm_monoid M] [semimodule R M] := M →ₗ[R] M
/--
Vector spaces are defined as an `abbreviation` for semimodules,
if the base ring is a field.
(A previous definition made `vector_space` a structure
defined to be `module`.)
This has as advantage that vector spaces are completely transparent
for type class inference, which means that all instances for semimodules
are immediately picked up for vector spaces as well.
A cosmetic disadvantage is that one can not extend vector spaces as such,
in definitions such as `normed_space`.
The solution is to extend `semimodule` instead.
-/
library_note "vector space definition"
/-- A vector space is the same as a module, except the scalar ring is actually
a field. (This adds commutativity of the multiplication and existence of inverses.)
This is the traditional generalization of spaces like `ℝ^n`, which have a natural
addition operation and a way to multiply them by real numbers, but no multiplication
operation between vectors. -/
abbreviation vector_space (R : Type u) (M : Type v) [field R] [add_comm_group M] :=
semimodule R M
namespace add_comm_monoid
open add_monoid
variables [add_comm_monoid M]
/-- The natural ℕ-semimodule structure on any `add_comm_monoid`. -/
-- We don't make this a global instance, as it results in too many instances,
-- and confusing ambiguity in the notation `n • x` when `n : ℕ`.
def nat_semimodule : semimodule ℕ M :=
{ smul := nsmul,
smul_add := λ _ _ _, nsmul_add _ _ _,
add_smul := λ _ _ _, add_nsmul _ _ _,
mul_smul := λ _ _ _, mul_nsmul _ _ _,
one_smul := one_nsmul,
zero_smul := zero_nsmul,
smul_zero := nsmul_zero }
end add_comm_monoid
namespace add_comm_group
variables [add_comm_group M]
/-- The natural ℤ-module structure on any `add_comm_group`. -/
-- We don't immediately make this a global instance, as it results in too many instances,
-- and confusing ambiguity in the notation `n • x` when `n : ℤ`.
-- We do turn it into a global instance, but only at the end of this file,
-- and I remain dubious whether this is a good idea.
def int_module : module ℤ M :=
{ smul := gsmul,
smul_add := λ _ _ _, gsmul_add _ _ _,
add_smul := λ _ _ _, add_gsmul _ _ _,
mul_smul := λ _ _ _, gsmul_mul _ _ _,
one_smul := one_gsmul,
zero_smul := zero_gsmul,
smul_zero := gsmul_zero }
instance : subsingleton (module ℤ M) :=
begin
split,
intros P Q,
ext,
-- isn't that lovely: `r • m = r • m`
have one_smul : by { haveI := P, exact (1 : ℤ) • m } = by { haveI := Q, exact (1 : ℤ) • m },
begin
rw [@one_smul ℤ _ _ (by { haveI := P, apply_instance, }) m],
rw [@one_smul ℤ _ _ (by { haveI := Q, apply_instance, }) m],
end,
have nat_smul : ∀ n : ℕ, by { haveI := P, exact (n : ℤ) • m } = by { haveI := Q, exact (n : ℤ) • m },
begin
intro n,
induction n with n ih,
{ erw [zero_smul, zero_smul], },
{ rw [int.coe_nat_succ, add_smul, add_smul],
erw ih,
rw [one_smul], }
end,
cases r,
{ rw [int.of_nat_eq_coe, nat_smul], },
{ rw [int.neg_succ_of_nat_coe, neg_smul, neg_smul, nat_smul], }
end
end add_comm_group
section
local attribute [instance] add_comm_monoid.nat_semimodule
lemma semimodule.smul_eq_smul (R : Type*) [semiring R]
{M : Type*} [add_comm_monoid M] [semimodule R M]
(n : ℕ) (b : M) : n • b = (n : R) • b :=
begin
induction n with n ih,
{ rw [nat.cast_zero, zero_smul, zero_smul] },
{ change (n + 1) • b = (n + 1 : R) • b,
rw [add_smul, add_smul, one_smul, ih, one_smul] }
end
lemma semimodule.nsmul_eq_smul (R : Type*) [semiring R]
{M : Type*} [add_comm_monoid M] [semimodule R M] (n : ℕ) (b : M) :
n •ℕ b = (n : R) • b :=
semimodule.smul_eq_smul R n b
lemma nat.smul_def {M : Type*} [add_comm_monoid M] (n : ℕ) (x : M) :
n • x = n •ℕ x :=
rfl
end
section
local attribute [instance] add_comm_group.int_module
lemma gsmul_eq_smul {M : Type*} [add_comm_group M] (n : ℤ) (x : M) : gsmul n x = n • x := rfl
lemma module.gsmul_eq_smul_cast (R : Type*) [ring R] {M : Type*} [add_comm_group M] [module R M]
(n : ℤ) (b : M) : gsmul n b = (n : R) • b :=
begin
cases n,
{ apply semimodule.nsmul_eq_smul, },
{ dsimp,
rw semimodule.nsmul_eq_smul R,
push_cast,
rw neg_smul, }
end
lemma module.gsmul_eq_smul {M : Type*} [add_comm_group M] [module ℤ M]
(n : ℤ) (b : M) : gsmul n b = n • b :=
by rw [module.gsmul_eq_smul_cast ℤ, int.cast_id]
end
-- We prove this without using the `add_comm_group.int_module` instance, so the `•`s here
-- come from whatever the local `module ℤ` structure actually is.
lemma add_monoid_hom.map_int_module_smul
[add_comm_group M] [add_comm_group M₂]
[module ℤ M] [module ℤ M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f (x • a) = x • f a :=
by simp only [← module.gsmul_eq_smul, f.map_gsmul]
lemma add_monoid_hom.map_int_cast_smul
[ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂]
(f : M →+ M₂) (x : ℤ) (a : M) : f ((x : R) • a) = (x : R) • f a :=
by simp only [← module.gsmul_eq_smul_cast, f.map_gsmul]
lemma add_monoid_hom.map_nat_cast_smul
[semiring R] [add_comm_monoid M] [add_comm_monoid M₂]
[semimodule R M] [semimodule R M₂] (f : M →+ M₂) (x : ℕ) (a : M) :
f ((x : R) • a) = (x : R) • f a :=
by simp only [← semimodule.nsmul_eq_smul, f.map_nsmul]
lemma add_monoid_hom.map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R]
{E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F]
(f : E →+ F) (c : ℚ) (x : E) :
f ((c : R) • x) = (c : R) • f x :=
begin
have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x,
{ intros x n hn,
replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn),
conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] },
rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat,
inv_mul_cancel hn, one_smul] },
refine c.num_denom_cases_on (λ m n hn hmn, _),
rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul,
rat.cast_coe_int, f.map_int_cast_smul, this _ n hn]
end
lemma add_monoid_hom.map_rat_module_smul {E : Type*} [add_comm_group E] [vector_space ℚ E]
{F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) :
f (c • x) = c • f x :=
rat.cast_id c ▸ f.map_rat_cast_smul c x
-- We finally turn on these instances globally:
attribute [instance] add_comm_monoid.nat_semimodule add_comm_group.int_module
/-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/
def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) :
M →ₗ[ℤ] M₂ :=
⟨f, f.map_add, f.map_int_module_smul⟩
/-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/
def add_monoid_hom.to_rat_linear_map [add_comm_group M] [vector_space ℚ M]
[add_comm_group M₂] [vector_space ℚ M₂] (f : M →+ M₂) :
M →ₗ[ℚ] M₂ :=
⟨f, f.map_add, f.map_rat_module_smul⟩
|
86a5c4292de82aa1f232cc54fa10d578a5ff1e4a | e9078bde91465351e1b354b353c9f9d8b8a9c8c2 | /colimit/omega_compact.hlean | 1d081511fb71fc60804ad5625a86bddf25fe2a0b | [
"Apache-2.0"
] | permissive | EgbertRijke/leansnippets | 09fb7a9813477471532fbdd50c99be8d8fe3e6c4 | 1d9a7059784c92c0281fcc7ce66ac7b3619c8661 | refs/heads/master | 1,610,743,957,626 | 1,442,532,603,000 | 1,442,532,603,000 | 41,563,379 | 0 | 0 | null | 1,440,787,514,000 | 1,440,787,514,000 | null | UTF-8 | Lean | false | false | 711 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Egbert Rijke
-/
import .seq_colim
open nat
namespace seq_colim
variables {A : ℕ → Type} [f : seq_diagram A]
variables {n : ℕ} (a : A n)
include f
definition arrow_colim_of_colim_arrow {X : Type} (g : seq_colim (λn, X → A n)) (x : X) :
seq_colim A :=
begin induction g with n g n g, exact ι (g x), exact glue (g x) end
definition omega_compact [class] (X : Type) : Type := Π(A : ℕ → Type) [f : seq_diagram A],
is_equiv (arrow_colim_of_colim_arrow : seq_colim (λn, X → A n) → (X → seq_colim A))
end seq_colim
|
23fdeb2f09fea8ce87041b154bb1f3ce8fd38db9 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/locally_convex/abs_convex.lean | cfefd68a51df4fc4394db2cd86469d78fe25fe2b | [
"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 | 6,334 | lean | /-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll
-/
import analysis.locally_convex.balanced_core_hull
import analysis.locally_convex.with_seminorms
import analysis.convex.gauge
/-!
# Absolutely convex sets
A set is called absolutely convex or disked if it is convex and balanced.
The importance of absolutely convex sets comes from the fact that every locally convex
topological vector space has a basis consisting of absolutely convex sets.
## Main definitions
* `gauge_seminorm_family`: the seminorm family induced by all open absolutely convex neighborhoods
of zero.
## Main statements
* `with_gauge_seminorm_family`: the topology of a locally convex space is induced by the family
`gauge_seminorm_family`.
## Todo
* Define the disked hull
## Tags
disks, convex, balanced
-/
open normed_field set
open_locale big_operators nnreal pointwise topological_space
variables {𝕜 E F G ι : Type*}
section nontrivially_normed_field
variables (𝕜 E) {s : set E}
variables [nontrivially_normed_field 𝕜] [add_comm_group E] [module 𝕜 E]
variables [module ℝ E] [smul_comm_class ℝ 𝕜 E]
variables [topological_space E] [locally_convex_space ℝ E] [has_continuous_smul 𝕜 E]
lemma nhds_basis_abs_convex : (𝓝 (0 : E)).has_basis
(λ (s : set E), s ∈ 𝓝 (0 : E) ∧ balanced 𝕜 s ∧ convex ℝ s) id :=
begin
refine (locally_convex_space.convex_basis_zero ℝ E).to_has_basis (λ s hs, _)
(λ s hs, ⟨s, ⟨hs.1, hs.2.2⟩, rfl.subset⟩),
refine ⟨convex_hull ℝ (balanced_core 𝕜 s), _, convex_hull_min (balanced_core_subset s) hs.2⟩,
refine ⟨filter.mem_of_superset (balanced_core_mem_nhds_zero hs.1) (subset_convex_hull ℝ _), _⟩,
refine ⟨balanced_convex_hull_of_balanced (balanced_core_balanced s), _⟩,
exact convex_convex_hull ℝ (balanced_core 𝕜 s),
end
variables [has_continuous_smul ℝ E] [topological_add_group E]
lemma nhds_basis_abs_convex_open : (𝓝 (0 : E)).has_basis
(λ (s : set E), (0 : E) ∈ s ∧ is_open s ∧ balanced 𝕜 s ∧ convex ℝ s) id :=
begin
refine (nhds_basis_abs_convex 𝕜 E).to_has_basis _ _,
{ rintros s ⟨hs_nhds, hs_balanced, hs_convex⟩,
refine ⟨interior s, _, interior_subset⟩,
exact ⟨mem_interior_iff_mem_nhds.mpr hs_nhds, is_open_interior,
hs_balanced.interior (mem_interior_iff_mem_nhds.mpr hs_nhds), hs_convex.interior⟩ },
rintros s ⟨hs_zero, hs_open, hs_balanced, hs_convex⟩,
exact ⟨s, ⟨hs_open.mem_nhds hs_zero, hs_balanced, hs_convex⟩, rfl.subset⟩,
end
end nontrivially_normed_field
section absolutely_convex_sets
variables [topological_space E] [add_comm_monoid E] [has_zero E] [semi_normed_ring 𝕜]
variables [has_smul 𝕜 E] [has_smul ℝ E]
variables (𝕜 E)
/-- The type of absolutely convex open sets. -/
def abs_convex_open_sets :=
{ s : set E // (0 : E) ∈ s ∧ is_open s ∧ balanced 𝕜 s ∧ convex ℝ s }
instance abs_convex_open_sets.has_coe : has_coe (abs_convex_open_sets 𝕜 E) (set E) := ⟨subtype.val⟩
namespace abs_convex_open_sets
variables {𝕜 E}
lemma coe_zero_mem (s : abs_convex_open_sets 𝕜 E) : (0 : E) ∈ (s : set E) := s.2.1
lemma coe_is_open (s : abs_convex_open_sets 𝕜 E) : is_open (s : set E) := s.2.2.1
lemma coe_nhds (s : abs_convex_open_sets 𝕜 E) : (s : set E) ∈ 𝓝 (0 : E) :=
s.coe_is_open.mem_nhds s.coe_zero_mem
lemma coe_balanced (s : abs_convex_open_sets 𝕜 E) : balanced 𝕜 (s : set E) := s.2.2.2.1
lemma coe_convex (s : abs_convex_open_sets 𝕜 E) : convex ℝ (s : set E) := s.2.2.2.2
end abs_convex_open_sets
instance : nonempty (abs_convex_open_sets 𝕜 E) :=
begin
rw ←exists_true_iff_nonempty,
dunfold abs_convex_open_sets,
rw subtype.exists,
exact ⟨set.univ, ⟨mem_univ 0, is_open_univ, balanced_univ, convex_univ⟩, trivial⟩,
end
end absolutely_convex_sets
variables [is_R_or_C 𝕜]
variables [add_comm_group E] [topological_space E]
variables [module 𝕜 E] [module ℝ E] [is_scalar_tower ℝ 𝕜 E]
variables [has_continuous_smul ℝ E]
variables (𝕜 E)
/-- The family of seminorms defined by the gauges of absolute convex open sets. -/
noncomputable
def gauge_seminorm_family : seminorm_family 𝕜 E (abs_convex_open_sets 𝕜 E) :=
λ s, gauge_seminorm s.coe_balanced s.coe_convex (absorbent_nhds_zero s.coe_nhds)
variables {𝕜 E}
lemma gauge_seminorm_family_ball (s : abs_convex_open_sets 𝕜 E) :
(gauge_seminorm_family 𝕜 E s).ball 0 1 = (s : set E) :=
begin
dunfold gauge_seminorm_family,
rw seminorm.ball_zero_eq,
simp_rw gauge_seminorm_to_fun,
exact gauge_lt_one_eq_self_of_open s.coe_convex s.coe_zero_mem s.coe_is_open,
end
variables [topological_add_group E] [has_continuous_smul 𝕜 E]
variables [smul_comm_class ℝ 𝕜 E] [locally_convex_space ℝ E]
/-- The topology of a locally convex space is induced by the gauge seminorm family. -/
lemma with_gauge_seminorm_family : with_seminorms (gauge_seminorm_family 𝕜 E) :=
begin
refine seminorm_family.with_seminorms_of_has_basis _ _,
refine filter.has_basis.to_has_basis (nhds_basis_abs_convex_open 𝕜 E) (λ s hs, _) (λ s hs, _),
{ refine ⟨s, ⟨_, rfl.subset⟩⟩,
rw seminorm_family.basis_sets_iff,
refine ⟨{⟨s, hs⟩}, 1, one_pos, _⟩,
simp only [finset.sup_singleton],
rw gauge_seminorm_family_ball,
simp only [subtype.coe_mk] },
refine ⟨s, ⟨_, rfl.subset⟩⟩,
rw seminorm_family.basis_sets_iff at hs,
rcases hs with ⟨t, r, hr, hs⟩,
rw seminorm.ball_finset_sup_eq_Inter _ _ _ hr at hs,
rw hs,
-- We have to show that the intersection contains zero, is open, balanced, and convex
refine ⟨mem_Inter₂.mpr (λ _ _, by simp [seminorm.mem_ball_zero, hr]),
is_open_bInter (to_finite _) (λ _ _, _),
balanced_Inter₂ (λ _ _, seminorm.balanced_ball_zero _ _),
convex_Inter₂ (λ _ _, seminorm.convex_ball _ _ _)⟩,
-- The only nontrivial part is to show that the ball is open
have hr' : r = ‖(r : 𝕜)‖ * 1 := by simp [abs_of_pos hr],
have hr'' : (r : 𝕜) ≠ 0 := by simp [ne_of_gt hr],
rw hr',
rw ←seminorm.smul_ball_zero (norm_pos_iff.mpr hr''),
refine is_open.smul₀ _ hr'',
rw gauge_seminorm_family_ball,
exact abs_convex_open_sets.coe_is_open _,
end
|
1b40b8202edd9906ca283678eed70813d98db62c | 556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e | /src/starkware/cairo/lean/semantics/cpu.lean | a6ff03c38a5e195b20037e9d78736adc9a496962 | [
"Apache-2.0"
] | permissive | starkware-libs/formal-proofs | d6b731604461bf99e6ba820e68acca62a21709e8 | f5fa4ba6a471357fd171175183203d0b437f6527 | refs/heads/master | 1,691,085,444,753 | 1,690,507,386,000 | 1,690,507,386,000 | 410,476,629 | 32 | 9 | Apache-2.0 | 1,690,506,773,000 | 1,632,639,790,000 | Lean | UTF-8 | Lean | false | false | 6,713 | lean | /-
Cairo CPU and instructions. Given the memory and the current processor state, this file specifies
the next state relation.
"Undefined" behavior means that it is possible for more than one state to be a valid next state.
When a function has return type `option F`, the value `none` signifies undefined behavior.
Note: mathlib has a function `bitvec.to_nat` which converts a bitvector to a natural numbers, but
makes bit 0 the msb. The Cairo convention takes bit 0 to be the lsb, so we define `bitvec.to_natr b`
to be `bitvec.to_nat b.reverse`.
-/
import starkware.cairo.lean.semantics.util
noncomputable theory
@[ext]
structure register_state (F : Type*) :=
(pc : F)
(ap : F)
(fp : F)
@[derive decidable_eq, ext]
structure instruction :=
(off_dst : bitvec 16)
(off_op0 : bitvec 16)
(off_op1 : bitvec 16)
(flags : bitvec 15)
-- flag bits
notation `DST_REG` := 0
notation `OP0_REG` := 1
notation `OP1_IMM` := 2
notation `OP1_FP` := 3
notation `OP1_AP` := 4
notation `RES_ADD` := 5
notation `RES_MUL` := 6
notation `PC_JUMP_ABS` := 7
notation `PC_JUMP_REL` := 8
notation `PC_JNZ` := 9
notation `AP_ADD` := 10
notation `AP_ADD1` := 11
notation `OPCODE_CALL` := 12
notation `OPCODE_RET` := 13
notation `OPCODE_ASSERT_EQ` := 14
namespace instruction
variable i : instruction
def dst_reg := i.flags.nth DST_REG
def op0_reg := i.flags.nth OP0_REG
def op1_imm := i.flags.nth OP1_IMM -- op1 src
def op1_fp := i.flags.nth OP1_FP -- op1 src
def op1_ap := i.flags.nth OP1_AP -- op1 src
def res_add := i.flags.nth RES_ADD -- res logic
def res_mul := i.flags.nth RES_MUL -- res logic
def pc_jump_abs := i.flags.nth PC_JUMP_ABS -- pc update
def pc_jump_rel := i.flags.nth PC_JUMP_REL -- pc update
def pc_jnz := i.flags.nth PC_JNZ -- pc update
def ap_add := i.flags.nth AP_ADD -- ap update
def ap_add1 := i.flags.nth AP_ADD1 -- ap update
def opcode_call := i.flags.nth OPCODE_CALL -- opcode
def opcode_ret := i.flags.nth OPCODE_RET -- opcode
def opcode_assert_eq := i.flags.nth OPCODE_ASSERT_EQ -- opcode
def to_nat (inst : instruction) : ℕ :=
inst.off_dst.to_natr +
2^16 * inst.off_op0.to_natr +
2^32 * inst.off_op1.to_natr +
2^48 * inst.flags.to_natr
end instruction
namespace instruction
variables {F : Type*} [field F]
variable i : instruction
variable mem : F → F
variables s : register_state F
def size : F :=
i.op1_imm.to_nat + 1
def op0 :=
cond i.op0_reg
(mem (s.fp + i.off_op0.to_biased_16))
(mem (s.ap + i.off_op0.to_biased_16))
def op1 : option F :=
match /- op1 src -/ i.op1_imm, i.op1_fp, i.op1_ap with
| ff, ff, ff := some (mem (i.op0 mem s + i.off_op1.to_biased_16))
| tt, ff, ff := some (mem (s.pc + i.off_op1.to_biased_16))
| ff, tt, ff := some (mem (s.fp + i.off_op1.to_biased_16))
| ff, ff, tt := some (mem (s.ap + i.off_op1.to_biased_16))
| _, _, _ := none
end
def res_aux : option F :=
match /- res logic -/ i.op1 mem s, i.res_add, i.res_mul with
| some op1, ff, ff := some op1
| some op1, tt, ff := some (i.op0 mem s + op1)
| some op1, ff, tt := some (i.op0 mem s * op1)
| _, _, _ := none
end
-- returns `none` if behavior undefined
def res : option F :=
match /- pc update -/ i.pc_jump_abs, i.pc_jump_rel, i.pc_jnz with
| ff, ff, ff := i.res_aux mem s
| tt, ff, ff := i.res_aux mem s
| ff, tt, ff := i.res_aux mem s
| _, _, _ := none -- undefined behavior
end
def dst :=
cond i.dst_reg
(mem (s.fp + i.off_dst.to_biased_16))
(mem (s.ap + i.off_dst.to_biased_16))
def next_pc [decidable_eq F] : option F :=
match /- pc update -/ i.pc_jump_abs, i.pc_jump_rel, i.pc_jnz with
| ff, ff, ff := some (s.pc + i.size) -- next instruction
| tt, ff, ff := i.res mem s -- absolute jump
| ff, tt, ff := match i.res mem s with -- relative jump
| some res := some (s.pc + res)
| none := none
end
| ff, ff, tt := if i.dst mem s = 0 then -- conditional jump
some (s.pc + i.size)
else
match i.op1 mem s with
| some op1 := some (s.pc + op1)
| none := none
end
| _, _, _ := none
end
def next_ap_aux : option F :=
match i.ap_add, i.ap_add1 with -- ap update
| ff, ff := some s.ap
| tt, ff := match i.res mem s with
| some res := some (s.ap + res)
| none := none
end
| ff, tt := some (s.ap + 1)
| _, _ := none
end
def next_ap : option F :=
match /- opcode -/ i.opcode_call, i.opcode_ret, i.opcode_assert_eq with
| ff, ff, ff := i.next_ap_aux mem s
| tt, ff, ff := match i.ap_add, i.ap_add1 with -- call instruction
| ff, ff := some (s.ap + 2)
| _, _ := none
end
| ff, tt, ff := i.next_ap_aux mem s -- ret instruction
| ff, ff, tt := i.next_ap_aux mem s -- assert equal instruction
| _, _, _ := none
end
def next_fp : option F :=
match /- opcode -/ i.opcode_call, i.opcode_ret, i.opcode_assert_eq with
| ff, ff, ff := some s.fp
| tt, ff, ff := some (s.ap + 2) -- call instruction
| ff, tt, ff := some (i.dst mem s) -- ret instruction
| ff, ff, tt := some s.fp -- assert equal instruction
| _, _, _ := none
end
def asserts : Prop :=
match /- opcode -/ i.opcode_call, i.opcode_ret, i.opcode_assert_eq with
| ff, ff, ff := true
| tt, ff, ff := i.op0 mem s = s.pc + i.size ∧ i.dst mem s = s.fp -- call instruction
| ff, tt, ff := true -- ret instruction
| ff, ff, tt := (i.res mem s).agrees (i.dst mem s) -- assert equal instruction
| _, _, _ := true
end
variables [decidable_eq F] (t : register_state F)
/-- Given instruction `i`, memory `mem`, and state `s`, `t` is a possible next state. -/
def next_state : Prop :=
(i.next_pc mem s).agrees t.pc ∧
(i.next_ap mem s).agrees t.ap ∧
(i.next_fp mem s).agrees t.fp ∧
i.asserts mem s
end instruction
/-- Given memory `mem` and current state `s`, `t` is a possible next state. -/
def next_state {F : Type*} [field F] [decidable_eq F] (mem : F → F) (s t : register_state F) :
Prop :=
∃ i : instruction, mem s.pc = ↑i.to_nat ∧ i.next_state mem s t
|
81e9502e261d31f4ce18cfeb75e0b1222bfc47d1 | 618003631150032a5676f229d13a079ac875ff77 | /src/algebra/field_power.lean | a1e9bb079af8d1ad9720b254b62351dee89ab686 | [
"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 | 5,151 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
Integer power operation on fields.
-/
import algebra.group_with_zero_power
import tactic.linarith
universe u
@[simp] lemma ring_hom.map_fpow {K L : Type*} [division_ring K] [division_ring L] (f : K →+* L)
(a : K) : ∀ (n : ℤ), f (a ^ n) = f a ^ n
| (n : ℕ) := f.map_pow a n
| -[1+n] := by simp only [fpow_neg_succ_of_nat, f.map_pow, f.map_inv, f.map_one]
namespace is_ring_hom
lemma map_fpow {K L : Type*} [division_ring K] [division_ring L] (f : K → L) [is_ring_hom f]
(a : K) : ∀ (n : ℤ), f (a ^ n) = f a ^ n :=
(ring_hom.of f).map_fpow a
end is_ring_hom
section ordered_field_power
open int
variables {K : Type u} [discrete_linear_ordered_field K]
lemma fpow_nonneg_of_nonneg {a : K} (ha : 0 ≤ a) : ∀ (z : ℤ), 0 ≤ a ^ z
| (of_nat n) := pow_nonneg ha _
| -[1+n] := inv_nonneg.2 $ pow_nonneg ha _
lemma fpow_pos_of_pos {a : K} (ha : 0 < a) : ∀ (z : ℤ), 0 < a ^ z
| (of_nat n) := pow_pos ha _
| -[1+n] := inv_pos.2 $ pow_pos ha _
lemma fpow_le_of_le {x : K} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b :=
begin
induction a with a a; induction b with b b,
{ simp only [fpow_of_nat, of_nat_eq_coe],
apply pow_le_pow hx,
apply le_of_coe_nat_le_coe_nat h },
{ apply absurd h,
apply not_le_of_gt,
exact lt_of_lt_of_le (neg_succ_lt_zero _) (of_nat_nonneg _) },
{ simp only [fpow_neg_succ_of_nat, one_div_eq_inv],
apply le_trans (inv_le_one _); apply one_le_pow_of_one_le hx },
{ simp only [fpow_neg_succ_of_nat],
apply (inv_le_inv _ _).2,
{ apply pow_le_pow hx,
have : -(↑(a+1) : ℤ) ≤ -(↑(b+1) : ℤ), from h,
have h' := le_of_neg_le_neg this,
apply le_of_coe_nat_le_coe_nat h' },
repeat { apply pow_pos (lt_of_lt_of_le zero_lt_one hx) } }
end
lemma pow_le_max_of_min_le {x : K} (hx : 1 ≤ x) {a b c : ℤ} (h : min a b ≤ c) :
x ^ (-c) ≤ max (x ^ (-a)) (x ^ (-b)) :=
begin
wlog hle : a ≤ b,
have hnle : -b ≤ -a, from neg_le_neg hle,
have hfle : x ^ (-b) ≤ x ^ (-a), from fpow_le_of_le hx hnle,
have : x ^ (-c) ≤ x ^ (-a),
{ apply fpow_le_of_le hx,
simpa only [min_eq_left hle, neg_le_neg_iff] using h },
simpa only [max_eq_left hfle]
end
lemma fpow_le_one_of_nonpos {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : z ≤ 0) : p ^ z ≤ 1 :=
calc p ^ z ≤ p ^ 0 : fpow_le_of_le hp hz
... = 1 : by simp
lemma one_le_fpow_of_nonneg {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : 0 ≤ z) : 1 ≤ p ^ z :=
calc p ^ z ≥ p ^ 0 : fpow_le_of_le hp hz
... = 1 : by simp
end ordered_field_power
lemma one_lt_pow {K} [linear_ordered_semiring K] {p : K} (hp : 1 < p) : ∀ {n : ℕ}, 1 ≤ n → 1 < p ^ n
| 1 h := by simp; assumption
| (k+2) h :=
begin
rw ←one_mul (1 : K),
apply mul_lt_mul,
{ assumption },
{ apply le_of_lt, simpa using one_lt_pow (nat.le_add_left 1 k)},
{ apply zero_lt_one },
{ apply le_of_lt (lt_trans zero_lt_one hp) }
end
lemma one_lt_fpow {K} [discrete_linear_ordered_field K] {p : K} (hp : 1 < p) :
∀ z : ℤ, 0 < z → 1 < p ^ z
| (int.of_nat n) h := one_lt_pow hp (nat.succ_le_of_lt (int.lt_of_coe_nat_lt_coe_nat h))
section ordered
variables {K : Type*} [discrete_linear_ordered_field K]
lemma nat.fpow_pos_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : 0 < (p:K)^n :=
by { apply fpow_pos_of_pos, exact_mod_cast h }
lemma nat.fpow_ne_zero_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : (p:K)^n ≠ 0 :=
ne_of_gt (nat.fpow_pos_of_pos h n)
lemma fpow_strict_mono {x : K} (hx : 1 < x) :
strict_mono (λ n:ℤ, x ^ n) :=
λ m n h, show x ^ m < x ^ n,
begin
have xpos : 0 < x := by linarith,
have h₀ : x ≠ 0 := by linarith,
have hxm : 0 < x^m := fpow_pos_of_pos xpos m,
have hxm₀ : x^m ≠ 0 := ne_of_gt hxm,
suffices : 1 < x^(n-m),
{ replace := mul_lt_mul_of_pos_right this hxm,
simp [sub_eq_add_neg] at this,
simpa [*, fpow_add, mul_assoc, fpow_neg, inv_mul_cancel], },
apply one_lt_fpow hx, linarith,
end
@[simp] lemma fpow_lt_iff_lt {x : K} (hx : 1 < x) {m n : ℤ} :
x ^ m < x ^ n ↔ m < n :=
(fpow_strict_mono hx).lt_iff_lt
@[simp] lemma fpow_le_iff_le {x : K} (hx : 1 < x) {m n : ℤ} :
x ^ m ≤ x ^ n ↔ m ≤ n :=
(fpow_strict_mono hx).le_iff_le
lemma injective_fpow {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) :
function.injective ((^) x : ℤ → K) :=
begin
intros m n h,
rcases lt_trichotomy x 1 with H|rfl|H,
{ apply (fpow_strict_mono (one_lt_inv h₀ H)).injective,
show x⁻¹ ^ m = x⁻¹ ^ n,
rw [← fpow_inv, ← fpow_mul, ← fpow_mul, mul_comm _ m, mul_comm _ n, fpow_mul, fpow_mul, h], },
{ contradiction },
{ exact (fpow_strict_mono H).injective h, },
end
@[simp] lemma fpow_inj {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) {m n : ℤ} :
x ^ m = x ^ n ↔ m = n :=
(injective_fpow h₀ h₁).eq_iff
end ordered
section
variables {K : Type*} [field K]
@[simp, norm_cast] theorem rat.cast_fpow [char_zero K] (q : ℚ) (n : ℤ) :
((q ^ n : ℚ) : K) = q ^ n :=
(rat.cast_hom K).map_fpow q n
end
|
ee13b1780fa9d3a1713edca562ebd569471855f2 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/category_theory/limits/shapes/terminal.lean | 05dbf9068685a1745d8eea68695fe306b237f04e | [
"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 | 12,428 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import category_theory.pempty
import category_theory.limits.has_limits
/-!
# Initial and terminal objects in a category.
## References
* [Stacks: Initial and final objects](https://stacks.math.columbia.edu/tag/002B)
-/
noncomputable theory
universes v u u₂
open category_theory
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
/-- Construct a cone for the empty diagram given an object. -/
@[simps] def as_empty_cone (X : C) : cone (functor.empty C) := { X := X, π := by tidy }
/-- Construct a cocone for the empty diagram given an object. -/
@[simps] def as_empty_cocone (X : C) : cocone (functor.empty C) := { X := X, ι := by tidy }
/-- `X` is terminal if the cone it induces on the empty diagram is limiting. -/
abbreviation is_terminal (X : C) := is_limit (as_empty_cone X)
/-- `X` is initial if the cocone it induces on the empty diagram is colimiting. -/
abbreviation is_initial (X : C) := is_colimit (as_empty_cocone X)
/-- An object `Y` is terminal if for every `X` there is a unique morphism `X ⟶ Y`. -/
def is_terminal.of_unique (Y : C) [h : Π X : C, unique (X ⟶ Y)] : is_terminal Y :=
{ lift := λ s, (h s.X).default }
/-- Transport a term of type `is_terminal` across an isomorphism. -/
def is_terminal.of_iso {Y Z : C} (hY : is_terminal Y) (i : Y ≅ Z) : is_terminal Z :=
is_limit.of_iso_limit hY
{ hom := { hom := i.hom },
inv := { hom := i.symm.hom } }
/-- An object `X` is initial if for every `Y` there is a unique morphism `X ⟶ Y`. -/
def is_initial.of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : is_initial X :=
{ desc := λ s, (h s.X).default }
/-- Transport a term of type `is_initial` across an isomorphism. -/
def is_initial.of_iso {X Y : C} (hX : is_initial X) (i : X ≅ Y) : is_initial Y :=
is_colimit.of_iso_colimit hX
{ hom := { hom := i.hom },
inv := { hom := i.symm.hom } }
/-- Give the morphism to a terminal object from any other. -/
def is_terminal.from {X : C} (t : is_terminal X) (Y : C) : Y ⟶ X :=
t.lift (as_empty_cone Y)
/-- Any two morphisms to a terminal object are equal. -/
lemma is_terminal.hom_ext {X Y : C} (t : is_terminal X) (f g : Y ⟶ X) : f = g :=
t.hom_ext (by tidy)
@[simp] lemma is_terminal.comp_from {Z : C} (t : is_terminal Z) {X Y : C} (f : X ⟶ Y) :
f ≫ t.from Y = t.from X :=
t.hom_ext _ _
@[simp] lemma is_terminal.from_self {X : C} (t : is_terminal X) : t.from X = 𝟙 X :=
t.hom_ext _ _
/-- Give the morphism from an initial object to any other. -/
def is_initial.to {X : C} (t : is_initial X) (Y : C) : X ⟶ Y :=
t.desc (as_empty_cocone Y)
/-- Any two morphisms from an initial object are equal. -/
lemma is_initial.hom_ext {X Y : C} (t : is_initial X) (f g : X ⟶ Y) : f = g :=
t.hom_ext (by tidy)
@[simp] lemma is_initial.to_comp {X : C} (t : is_initial X) {Y Z : C} (f : Y ⟶ Z) :
t.to Y ≫ f = t.to Z :=
t.hom_ext _ _
@[simp] lemma is_initial.to_self {X : C} (t : is_initial X) : t.to X = 𝟙 X :=
t.hom_ext _ _
/-- Any morphism from a terminal object is mono. -/
lemma is_terminal.mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : mono f :=
⟨λ Z g h eq, t.hom_ext _ _⟩
/-- Any morphism to an initial object is epi. -/
lemma is_initial.epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : epi f :=
⟨λ Z g h eq, t.hom_ext _ _⟩
variable (C)
/--
A category has a terminal object if it has a limit over the empty diagram.
Use `has_terminal_of_unique` to construct instances.
-/
abbreviation has_terminal := has_limits_of_shape (discrete pempty) C
/--
A category has an initial object if it has a colimit over the empty diagram.
Use `has_initial_of_unique` to construct instances.
-/
abbreviation has_initial := has_colimits_of_shape (discrete pempty) C
/--
An arbitrary choice of terminal object, if one exists.
You can use the notation `⊤_ C`.
This object is characterized by having a unique morphism from any object.
-/
abbreviation terminal [has_terminal C] : C := limit (functor.empty C)
/--
An arbitrary choice of initial object, if one exists.
You can use the notation `⊥_ C`.
This object is characterized by having a unique morphism to any object.
-/
abbreviation initial [has_initial C] : C := colimit (functor.empty C)
notation `⊤_` C:20 := terminal C
notation `⊥_` C:20 := initial C
section
variables {C}
/-- We can more explicitly show that a category has a terminal object by specifying the object,
and showing there is a unique morphism to it from any other object. -/
lemma has_terminal_of_unique (X : C) [h : Π Y : C, unique (Y ⟶ X)] : has_terminal C :=
{ has_limit := λ F, has_limit.mk
{ cone := { X := X, π := { app := pempty.rec _ } },
is_limit := { lift := λ s, (h s.X).default } } }
/-- We can more explicitly show that a category has an initial object by specifying the object,
and showing there is a unique morphism from it to any other object. -/
lemma has_initial_of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : has_initial C :=
{ has_colimit := λ F, has_colimit.mk
{ cocone := { X := X, ι := { app := pempty.rec _ } },
is_colimit := { desc := λ s, (h s.X).default } } }
/-- The map from an object to the terminal object. -/
abbreviation terminal.from [has_terminal C] (P : C) : P ⟶ ⊤_ C :=
limit.lift (functor.empty C) (as_empty_cone P)
/-- The map to an object from the initial object. -/
abbreviation initial.to [has_initial C] (P : C) : ⊥_ C ⟶ P :=
colimit.desc (functor.empty C) (as_empty_cocone P)
instance unique_to_terminal [has_terminal C] (P : C) : unique (P ⟶ ⊤_ C) :=
{ default := terminal.from P,
uniq := λ m, by { apply limit.hom_ext, rintro ⟨⟩ } }
instance unique_from_initial [has_initial C] (P : C) : unique (⊥_ C ⟶ P) :=
{ default := initial.to P,
uniq := λ m, by { apply colimit.hom_ext, rintro ⟨⟩ } }
@[simp] lemma terminal.comp_from [has_terminal C] {P Q : C} (f : P ⟶ Q) :
f ≫ terminal.from Q = terminal.from P :=
by tidy
@[simp] lemma initial.to_comp [has_initial C] {P Q : C} (f : P ⟶ Q) :
initial.to P ≫ f = initial.to Q :=
by tidy
/-- A terminal object is terminal. -/
def terminal_is_terminal [has_terminal C] : is_terminal (⊤_ C) :=
{ lift := λ s, terminal.from _ }
/-- An initial object is initial. -/
def initial_is_initial [has_initial C] : is_initial (⊥_ C) :=
{ desc := λ s, initial.to _ }
/-- Any morphism from a terminal object is mono. -/
instance terminal.mono_from {Y : C} [has_terminal C] (f : ⊤_ C ⟶ Y) : mono f :=
is_terminal.mono_from terminal_is_terminal _
/-- Any morphism to an initial object is epi. -/
instance initial.epi_to {Y : C} [has_initial C] (f : Y ⟶ ⊥_ C) : epi f :=
is_initial.epi_to initial_is_initial _
/-- An initial object is terminal in the opposite category. -/
def terminal_op_of_initial {X : C} (t : is_initial X) : is_terminal (opposite.op X) :=
{ lift := λ s, (t.to s.X.unop).op,
uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) }
/-- An initial object in the opposite category is terminal in the original category. -/
def terminal_unop_of_initial {X : Cᵒᵖ} (t : is_initial X) : is_terminal X.unop :=
{ lift := λ s, (t.to (opposite.op s.X)).unop,
uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) }
/-- A terminal object is initial in the opposite category. -/
def initial_op_of_terminal {X : C} (t : is_terminal X) : is_initial (opposite.op X) :=
{ desc := λ s, (t.from s.X.unop).op,
uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) }
/-- A terminal object in the opposite category is initial in the original category. -/
def initial_unop_of_terminal {X : Cᵒᵖ} (t : is_terminal X) : is_initial X.unop :=
{ desc := λ s, (t.from (opposite.op s.X)).unop,
uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) }
/-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cone for `J`.
In `limit_of_diagram_initial` we show it is a limit cone. -/
@[simps]
def cone_of_diagram_initial {J : Type v} [small_category J]
{X : J} (tX : is_initial X) (F : J ⥤ C) : cone F :=
{ X := F.obj X,
π :=
{ app := λ j, F.map (tX.to j),
naturality' := λ j j' k,
begin
dsimp,
rw [← F.map_comp, category.id_comp, tX.hom_ext (tX.to j ≫ k) (tX.to j')],
end } }
/-- From a functor `F : J ⥤ C`, given an initial object of `J`, show the cone
`cone_of_diagram_initial` is a limit. -/
def limit_of_diagram_initial {J : Type v} [small_category J]
{X : J} (tX : is_initial X) (F : J ⥤ C) :
is_limit (cone_of_diagram_initial tX F) :=
{ lift := λ s, s.π.app X,
uniq' := λ s m w,
begin
rw [← w X, cone_of_diagram_initial_π_app, tX.hom_ext (tX.to X) (𝟙 _)],
dsimp, simp -- See note [dsimp, simp]
end}
-- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`.
/-- For a functor `F : J ⥤ C`, if `J` has an initial object then the image of it is isomorphic
to the limit of `F`. -/
@[reducible]
def limit_of_initial {J : Type v} [small_category J] (F : J ⥤ C)
[has_initial J] [has_limit F] :
limit F ≅ F.obj (⊥_ J) :=
is_limit.cone_point_unique_up_to_iso
(limit.is_limit _)
(limit_of_diagram_initial initial_is_initial F)
/-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cocone for `J`.
In `colimit_of_diagram_terminal` we show it is a colimit cocone. -/
@[simps]
def cocone_of_diagram_terminal {J : Type v} [small_category J]
{X : J} (tX : is_terminal X) (F : J ⥤ C) : cocone F :=
{ X := F.obj X,
ι :=
{ app := λ j, F.map (tX.from j),
naturality' := λ j j' k,
begin
dsimp,
rw [← F.map_comp, category.comp_id, tX.hom_ext (k ≫ tX.from j') (tX.from j)],
end } }
/-- From a functor `F : J ⥤ C`, given a terminal object of `J`, show the cocone
`cocone_of_diagram_terminal` is a colimit. -/
def colimit_of_diagram_terminal {J : Type v} [small_category J]
{X : J} (tX : is_terminal X) (F : J ⥤ C) :
is_colimit (cocone_of_diagram_terminal tX F) :=
{ desc := λ s, s.ι.app X,
uniq' := λ s m w,
by { rw [← w X, cocone_of_diagram_terminal_ι_app, tX.hom_ext (tX.from X) (𝟙 _)], simp } }
-- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`.
/-- For a functor `F : J ⥤ C`, if `J` has a terminal object then the image of it is isomorphic
to the colimit of `F`. -/
@[reducible]
def colimit_of_terminal {J : Type v} [small_category J] (F : J ⥤ C)
[has_terminal J] [has_colimit F] :
colimit F ≅ F.obj (⊤_ J) :=
is_colimit.cocone_point_unique_up_to_iso
(colimit.is_colimit _)
(colimit_of_diagram_terminal terminal_is_terminal F)
end
section comparison
variables {C} {D : Type u₂} [category.{v} D] (G : C ⥤ D)
/--
The comparison morphism from the image of a terminal object to the terminal object in the target
category.
-/
-- TODO: Show this is an isomorphism if and only if `G` preserves terminal objects.
def terminal_comparison [has_terminal C] [has_terminal D] :
G.obj (⊤_ C) ⟶ ⊤_ D :=
terminal.from _
/--
The comparison morphism from the initial object in the target category to the image of the initial
object.
-/
-- TODO: Show this is an isomorphism if and only if `G` preserves initial objects.
def initial_comparison [has_initial C] [has_initial D] :
⊥_ D ⟶ G.obj (⊥_ C) :=
initial.to _
end comparison
variables {C} {J : Type v} [small_category J]
/--
If `j` is initial in the index category, then the map `limit.π F j` is an isomorphism.
-/
lemma is_iso_π_of_is_initial {j : J} (I : is_initial j) (F : J ⥤ C) [has_limit F] :
is_iso (limit.π F j) :=
⟨⟨limit.lift _ (cone_of_diagram_initial I F), ⟨by { ext, simp }, by simp⟩⟩⟩
instance is_iso_π_initial [has_initial J] (F : J ⥤ C) [has_limit F] :
is_iso (limit.π F (⊥_ J)) :=
is_iso_π_of_is_initial (initial_is_initial) F
/--
If `j` is terminal in the index category, then the map `colimit.ι F j` is an isomorphism.
-/
lemma is_iso_ι_of_is_terminal {j : J} (I : is_terminal j) (F : J ⥤ C) [has_colimit F] :
is_iso (colimit.ι F j) :=
⟨⟨colimit.desc _ (cocone_of_diagram_terminal I F), ⟨by simp, by { ext, simp }⟩⟩⟩
instance is_iso_ι_terminal [has_terminal J] (F : J ⥤ C) [has_colimit F] :
is_iso (colimit.ι F (⊤_ J)) :=
is_iso_ι_of_is_terminal (terminal_is_terminal) F
end category_theory.limits
|
ad6b9349c8c28c0dd5f45be4a76eceb27f9b9c88 | a7602958ab456501ff85db8cf5553f7bcab201d7 | /Notes/Theorem_Proving_in_Lean/Chapter2/2.1.lean | f344108bdec4d385d824d678fb42ccce047bef21 | [] | no_license | enlauren/math-logic | 081e2e737c8afb28dbb337968df95ead47321ba0 | 086b6935543d1841f1db92d0e49add1124054c37 | refs/heads/master | 1,594,506,621,950 | 1,558,634,976,000 | 1,558,634,976,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,224 | lean | -- 2.1 Simple Type Theory
constants m n: nat
constant f: ℕ → ℕ -- Function mapping natural nums → natural nums.
-- Function mapping a ℕ to a function that maps ℕs to ℕs.
constant g: ℕ → ℕ → ℕ
-- Defines the type of cartesian product of (ℕ, ℕ).
constant p: ℕ × ℕ
-- Example checks.
#check f (p.1)
#check f (p.2)
#check f (p.fst)
#check f (p.snd)
#check p.fst
#check (m, n).fst
-- Some more.
#check (m, n) -- Produces a cartesian product.
#check (g p.1) p.2
#check g p.1 p.2 -- Just another way to write the above.
-- Functions like |g| are useful because having them return another
-- function, instead of forcing us to apply two arguments "g(a, b)" right
-- away allows us to partially apply |g|. Put differently, the fact that
-- |g| returns a function of type ℕ → ℕ allows us to apply arguments to
-- |g| one at a time. This is a very common concept in functional
-- programming.
-- You might realize the same kind of function can be written to take
-- all or both of its arguments at once:
constant c: ℕ × ℕ → ℕ
#check c (m, n)
-- The process of redefining |c| to look like |g| is called currying,
-- which as stated above, is a very common functional paradigm. |
0a7dd2a01573bf01d82eae1c5f482c99c257f84f | 6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf | /src/game/world10/level14.lean | e55e617e4257d67ba71c5465107db969a58231eb | [
"Apache-2.0"
] | permissive | arolihas/natural_number_game | 4f0c93feefec93b8824b2b96adff8b702b8b43ce | 8e4f7b4b42888a3b77429f90cce16292bd288138 | refs/heads/master | 1,621,872,426,808 | 1,586,270,467,000 | 1,586,270,467,000 | 253,648,466 | 0 | 0 | null | 1,586,219,694,000 | 1,586,219,694,000 | null | UTF-8 | Lean | false | false | 730 | lean | import game.world10.level13 -- hide
namespace mynat -- hide
/-
# Inequality world.
## Level 14: `add_le_add_left`
I know these are easy and we've done several already, but this is one
of the axioms for an ordered commutative monoid! The nature of formalising
is that we should formalise all "obvious" lemmas, and then when we're
actually using $\le$ in real life, everything will be there. Note also,
of course, that all of these lemmas are already formalised in Lean's
maths library already, for Lean's inbuilt natural numbers.
-/
/- Lemma
If $a\le b$ then for all $t$, $t+a\le t+b$.
-/
theorem add_le_add_left (a b : mynat) (h : a ≤ b) (t : mynat) :
t + a ≤ t + b :=
begin [nat_num_game]
end
end mynat -- hide
|
3c336efdf7a1016caaca64e0e4363ec5bfeaa3b3 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/data/real/cau_seq.lean | 1f41e66944deab0dbd639408a1f9bc6907e895bc | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 23,703 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.order.absolute_value
import algebra.big_operators.order
/-!
# Cauchy sequences
A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where
applicable, lemmas that will be reused in other contexts have been stated in extra generality.
There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology.
This is a concrete implementation that is useful for simplicity and computability reasons.
## Important definitions
* `is_cau_seq`: a predicate that says `f : ℕ → β` is Cauchy.
* `cau_seq`: the type of Cauchy sequences valued in type `β` with respect to an absolute value
function `abv`.
## Tags
sequence, cauchy, abs val, absolute value
-/
open_locale big_operators
open is_absolute_value
theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} :
(∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) →
∃ i, ∀ j ≥ i, P j ∧ Q j
| ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in
⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩
section
variables {α : Type*} [linear_ordered_field α]
{β : Type*} [ring β] (abv : β → α) [is_absolute_value abv]
theorem rat_add_continuous_lemma
{ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β},
abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε :=
⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂,
by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]
using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩
theorem rat_mul_continuous_lemma
{ε K₁ K₂ : α} (ε0 : 0 < ε) :
∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ →
abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε :=
begin
have K0 : (0 : α) < max 1 (max K₁ K₂) := lt_of_lt_of_le zero_lt_one (le_max_left _ _),
have εK := div_pos (half_pos ε0) K0,
refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩,
replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ K₂) (le_max_right 1 _)),
replace hb₂ := lt_of_lt_of_le hb₂ (le_trans (le_max_right K₁ _) (le_max_right 1 _)),
have := add_lt_add
(mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK)
(mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK),
rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this,
simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm]
using lt_of_le_of_lt (abv_add abv _ _) this
end
theorem rat_inv_continuous_lemma
{β : Type*} [field β] (abv : β → α) [is_absolute_value abv]
{ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) :
∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b →
abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε :=
begin
have KK := mul_pos K0 K0,
have εK := mul_pos ε0 KK,
refine ⟨_, εK, λ a b ha hb h, _⟩,
have a0 := lt_of_lt_of_le K0 ha,
have b0 := lt_of_lt_of_le K0 hb,
rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0),
abv_div abv, abv_mul abv, mul_comm, abv_sub abv,
← mul_div_cancel ε (ne_of_gt KK)],
exact div_lt_div h
(mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _))
(le_of_lt $ mul_pos ε0 KK) KK
end
end
/-- A sequence is Cauchy if the distance between its entries tends to zero. -/
def is_cau_seq {α : Type*} [linear_ordered_field α]
{β : Type*} [ring β] (abv : β → α) (f : ℕ → β) : Prop :=
∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε
namespace is_cau_seq
variables {α : Type*} [linear_ordered_field α]
{β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] {f : ℕ → β}
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchy₂ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j k ≥ i, abv (f j - f k) < ε :=
begin
refine (hf _ (half_pos ε0)).imp (λ i hi j k ij ik, _),
rw ← add_halves ε,
refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _),
rw abv_sub abv, exact hi _ ik
end
theorem cauchy₃ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε :=
let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ _ (le_trans ij jk) ij⟩
end is_cau_seq
/-- `cau_seq β abv` is the type of `β`-valued Cauchy sequences, with respect to the absolute value
function `abv`. -/
def cau_seq {α : Type*} [linear_ordered_field α]
(β : Type*) [ring β] (abv : β → α) : Type* :=
{f : ℕ → β // is_cau_seq abv f}
namespace cau_seq
variables {α : Type*} [linear_ordered_field α]
section ring
variables {β : Type*} [ring β] {abv : β → α}
instance : has_coe_to_fun (cau_seq β abv) (λ _, ℕ → β) := ⟨subtype.val⟩
@[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) :
@coe_fn (cau_seq β abv) _ _ ⟨f, hf⟩ = f := rfl
theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g :=
subtype.eq (funext h)
theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2
theorem cauchy (f : cau_seq β abv) :
∀ {ε}, 0 < ε → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2
/-- Given a Cauchy sequence `f`, create a Cauchy sequence from a sequence `g` with
the same values as `f`. -/
def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv :=
⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩
variable [is_absolute_value abv]
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchy₂ (f : cau_seq β abv) {ε} : 0 < ε →
∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂
theorem cauchy₃ (f : cau_seq β abv) {ε} : 0 < ε →
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃
theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r :=
begin
cases f.cauchy zero_lt_one with i h,
let R := ∑ j in finset.range (i+1), abv (f j),
have : ∀ j ≤ i, abv (f j) ≤ R,
{ intros j ij, change (λ j, abv (f j)) j ≤ R,
apply finset.single_le_sum,
{ intros, apply abv_nonneg abv },
{ rwa [finset.mem_range, nat.lt_succ_iff] } },
refine ⟨R + 1, λ j, _⟩,
cases lt_or_le j i with ij ij,
{ exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) },
{ have := lt_of_le_of_lt (abv_add abv _ _)
(add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)),
rw [add_sub, add_comm] at this, simpa }
end
theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r :=
let ⟨r, h⟩ := f.bounded in
⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _),
λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩
instance : has_add (cau_seq β abv) :=
⟨λ f g, ⟨λ i, (f i + g i : β), λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0,
⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (H₁ _ ij) (H₂ _ ij)⟩⟩⟩
@[simp] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl
variable (abv)
/-- The constant Cauchy sequence. -/
def const (x : β) : cau_seq β abv :=
⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩
variable {abv}
local notation `const` := const abv
@[simp] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl
theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y :=
⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩
instance : has_zero (cau_seq β abv) := ⟨const 0⟩
instance : has_one (cau_seq β abv) := ⟨const 1⟩
instance : inhabited (cau_seq β abv) := ⟨0⟩
@[simp] theorem zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl
@[simp] theorem one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl
@[simp] theorem const_zero : const 0 = 0 := rfl
theorem const_add (x y : β) : const (x + y) = const x + const y :=
ext $ λ i, rfl
instance : has_mul (cau_seq β abv) :=
⟨λ f g, ⟨λ i, (f i * g i : β), λ ε ε0,
let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0,
⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0,
⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in
Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩
@[simp] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl
theorem const_mul (x y : β) : const (x * y) = const x * const y :=
ext $ λ i, rfl
instance : has_neg (cau_seq β abv) :=
⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩
@[simp] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl
theorem const_neg (x : β) : const (-x) = -const x :=
ext $ λ i, rfl
instance : has_sub (cau_seq β abv) :=
⟨λ f g, of_eq (f + -g) (λ x, f x - g x) (λ i, by simp [sub_eq_add_neg])⟩
@[simp] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl
theorem const_sub (x y : β) : const (x - y) = const x - const y :=
ext $ λ i, rfl
instance : ring (cau_seq β abv) :=
by refine_struct
{ neg := has_neg.neg,
add := (+),
zero := (0 : cau_seq β abv),
mul := (*),
one := 1,
sub := has_sub.sub,
npow := @npow_rec (cau_seq β abv) ⟨1⟩ ⟨(*)⟩,
nsmul := @nsmul_rec (cau_seq β abv) ⟨0⟩ ⟨(+)⟩,
gsmul := @gsmul_rec (cau_seq β abv) ⟨0⟩ ⟨(+)⟩ ⟨has_neg.neg⟩ };
intros; try { refl }; apply ext;
simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm, sub_eq_add_neg]
instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] :
comm_ring (cau_seq β abv) :=
{ mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm],
..cau_seq.ring }
/-- `lim_zero f` holds when `f` approaches 0. -/
def lim_zero {abv : β → α} (f : cau_seq β abv) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε
theorem add_lim_zero {f g : cau_seq β abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g)
| ε ε0 := (exists_forall_ge_and
(hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $
λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in
by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂)
theorem mul_lim_zero_right (f : cau_seq β abv) {g}
(hg : lim_zero g) : lim_zero (f * g)
| ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in
(hg _ $ div_pos ε0 F0).imp $ λ i H j ij,
by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0;
rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this
theorem mul_lim_zero_left {f} (g : cau_seq β abv)
(hg : lim_zero f) : lim_zero (f * g)
| ε ε0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in
(hg _ $ div_pos ε0 G0).imp $ λ i H j ij,
by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _);
rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this
theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) :=
by rw ← neg_one_mul; exact mul_lim_zero_right _ hf
theorem sub_lim_zero {f g : cau_seq β abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) :=
by simpa only [sub_eq_add_neg] using add_lim_zero hf (neg_lim_zero hg)
theorem lim_zero_sub_rev {f g : cau_seq β abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) :=
by simpa using neg_lim_zero hfg
theorem zero_lim_zero : lim_zero (0 : cau_seq β abv)
| ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩
theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 :=
⟨λ H, (abv_eq_zero abv).1 $
eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $
λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ (le_refl _),
λ e, e.symm ▸ zero_lim_zero⟩
instance equiv : setoid (cau_seq β abv) :=
⟨λ f g, lim_zero (f - g),
⟨λ f, by simp [zero_lim_zero],
λ f g h, by simpa using neg_lim_zero h,
λ f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg gh⟩⟩
lemma add_equiv_add {f1 f2 g1 g2 : cau_seq β abv} (hf : f1 ≈ f2) (hg : g1 ≈ g2) :
f1 + g1 ≈ f2 + g2 :=
begin
change lim_zero ((f1 + g1) - _),
convert add_lim_zero hf hg using 1,
simp only [sub_eq_add_neg, add_assoc],
rw add_comm (-f2), simp only [add_assoc],
congr' 2, simp
end
lemma neg_equiv_neg {f g : cau_seq β abv} (hf : f ≈ g) : -f ≈ -g :=
begin
have hf : lim_zero _ := neg_lim_zero hf,
show lim_zero (-f - -g),
convert hf using 1, simp
end
theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε :=
(exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $
λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in
by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk));
rwa [sub_add_sub_cancel', add_halves] at this
theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g :=
⟨λ l, by simpa using add_lim_zero (setoid.symm h) l,
λ l, by simpa using add_lim_zero h l⟩
theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) :
∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) :=
begin
haveI := classical.prop_decidable,
by_contra nk,
refine hf (λ ε ε0, _),
simp [not_forall] at nk,
cases f.cauchy₃ (half_pos ε0) with i hi,
rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩,
refine ⟨j, λ k jk, _⟩,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj),
rwa [sub_add_cancel, add_halves] at this
end
theorem of_near (f : ℕ → β) (g : cau_seq β abv)
(h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f
| ε ε0 :=
let ⟨i, hi⟩ := exists_forall_ge_and
(h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in
⟨i, λ j ij, begin
cases hi _ (le_refl _) with h₁ h₂, rw abv_sub abv at h₁,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁),
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)),
rwa [add_halves, add_halves, add_right_comm,
sub_add_sub_cancel, sub_add_sub_cancel] at this
end⟩
lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : ¬ f ≈ 0) : ¬ lim_zero f :=
assume : lim_zero f,
have lim_zero (f - 0), by simpa,
hf this
lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : g * f ≈ 0 :=
have lim_zero (f - 0), from hf,
have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa,
show lim_zero (g*f - 0), by simpa
lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : ¬ (f * g) ≈ 0 :=
assume : lim_zero (f*g - 0),
have hlz : lim_zero (f*g), by simpa,
have hf' : ¬ lim_zero f, by simpa using (show ¬ lim_zero (f - 0), from hf),
have hg' : ¬ lim_zero g, by simpa using (show ¬ lim_zero (g - 0), from hg),
begin
rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩,
rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩,
have : 0 < a1 * a2, from mul_pos ha1 ha2,
cases hlz _ this with N hN,
let i := max N (max N1 N2),
have hN' := hN i (le_max_left _ _),
have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)),
have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)),
apply not_le_of_lt hN',
change _ ≤ abv (_ * _),
rw is_absolute_value.abv_mul abv,
apply mul_le_mul; try { assumption },
{ apply le_of_lt ha2 },
{ apply is_absolute_value.abv_nonneg abv }
end
theorem const_equiv {x y : β} : const x ≈ const y ↔ x = y :=
show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero]
end ring
section comm_ring
variables {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv]
lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : f * g ≈ 0 :=
by rw mul_comm; apply mul_equiv_zero _ hf
end comm_ring
section is_domain
variables {β : Type*} [ring β] [is_domain β] (abv : β → α) [is_absolute_value abv]
lemma one_not_equiv_zero : ¬ (const abv 1) ≈ (const abv 0) :=
assume h,
have ∀ ε > 0, ∃ i, ∀ k, i ≤ k → abv (1 - 0) < ε, from h,
have h1 : abv 1 ≤ 0, from le_of_not_gt $
assume h2 : 0 < abv 1,
exists.elim (this _ h2) $ λ i hi,
lt_irrefl (abv 1) $ by simpa using hi _ (le_refl _),
have h2 : 0 ≤ abv 1, from is_absolute_value.abv_nonneg _ _,
have abv 1 = 0, from le_antisymm h1 h2,
have (1 : β) = 0, from (is_absolute_value.abv_eq_zero abv).1 this,
absurd this one_ne_zero
end is_domain
section field
variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv]
theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) :
∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 :=
let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf,
⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0,
⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in Hδ (H _ ij).1 iK (H' _ ij)⟩
/-- Given a Cauchy sequence `f` with nonzero limit, create a Cauchy sequence with values equal to
the inverses of the values of `f`. -/
def inv (f : cau_seq β abv) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩
@[simp] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl
theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 :=
λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in
⟨i, λ j ij,
by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)),
abv_zero abv] using ε0⟩
theorem const_inv {x : β} (hx : x ≠ 0) :
const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) :=
ext (assume n, by simp[inv_apply, const_apply])
end field
section abs
local notation `const` := const abs
/-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/
def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j
theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f
| ⟨F, F0, hF⟩ H :=
let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0),
⟨h₁, h₂⟩ := h _ (le_refl _) in
not_lt_of_le h₁ (abs_lt.1 h₂).2
theorem const_pos {x : α} : pos (const x) ↔ 0 < x :=
⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)),
λ h, ⟨x, h, 0, λ j _, le_refl _⟩⟩
theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g)
| ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ :=
let ⟨i, h⟩ := exists_forall_ge_and hF hG in
⟨_, _root_.add_pos F0 G0, i,
λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩
theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g)
| ⟨F, F0, hF⟩ H :=
let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in
⟨_, half_pos F0, i, λ j ij, begin
cases h j ij with h₁ h₂,
have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1),
rwa [← sub_eq_add_neg, sub_self_div_two] at this
end⟩
protected theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g)
| ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ :=
let ⟨i, h⟩ := exists_forall_ge_and hF hG in
⟨_, _root_.mul_pos F0 G0, i,
λ j ij, let ⟨h₁, h₂⟩ := h _ ij in
mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩
theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) :=
begin
cases classical.em (lim_zero f); simp *,
rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩,
rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩,
refine (le_total 0 (f i)).imp _ _;
refine (λ h, ⟨K, K0, i, λ j ij, _⟩);
have := (hi _ ij).1;
cases hi _ (le_refl _) with h₁ h₂,
{ rwa abs_of_nonneg at this,
rw abs_of_nonneg h at h₁,
exact (le_add_iff_nonneg_right _).1
(le_trans h₁ $ neg_le_sub_iff_le_add'.1 $
le_of_lt (abs_lt.1 $ h₂ _ ij).1) },
{ rwa abs_of_nonpos at this,
rw abs_of_nonpos h at h₁,
rw [← sub_le_sub_iff_right, zero_sub],
exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ }
end
instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩
instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩
theorem lt_of_lt_of_eq {f g h : cau_seq α abs}
(fg : f < g) (gh : g ≈ h) : f < h :=
show pos (h - f),
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh)
theorem lt_of_eq_of_lt {f g h : cau_seq α abs}
(fg : f ≈ g) (gh : g < h) : f < h :=
by have := pos_add_lim_zero gh (neg_lim_zero fg);
rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this
theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h :=
show pos (h - f),
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh
theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f
| h := not_lim_zero_of_pos h (by simp [zero_lim_zero])
lemma le_of_eq_of_le {f g h : cau_seq α abs}
(hfg : f ≈ g) (hgh : g ≤ h) : f ≤ h :=
hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg)
(or.inr ∘ setoid.trans hfg)
lemma le_of_le_of_eq {f g h : cau_seq α abs}
(hfg : f ≤ g) (hgh : g ≈ h) : f ≤ h :=
hfg.elim (λ h, or.inl (cau_seq.lt_of_lt_of_eq h hgh))
(λ h, or.inr (setoid.trans h hgh))
instance : preorder (cau_seq α abs) :=
{ lt := (<),
le := λ f g, f < g ∨ f ≈ g,
le_refl := λ f, or.inr (setoid.refl _),
le_trans := λ f g h fg, match fg with
| or.inl fg, or.inl gh := or.inl $ lt_trans fg gh
| or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh
| or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh
| or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh
end,
lt_iff_le_not_le := λ f g,
⟨λ h, ⟨or.inl h,
not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩,
λ ⟨h₁, h₂⟩, h₁.resolve_right
(mt (λ h, or.inr (setoid.symm h)) h₂)⟩ }
theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g :=
fg.resolve_left (not_lt_of_le gf)
theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f :=
(trichotomy (g - f)).imp_right
(λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h))
theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f :=
(or.assoc.2 (lt_total f g)).imp_right or.inl
theorem const_lt {x y : α} : const x < const y ↔ x < y :=
show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos]
theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y :=
by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv
lemma le_of_exists {f g : cau_seq α abs}
(h : ∃ i, ∀ j ≥ i, f j ≤ g j) : f ≤ g :=
let ⟨i, hi⟩ := h in
(or.assoc.2 (cau_seq.lt_total f g)).elim
id
(λ hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in
not_lt_of_ge (hi (max i j) (le_max_left _ _))
(sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _))))))
theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a :=
let ⟨K, H⟩ := f.bounded in
⟨K + 1, 1, zero_lt_one, 0, λ i _, begin
rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right],
exact le_of_lt (abs_lt.1 (H _)).2
end⟩
theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f :=
let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _,
by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩
end abs
end cau_seq
|
baa78e5507c251785762e552453f848c11fbbc1c | 7da5ceac20aaab989eeb795a4be9639982e7b35a | /src/basic.lean | 86267fc9f3e794ef4b76c987cdbe131c338a5966 | [
"MIT"
] | permissive | formalabstracts/formalabstracts | 46c2f1b3a172e62ca6ffeb46fbbdf1705718af49 | b0173da1af45421239d44492eeecd54bf65ee0f6 | refs/heads/master | 1,606,896,370,374 | 1,572,988,776,000 | 1,572,988,776,000 | 96,763,004 | 165 | 28 | null | 1,555,709,319,000 | 1,499,680,948,000 | Lean | UTF-8 | Lean | false | false | 4,810 | lean | /- This file contains various definitions and lemmas which don't fit anywhere else, or when there
is not enough material to make its own file -/
import data.pfun data.set.finite data.nat.enat topology.basic
import tactic.fattribute
universes u v
axiom omitted {P : Prop} : P
notation `ℕ∞` := enat
def is_finite (α : Type*) : Prop := nonempty (fintype α) -- set.finite (set.univ : set α)
namespace subtype
attribute [extensionality] subtype.eq'
variables {α : Sort*} {p : α → Prop}
protected lemma subsingleton (h : ∃ x, ∀ y, p y → y = x) : subsingleton {x // p x} :=
begin
rcases h with ⟨x, px⟩, constructor, rintro ⟨y, py⟩ ⟨z, pz⟩, ext,
cases px y py, cases px z pz, refl
end
protected lemma subsingleton' (h : ∃! x, p x) : subsingleton {x // p x} :=
let ⟨x, px, qx⟩ := h in subtype.subsingleton ⟨x, qx⟩
protected lemma nonempty (h : ∃ x, p x) : nonempty {x // p x} :=
let ⟨x, hx⟩ := h in ⟨⟨x, hx⟩⟩
end subtype
namespace trunc
instance nonempty {α : Sort u} [h : nonempty α] : nonempty (trunc α) :=
let ⟨x⟩ := h in ⟨trunc.mk x⟩
end trunc
namespace classical
variables {α : Sort u} {β : Sort v} {p : α → Prop}
noncomputable def unique_choice : nonempty α ∧ subsingleton α → α :=
classical.choice ∘ and.left
noncomputable def unique_indefinite_description (p : α → Prop)
(h : ∃! x, p x) : {x // p x} :=
unique_choice $ let ⟨x, px, qx⟩ := h in ⟨⟨⟨x, px⟩⟩, subtype.subsingleton' h⟩
noncomputable def the (p : α → Prop) (h : ∃! x, p x) : α :=
(unique_indefinite_description p h).1
lemma the_spec (h : ∃! x, p x) : p (the p h) :=
(unique_indefinite_description p h).2
lemma the_unique (h : ∃! x, p x) (y : α) (py : p y) : y = the p h :=
let ⟨x, px, qx⟩ := h in (qx y py).trans (qx _ (the_spec h)).symm
noncomputable def choose_trunc (h : nonempty α) : trunc α :=
unique_choice $ by split; apply_instance
open set
noncomputable def take_arbitrary {α β : Type*} (f : α → β) (h : nonempty α)
(hf : ∀x y : α, f x = f y) : β :=
the (range f) $ let ⟨x⟩ := h in
⟨f x, mem_range_self x, λ y hy, let ⟨x', hx'⟩ := hy in hx'.symm.trans $ hf x' x⟩
noncomputable def take_arbitrary_in {α β : Type*} (s : set α) (f : α → β) (h : nonempty s)
(hf : ∀x y ∈ s, f x = f y) : β :=
take_arbitrary (λ x : s, f x.1) (let ⟨⟨x, hx⟩⟩ := h in ⟨⟨x, hx⟩⟩) (λ⟨x, hx⟩ ⟨y, hy⟩, hf x y hx hy)
noncomputable def take_arbitrary_such_that {α β : Type*} {p : α → Prop} (f : α → β)
(h : ∃ x, p x) (hf : ∀x y, p x → p y → f x = f y) : β :=
take_arbitrary_in {x | p x } f (let ⟨x, px⟩ := h in ⟨⟨x, px⟩⟩) hf
end classical
variables {α : Type*} {β : Type*}
noncomputable def roption.classical_to_option {α} (x : roption α) : option α :=
by haveI := classical.dec; exact x.to_option
namespace vector
def vector_one_equiv : vector α 1 ≃ α :=
{ to_fun := λ x, x.head,
inv_fun := λ x, ⟨[x], dec_trivial⟩,
left_inv := omitted,
right_inv := omitted}
end vector
namespace set
lemma finite_of_subset_finset {s : set α} (t : finset α) (h : s ⊆ ↑t) : s.finite :=
finite_subset (finset.finite_to_set t) h
/-- The cardinality of any subset of a finite type. -/
noncomputable def cardinality [fintype α] (s : set α) : ℕ :=
by haveI := classical.dec; haveI := (set_fintype s); exact fintype.card s
end set
namespace finset
variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r]
lemma sort_length [decidable_eq α] (s : finset α) : (sort r s).length = s.card :=
by rw [←list.to_finset_card_of_nodup (sort_nodup r s), sort_to_finset r s]
end finset
/-- the pullback of a relation along a function -/
-- cf. preorder_lift
def pullback_rel (f : α → β) (r : β → β → Prop) : α → α → Prop := λ x y, r (f x) (f y)
namespace pullback_rel
instance (f : α → β) (r : β → β → Prop) [is_trans β r] : is_trans α (pullback_rel f r) :=
⟨λ x y z h₁ h₂, (trans h₁ h₂ : r (f x) (f z))⟩
protected def is_antisymm (f : α → β) (r : β → β → Prop) (h : function.injective f)
[is_antisymm β r] : is_antisymm α (pullback_rel f r) :=
⟨λ x y h₁ h₂, h $ antisymm h₁ h₂⟩
instance (f : α → β) (r : β → β → Prop) [is_total β r] : is_total α (pullback_rel f r) :=
⟨λ x y, total_of r (f x) (f y)⟩
instance (f : α → β) (r : β → β → Prop) [decidable_rel r] : decidable_rel (pullback_rel f r) :=
by dsimp [pullback_rel]; apply_instance
end pullback_rel
def is_maximal {α : Type*} [preorder α] (s : set α) (x : α) : Prop := x ∈ s ∧ ∀(y ∈ s), ¬y > x
def is_minimal {α : Type*} [preorder α] (s : set α) (x : α) : Prop := x ∈ s ∧ ∀(y ∈ s), ¬y < x |
be2f5016a4d8e7b90b83c394217b1c9be331abf1 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/coe5.lean | 9b63ab79cc036c80bf16a1383d716e2635ed2fce | [
"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 | 302 | lean | open tactic
attribute [instance]
meta def expr_to_app : has_coe_to_fun expr (λ e, expr → expr) :=
⟨expr.app⟩
meta constants f a b : expr
#check f a
#check f a b
#check f a b a
set_option pp.coercions false
#check f a b a
set_option pp.all true
set_option pp.coercions true
#check f a b
|
1187d8ad02bd336f1729cdc12fc2dc2770cd6393 | b00eb947a9c4141624aa8919e94ce6dcd249ed70 | /src/Lean/Meta/ExprDefEq.lean | 5a5799ca4784377d7aae3b3bd41d58a60d35c395 | [
"Apache-2.0"
] | permissive | gebner/lean4-old | a4129a041af2d4d12afb3a8d4deedabde727719b | ee51cdfaf63ee313c914d83264f91f414a0e3b6e | refs/heads/master | 1,683,628,606,745 | 1,622,651,300,000 | 1,622,654,405,000 | 142,608,821 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 57,720 | 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.ProjFns
import Lean.Meta.WHNF
import Lean.Meta.InferType
import Lean.Meta.FunInfo
import Lean.Meta.LevelDefEq
import Lean.Meta.Check
import Lean.Meta.Offset
import Lean.Meta.ForEachExpr
import Lean.Meta.UnificationHint
namespace Lean.Meta
/--
Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`.
Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean.
Example:
```
(fun x : A => f ?m) =?= f
```
The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/
private def isDefEqEta (a b : Expr) : MetaM Bool := do
if a.isLambda && !b.isLambda then
let bType ← inferType b
let bType ← whnfD bType
match bType with
| Expr.forallE n d _ c =>
let b' := mkLambda n c.binderInfo d (mkApp b (mkBVar 0))
checkpointDefEq <| Meta.isExprDefEqAux a b'
| _ => pure false
else
pure false
/-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/
def isDefEqNative (s t : Expr) : MetaM LBool := do
let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t
let s? ← reduceNative? s
let t? ← reduceNative? t
match s?, t? with
| some s, some t => isDefEq s t
| some s, none => isDefEq s t
| none, some t => isDefEq s t
| none, none => pure LBool.undef
/-- Support for reducing Nat basic operations. -/
def isDefEqNat (s t : Expr) : MetaM LBool := do
let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t
if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then
pure LBool.undef
else
let s? ← reduceNat? s
let t? ← reduceNat? t
match s?, t? with
| some s, some t => isDefEq s t
| some s, none => isDefEq s t
| none, some t => isDefEq s t
| none, none => pure LBool.undef
/-- Support for constraints of the form `("..." =?= String.mk cs)` -/
def isDefEqStringLit (s t : Expr) : MetaM LBool := do
let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t
if s.isStringLit && t.isAppOf `String.mk then
isDefEq (toCtorIfLit s) t
else if s.isAppOf `String.mk && t.isStringLit then
isDefEq s (toCtorIfLit t)
else
pure LBool.undef
/--
Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned.
Remark: `n` may be 0. -/
def isEtaUnassignedMVar (e : Expr) : MetaM Bool := do
match e.etaExpanded? with
| some (Expr.mvar mvarId _) =>
if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then
pure false
else if (← isExprMVarAssigned mvarId) then
pure false
else
pure true
| _ => pure false
/-
First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases
Here, we say a case is easy if it is of the form
?m =?= t
or
t =?= ?m
where `?m` is unassigned.
These easy cases are not just an optimization. When
`?m` is a function, by assigning it to t, we make sure
a unification constraint (in the explicit part)
```
?m t =?= f s
```
is not higher-order.
We also handle the eta-expanded cases:
```
fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t
t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ
```
This is important because type inference often produces
eta-expanded terms, and without this extra case, we could
introduce counter intuitive behavior.
Pre: `paramInfo.size <= args₁.size = args₂.size`
-/
private partial def isDefEqArgsFirstPass
(paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : MetaM (Option (Array Nat)) := do
let rec loop (i : Nat) (postponed : Array Nat) := do
if h : i < paramInfo.size then
let info := paramInfo.get ⟨i, h⟩
let a₁ := args₁[i]
let a₂ := args₂[i]
if info.implicit || info.instImplicit then
if (← isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) then
if (← Meta.isExprDefEqAux a₁ a₂) then
loop (i+1) postponed
else
pure none
else
loop (i+1) (postponed.push i)
else if (← Meta.isExprDefEqAux a₁ a₂) then
loop (i+1) postponed
else
pure none
else
pure (some postponed)
loop 0 #[]
@[specialize] private def trySynthPending (e : Expr) : MetaM Bool := do
let mvarId? ← getStuckMVar? e
match mvarId? with
| some mvarId => Meta.synthPending mvarId
| none => pure false
private partial def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : MetaM Bool :=
if h : args₁.size = args₂.size then do
let finfo ← getFunInfoNArgs f args₁.size
let (some postponed) ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ | pure false
let rec processOtherArgs (i : Nat) : MetaM Bool := do
if h₁ : i < args₁.size then
let a₁ := args₁.get ⟨i, h₁⟩
let a₂ := args₂.get ⟨i, Eq.subst h h₁⟩
if (← Meta.isExprDefEqAux a₁ a₂) then
processOtherArgs (i+1)
else
pure false
else
pure true
if (← processOtherArgs finfo.paramInfo.size) then
postponed.allM fun i => do
/- Second pass: unify implicit arguments.
In the second pass, we make sure we are unfolding at
least non reducible definitions (default setting). -/
let a₁ := args₁[i]
let a₂ := args₂[i]
let info := finfo.paramInfo[i]
if info.instImplicit then
discard <| trySynthPending a₁
discard <| trySynthPending a₂
withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a₁ a₂
else
pure false
else
pure false
/--
Check whether the types of the free variables at `fvars` are
definitionally equal to the types at `ds₂`.
Pre: `fvars.size == ds₂.size`
This method also updates the set of local instances, and invokes
the continuation `k` with the updated set.
We can't use `withNewLocalInstances` because the `isDeq fvarType d₂`
may use local instances. -/
@[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) (k : MetaM Bool) : MetaM Bool :=
let rec loop (i : Nat) := do
if h : i < fvars.size then do
let fvar := fvars.get ⟨i, h⟩
let fvarDecl ← getFVarLocalDecl fvar
let fvarType := fvarDecl.type
let d₂ := ds₂[i]
if (← Meta.isExprDefEqAux fvarType d₂) then
match (← isClass? fvarType) with
| some className => withNewLocalInstance className fvar <| loop (i+1)
| none => loop (i+1)
else
pure false
else
k
loop 0
/- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`.
It accumulates the new free variables in `fvars`, and declare them at `lctx`.
We use the domain types of `e₁` to create the new free variables.
We store the domain types of `e₂` at `ds₂`. -/
private partial def isDefEqBindingAux (lctx : LocalContext) (fvars : Array Expr) (e₁ e₂ : Expr) (ds₂ : Array Expr) : MetaM Bool :=
let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : MetaM Bool := do
let d₁ := d₁.instantiateRev fvars
let d₂ := d₂.instantiateRev fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLocalDecl fvarId n d₁
let fvars := fvars.push (mkFVar fvarId)
isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂)
match e₁, e₂ with
| Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂
| Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂
| _, _ =>
withReader (fun ctx => { ctx with lctx := lctx }) do
isDefEqBindingDomain fvars ds₂ do
Meta.isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars)
@[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do
let lctx ← getLCtx
isDefEqBindingAux lctx #[] a b #[]
private def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool :=
traceCtx `Meta.isDefEq.assign.checkTypes do
if !mvar.isMVar then
trace[Meta.isDefEq.assign.final] "metavariable expected at {mvar} := {v}"
return false
else
-- must check whether types are definitionally equal or not, before assigning and returning true
let mvarType ← inferType mvar
let vType ← inferType v
if (← withTransparency TransparencyMode.default <| Meta.isExprDefEqAux mvarType vType) then
trace[Meta.isDefEq.assign.final] "{mvar} := {v}"
assignExprMVar mvar.mvarId! v
pure true
else
trace[Meta.isDefEq.assign.typeMismatch] "{mvar} : {mvarType} := {v} : {vType}"
pure false
/--
Auxiliary method for solving constraints of the form `?m xs := v`.
It creates a lambda using `mkLambdaFVars ys v`, where `ys` is a superset of `xs`.
`ys` is often equal to `xs`. It is a bigger when there are let-declaration dependencies in `xs`.
For example, suppose we have `xs` of the form `#[a, c]` where
```
a : Nat
b : Nat := f a
c : b = a
```
In this scenario, the type of `?m` is `(x1 : Nat) -> (x2 : f x1 = x1) -> C[x1, x2]`,
and type of `v` is `C[a, c]`. Note that, `?m a c` is type correct since `f a = a` is definitionally equal
to the type of `c : b = a`, and the type of `?m a c` is equal to the type of `v`.
Note that `fun xs => v` is the term `fun (x1 : Nat) (x2 : b = x1) => v` which has type
`(x1 : Nat) -> (x2 : b = x1) -> C[x1, x2]` which is not definitionally equal to the type of `?m`,
and may not even be type correct.
The issue here is that we are not capturing the `let`-declarations.
This method collects let-declarations `y` occurring between `xs[0]` and `xs.back` s.t.
some `x` in `xs` depends on `y`.
`ys` is the `xs` with these extra let-declarations included.
In the example above, `ys` is `#[a, b, c]`, and `mkLambdaFVars ys v` produces
`fun a => let b := f a; fun (c : b = a) => v` which has a type definitionally equal to the type of `?m`.
Recall that the method `checkAssignment` ensures `v` does not contain offending `let`-declarations.
This method assumes that for any `xs[i]` and `xs[j]` where `i < j`, we have that `index of xs[i]` < `index of xs[j]`.
where the index is the position in the local context.
-/
private partial def mkLambdaFVarsWithLetDeps (xs : Array Expr) (v : Expr) : MetaM (Option Expr) := do
if not (← hasLetDeclsInBetween) then
mkLambdaFVars xs v
else
let ys ← addLetDeps
trace[Meta.debug] "ys: {ys}, v: {v}"
mkLambdaFVars ys v
where
/- Return true if there are let-declarions between `xs[0]` and `xs[xs.size-1]`.
We use it a quick-check to avoid the more expensive collection procedure. -/
hasLetDeclsInBetween : MetaM Bool := do
let check (lctx : LocalContext) : Bool := do
let start := lctx.getFVar! xs[0] |>.index
let stop := lctx.getFVar! xs.back |>.index
for i in [start+1:stop] do
match lctx.getAt? i with
| some localDecl =>
if localDecl.isLet then
return true
| _ => pure ()
return false
if xs.size <= 1 then
pure false
else
check (← getLCtx)
/- Traverse `e` and stores in the state `NameHashSet` any let-declaration with index greater than `(← read)`.
The context `Nat` is the position of `xs[0]` in the local context. -/
collectLetDeclsFrom (e : Expr) : ReaderT Nat (StateRefT NameHashSet MetaM) Unit := do
let rec visit (e : Expr) : MonadCacheT Expr Unit (ReaderT Nat (StateRefT NameHashSet MetaM)) Unit :=
checkCache e fun _ => do
match e with
| Expr.forallE _ d b _ => visit d; visit b
| Expr.lam _ d b _ => visit d; visit b
| Expr.letE _ t v b _ => visit t; visit v; visit b
| Expr.app f a _ => visit f; visit a
| Expr.mdata _ b _ => visit b
| Expr.proj _ _ b _ => visit b
| Expr.fvar fvarId _ =>
let localDecl ← getLocalDecl fvarId
if localDecl.isLet && localDecl.index > (← read) then
modify fun s => s.insert localDecl.fvarId
| _ => pure ()
visit (← instantiateMVars e) |>.run
/-
Auxiliary definition for traversing all declarations between `xs[0]` ... `xs.back` backwards.
The `Nat` argument is the current position in the local context being visited, and it is less than
or equal to the position of `xs.back` in the local context.
The `Nat` context `(← read)` is the position of `xs[0]` in the local context.
-/
collectLetDepsAux : Nat → ReaderT Nat (StateRefT NameHashSet MetaM) Unit
| 0 => return ()
| i+1 => do
if i+1 == (← read) then
return ()
else
match (← getLCtx).getAt? (i+1) with
| none => collectLetDepsAux i
| some localDecl =>
if (← get).contains localDecl.fvarId then
collectLetDeclsFrom localDecl.type
match localDecl.value? with
| some val => collectLetDeclsFrom val
| _ => pure ()
collectLetDepsAux i
/- Computes the set `ys`. It is a set of `FVarId`s, -/
collectLetDeps : MetaM NameHashSet := do
let lctx ← getLCtx
let start := lctx.getFVar! xs[0] |>.index
let stop := lctx.getFVar! xs.back |>.index
let s := xs.foldl (init := {}) fun s x => s.insert x.fvarId!
let (_, s) ← collectLetDepsAux stop |>.run start |>.run s
return s
/- Computes the array `ys` containing let-decls between `xs[0]` and `xs.back` that
some `x` in `xs` depends on. -/
addLetDeps : MetaM (Array Expr) := do
let lctx ← getLCtx
let s ← collectLetDeps
/- Convert `s` into the array `ys` -/
let start := lctx.getFVar! xs[0] |>.index
let stop := lctx.getFVar! xs.back |>.index
let mut ys := #[]
for i in [start:stop+1] do
match lctx.getAt? i with
| none => pure ()
| some localDecl =>
if s.contains localDecl.fvarId then
ys := ys.push localDecl.toExpr
return ys
/-
Each metavariable is declared in a particular local context.
We use the notation `C |- ?m : t` to denote a metavariable `?m` that
was declared at the local context `C` with type `t` (see `MetavarDecl`).
We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`.
The following method process the unification constraint
?m@C a₁ ... aₙ =?= t
We say the unification constraint is a pattern IFF
1) `a₁ ... aₙ` are pairwise distinct free variables that are *not* let-variables.
2) `a₁ ... aₙ` are not in `C`
3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}`
4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C`
5) `?m` does not occur in `t`
Claim: we don't have to check free variable declarations. That is,
if `t` contains a reference to `x : A := v`, we don't need to check `v`.
Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3).
If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`.
So, condition 4 and 5 are satisfied.
If the conditions above have been satisfied, then the
solution for the unification constrain is
?m := fun a₁ ... aₙ => t
Now, we consider some workarounds/approximations.
A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3)
(precise) solution: unfold `x` in `t`.
A2) Suppose some `aᵢ` is in `C` (failed condition 2)
(approximated) solution (when `config.ctxApprox` is set to true) :
ignore condition and also use
?m := fun a₁ ... aₙ => t
Here is an example where this approximation fails:
Given `C` containing `a : nat`, consider the following two constraints
?m@C a =?= a
?m@C b =?= a
If we use the approximation in the first constraint, we get
?m := fun x => x
when we apply this solution to the second one we get a failure.
IMPORTANT: When applying this approximation we need to make sure the
abstracted term `fun a₁ ... aₙ => t` is type correct. The check
can only be skipped in the pattern case described above. Consider
the following example. Given the local context
(α : Type) (a : α)
we try to solve
?m α =?= @id α a
If we use the approximation above we obtain:
?m := (fun α' => @id α' a)
which is a type incorrect term. `a` has type `α` but it is expected to have
type `α'`.
The problem occurs because the right hand side contains a free variable
`a` that depends on the free variable `α` being abstracted. Note that
this dependency cannot occur in patterns.
We can address this by type checking
the term after abstraction. This is not a significant performance
bottleneck because this case doesn't happen very often in practice
(262 times when compiling stdlib on Jan 2018). The second example
is trickier, but it also occurs less frequently (8 times when compiling
stdlib on Jan 2018, and all occurrences were at Init/Control when
we define monads and auxiliary combinators for them).
We considered three options for the addressing the issue on the second example:
A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1).
In Lean3, we would try to approximate this case using an approach similar to A2.
However, this approximation complicates the code, and is never used in the
Lean3 stdlib and mathlib.
A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`.
If `?m'` is assigned, we substitute.
If not, we create an auxiliary metavariable with a smaller scope.
Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step.
A5) If some `aᵢ` is not a free variable,
then we use first-order unification (if `config.foApprox` is set to true)
?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k
reduces to
?M a_1 ... a_i =?= f
a_{i+1} =?= b_1
...
a_{i+k} =?= b_k
A6) If (m =?= v) is of the form
?m a_1 ... a_n =?= ?m b_1 ... b_k
then we use first-order unification (if `config.foApprox` is set to true)
A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form
```
?m s₁ ... sₙ =?= t
```
where `s₁ ... sₙ` are arbitrary terms. We solve them by assigning the constant function to `?m`.
```
?m := fun _ ... _ => t
```
In general, this approximation may produce bad solutions, and may prevent coercions from being tried.
For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`.
In this situation, the
elaborator generates the unification constraint
```
?m Prop =?= IO Bool
```
It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation
produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from
the decidable proposition `x > 0` to `Bool`.
On the other hand, the constant approximation is desirable for elaborating the term
```
let f (x : _) := pure "hello"; f ()
```
with expected type `IO String`.
In this example, the following unification contraint is generated.
```
?m () String =?= IO String
```
It is not a higher-order pattern, first-order approximation reduces it to
```
?m () =?= IO
```
which fails to be solved. However, constant approximation solves it by assigning
```
?m := fun _ => IO
```
Note that `f`s type is `(x : ?α) -> ?m x String`. The metavariable `?m` may depend on `x`.
If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide
whether we should apply it or not. The heuristic is based on observing where the constraints above come from.
In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to
be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model
a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f`
does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected
by any functional programmer used to non-dependently type languages (e.g., Haskell).
We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks
how many metavariable arguments are representing dependencies.
-/
def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : MetaM Expr := do
mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs
namespace CheckAssignment
builtin_initialize checkAssignmentExceptionId : InternalExceptionId ← registerInternalExceptionId `checkAssignment
builtin_initialize outOfScopeExceptionId : InternalExceptionId ← registerInternalExceptionId `outOfScope
structure State where
cache : ExprStructMap Expr := {}
structure Context where
mvarId : MVarId
mvarDecl : MetavarDecl
fvars : Array Expr
hasCtxLocals : Bool
rhs : Expr
abbrev CheckAssignmentM := ReaderT Context $ StateRefT State MetaM
def throwCheckAssignmentFailure : CheckAssignmentM α :=
throw <| Exception.internal checkAssignmentExceptionId
def throwOutOfScopeFVar : CheckAssignmentM α :=
throw <| Exception.internal outOfScopeExceptionId
private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do
return (← get).cache.find? e
private def cache (e r : Expr) : CheckAssignmentM Unit := do
modify fun s => { s with cache := s.cache.insert e r }
instance : MonadCache Expr Expr CheckAssignmentM where
findCached? := findCached?
cache := cache
@[inline] private def visit (f : Expr → CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr :=
if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e (fun _ => f e)
private def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do
let ctx ← read
return m!"{msg} @ {mkMVar ctx.mvarId} {ctx.fvars} := {ctx.rhs}"
@[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do
let mvarDecl ← getMVarDecl mvarId
let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context }
let x : CheckAssignmentM (Option Expr) :=
catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId]
(do let e ← x; return some e)
(fun _ => pure none)
x.run ctx |>.run' {}
mutual
partial def checkFVar (fvar : Expr) : CheckAssignmentM Expr := do
let ctxMeta ← readThe Meta.Context
let ctx ← read
if ctx.mvarDecl.lctx.containsFVar fvar then
pure fvar
else
let lctx := ctxMeta.lctx
match lctx.findFVar? fvar with
| some (LocalDecl.ldecl (value := v) ..) => visit check v
| _ =>
if ctx.fvars.contains fvar then pure fvar
else
traceM `Meta.isDefEq.assign.outOfScopeFVar do addAssignmentInfo fvar
throwOutOfScopeFVar
partial def checkMVar (mvar : Expr) : CheckAssignmentM Expr := do
let mvarId := mvar.mvarId!
let ctx ← read
let mctx ← getMCtx
if mvarId == ctx.mvarId then
traceM `Meta.isDefEq.assign.occursCheck <| addAssignmentInfo "occurs check failed"
throwCheckAssignmentFailure
else match mctx.getExprAssignment? mvarId with
| some v => check v
| none =>
match mctx.findDecl? mvarId with
| none => throwUnknownMVar mvarId
| some mvarDecl =>
if ctx.hasCtxLocals then
throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification
else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then
/- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned.
We "substract" variables being abstracted because we use `elimMVarDeps` -/
pure mvar
else if mvarDecl.depth != mctx.depth || mvarDecl.kind.isSyntheticOpaque then
traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId)
throwCheckAssignmentFailure
else
let ctxMeta ← readThe Meta.Context
if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then
/- Create an auxiliary metavariable with a smaller context and "checked" type.
Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains
a metavariable that we also need to reduce the context.
We remove from `ctx.mvarDecl.lctx` any variable that is not in `mvarDecl.lctx`
or in `ctx.fvars`. We don't need to remove the ones in `ctx.fvars` because
`elimMVarDeps` will take care of them.
First, we collect `toErase` the variables that need to be erased.
Notat that if a variable is `ctx.fvars`, but it depends on variable at `toErase`,
we must also erase it.
-/
let toErase := mvarDecl.lctx.foldl (init := #[]) fun toErase localDecl =>
if ctx.mvarDecl.lctx.contains localDecl.fvarId then
toErase
else if ctx.fvars.any fun fvar => fvar.fvarId! == localDecl.fvarId then
if mctx.findLocalDeclDependsOn localDecl fun fvarId => toErase.contains fvarId then
-- localDecl depends on a variable that will be erased. So, we must add it to `toErase` too
toErase.push localDecl.fvarId
else
toErase
else
toErase.push localDecl.fvarId
let lctx := toErase.foldl (init := mvarDecl.lctx) fun lctx toEraseFVar =>
lctx.erase toEraseFVar
/- Compute new set of local instances. -/
let localInsts := mvarDecl.localInstances.filter fun localInst => toErase.contains localInst.fvar.fvarId!
let mvarType ← check mvarDecl.type
let newMVar ← mkAuxMVar lctx localInsts mvarType mvarDecl.numScopeArgs
modifyThe Meta.State fun s => { s with mctx := s.mctx.assignExpr mvarId newMVar }
pure newMVar
else
traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId)
throwCheckAssignmentFailure
/-
Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables,
and one of them is out-of-scope.
See `Expr.app` case at `check`.
If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope,
an assigning `?m := fun _ ... _ => ?n` -/
partial def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do
let mvarType ← inferType mvar
forallBoundedTelescope mvarType numArgs fun xs _ => do
if xs.size != numArgs then pure false
else
let some v ← mkLambdaFVarsWithLetDeps xs newMVar | return false
match (← checkAssignmentAux mvar.mvarId! #[] false v) with
| some v => checkTypesAndAssign mvar v
| none => return false
-- See checkAssignment
partial def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do
run (check v) mvarId fvars hasCtxLocals v
partial def checkApp (e : Expr) : CheckAssignmentM Expr :=
e.withApp fun f args => do
let ctxMeta ← readThe Meta.Context
if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then
let f ← visit checkMVar f
catchInternalId outOfScopeExceptionId
(do
let args ← args.mapM (visit check)
return mkAppN f args)
(fun ex => do
if !f.isMVar then
throw ex
else if (← isDelayedAssigned f.mvarId!) then
throw ex
else
let eType ← inferType e
let mvarType ← check eType
/- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar`
Note that `mvarType` may be different from `eType`. -/
let ctx ← read
let newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType
if (← assignToConstFun f args.size newMVar) then
pure newMVar
else
throw ex)
else
let f ← visit check f
let args ← args.mapM (visit check)
return mkAppN f args
partial def check (e : Expr) : CheckAssignmentM Expr := do
match e with
| Expr.mdata _ b _ => return e.updateMData! (← visit check b)
| Expr.proj _ _ s _ => return e.updateProj! (← visit check s)
| Expr.lam _ d b _ => return e.updateLambdaE! (← visit check d) (← visit check b)
| Expr.forallE _ d b _ => return e.updateForallE! (← visit check d) (← visit check b)
| Expr.letE _ t v b _ => return e.updateLet! (← visit check t) (← visit check v) (← visit check b)
| Expr.bvar .. => return e
| Expr.sort .. => return e
| Expr.const .. => return e
| Expr.lit .. => return e
| Expr.fvar .. => visit checkFVar e
| Expr.mvar .. => visit checkMVar e
| Expr.app .. =>
checkApp e
-- TODO: investigate whether the following feature is too expensive or not
/-
catchInternalIds [checkAssignmentExceptionId, outOfScopeExceptionId]
(checkApp e)
fun ex => do
let e' ← whnfR e
if e != e' then
check e'
else
throw ex
-/
end
end CheckAssignment
namespace CheckAssignmentQuick
partial def check
(hasCtxLocals ctxApprox : Bool)
(mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) (e : Expr) : Bool :=
let rec visit (e : Expr) : Bool :=
if !e.hasExprMVar && !e.hasFVar then
true
else match e with
| Expr.mdata _ b _ => visit b
| Expr.proj _ _ s _ => visit s
| Expr.app f a _ => visit f && visit a
| Expr.lam _ d b _ => visit d && visit b
| Expr.forallE _ d b _ => visit d && visit b
| Expr.letE _ t v b _ => visit t && visit v && visit b
| Expr.bvar .. => true
| Expr.sort .. => true
| Expr.const .. => true
| Expr.lit .. => true
| Expr.fvar fvarId .. =>
if mvarDecl.lctx.contains fvarId then true
else match lctx.find? fvarId with
| some (LocalDecl.ldecl (value := v) ..) => false -- need expensive CheckAssignment.check
| _ =>
if fvars.any fun x => x.fvarId! == fvarId then true
else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it
| Expr.mvar mvarId' _ =>
match mctx.getExprAssignment? mvarId' with
| some _ => false -- use CheckAssignment.check to instantiate
| none =>
if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception
else match mctx.findDecl? mvarId' with
| none => false
| some mvarDecl' =>
if hasCtxLocals then false -- use CheckAssignment.check
else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true
else false -- use CheckAssignment.check
visit e
end CheckAssignmentQuick
/--
Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`.
It will check whether we can perform the assignment
```
?m := fun fvars => v
```
The result is `none` if the assignment can't be performed.
The result is `some newV` where `newV` is a possibly updated `v`. This method may need
to unfold let-declarations. -/
def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do
/- Check whether `mvarId` occurs in the type of `fvars` or not. If it does, return `none`
to prevent us from creating the cyclic assignment `?m := fun fvars => v` -/
for fvar in fvars do
unless (← occursCheck mvarId (← inferType fvar)) do
return none
if !v.hasExprMVar && !v.hasFVar then
pure (some v)
else
let mvarDecl ← getMVarDecl mvarId
let hasCtxLocals := fvars.any fun fvar => mvarDecl.lctx.containsFVar fvar
let ctx ← read
let mctx ← getMCtx
if CheckAssignmentQuick.check hasCtxLocals ctx.config.ctxApprox mctx ctx.lctx mvarDecl mvarId fvars v then
pure (some v)
else
let v ← instantiateMVars v
CheckAssignment.checkAssignmentAux mvarId fvars hasCtxLocals v
private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool :=
match v with
| Expr.app f a _ =>
if args.isEmpty then
pure false
else
Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f
| _ => pure false
/-
Auxiliary method for applying first-order unification. It is an approximation.
Remark: this method is trying to solve the unification constraint:
?m a₁ ... aₙ =?= v
It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`.
We have added support for unfolding here because we want to be able to solve unification problems such as
?m Unit =?= ITactic
where `ITactic` is defined as
def ITactic := Tactic Unit
-/
private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool :=
let rec loop (v : Expr) := do
let cfg ← getConfig
if !cfg.foApprox then
pure false
else
trace[Meta.isDefEq.foApprox] "{mvar} {args} := {v}"
let v := v.headBeta
if (← checkpointDefEq <| processAssignmentFOApproxAux mvar args v) then
pure true
else
match (← unfoldDefinition? v) with
| none => pure false
| some v => loop v
loop v
private partial def simpAssignmentArgAux : Expr → MetaM Expr
| Expr.mdata _ e _ => simpAssignmentArgAux e
| e@(Expr.fvar fvarId _) => do
let decl ← getLocalDecl fvarId
match decl.value? with
| some value => simpAssignmentArgAux value
| _ => pure e
| e => pure e
/- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`.
We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`,
and then removes metadata, and zeta-expand let-decls. -/
private def simpAssignmentArg (arg : Expr) : MetaM Expr := do
let arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg
simpAssignmentArgAux arg
/- Assign `mvar := fun a_1 ... a_{numArgs} => v`.
We use it at `processConstApprox` and `isDefEqMVarSelf` -/
private def assignConst (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do
let mvarDecl ← getMVarDecl mvar.mvarId!
forallBoundedTelescope mvarDecl.type numArgs fun xs _ => do
if xs.size != numArgs then
pure false
else
let some v ← mkLambdaFVarsWithLetDeps xs v | pure false
match (← checkAssignment mvar.mvarId! #[] v) with
| none => pure false
| some v =>
trace[Meta.isDefEq.constApprox] "{mvar} := {v}"
checkTypesAndAssign mvar v
private def processConstApprox (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do
let cfg ← getConfig
let mvarId := mvar.mvarId!
let mvarDecl ← getMVarDecl mvarId
if mvarDecl.numScopeArgs == numArgs || cfg.constApprox then
assignConst mvar numArgs v
else
pure false
/-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`.
It assumes `?m` is unassigned. -/
private partial def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool :=
traceCtx `Meta.isDefEq.assign do
trace[Meta.isDefEq.assign] "{mvarApp} := {v}"
let mvar := mvarApp.getAppFn
let mvarDecl ← getMVarDecl mvar.mvarId!
let rec process (i : Nat) (args : Array Expr) (v : Expr) := do
let cfg ← getConfig
let useFOApprox (args : Array Expr) : MetaM Bool :=
processAssignmentFOApprox mvar args v <||> processConstApprox mvar args.size v
if h : i < args.size then
let arg := args.get ⟨i, h⟩
let arg ← simpAssignmentArg arg
let args := args.set ⟨i, h⟩ arg
match arg with
| Expr.fvar fvarId _ =>
if args[0:i].any fun prevArg => prevArg == arg then
useFOApprox args
else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then
useFOApprox args
else
process (i+1) args v
| _ =>
useFOApprox args
else
let v ← instantiateMVars v -- enforce A4
if v.getAppFn == mvar then
-- using A6
useFOApprox args
else
let mvarId := mvar.mvarId!
match (← checkAssignment mvarId args v) with
| none => useFOApprox args
| some v => do
trace[Meta.isDefEq.assign.beforeMkLambda] "{mvar} {args} := {v}"
let some v ← mkLambdaFVarsWithLetDeps args v | return false
if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then
/- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced
a type incorrect term. See discussion at A2 -/
if (← isTypeCorrect v) then
checkTypesAndAssign mvar v
else
trace[Meta.isDefEq.assign.typeError] "{mvar} := {v}"
useFOApprox args
else
checkTypesAndAssign mvar v
process 0 mvarApp.getAppArgs v
/--
Similar to processAssignment, but if it fails, compute v's whnf and try again.
This helps to solve constraints such as `?m =?= { α := ?m, ... }.α`
Note this is not perfect solution since we still fail occurs check for constraints such as
```lean
?m =?= List { α := ?m, β := Nat }.β
```
-/
private def processAssignment' (mvarApp : Expr) (v : Expr) : MetaM Bool := do
if (← processAssignment mvarApp v) then
return true
else
let vNew ← whnf v
if vNew != v then
if mvarApp == vNew then
return true
else
processAssignment mvarApp vNew
else
return false
private def isDeltaCandidate? (t : Expr) : MetaM (Option ConstantInfo) := do
match t.getAppFn with
| Expr.const c _ _ =>
match (← getConst? c) with
| r@(some info) => if info.hasValue then return r else return none
| _ => return none
| _ => pure none
/-- Auxiliary method for isDefEqDelta -/
private def isListLevelDefEq (us vs : List Level) : MetaM LBool :=
toLBoolM <| isListLevelDefEqAux us vs
/-- Auxiliary method for isDefEqDelta -/
private def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do
trace[Meta.isDefEq.delta.unfoldLeft] fn
toLBoolM <| Meta.isExprDefEqAux t s
/-- Auxiliary method for isDefEqDelta -/
private def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do
trace[Meta.isDefEq.delta.unfoldRight] fn
toLBoolM <| Meta.isExprDefEqAux t s
/-- Auxiliary method for isDefEqDelta -/
private def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do
trace[Meta.isDefEq.delta.unfoldLeftRight] fn
toLBoolM <| Meta.isExprDefEqAux t s
/-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`.
Auxiliary method for isDefEqDelta -/
private def tryHeuristic (t s : Expr) : MetaM Bool :=
let tFn := t.getAppFn
let sFn := s.getAppFn
traceCtx `Meta.isDefEq.delta do
/-
We process arguments before universe levels to reduce a source of brittleness in the TC procedure.
In the TC procedure, we can solve problems containing metavariables.
If the TC procedure tries to assign one of these metavariables, it interrupts the search
using a "stuck" exception. The elaborator catches it, and "interprets" it as "we should try again later".
Now suppose we have a TC problem, and there are two "local" candidate instances we can try: "bad" and "good".
The "bad" candidate is stuck because of a universe metavariable in the TC problem.
If we try "bad" first, the TC procedure is interrupted. Moreover, if we have ignored the exception,
"bad" would fail anyway trying to assign two different free variables `α =?= β`.
Example: `Preorder.{?u} α =?= Preorder.{?v} β`, where `?u` and `?v` are universe metavariables that were
not created by the TC procedure.
The key issue here is that we have an `isDefEq t s` invocation that is interrupted by the "stuck" exception,
but it would have failed anyway if we had continued processing it.
By solving the arguments first, we make the example above fail without throwing the "stuck" exception.
TODO: instead of throwing an exception as soon as we get stuck, we should just set a flag.
Then the entry-point for `isDefEq` checks the flag before returning `true`.
-/
checkpointDefEq do
let b ← isDefEqArgs tFn t.getAppArgs s.getAppArgs
<&&>
isListLevelDefEqAux tFn.constLevels! sFn.constLevels!
unless b do
trace[Meta.isDefEq.delta] "heuristic failed {t} =?= {s}"
pure b
/-- Auxiliary method for isDefEqDelta -/
private abbrev unfold (e : Expr) (failK : MetaM α) (successK : Expr → MetaM α) : MetaM α := do
match (← unfoldDefinition? e) with
| some e => successK e
| none => failK
/-- Auxiliary method for isDefEqDelta -/
private def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := do
match t, s with
| Expr.const _ ls₁ _, Expr.const _ ls₂ _ => isListLevelDefEq ls₁ ls₂
| Expr.app _ _ _, Expr.app _ _ _ =>
if (← tryHeuristic t s) then
pure LBool.true
else
unfold t
(unfold s (pure LBool.false) (fun s => isDefEqRight fn t s))
(fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s))
| _, _ => pure LBool.false
private def sameHeadSymbol (t s : Expr) : Bool :=
match t.getAppFn, s.getAppFn with
| Expr.const c₁ _ _, Expr.const c₂ _ _ => true
| _, _ => false
/--
- If headSymbol (unfold t) == headSymbol s, then unfold t
- If headSymbol (unfold s) == headSymbol t, then unfold s
- Otherwise unfold t and s if possible.
Auxiliary method for isDefEqDelta -/
private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool :=
unfold t
(unfold s
(pure LBool.undef) -- `t` and `s` failed to be unfolded
(fun s => isDefEqRight sInfo.name t s))
(fun tNew =>
if sameHeadSymbol tNew s then
isDefEqLeft tInfo.name tNew s
else
unfold s
(isDefEqLeft tInfo.name tNew s)
(fun sNew =>
if sameHeadSymbol t sNew then
isDefEqRight sInfo.name t sNew
else
isDefEqLeftRight tInfo.name tNew sNew))
/-- If `t` and `s` do not contain metavariables, then use
kernel definitional equality heuristics.
Otherwise, use `unfoldComparingHeadsDefEq`.
Auxiliary method for isDefEqDelta -/
private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool :=
if !t.hasExprMVar && !s.hasExprMVar then
/- If `t` and `s` do not contain metavariables,
we simulate strategy used in the kernel. -/
if tInfo.hints.lt sInfo.hints then
unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s
else if sInfo.hints.lt tInfo.hints then
unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s
else
unfoldComparingHeadsDefEq tInfo sInfo t s
else
unfoldComparingHeadsDefEq tInfo sInfo t s
/--
When `TransparencyMode` is set to `default` or `all`.
If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s`
If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)`
Otherwise, use `unfoldDefEq`
Auxiliary method for isDefEqDelta -/
private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do
if (← shouldReduceReducibleOnly) then
unfoldDefEq tInfo sInfo t s
else
let tReducible ← isReducible tInfo.name
let sReducible ← isReducible sInfo.name
if tReducible && !sReducible then
unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s
else if !tReducible && sReducible then
unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s
else
unfoldDefEq tInfo sInfo t s
/--
If `t` is a projection function application and `s` is not ==> `isDefEqRight t (unfold s)`
If `s` is a projection function application and `t` is not ==> `isDefEqRight (unfold t) s`
Otherwise, use `unfoldReducibeDefEq`
Auxiliary method for isDefEqDelta -/
private def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do
let tProj? ← isProjectionFn tInfo.name
let sProj? ← isProjectionFn sInfo.name
if tProj? && !sProj? then
unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s
else if !tProj? && sProj? then
unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s
else
unfoldReducibeDefEq tInfo sInfo t s
/--
isDefEq by lazy delta reduction.
This method implements many different heuristics:
1- If only `t` can be unfolded => then unfold `t` and continue
2- If only `s` can be unfolded => then unfold `s` and continue
3- If `t` and `s` can be unfolded and they have the same head symbol, then
a) First try to solve unification by unifying arguments.
b) If it fails, unfold both and continue.
Implemented by `unfoldBothDefEq`
4- If `t` is a projection function application and `s` is not => then unfold `s` and continue.
5- If `s` is a projection function application and `t` is not => then unfold `t` and continue.
Remark: 4&5 are implemented by `unfoldNonProjFnDefEq`
6- If `t` is reducible and `s` is not => then unfold `t` and continue.
7- If `s` is reducible and `t` is not => then unfold `s` and continue
Remark: 6&7 are implemented by `unfoldReducibeDefEq`
8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel.
Implemented by `unfoldDefEq`
9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue.
10- If `headSymbol (unfold s) == headSymbol t`, then unfold s
11- Otherwise, unfold `t` and `s` and continue.
Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/
private def isDefEqDelta (t s : Expr) : MetaM LBool := do
let tInfo? ← isDeltaCandidate? t.getAppFn
let sInfo? ← isDeltaCandidate? s.getAppFn
match tInfo?, sInfo? with
| none, none => pure LBool.undef
| some tInfo, none => unfold t (pure LBool.undef) fun t => isDefEqLeft tInfo.name t s
| none, some sInfo => unfold s (pure LBool.undef) fun s => isDefEqRight sInfo.name t s
| some tInfo, some sInfo =>
if tInfo.name == sInfo.name then
unfoldBothDefEq tInfo.name t s
else
unfoldNonProjFnDefEq tInfo sInfo t s
private def isAssigned : Expr → MetaM Bool
| Expr.mvar mvarId _ => isExprMVarAssigned mvarId
| _ => pure false
private def isDelayedAssignedHead (tFn : Expr) (t : Expr) : MetaM Bool := do
match tFn with
| Expr.mvar mvarId _ =>
if (← isDelayedAssigned mvarId) then
let tNew ← instantiateMVars t
return tNew != t
else
pure false
| _ => pure false
private def isSynthetic : Expr → MetaM Bool
| Expr.mvar mvarId _ => do
let mvarDecl ← getMVarDecl mvarId
match mvarDecl.kind with
| MetavarKind.synthetic => pure true
| MetavarKind.syntheticOpaque => pure true
| MetavarKind.natural => pure false
| _ => pure false
private def isAssignable : Expr → MetaM Bool
| Expr.mvar mvarId _ => do let b ← isReadOnlyOrSyntheticOpaqueExprMVar mvarId; pure (!b)
| _ => pure false
private def etaEq (t s : Expr) : Bool :=
match t.etaExpanded? with
| some t => t == s
| none => false
private def isLetFVar (fvarId : FVarId) : MetaM Bool := do
let decl ← getLocalDecl fvarId
pure decl.isLet
private def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do
if (← getConfig).proofIrrelevance then
let status ← isProofQuick t
match status with
| LBool.false =>
pure LBool.undef
| LBool.true =>
let tType ← inferType t
let sType ← inferType s
toLBoolM <| Meta.isExprDefEqAux tType sType
| LBool.undef =>
let tType ← inferType t
if (← isProp tType) then
let sType ← inferType s
toLBoolM <| Meta.isExprDefEqAux tType sType
else
pure LBool.undef
else
pure LBool.undef
/- Try to solve constraint of the form `?m args₁ =?= ?m args₂`.
- First try to unify `args₁` and `args₂`, and return true if successful
- Otherwise, try to assign `?m` to a constant function of the form `fun x_1 ... x_n => ?n`
where `?n` is a fresh metavariable. See `processConstApprox`. -/
private def isDefEqMVarSelf (mvar : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do
if args₁.size != args₂.size then
pure false
else if (← isDefEqArgs mvar args₁ args₂) then
pure true
else if !(← isAssignable mvar) then
pure false
else
let cfg ← getConfig
let mvarId := mvar.mvarId!
let mvarDecl ← getMVarDecl mvarId
if mvarDecl.numScopeArgs == args₁.size || cfg.constApprox then
let type ← inferType (mkAppN mvar args₁)
let auxMVar ← mkAuxMVar mvarDecl.lctx mvarDecl.localInstances type
assignConst mvar args₁.size auxMVar
else
pure false
/- Remove unnecessary let-decls -/
private def consumeLet : Expr → Expr
| e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b
| e => e
mutual
private partial def isDefEqQuick (t s : Expr) : MetaM LBool :=
let t := consumeLet t
let s := consumeLet s
match t, s with
| Expr.lit l₁ _, Expr.lit l₂ _ => return (l₁ == l₂).toLBool
| Expr.sort u _, Expr.sort v _ => toLBoolM <| isLevelDefEqAux u v
| Expr.lam .., Expr.lam .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s
| Expr.forallE .., Expr.forallE .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s
| Expr.mdata _ t _, s => isDefEqQuick t s
| t, Expr.mdata _ s _ => isDefEqQuick t s
| Expr.fvar fvarId₁ _, Expr.fvar fvarId₂ _ => do
if (← isLetFVar fvarId₁ <||> isLetFVar fvarId₂) then
pure LBool.undef
else if fvarId₁ == fvarId₂ then
pure LBool.true
else
isDefEqProofIrrel t s
| t, s =>
isDefEqQuickOther t s
private partial def isDefEqQuickOther (t s : Expr) : MetaM LBool := do
if t == s then
pure LBool.true
else if etaEq t s || etaEq s t then
pure LBool.true -- t =?= (fun xs => t xs)
else
let tFn := t.getAppFn
let sFn := s.getAppFn
if !tFn.isMVar && !sFn.isMVar then
pure LBool.undef
else if (← isAssigned tFn) then
let t ← instantiateMVars t
isDefEqQuick t s
else if (← isAssigned sFn) then
let s ← instantiateMVars s
isDefEqQuick t s
else if (← isDelayedAssignedHead tFn t) then
let t ← instantiateMVars t
isDefEqQuick t s
else if (← isDelayedAssignedHead sFn s) then
let s ← instantiateMVars s
isDefEqQuick t s
else if (← isSynthetic tFn <&&> trySynthPending tFn) then
let t ← instantiateMVars t
isDefEqQuick t s
else if (← isSynthetic sFn <&&> trySynthPending sFn) then
let s ← instantiateMVars s
isDefEqQuick t s
else if tFn.isMVar && sFn.isMVar && tFn == sFn then
Bool.toLBool <$> isDefEqMVarSelf tFn t.getAppArgs s.getAppArgs
else
let tAssign? ← isAssignable tFn
let sAssign? ← isAssignable sFn
let assignableMsg (b : Bool) := if b then "[assignable]" else "[nonassignable]"
trace[Meta.isDefEq] "{t} {assignableMsg tAssign?} =?= {s} {assignableMsg sAssign?}"
if tAssign? && !sAssign? then
toLBoolM <| processAssignment' t s
else if !tAssign? && sAssign? then
toLBoolM <| processAssignment' s t
else if !tAssign? && !sAssign? then
if tFn.isMVar || sFn.isMVar then
let ctx ← read
if ctx.config.isDefEqStuckEx then do
trace[Meta.isDefEq.stuck] "{t} =?= {s}"
Meta.throwIsDefEqStuck
else
pure LBool.false
else
pure LBool.undef
else
isDefEqQuickMVarMVar t s
-- Both `t` and `s` are terms of the form `?m ...`
private partial def isDefEqQuickMVarMVar (t s : Expr) : MetaM LBool := do
let tFn := t.getAppFn
let sFn := s.getAppFn
let tMVarDecl ← getMVarDecl tFn.mvarId!
let sMVarDecl ← getMVarDecl sFn.mvarId!
if s.isMVar && !t.isMVar then
/- Solve `?m t =?= ?n` by trying first `?n := ?m t`.
Reason: this assignment is precise. -/
if (← checkpointDefEq (processAssignment s t)) then
pure LBool.true
else
toLBoolM <| processAssignment t s
else
if (← checkpointDefEq (processAssignment t s)) then
pure LBool.true
else
toLBoolM <| processAssignment s t
end
@[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do
let status ← x
match status with
| LBool.true => pure true
| LBool.false => pure false
| LBool.undef => k
@[specialize] private def unstuckMVar (e : Expr) (successK : Expr → MetaM Bool) (failK : MetaM Bool): MetaM Bool := do
match (← getStuckMVar? e) with
| some mvarId =>
trace[Meta.isDefEq.stuckMVar] "found stuck MVar {mkMVar mvarId} : {← inferType (mkMVar mvarId)}"
if (← Meta.synthPending mvarId) then
let e ← instantiateMVars e
successK e
else
failK
| none => failK
private def isDefEqOnFailure (t s : Expr) : MetaM Bool :=
unstuckMVar t (fun t => Meta.isExprDefEqAux t s) <|
unstuckMVar s (fun s => Meta.isExprDefEqAux t s) <|
tryUnificationHints t s <||> tryUnificationHints s t
private def isDefEqProj : Expr → Expr → MetaM Bool
| Expr.proj _ i t _, Expr.proj _ j s _ => pure (i == j) <&&> Meta.isExprDefEqAux t s
| _, _ => pure false
/-
Given applications `t` and `s` that are in WHNF (modulo the current transparency setting),
check whether they are definitionally equal or not.
-/
private def isDefEqApp (t s : Expr) : MetaM Bool := do
let tFn := t.getAppFn
let sFn := s.getAppFn
if tFn.isConst && sFn.isConst && tFn.constName! == sFn.constName! then
/- See comment at `tryHeuristic` explaining why we processe arguments before universe levels. -/
if (← checkpointDefEq (isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!)) then
return true
else
isDefEqOnFailure t s
else if (← checkpointDefEq (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) then
return true
else
isDefEqOnFailure t s
partial def isExprDefEqAuxImpl (t : Expr) (s : Expr) : MetaM Bool := do
trace[Meta.isDefEq.step] "{t} =?= {s}"
checkMaxHeartbeats "isDefEq"
withNestedTraces do
whenUndefDo (isDefEqQuick t s) do
whenUndefDo (isDefEqProofIrrel t s) do
let t' ← whnfCore t
let s' ← whnfCore s
if t != t' || s != s' then
isExprDefEqAuxImpl t' s'
else do
if (← (isDefEqEta t s <||> isDefEqEta s t)) then pure true else
if (← isDefEqProj t s) then pure true else
whenUndefDo (isDefEqNative t s) do
whenUndefDo (isDefEqNat t s) do
whenUndefDo (isDefEqOffset t s) do
whenUndefDo (isDefEqDelta t s) do
if t.isConst && s.isConst then
if t.constName! == s.constName! then isListLevelDefEqAux t.constLevels! s.constLevels! else pure false
else if t.isApp && s.isApp then
isDefEqApp t s
else
whenUndefDo (isDefEqStringLit t s) do
isDefEqOnFailure t s
builtin_initialize
isExprDefEqAuxRef.set isExprDefEqAuxImpl
builtin_initialize
registerTraceClass `Meta.isDefEq
registerTraceClass `Meta.isDefEq.foApprox
registerTraceClass `Meta.isDefEq.constApprox
registerTraceClass `Meta.isDefEq.delta
registerTraceClass `Meta.isDefEq.step
registerTraceClass `Meta.isDefEq.assign
end Lean.Meta
|
a0b593dd3757ebce40f39dc06c14919f9d71cd53 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Data/PersistentHashMap/Basic.lean | 0e638f8ac7dbeb1610ba8ffce969e67bbda14f4d | [
"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 | 13,441 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Array
import Init.Data.Hashable
universes u v w w'
namespace PersistentHashMap
inductive Entry (α : Type u) (β : Type v) (σ : Type w)
| entry {} (key : α) (val : β) : Entry
| ref {} (node : σ) : Entry
| null {} : Entry
instance Entry.inhabited {α β σ} : Inhabited (Entry α β σ) := ⟨Entry.null⟩
inductive Node (α : Type u) (β : Type v) : Type (max u v)
| entries (es : Array (Entry α β Node)) : Node
| collision (ks : Array α) (vs : Array β) (h : ks.size = vs.size) : Node
instance Node.inhabited {α β} : Inhabited (Node α β) := ⟨Node.entries #[]⟩
abbrev shift : USize := 5
abbrev branching : USize := USize.ofNat (2 ^ shift.toNat)
abbrev maxDepth : USize := 7
abbrev maxCollisions : Nat := 4
def mkEmptyEntriesArray {α β} : Array (Entry α β (Node α β)) :=
(Array.mkArray PersistentHashMap.branching.toNat PersistentHashMap.Entry.null)
end PersistentHashMap
structure PersistentHashMap (α : Type u) (β : Type v) [HasBeq α] [Hashable α] :=
(root : PersistentHashMap.Node α β := PersistentHashMap.Node.entries PersistentHashMap.mkEmptyEntriesArray)
(size : Nat := 0)
abbrev PHashMap (α : Type u) (β : Type v) [HasBeq α] [Hashable α] := PersistentHashMap α β
namespace PersistentHashMap
variables {α : Type u} {β : Type v}
def empty [HasBeq α] [Hashable α] : PersistentHashMap α β := {}
instance [HasBeq α] [Hashable α] : HasEmptyc (PersistentHashMap α β) := ⟨empty⟩
def isEmpty [HasBeq α] [Hashable α] (m : PersistentHashMap α β) : Bool :=
m.size == 0
instance [HasBeq α] [Hashable α] : Inhabited (PersistentHashMap α β) := ⟨{}⟩
def mkEmptyEntries {α β} : Node α β :=
Node.entries mkEmptyEntriesArray
abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift
abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift
abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1)
inductive IsCollisionNode : Node α β → Prop
| mk (keys : Array α) (vals : Array β) (h : keys.size = vals.size) : IsCollisionNode (Node.collision keys vals h)
abbrev CollisionNode (α β) := { n : Node α β // IsCollisionNode n }
inductive IsEntriesNode : Node α β → Prop
| mk (entries : Array (Entry α β (Node α β))) : IsEntriesNode (Node.entries entries)
abbrev EntriesNode (α β) := { n : Node α β // IsEntriesNode n }
private theorem setSizeEq {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (i : Fin ks.size) (j : Fin vs.size) (k : α) (v : β)
: (ks.set i k).size = (vs.set j v).size :=
have h₁ : (ks.set i k).size = ks.size from Array.szFSetEq _ _ _;
have h₂ : (vs.set j v).size = vs.size from Array.szFSetEq _ _ _;
(h₁.trans h).trans h₂.symm
private theorem pushSizeEq {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (k : α) (v : β) : (ks.push k).size = (vs.push v).size :=
have h₁ : (ks.push k).size = ks.size + 1 from Array.szPushEq _ _;
have h₂ : (vs.push v).size = vs.size + 1 from Array.szPushEq _ _;
have h₃ : ks.size + 1 = vs.size + 1 from h ▸ rfl;
(h₁.trans h₃).trans h₂.symm
partial def insertAtCollisionNodeAux [HasBeq α] : CollisionNode α β → Nat → α → β → CollisionNode α β
| n@⟨Node.collision keys vals heq, _⟩, i, k, v =>
if h : i < keys.size then
let idx : Fin keys.size := ⟨i, h⟩;
let k' := keys.get idx;
if k == k' then
let j : Fin vals.size := ⟨i, heq ▸ h⟩;
⟨Node.collision (keys.set idx k) (vals.set j v) (setSizeEq heq idx j k v), IsCollisionNode.mk _ _ _⟩
else insertAtCollisionNodeAux n (i+1) k v
else
⟨Node.collision (keys.push k) (vals.push v) (pushSizeEq heq k v), IsCollisionNode.mk _ _ _⟩
| ⟨Node.entries _, h⟩, _, _, _ => False.elim (nomatch h)
def insertAtCollisionNode [HasBeq α] : CollisionNode α β → α → β → CollisionNode α β :=
fun n k v => insertAtCollisionNodeAux n 0 k v
def getCollisionNodeSize : CollisionNode α β → Nat
| ⟨Node.collision keys _ _, _⟩ => keys.size
| ⟨Node.entries _, h⟩ => False.elim (nomatch h)
def mkCollisionNode (k₁ : α) (v₁ : β) (k₂ : α) (v₂ : β) : Node α β :=
let ks : Array α := Array.mkEmpty maxCollisions;
let ks := (ks.push k₁).push k₂;
let vs : Array β := Array.mkEmpty maxCollisions;
let vs := (vs.push v₁).push v₂;
Node.collision ks vs rfl
partial def insertAux [HasBeq α] [Hashable α] : Node α β → USize → USize → α → β → Node α β
| Node.collision keys vals heq, _, depth, k, v =>
let newNode := insertAtCollisionNode ⟨Node.collision keys vals heq, IsCollisionNode.mk _ _ _⟩ k v;
if depth >= maxDepth || getCollisionNodeSize newNode < maxCollisions then newNode.val
else match newNode with
| ⟨Node.entries _, h⟩ => False.elim (nomatch h)
| ⟨Node.collision keys vals heq, _⟩ =>
let entries : Node α β := mkEmptyEntries;
keys.iterate entries $ fun i k entries =>
let v := vals.get ⟨i.val, heq ▸ i.isLt⟩;
let h := hash k;
-- dbgTrace ("toCollision " ++ toString i ++ ", h: " ++ toString h ++ ", depth: " ++ toString depth ++ ", h': " ++
-- toString (div2Shift h (shift * (depth - 1)))) $ fun _ =>
let h := div2Shift h (shift * (depth - 1));
insertAux entries h depth k v
| Node.entries entries, h, depth, k, v =>
let j := (mod2Shift h shift).toNat;
Node.entries $ entries.modify j $ fun entry =>
match entry with
| Entry.null => Entry.entry k v
| Entry.ref node => Entry.ref $ insertAux node (div2Shift h shift) (depth+1) k v
| Entry.entry k' v' =>
if k == k' then Entry.entry k v
else Entry.ref $ mkCollisionNode k' v' k v
def insert [HasBeq α] [Hashable α] : PersistentHashMap α β → α → β → PersistentHashMap α β
| { root := n, size := sz }, k, v => { root := insertAux n (hash k) 1 k v, size := sz + 1 }
partial def findAtAux [HasBeq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) : Nat → α → Option β
| i, k =>
if h : i < keys.size then
let k' := keys.get ⟨i, h⟩;
if k == k' then some (vals.get ⟨i, heq ▸ h⟩)
else findAtAux (i+1) k
else none
partial def findAux [HasBeq α] : Node α β → USize → α → Option β
| Node.entries entries, h, k =>
let j := (mod2Shift h shift).toNat;
match entries.get! j with
| Entry.null => none
| Entry.ref node => findAux node (div2Shift h shift) k
| Entry.entry k' v => if k == k' then some v else none
| Node.collision keys vals heq, _, k => findAtAux keys vals heq 0 k
def find? [HasBeq α] [Hashable α] : PersistentHashMap α β → α → Option β
| { root := n, .. }, k => findAux n (hash k) k
@[inline] def getOp [HasBeq α] [Hashable α] (self : PersistentHashMap α β) (idx : α) : Option β :=
self.find? idx
@[inline] def findD [HasBeq α] [Hashable α] (m : PersistentHashMap α β) (a : α) (b₀ : β) : β :=
(m.find? a).getD b₀
@[inline] def find! [HasBeq α] [Hashable α] [Inhabited β] (m : PersistentHashMap α β) (a : α) : β :=
match m.find? a with
| some b => b
| none => panic! "key is not in the map"
partial def findEntryAtAux [HasBeq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) : Nat → α → Option (α × β)
| i, k =>
if h : i < keys.size then
let k' := keys.get ⟨i, h⟩;
if k == k' then some (k', vals.get ⟨i, heq ▸ h⟩)
else findEntryAtAux (i+1) k
else none
partial def findEntryAux [HasBeq α] : Node α β → USize → α → Option (α × β)
| Node.entries entries, h, k =>
let j := (mod2Shift h shift).toNat;
match entries.get! j with
| Entry.null => none
| Entry.ref node => findEntryAux node (div2Shift h shift) k
| Entry.entry k' v => if k == k' then some (k', v) else none
| Node.collision keys vals heq, _, k => findEntryAtAux keys vals heq 0 k
def findEntry? [HasBeq α] [Hashable α] : PersistentHashMap α β → α → Option (α × β)
| { root := n, .. }, k => findEntryAux n (hash k) k
partial def containsAtAux [HasBeq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) : Nat → α → Bool
| i, k =>
if h : i < keys.size then
let k' := keys.get ⟨i, h⟩;
if k == k' then true
else containsAtAux (i+1) k
else false
partial def containsAux [HasBeq α] : Node α β → USize → α → Bool
| Node.entries entries, h, k =>
let j := (mod2Shift h shift).toNat;
match entries.get! j with
| Entry.null => false
| Entry.ref node => containsAux node (div2Shift h shift) k
| Entry.entry k' v => k == k'
| Node.collision keys vals heq, _, k => containsAtAux keys vals heq 0 k
def contains [HasBeq α] [Hashable α] : PersistentHashMap α β → α → Bool
| { root := n, .. }, k => containsAux n (hash k) k
partial def isUnaryEntries (a : Array (Entry α β (Node α β))) : Nat → Option (α × β) → Option (α × β)
| i, acc =>
if h : i < a.size then
match a.get ⟨i, h⟩ with
| Entry.null => isUnaryEntries (i+1) acc
| Entry.ref _ => none
| Entry.entry k v =>
match acc with
| none => isUnaryEntries (i+1) (some (k, v))
| some _ => none
else acc
def isUnaryNode : Node α β → Option (α × β)
| Node.entries entries => isUnaryEntries entries 0 none
| Node.collision keys vals heq =>
if h : 1 = keys.size then
have 0 < keys.size from h ▸ (Nat.zeroLtSucc _);
some (keys.get ⟨0, this⟩, vals.get ⟨0, heq ▸ this⟩)
else
none
partial def eraseAux [HasBeq α] : Node α β → USize → α → Node α β × Bool
| n@(Node.collision keys vals heq), _, k =>
match keys.indexOf k with
| some idx =>
let ⟨keys', keq⟩ := keys.eraseIdx' idx;
let ⟨vals', veq⟩ := vals.eraseIdx' (Eq.rec idx heq);
have keys.size - 1 = vals.size - 1 from heq ▸ rfl;
(Node.collision keys' vals' (keq.trans (this.trans veq.symm)), true)
| none => (n, false)
| n@(Node.entries entries), h, k =>
let j := (mod2Shift h shift).toNat;
let entry := entries.get! j;
match entry with
| Entry.null => (n, false)
| Entry.entry k' v =>
if k == k' then (Node.entries (entries.set! j Entry.null), true) else (n, false)
| Entry.ref node =>
let entries := entries.set! j Entry.null;
let (newNode, deleted) := eraseAux node (div2Shift h shift) k;
if !deleted then (n, false)
else match isUnaryNode newNode with
| none => (Node.entries (entries.set! j (Entry.ref newNode)), true)
| some (k, v) => (Node.entries (entries.set! j (Entry.entry k v)), true)
def erase [HasBeq α] [Hashable α] : PersistentHashMap α β → α → PersistentHashMap α β
| { root := n, size := sz }, k =>
let h := hash k;
let (n, del) := eraseAux n h k;
{ root := n, size := if del then sz - 1 else sz }
section
variables {m : Type w → Type w'} [Monad m]
variables {σ : Type w}
@[specialize] partial def foldlMAux (f : σ → α → β → m σ) : Node α β → σ → m σ
| Node.collision keys vals heq, acc => keys.iterateM acc $ fun i k acc => f acc k (vals.get ⟨i.val, heq ▸ i.isLt⟩)
| Node.entries entries, acc => entries.foldlM (fun acc entry =>
match entry with
| Entry.null => pure acc
| Entry.entry k v => f acc k v
| Entry.ref node => foldlMAux node acc)
acc
@[specialize] def foldlM [HasBeq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → m σ) (acc : σ) : m σ :=
foldlMAux f map.root acc
@[specialize] def forM [HasBeq α] [Hashable α] (map : PersistentHashMap α β) (f : α → β → m PUnit) : m PUnit :=
map.foldlM (fun _ => f) ⟨⟩
@[specialize] def foldl [HasBeq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → σ) (acc : σ) : σ :=
Id.run $ map.foldlM f acc
end
def toList [HasBeq α] [Hashable α] (m : PersistentHashMap α β) : List (α × β) :=
m.foldl (fun ps k v => (k, v) :: ps) []
structure Stats :=
(numNodes : Nat := 0)
(numNull : Nat := 0)
(numCollisions : Nat := 0)
(maxDepth : Nat := 0)
partial def collectStats : Node α β → Stats → Nat → Stats
| Node.collision keys _ _, stats, depth =>
{ numNodes := stats.numNodes + 1,
numCollisions := stats.numCollisions + keys.size - 1,
maxDepth := Nat.max stats.maxDepth depth,
.. stats }
| Node.entries entries, stats, depth =>
let stats :=
{ numNodes := stats.numNodes + 1,
maxDepth := Nat.max stats.maxDepth depth,
.. stats };
entries.foldl (fun stats entry =>
match entry with
| Entry.null => { numNull := stats.numNull + 1, .. stats }
| Entry.ref node => collectStats node stats (depth + 1)
| Entry.entry _ _ => stats)
stats
def stats [HasBeq α] [Hashable α] (m : PersistentHashMap α β) : Stats :=
collectStats m.root {} 1
def Stats.toString (s : Stats) : String :=
"{ nodes := " ++ toString s.numNodes ++ ", null := " ++ toString s.numNull ++
", collisions := " ++ toString s.numCollisions ++ ", depth := " ++ toString s.maxDepth ++ "}"
instance : HasToString Stats := ⟨Stats.toString⟩
end PersistentHashMap
|
39bc1f90de351d0093b17f891fca6aa7ef0831eb | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/init/data/nat/lemmas.lean | 94f17f0a604f06217dbdc6487357df7c1e583823 | [
"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 | 50,489 | 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, Jeremy Avigad
-/
prelude
import init.data.nat.basic init.data.nat.div init.data.nat.pow init.meta init.algebra.functions
universes u
namespace nat
attribute [pre_smt] nat_zero_eq_zero
protected lemma zero_add : ∀ n : ℕ, 0 + n = n
| 0 := rfl
| (n+1) := congr_arg succ (zero_add n)
lemma succ_add : ∀ n m : ℕ, (succ n) + m = succ (n + m)
| n 0 := rfl
| n (m+1) := congr_arg succ (succ_add n m)
lemma add_succ (n m : ℕ) : n + succ m = succ (n + m) :=
rfl
protected lemma add_zero (n : ℕ) : n + 0 = n :=
rfl
lemma add_one (n : ℕ) : n + 1 = succ n :=
rfl
lemma succ_eq_add_one (n : ℕ) : succ n = n + 1 :=
rfl
protected lemma add_comm : ∀ n m : ℕ, n + m = m + n
| n 0 := eq.symm (nat.zero_add n)
| n (m+1) :=
suffices succ (n + m) = succ (m + n), from
eq.symm (succ_add m n) ▸ this,
congr_arg succ (add_comm n m)
protected lemma add_assoc : ∀ n m k : ℕ, (n + m) + k = n + (m + k)
| n m 0 := rfl
| n m (succ k) := by rw [add_succ, add_succ, add_assoc]
protected lemma add_left_comm : ∀ (n m k : ℕ), n + (m + k) = m + (n + k) :=
left_comm nat.add nat.add_comm nat.add_assoc
protected lemma add_left_cancel : ∀ {n m k : ℕ}, n + m = n + k → m = k
| 0 m k := by simp [nat.zero_add] {contextual := tt}
| (succ n) m k := λ h,
have n+m = n+k, by simp [succ_add] at h; injection h,
add_left_cancel this
protected lemma add_right_cancel {n m k : ℕ} (h : n + m = k + m) : n = k :=
have m + n = m + k, by rwa [nat.add_comm n m, nat.add_comm k m] at h,
nat.add_left_cancel this
lemma succ_ne_zero (n : ℕ) : succ n ≠ 0 :=
assume h, nat.no_confusion h
lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n
| 0 h := absurd h (nat.succ_ne_zero 0)
| (n+1) h := succ_ne_self n (nat.no_confusion h (λ h, h))
protected lemma one_ne_zero : 1 ≠ (0 : ℕ) :=
assume h, nat.no_confusion h
protected lemma zero_ne_one : 0 ≠ (1 : ℕ) :=
assume h, nat.no_confusion h
instance : zero_ne_one_class ℕ :=
{ zero := 0, one := 1, zero_ne_one := nat.zero_ne_one }
lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0
| 0 m := by simp [nat.zero_add]
| (n+1) m := λ h,
begin
exfalso,
rw [add_one, succ_add] at h,
apply succ_ne_zero _ h
end
lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 :=
@eq_zero_of_add_eq_zero_right m n (nat.add_comm n m ▸ h)
@[simp]
lemma pred_zero : pred 0 = 0 :=
rfl
@[simp]
lemma pred_succ (n : ℕ) : pred (succ n) = n :=
rfl
protected lemma mul_zero (n : ℕ) : n * 0 = 0 :=
rfl
lemma mul_succ (n m : ℕ) : n * succ m = n * m + n :=
rfl
protected theorem zero_mul : ∀ (n : ℕ), 0 * n = 0
| 0 := rfl
| (succ n) := by rw [mul_succ, zero_mul]
private meta def sort_add :=
`[simp [nat.add_assoc, nat.add_comm, nat.add_left_comm]]
lemma succ_mul : ∀ (n m : ℕ), (succ n) * m = (n * m) + m
| n 0 := rfl
| n (succ m) :=
begin
simp [mul_succ, add_succ, succ_mul n m],
sort_add
end
protected lemma right_distrib : ∀ (n m k : ℕ), (n + m) * k = n * k + m * k
| n m 0 := rfl
| n m (succ k) :=
begin simp [mul_succ, right_distrib n m k], sort_add end
protected lemma left_distrib : ∀ (n m k : ℕ), n * (m + k) = n * m + n * k
| 0 m k := by simp [nat.zero_mul]
| (succ n) m k :=
begin simp [succ_mul, left_distrib n m k], sort_add end
protected lemma mul_comm : ∀ (n m : ℕ), n * m = m * n
| n 0 := by rw [nat.zero_mul, nat.mul_zero]
| n (succ m) := by simp [mul_succ, succ_mul, mul_comm n m]
protected lemma mul_assoc : ∀ (n m k : ℕ), (n * m) * k = n * (m * k)
| n m 0 := rfl
| n m (succ k) := by simp [mul_succ, nat.left_distrib, mul_assoc n m k]
protected lemma mul_one : ∀ (n : ℕ), n * 1 = n := nat.zero_add
protected lemma one_mul (n : ℕ) : 1 * n = n :=
by rw [nat.mul_comm, nat.mul_one]
instance : comm_semiring nat :=
{add := nat.add,
add_assoc := nat.add_assoc,
zero := nat.zero,
zero_add := nat.zero_add,
add_zero := nat.add_zero,
add_comm := nat.add_comm,
mul := nat.mul,
mul_assoc := nat.mul_assoc,
one := nat.succ nat.zero,
one_mul := nat.one_mul,
mul_one := nat.mul_one,
left_distrib := nat.left_distrib,
right_distrib := nat.right_distrib,
zero_mul := nat.zero_mul,
mul_zero := nat.mul_zero,
mul_comm := nat.mul_comm}
/- properties of inequality -/
protected lemma le_of_eq {n m : ℕ} (p : n = m) : n ≤ m :=
p ▸ less_than_or_equal.refl n
lemma le_succ_of_le {n m : ℕ} (h : n ≤ m) : n ≤ succ m :=
nat.le_trans h (le_succ m)
lemma le_of_succ_le {n m : ℕ} (h : succ n ≤ m) : n ≤ m :=
nat.le_trans (le_succ n) h
protected lemma le_of_lt {n m : ℕ} (h : n < m) : n ≤ m :=
le_of_succ_le h
def lt.step {n m : ℕ} : n < m → n < succ m := less_than_or_equal.step
lemma eq_zero_or_pos (n : ℕ) : n = 0 ∨ n > 0 :=
by {cases n, exact or.inl rfl, exact or.inr (succ_pos _)}
protected lemma pos_of_ne_zero {n : nat} : n ≠ 0 → n > 0 :=
or.resolve_left (eq_zero_or_pos n)
protected lemma lt_trans {n m k : ℕ} (h₁ : n < m) : m < k → n < k :=
nat.le_trans (less_than_or_equal.step h₁)
protected lemma lt_of_le_of_lt {n m k : ℕ} (h₁ : n ≤ m) : m < k → n < k :=
nat.le_trans (succ_le_succ h₁)
def lt.base (n : ℕ) : n < succ n := nat.le_refl (succ n)
lemma lt_succ_self (n : ℕ) : n < succ n := lt.base n
protected lemma le_antisymm {n m : ℕ} (h₁ : n ≤ m) : m ≤ n → n = m :=
less_than_or_equal.cases_on h₁ (λ a, rfl) (λ a b c, absurd (nat.lt_of_le_of_lt b c) (nat.lt_irrefl n))
protected lemma lt_or_ge : ∀ (a b : ℕ), a < b ∨ a ≥ b
| a 0 := or.inr (zero_le a)
| a (b+1) :=
match lt_or_ge a b with
| or.inl h := or.inl (le_succ_of_le h)
| or.inr h :=
match nat.eq_or_lt_of_le h with
| or.inl h1 := or.inl (h1 ▸ lt_succ_self b)
| or.inr h1 := or.inr h1
end
end
protected lemma le_total {m n : ℕ} : m ≤ n ∨ n ≤ m :=
or.imp_left nat.le_of_lt (nat.lt_or_ge m n)
protected lemma lt_of_le_and_ne {m n : ℕ} (h1 : m ≤ n) : m ≠ n → m < n :=
or.resolve_right (or.swap (nat.eq_or_lt_of_le h1))
protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ (m ≤ n ∧ ¬ n ≤ m) :=
⟨λ hmn, ⟨nat.le_of_lt hmn, λ hnm, nat.lt_irrefl _ (nat.lt_of_le_of_lt hnm hmn)⟩,
λ ⟨hmn, hnm⟩, nat.lt_of_le_and_ne hmn (λ heq, hnm (heq ▸ nat.le_refl _))⟩
instance : linear_order ℕ :=
{ le := nat.less_than_or_equal,
le_refl := @nat.le_refl,
le_trans := @nat.le_trans,
le_antisymm := @nat.le_antisymm,
le_total := @nat.le_total,
lt := nat.lt,
lt_iff_le_not_le := @nat.lt_iff_le_not_le }
lemma eq_zero_of_le_zero {n : nat} (h : n ≤ 0) : n = 0 :=
le_antisymm h (zero_le _)
lemma succ_lt_succ {a b : ℕ} : a < b → succ a < succ b :=
succ_le_succ
lemma lt_of_succ_lt {a b : ℕ} : succ a < b → a < b :=
le_of_succ_le
lemma lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b :=
le_of_succ_le_succ
lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → m ≠ 0 → n < m → pred n < pred m
| 0 _ h₁ h₂ h := absurd rfl h₁
| _ 0 h₁ h₂ h := absurd rfl h₂
| (succ n) (succ m) _ _ h := lt_of_succ_lt_succ h
lemma lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h
lemma succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h
lemma le_add_right : ∀ (n k : ℕ), n ≤ n + k
| n 0 := nat.le_refl n
| n (k+1) := le_succ_of_le (le_add_right n k)
lemma le_add_left (n m : ℕ): n ≤ m + n :=
nat.add_comm n m ▸ le_add_right n m
lemma le.dest : ∀ {n m : ℕ}, n ≤ m → ∃ k, n + k = m
| n ._ (less_than_or_equal.refl ._) := ⟨0, rfl⟩
| n ._ (@less_than_or_equal.step ._ m h) :=
match le.dest h with
| ⟨w, hw⟩ := ⟨succ w, hw ▸ add_succ n w⟩
end
lemma le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m :=
h ▸ le_add_right n k
protected lemma add_le_add_left {n m : ℕ} (h : n ≤ m) (k : ℕ) : k + n ≤ k + m :=
match le.dest h with
| ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc, hw] end
end
protected lemma add_le_add_right {n m : ℕ} (h : n ≤ m) (k : ℕ) : n + k ≤ m + k :=
begin rw [nat.add_comm n k, nat.add_comm m k], apply nat.add_le_add_left h end
protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m :=
match le.dest h with
| ⟨w, hw⟩ := @le.intro _ _ w
begin
rw [nat.add_assoc] at hw,
apply nat.add_left_cancel hw
end
end
protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m :=
begin
rw [nat.add_comm _ k, nat.add_comm _ k],
apply nat.le_of_add_le_add_left
end
protected lemma add_le_add_iff_le_right (k n m : ℕ) : n + k ≤ m + k ↔ n ≤ m :=
⟨ nat.le_of_add_le_add_right , assume h, nat.add_le_add_right h _ ⟩
protected theorem lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m :=
let h' := nat.le_of_lt h in
nat.lt_of_le_and_ne
(nat.le_of_add_le_add_left h')
(λ heq, nat.lt_irrefl (k + m) begin rw heq at h, assumption end)
protected lemma add_lt_add_left {n m : ℕ} (h : n < m) (k : ℕ) : k + n < k + m :=
lt_of_succ_le (add_succ k n ▸ nat.add_le_add_left (succ_le_of_lt h) k)
protected lemma add_lt_add_right {n m : ℕ} (h : n < m) (k : ℕ) : n + k < m + k :=
nat.add_comm k m ▸ nat.add_comm k n ▸ nat.add_lt_add_left h k
protected lemma lt_add_of_pos_right {n k : ℕ} (h : k > 0) : n < n + k :=
nat.add_lt_add_left h n
protected lemma lt_add_of_pos_left {n k : ℕ} (h : k > 0) : n < k + n :=
by rw add_comm; exact nat.lt_add_of_pos_right h
protected lemma zero_lt_one : 0 < (1:nat) :=
zero_lt_succ 0
lemma mul_le_mul_left {n m : ℕ} (k : ℕ) (h : n ≤ m) : k * n ≤ k * m :=
match le.dest h with
| ⟨l, hl⟩ :=
have k * n + k * l = k * m, by rw [← left_distrib, hl],
le.intro this
end
lemma mul_le_mul_right {n m : ℕ} (k : ℕ) (h : n ≤ m) : n * k ≤ m * k :=
mul_comm k m ▸ mul_comm k n ▸ mul_le_mul_left k h
protected lemma mul_lt_mul_of_pos_left {n m k : ℕ} (h : n < m) (hk : k > 0) : k * n < k * m :=
nat.lt_of_lt_of_le (nat.lt_add_of_pos_right hk) (mul_succ k n ▸ nat.mul_le_mul_left k (succ_le_of_lt h))
protected lemma mul_lt_mul_of_pos_right {n m k : ℕ} (h : n < m) (hk : k > 0) : n * k < m * k :=
mul_comm k m ▸ mul_comm k n ▸ nat.mul_lt_mul_of_pos_left h hk
instance : decidable_linear_ordered_semiring nat :=
{ nat.comm_semiring with
add_left_cancel := @nat.add_left_cancel,
add_right_cancel := @nat.add_right_cancel,
lt := nat.lt,
le := nat.le,
le_refl := nat.le_refl,
le_trans := @nat.le_trans,
le_antisymm := @nat.le_antisymm,
le_total := @nat.le_total,
lt_of_add_lt_add_left := @nat.lt_of_add_lt_add_left,
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
add_lt_add_left := @nat.add_lt_add_left,
add_le_add_left := @nat.add_le_add_left,
le_of_add_le_add_left := @nat.le_of_add_le_add_left,
zero_lt_one := zero_lt_succ 0,
mul_le_mul_of_nonneg_left := assume a b c h₁ h₂, nat.mul_le_mul_left c h₁,
mul_le_mul_of_nonneg_right := assume a b c h₁ h₂, nat.mul_le_mul_right c h₁,
mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left,
mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right,
decidable_lt := nat.decidable_lt,
decidable_le := nat.decidable_le,
decidable_eq := nat.decidable_eq }
-- all the fields are already included in the decidable_linear_ordered_semiring instance
instance : decidable_linear_ordered_cancel_comm_monoid ℕ :=
{ nat.decidable_linear_ordered_semiring with
add_left_cancel := @nat.add_left_cancel }
lemma le_of_lt_succ {m n : nat} : m < succ n → m ≤ n :=
le_of_succ_le_succ
theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k :=
le_antisymm (le_of_mul_le_mul_left (le_of_eq H) Hn)
(le_of_mul_le_mul_left (le_of_eq H.symm) Hn)
theorem eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k :=
by rw [mul_comm n m, mul_comm k m] at H; exact eq_of_mul_eq_mul_left Hm H
/- sub properties -/
@[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0
| 0 := rfl
| (a+1) := congr_arg pred (zero_sub a)
lemma sub_lt_succ (a b : ℕ) : a - b < succ a :=
lt_succ_of_le (sub_le a b)
protected theorem sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k
| 0 := h
| (succ z) := pred_le_pred (sub_le_sub_right z)
/- bit0/bit1 properties -/
protected lemma bit0_succ_eq (n : ℕ) : bit0 (succ n) = succ (succ (bit0 n)) :=
show succ (succ n + n) = succ (succ (n + n)), from
congr_arg succ (succ_add n n)
protected lemma bit1_eq_succ_bit0 (n : ℕ) : bit1 n = succ (bit0 n) :=
rfl
protected lemma bit1_succ_eq (n : ℕ) : bit1 (succ n) = succ (succ (bit1 n)) :=
eq.trans (nat.bit1_eq_succ_bit0 (succ n)) (congr_arg succ (nat.bit0_succ_eq n))
protected lemma bit0_ne_zero : ∀ {n : ℕ}, n ≠ 0 → bit0 n ≠ 0
| 0 h := absurd rfl h
| (n+1) h := succ_ne_zero _
protected lemma bit1_ne_zero (n : ℕ) : bit1 n ≠ 0 :=
show succ (n + n) ≠ 0, from
succ_ne_zero (n + n)
protected lemma bit1_ne_one : ∀ {n : ℕ}, n ≠ 0 → bit1 n ≠ 1
| 0 h h1 := absurd rfl h
| (n+1) h h1 := nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero _))
protected lemma bit0_ne_one : ∀ n : ℕ, bit0 n ≠ 1
| 0 h := absurd h (ne.symm nat.one_ne_zero)
| (n+1) h :=
have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h,
nat.no_confusion h1
(λ h2, absurd h2 (succ_ne_zero (n + n)))
protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1
| 0 h := nat.no_confusion h
| (n+1) h :=
have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h,
nat.no_confusion h1 (λ h2, absurd h2 (nat.succ_ne_zero (n + n)))
protected lemma bit1_ne_bit0 : ∀ (n m : ℕ), bit1 n ≠ bit0 m
| 0 m h := absurd h (ne.symm (nat.add_self_ne_one m))
| (n+1) 0 h :=
have h1 : succ (bit0 (succ n)) = 0, from h,
absurd h1 (nat.succ_ne_zero _)
| (n+1) (m+1) h :=
have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)), from
nat.bit0_succ_eq m ▸ nat.bit1_succ_eq n ▸ h,
have h2 : bit1 n = bit0 m, from
nat.no_confusion h1 (λ h2', nat.no_confusion h2' (λ h2'', h2'')),
absurd h2 (bit1_ne_bit0 n m)
protected lemma bit0_ne_bit1 : ∀ (n m : ℕ), bit0 n ≠ bit1 m :=
λ n m : nat, ne.symm (nat.bit1_ne_bit0 m n)
protected lemma bit0_inj : ∀ {n m : ℕ}, bit0 n = bit0 m → n = m
| 0 0 h := rfl
| 0 (m+1) h := by contradiction
| (n+1) 0 h := by contradiction
| (n+1) (m+1) h :=
have succ (succ (n + n)) = succ (succ (m + m)),
begin unfold bit0 at h, simp [add_one, add_succ, succ_add] at h, exact h end,
have n + n = m + m, by repeat {injection this with this},
have n = m, from bit0_inj this,
by rw this
protected lemma bit1_inj : ∀ {n m : ℕ}, bit1 n = bit1 m → n = m :=
λ n m h,
have succ (bit0 n) = succ (bit0 m), begin simp [nat.bit1_eq_succ_bit0] at h, assumption end,
have bit0 n = bit0 m, by injection this,
nat.bit0_inj this
protected lemma bit0_ne {n m : ℕ} : n ≠ m → bit0 n ≠ bit0 m :=
λ h₁ h₂, absurd (nat.bit0_inj h₂) h₁
protected lemma bit1_ne {n m : ℕ} : n ≠ m → bit1 n ≠ bit1 m :=
λ h₁ h₂, absurd (nat.bit1_inj h₂) h₁
protected lemma zero_ne_bit0 {n : ℕ} : n ≠ 0 → 0 ≠ bit0 n :=
λ h, ne.symm (nat.bit0_ne_zero h)
protected lemma zero_ne_bit1 (n : ℕ) : 0 ≠ bit1 n :=
ne.symm (nat.bit1_ne_zero n)
protected lemma one_ne_bit0 (n : ℕ) : 1 ≠ bit0 n :=
ne.symm (nat.bit0_ne_one n)
protected lemma one_ne_bit1 {n : ℕ} : n ≠ 0 → 1 ≠ bit1 n :=
λ h, ne.symm (nat.bit1_ne_one h)
protected lemma zero_lt_bit1 (n : nat) : 0 < bit1 n :=
zero_lt_succ _
protected lemma zero_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 0 < bit0 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit0_succ_eq,
apply zero_lt_succ
end
protected lemma one_lt_bit1 : ∀ {n : nat}, n ≠ 0 → 1 < bit1 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit1_succ_eq,
apply succ_lt_succ,
apply zero_lt_succ
end
protected lemma one_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 1 < bit0 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit0_succ_eq,
apply succ_lt_succ,
apply zero_lt_succ
end
protected lemma bit0_lt {n m : nat} (h : n < m) : bit0 n < bit0 m :=
add_lt_add h h
protected lemma bit1_lt {n m : nat} (h : n < m) : bit1 n < bit1 m :=
succ_lt_succ (add_lt_add h h)
protected lemma bit0_lt_bit1 {n m : nat} (h : n ≤ m) : bit0 n < bit1 m :=
lt_succ_of_le (add_le_add h h)
protected lemma bit1_lt_bit0 : ∀ {n m : nat}, n < m → bit1 n < bit0 m
| n 0 h := absurd h (not_lt_zero _)
| n (succ m) h :=
have n ≤ m, from le_of_lt_succ h,
have succ (n + n) ≤ succ (m + m), from succ_le_succ (add_le_add this this),
have succ (n + n) ≤ succ m + m, {rw succ_add, assumption},
show succ (n + n) < succ (succ m + m), from lt_succ_of_le this
protected lemma one_le_bit1 (n : ℕ) : 1 ≤ bit1 n :=
show 1 ≤ succ (bit0 n), from
succ_le_succ (zero_le (bit0 n))
protected lemma one_le_bit0 : ∀ (n : ℕ), n ≠ 0 → 1 ≤ bit0 n
| 0 h := absurd rfl h
| (n+1) h :=
suffices 1 ≤ succ (succ (bit0 n)), from
eq.symm (nat.bit0_succ_eq n) ▸ this,
succ_le_succ (zero_le (succ (bit0 n)))
/- Extra instances to short-circuit type class resolution -/
instance : add_comm_monoid nat := by apply_instance
instance : add_monoid nat := by apply_instance
instance : monoid nat := by apply_instance
instance : comm_monoid nat := by apply_instance
instance : comm_semigroup nat := by apply_instance
instance : semigroup nat := by apply_instance
instance : add_comm_semigroup nat := by apply_instance
instance : add_semigroup nat := by apply_instance
instance : distrib nat := by apply_instance
instance : semiring nat := by apply_instance
instance : ordered_semiring nat := by apply_instance
/- subtraction -/
@[simp]
protected theorem sub_zero (n : ℕ) : n - 0 = n :=
rfl
theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) :=
rfl
theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m :=
succ_sub_succ_eq_sub n m
protected theorem sub_self : ∀ (n : ℕ), n - n = 0
| 0 := by rw nat.sub_zero
| (succ n) := by rw [succ_sub_succ, sub_self n]
/- TODO(Leo): remove the following ematch annotations as soon as we have
arithmetic theory in the smt_stactic -/
@[ematch_lhs]
protected theorem add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m
| n 0 m := by rw [add_zero, add_zero]
| n (succ k) m := by rw [add_succ, add_succ, succ_sub_succ, add_sub_add_right n k m]
@[ematch_lhs]
protected theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m :=
by rw [add_comm k n, add_comm k m, nat.add_sub_add_right]
@[ematch_lhs]
protected theorem add_sub_cancel (n m : ℕ) : n + m - m = n :=
suffices n + m - (0 + m) = n, from
by rwa [zero_add] at this,
by rw [nat.add_sub_add_right, nat.sub_zero]
@[ematch_lhs]
protected theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m :=
show n + m - (n + 0) = m, from
by rw [nat.add_sub_add_left, nat.sub_zero]
protected theorem sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k)
| n m 0 := by rw [add_zero, nat.sub_zero]
| n m (succ k) := by rw [add_succ, nat.sub_succ, nat.sub_succ, sub_sub n m k]
theorem le_of_le_of_sub_le_sub_right {n m k : ℕ}
(h₀ : k ≤ m)
(h₁ : n - k ≤ m - k)
: n ≤ m :=
begin
revert k m,
induction n with n ; intros k m h₀ h₁,
{ apply zero_le },
{ cases k with k,
{ apply h₁ },
cases m with m,
{ cases not_succ_le_zero _ h₀ },
{ simp [succ_sub_succ] at h₁,
apply succ_le_succ,
apply ih_1 _ h₁,
apply le_of_succ_le_succ h₀ }, }
end
protected theorem sub_le_sub_right_iff (n m k : ℕ)
(h : k ≤ m)
: n - k ≤ m - k ↔ n ≤ m :=
⟨ le_of_le_of_sub_le_sub_right h , assume h, nat.sub_le_sub_right h k ⟩
theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 :=
show (n + 0) - (n + m) = 0, from
by rw [nat.add_sub_add_left, nat.zero_sub]
theorem add_le_to_le_sub (x : ℕ) {y k : ℕ}
(h : k ≤ y)
: x + k ≤ y ↔ x ≤ y - k :=
by rw [← nat.add_sub_cancel x k, nat.sub_le_sub_right_iff _ _ _ h, nat.add_sub_cancel]
lemma sub_lt_of_pos_le (a b : ℕ) (h₀ : 0 < a) (h₁ : a ≤ b)
: b - a < b :=
begin
apply sub_lt _ h₀,
apply lt_of_lt_of_le h₀ h₁
end
theorem sub_one (n : ℕ) : n - 1 = pred n :=
rfl
theorem succ_sub_one (n : ℕ) : succ n - 1 = n :=
rfl
theorem succ_pred_eq_of_pos : ∀ {n : ℕ}, n > 0 → succ (pred n) = n
| 0 h := absurd h (lt_irrefl 0)
| (succ k) h := rfl
theorem sub_eq_zero_of_le {n m : ℕ} (h : n ≤ m) : n - m = 0 :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m, by rw [← hk, sub_self_add])
protected theorem le_of_sub_eq_zero : ∀{n m : ℕ}, n - m = 0 → n ≤ m
| n 0 H := begin rw [nat.sub_zero] at H, simp [H] end
| 0 (m+1) H := zero_le _
| (n+1) (m+1) H := add_le_add_right
(le_of_sub_eq_zero begin simp [nat.add_sub_add_right] at H, exact H end) _
protected theorem sub_eq_zero_iff_le {n m : ℕ} : n - m = 0 ↔ n ≤ m :=
⟨nat.le_of_sub_eq_zero, nat.sub_eq_zero_of_le⟩
theorem add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m,
by rw [← hk, nat.add_sub_cancel_left])
protected theorem sub_add_cancel {n m : ℕ} (h : n ≥ m) : n - m + m = n :=
by rw [add_comm, add_sub_of_le h]
protected theorem add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) :=
exists.elim (nat.le.dest h)
(assume l, assume hl : k + l = m,
by rw [← hl, nat.add_sub_cancel_left, add_comm k, ← add_assoc, nat.add_sub_cancel])
protected lemma sub_eq_iff_eq_add {a b c : ℕ} (ab : b ≤ a) : a - b = c ↔ a = c + b :=
⟨assume c_eq, begin rw [c_eq.symm, nat.sub_add_cancel ab] end,
assume a_eq, begin rw [a_eq, nat.add_sub_cancel] end⟩
protected lemma lt_of_sub_eq_succ {m n l : ℕ} (H : m - n = nat.succ l) : n < m :=
lt_of_not_ge
(assume (H' : n ≥ m), begin simp [nat.sub_eq_zero_of_le H'] at H, contradiction end)
@[simp] lemma zero_min (a : ℕ) : min 0 a = 0 :=
min_eq_left (zero_le a)
@[simp] lemma min_zero (a : ℕ) : min a 0 = 0 :=
min_eq_right (zero_le a)
-- Distribute succ over min
theorem min_succ_succ (x y : ℕ) : min (succ x) (succ y) = succ (min x y) :=
have f : x ≤ y → min (succ x) (succ y) = succ (min x y), from λp,
calc min (succ x) (succ y)
= succ x : if_pos (succ_le_succ p)
... = succ (min x y) : congr_arg succ (eq.symm (if_pos p)),
have g : ¬ (x ≤ y) → min (succ x) (succ y) = succ (min x y), from λp,
calc min (succ x) (succ y)
= succ y : if_neg (λeq, p (pred_le_pred eq))
... = succ (min x y) : congr_arg succ (eq.symm (if_neg p)),
decidable.by_cases f g
theorem sub_eq_sub_min (n m : ℕ) : n - m = n - min n m :=
if h : n ≥ m then by rewrite [min_eq_right h]
else by rewrite [sub_eq_zero_of_le (le_of_not_ge h), min_eq_left (le_of_not_ge h), nat.sub_self]
@[simp] theorem sub_add_min_cancel (n m : ℕ) : n - m + min n m = n :=
by rw [sub_eq_sub_min, nat.sub_add_cancel (min_le_left n m)]
/- TODO(Leo): sub + inequalities -/
protected def strong_rec_on {p : nat → Sort u} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n :=
suffices ∀ n m, m < n → p m, from this (succ n) n (lt_succ_self _),
begin
intros n, induction n with n ih,
{intros m h₁, exact absurd h₁ (not_lt_zero _)},
{intros m h₁,
apply or.by_cases (lt_or_eq_of_le (le_of_lt_succ h₁)),
{intros, apply ih, assumption},
{intros, subst m, apply h _ ih}}
end
protected lemma strong_induction_on {p : nat → Prop} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n :=
nat.strong_rec_on n h
protected lemma case_strong_induction_on {p : nat → Prop} (a : nat)
(hz : p 0)
(hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a :=
nat.strong_induction_on a $ λ n,
match n with
| 0 := λ _, hz
| (n+1) := λ h₁, hi n (λ m h₂, h₁ _ (lt_succ_of_le h₂))
end
/- mod -/
lemma mod_def (x y : nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x :=
by have h := mod_def_aux x y; rwa [dif_eq_if] at h
@[simp] lemma mod_zero (a : nat) : a % 0 = a :=
begin
rw mod_def,
have h : ¬ (0 < 0 ∧ 0 ≤ a),
simp [lt_irrefl],
simp [if_neg, h]
end
lemma mod_eq_of_lt {a b : nat} (h : a < b) : a % b = a :=
begin
rw mod_def,
have h' : ¬(0 < b ∧ b ≤ a),
simp [not_le_of_gt h],
simp [if_neg, h']
end
@[simp] lemma zero_mod (b : nat) : 0 % b = 0 :=
begin
rw mod_def,
have h : ¬(0 < b ∧ b ≤ 0),
{intro hn, cases hn with l r, exact absurd (lt_of_lt_of_le l r) (lt_irrefl 0)},
simp [if_neg, h]
end
lemma mod_eq_sub_mod {a b : nat} (h : a ≥ b) : a % b = (a - b) % b :=
or.elim (eq_zero_or_pos b)
(λb0, by rw [b0, nat.sub_zero])
(λh₂, by rw [mod_def, if_pos (and.intro h₂ h)])
lemma mod_lt (x : nat) {y : nat} (h : y > 0) : x % y < y :=
begin
induction x using nat.case_strong_induction_on with x ih,
{rw zero_mod, assumption},
{apply or.elim (decidable.em (succ x < y)),
{intro h₁, rwa [mod_eq_of_lt h₁]},
{intro h₁,
have h₁ : succ x % y = (succ x - y) % y, {exact mod_eq_sub_mod (le_of_not_gt h₁)},
have this : succ x - y ≤ x, {exact le_of_lt_succ (sub_lt (succ_pos x) h)},
have h₂ : (succ x - y) % y < y, {exact ih _ this},
rwa [← h₁] at h₂}}
end
@[simp] theorem mod_self (n : nat) : n % n = 0 :=
by rw [mod_eq_sub_mod (le_refl _), nat.sub_self, zero_mod]
@[simp] lemma mod_one (n : ℕ) : n % 1 = 0 :=
have n % 1 < 1, from (mod_lt n) (succ_pos 0),
eq_zero_of_le_zero (le_of_lt_succ this)
lemma mod_two_eq_zero_or_one (n : ℕ) : n % 2 = 0 ∨ n % 2 = 1 :=
match n % 2, @nat.mod_lt n 2 dec_trivial with
| 0, _ := or.inl rfl
| 1, _ := or.inr rfl
| k+2, h := absurd h dec_trivial
end
/- div & mod -/
lemma div_def (x y : nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 :=
by have h := div_def_aux x y; rwa dif_eq_if at h
lemma mod_add_div (m k : ℕ)
: m % k + k * (m / k) = m :=
begin
apply nat.strong_induction_on m,
clear m,
intros m IH,
cases decidable.em (0 < k ∧ k ≤ m) with h h',
-- 0 < k ∧ k ≤ m
{ have h' : m - k < m,
{ apply nat.sub_lt _ h.left,
apply lt_of_lt_of_le h.left h.right },
rw [div_def, mod_def, if_pos h, if_pos h],
simp [left_distrib, IH _ h'],
rw [← nat.add_sub_assoc h.right, nat.add_sub_cancel_left] },
-- ¬ (0 < k ∧ k ≤ m)
{ rw [div_def, mod_def, if_neg h', if_neg h'], simp },
end
/- div -/
@[simp] protected lemma div_one (n : ℕ) : n / 1 = n :=
have n % 1 + 1 * (n / 1) = n, from mod_add_div _ _,
by simp [mod_one] at this; assumption
@[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 :=
begin rw [div_def], simp [lt_irrefl] end
@[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 :=
eq.trans (div_def 0 b) $ if_neg (and.rec not_le_of_gt)
protected lemma div_le_of_le_mul {m n : ℕ} : ∀ {k}, m ≤ k * n → m / k ≤ n
| 0 h := by simp [nat.div_zero]; apply zero_le
| (succ k) h :=
suffices succ k * (m / succ k) ≤ succ k * n, from le_of_mul_le_mul_left this (zero_lt_succ _),
calc
succ k * (m / succ k) ≤ m % succ k + succ k * (m / succ k) : le_add_left _ _
... = m : by rw mod_add_div
... ≤ succ k * n : h
protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m
| m 0 := by simp [nat.div_zero]; apply zero_le
| m (succ n) :=
have m ≤ succ n * m, from calc
m = 1 * m : by simp
... ≤ succ n * m : mul_le_mul_right _ (succ_le_succ (zero_le _)),
nat.div_le_of_le_mul this
lemma div_eq_sub_div {a b : nat} (h₁ : b > 0) (h₂ : a ≥ b) : a / b = (a - b) / b + 1 :=
begin
rw [div_def a, if_pos],
split ; assumption
end
lemma div_eq_of_lt {a b : ℕ} (h₀ : a < b) : a / b = 0 :=
begin
rw [div_def a, if_neg],
intro h₁,
apply not_le_of_gt h₀ h₁.right
end
-- this is a Galois connection
-- f x ≤ y ↔ x ≤ g y
-- with
-- f x = x * k
-- g y = y / k
theorem le_div_iff_mul_le (x y : ℕ) {k : ℕ}
(Hk : k > 0)
: x ≤ y / k ↔ x * k ≤ y :=
begin
-- Hk is needed because, despite div being made total, y / 0 := 0
-- x * 0 ≤ y ↔ x ≤ y / 0
-- ↔ 0 ≤ y ↔ x ≤ 0
-- ↔ true ↔ x = 0
-- ↔ x = 0
revert x,
apply nat.strong_induction_on y _,
clear y,
intros y IH x,
cases lt_or_ge y k with h h,
-- base case: y < k
{ rw [div_eq_of_lt h],
cases x with x,
{ simp [zero_mul, zero_le] },
{ simp [succ_mul, not_succ_le_zero],
apply not_le_of_gt,
apply lt_of_lt_of_le h,
apply le_add_right } },
-- step: k ≤ y
{ rw [div_eq_sub_div Hk h],
cases x with x,
{ simp [zero_mul, zero_le] },
{ have Hlt : y - k < y,
{ apply sub_lt_of_pos_le ; assumption },
rw [ ← add_one
, nat.add_le_add_iff_le_right
, IH (y - k) Hlt x
, add_one
, succ_mul, add_le_to_le_sub _ h ]
} }
end
theorem div_lt_iff_lt_mul (x y : ℕ) {k : ℕ}
(Hk : k > 0)
: x / k < y ↔ x < y * k :=
begin
simp [lt_iff_not_ge],
apply not_iff_not_of_iff,
apply le_div_iff_mul_le _ _ Hk
end
def iterate {A : Type} (op : A → A) : ℕ → A → A
| 0 := λ a, a
| (succ k) := λ a, op (iterate k a)
notation f`^[`n`]` := iterate f n
/- successor and predecessor -/
theorem add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _
theorem eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) :=
by cases n; simp
theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : ∃k : ℕ, n = succ k :=
⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩
theorem succ_inj {n m : ℕ} (H : succ n = succ m) : n = m :=
nat.succ.inj_arrow H id
theorem discriminate {B : Sort u} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B :=
by ginduction n with h; [exact H1 h, exact H2 _ h]
theorem one_succ_zero : 1 = succ 0 := rfl
theorem two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1)
(H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : Π (a : ℕ), P a
| 0 := H1
| 1 := H2
| (succ (succ n)) := H3 _ (two_step_induction _) (two_step_induction _)
theorem sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m)
(H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : Π (n m : ℕ), P n m
| 0 m := H1 _
| (succ n) 0 := H2 _
| (succ n) (succ m) := H3 _ _ (sub_induction n m)
/- addition -/
theorem succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m :=
by simp [succ_add, add_succ]
theorem one_add (n : ℕ) : 1 + n = succ n := by simp
protected theorem add_right_comm : ∀ (n m k : ℕ), n + m + k = n + k + m :=
right_comm nat.add nat.add_comm nat.add_assoc
theorem eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 :=
⟨nat.eq_zero_of_add_eq_zero_right H, nat.eq_zero_of_add_eq_zero_left H⟩
theorem eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0
| 0 m := λ h, or.inl rfl
| (succ n) m :=
begin
rw succ_mul, intro h,
exact or.inr (eq_zero_of_add_eq_zero_left h)
end
/- properties of inequality -/
theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m :=
nat.cases_on n less_than_or_equal.step (λ a, succ_le_succ)
theorem le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : false :=
nat.lt_irrefl n (nat.lt_of_le_of_lt h₁ h₂)
theorem lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : false :=
le_lt_antisymm h₂ h₁
protected theorem nat.lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n :=
le_lt_antisymm (nat.le_of_lt h₁)
protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a ≥ b → C) : C :=
decidable.by_cases h₁ (λ h, h₂ (or.elim (nat.lt_or_ge a b) (λ a, absurd a h) (λ a, a)))
protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C)
(h₃ : b < a → C) : C :=
nat.lt_ge_by_cases h₁ (λ h₁,
nat.lt_ge_by_cases h₃ (λ h, h₂ (nat.le_antisymm h h₁)))
protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a :=
nat.lt_by_cases (λ h, or.inl h) (λ h, or.inr (or.inl h)) (λ h, or.inr (or.inr h))
protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a :=
(nat.lt_trichotomy a b).resolve_left hnlt
theorem lt_succ_of_lt {a b : nat} (h : a < b) : a < succ b := le_succ_of_le h
def one_pos := nat.zero_lt_one
theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m :=
mul_le_mul h h (zero_le _) (zero_le _)
theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m
| 0 m h := mul_pos h h
| (succ n) m h := mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _)
theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m :=
⟨mul_self_le_mul_self, λh, decidable.by_contradiction $
λhn, not_lt_of_ge h $ mul_self_lt_mul_self $ lt_of_not_ge hn⟩
theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m :=
iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff mul_self_le_mul_self_iff) $
iff.symm (lt_iff_not_ge _ _)
theorem le_mul_self : Π (n : ℕ), n ≤ n * n
| 0 := le_refl _
| (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t
/- subtraction -/
protected theorem sub_le_sub_left {n m : ℕ} (k) (h : n ≤ m) : k - m ≤ k - n :=
by induction h; [refl, exact le_trans (pred_le _) ih_1]
theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k :=
by rw [nat.sub_sub, nat.sub_sub, add_succ, succ_sub_succ]
protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n :=
by rw [nat.sub_sub, nat.sub_sub, add_comm]
theorem mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m
| 0 m := by simp [nat.zero_sub, pred_zero, zero_mul]
| (succ n) m := by rw [pred_succ, succ_mul, nat.add_sub_cancel]
theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n :=
by rw [mul_comm, mul_pred_left, mul_comm]
protected theorem mul_sub_right_distrib : ∀ (n m k : ℕ), (n - m) * k = n * k - m * k
| n 0 k := by simp [nat.sub_zero]
| n (succ m) k := by rw [nat.sub_succ, mul_pred_left, mul_sub_right_distrib, succ_mul, nat.sub_sub]
protected theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k :=
by rw [mul_comm, nat.mul_sub_right_distrib, mul_comm m n, mul_comm n k]
protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) :=
by rw [nat.mul_sub_left_distrib, right_distrib, right_distrib, mul_comm b a, add_comm (a*a) (a*b),
nat.add_sub_add_left]
theorem succ_mul_succ_eq (a b : nat) : succ a * succ b = a*b + a + b + 1 :=
begin rw [← add_one, ← add_one], simp [right_distrib, left_distrib] end
theorem succ_sub {m n : ℕ} (h : m ≥ n) : succ m - n = succ (m - n) :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m,
by rw [← hk, nat.add_sub_cancel_left, ← add_succ, nat.add_sub_cancel_left])
protected theorem sub_pos_of_lt {m n : ℕ} (h : m < n) : n - m > 0 :=
have 0 + m < n - m + m, begin rw [zero_add, nat.sub_add_cancel (le_of_lt h)], exact h end,
lt_of_add_lt_add_right this
protected theorem sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m :=
(nat.sub_eq_iff_eq_add (nat.sub_le _ _)).2 (eq.symm (add_sub_of_le h))
protected theorem sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m :=
(nat.sub_eq_iff_eq_add (nat.le_trans h (nat.le_add_right _ _))).2
(by rwa [nat.add_right_comm, nat.sub_add_cancel])
theorem sub_one_sub_lt {n i} (h : i < n) : n - 1 - i < n := begin
rw nat.sub_sub,
apply nat.sub_lt,
apply lt_of_lt_of_le (nat.zero_lt_succ _) h,
rw add_comm,
apply nat.zero_lt_succ
end
theorem pred_inj : ∀ {a b : nat}, a > 0 → b > 0 → nat.pred a = nat.pred b → a = b
| (succ a) (succ b) ha hb h := have a = b, from h, by rw this
| (succ a) 0 ha hb h := absurd hb (lt_irrefl _)
| 0 (succ b) ha hb h := absurd ha (lt_irrefl _)
| 0 0 ha hb h := rfl
/- find -/
section find
parameter {p : ℕ → Prop}
private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ¬p k
parameters [decidable_pred p] (H : ∃n, p n)
private def wf_lbp : well_founded lbp :=
⟨let ⟨n, pn⟩ := H in
suffices ∀m k, n ≤ k + m → acc lbp k, from λa, this _ _ (nat.le_add_left _ _),
λm, nat.rec_on m
(λk kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := absurd pn (a _ kn) end⟩)
(λm IH k kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := IH _ (by rw nat.add_right_comm; exact kn) end⟩)⟩
protected def find_x : {n // p n ∧ ∀m < n, ¬p m} :=
@well_founded.fix _ (λk, (∀n < k, ¬p n) → {n // p n ∧ ∀m < n, ¬p m}) lbp wf_lbp
(λm IH al, if pm : p m then ⟨m, pm, al⟩ else
have ∀ n ≤ m, ¬p n, from λn h, or.elim (lt_or_eq_of_le h) (al n) (λe, by rw e; exact pm),
IH _ ⟨rfl, this⟩ (λn h, this n $ nat.le_of_succ_le_succ h))
0 (λn h, absurd h (nat.not_lt_zero _))
protected def find : ℕ := nat.find_x.1
protected theorem find_spec : p nat.find := nat.find_x.2.left
protected theorem find_min : ∀ {m : ℕ}, m < nat.find → ¬p m := nat.find_x.2.right
protected theorem find_min' {m : ℕ} (h : p m) : nat.find ≤ m :=
le_of_not_gt (λ l, find_min l h)
end find
/- mod -/
theorem mod_le (x y : ℕ) : x % y ≤ x :=
or.elim (lt_or_ge x y)
(λxlty, by rw mod_eq_of_lt xlty; refl)
(λylex, or.elim (eq_zero_or_pos y)
(λy0, by rw [y0, mod_zero]; refl)
(λypos, le_trans (le_of_lt (mod_lt _ ypos)) ylex))
@[simp] theorem add_mod_right (x z : ℕ) : (x + z) % z = x % z :=
by rw [mod_eq_sub_mod (nat.le_add_left _ _), nat.add_sub_cancel]
@[simp] theorem add_mod_left (x z : ℕ) : (x + z) % x = z % x :=
by rw [add_comm, add_mod_right]
@[simp] theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y :=
by {induction z with z ih, simp, rw[mul_succ, ← add_assoc, add_mod_right, ih]}
@[simp] theorem add_mul_mod_self_right (x y z : ℕ) : (x + y * z) % z = x % z :=
by rw [mul_comm, add_mul_mod_self_left]
@[simp] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 :=
by rw [← zero_add (m*n), add_mul_mod_self_left, zero_mod]
@[simp] theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 :=
by rw [mul_comm, mul_mod_right]
theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) :=
if y0 : y = 0 then
by rw [y0, mul_zero, mod_zero, mod_zero]
else if z0 : z = 0 then
by rw [z0, zero_mul, zero_mul, zero_mul, mod_zero]
else x.strong_induction_on $ λn IH,
have y0 : y > 0, from nat.pos_of_ne_zero y0,
have z0 : z > 0, from nat.pos_of_ne_zero z0,
or.elim (le_or_gt y n)
(λyn, by rw [
mod_eq_sub_mod yn,
mod_eq_sub_mod (mul_le_mul_left z yn),
← nat.mul_sub_left_distrib];
exact IH _ (sub_lt (lt_of_lt_of_le y0 yn) y0))
(λyn, by rw [mod_eq_of_lt yn, mod_eq_of_lt (mul_lt_mul_of_pos_left yn z0)])
theorem mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z :=
by rw [mul_comm x z, mul_comm y z, mul_comm (x % y) z]; apply mul_mod_mul_left
theorem cond_to_bool_mod_two (x : ℕ) [d : decidable (x % 2 = 1)]
: cond (@to_bool (x % 2 = 1) d) 1 0 = x % 2 :=
begin
cases d with h h
; unfold decidable.to_bool cond,
{ cases mod_two_eq_zero_or_one x with h' h',
rw h', cases h h' },
{ rw h },
end
theorem sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n :=
begin
induction k with k,
{ simp },
{ have h₂ : n * k ≤ x,
{ rw [mul_succ] at h₁,
apply nat.le_trans _ h₁,
apply le_add_right _ n },
have h₄ : x - n * k ≥ n,
{ apply @nat.le_of_add_le_add_right (n*k),
rw [nat.sub_add_cancel h₂],
simp [mul_succ] at h₁, simp [h₁] },
rw [mul_succ, ← nat.sub_sub, ← mod_eq_sub_mod h₄, ih_1 h₂] }
end
/- div -/
theorem sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p :=
begin
cases eq_zero_or_pos n with h₀ h₀,
{ rw [h₀, nat.div_zero, nat.div_zero, nat.zero_sub] },
{ induction p with p,
{ simp },
{ have h₂ : n*p ≤ x,
{ transitivity,
{ apply nat.mul_le_mul_left, apply le_succ },
{ apply h₁ } },
have h₃ : x - n * p ≥ n,
{ apply le_of_add_le_add_right,
rw [nat.sub_add_cancel h₂, add_comm],
rw [mul_succ] at h₁,
apply h₁ },
rw [sub_succ, ← ih_1 h₂],
rw [@div_eq_sub_div (x - n*p) _ h₀ h₃],
simp [add_one, pred_succ, mul_succ, nat.sub_sub] } }
end
theorem div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m
| m 0 := by simp; apply zero_le
| m (succ n) := (le_div_iff_mul_le _ _ (nat.succ_pos _)).1 (le_refl _)
@[simp] theorem add_div_right (x : ℕ) {z : ℕ} (H : z > 0) : (x + z) / z = succ (x / z) :=
by rw [div_eq_sub_div H (nat.le_add_left _ _), nat.add_sub_cancel]
@[simp] theorem add_div_left (x : ℕ) {z : ℕ} (H : z > 0) : (z + x) / z = succ (x / z) :=
by rw [add_comm, add_div_right x H]
@[simp] theorem mul_div_right (n : ℕ) {m : ℕ} (H : m > 0) : m * n / m = n :=
by {induction n; simp [*, mul_succ, -mul_comm]}
@[simp] theorem mul_div_left (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m :=
by rw [mul_comm, mul_div_right _ H]
protected theorem div_self {n : ℕ} (H : n > 0) : n / n = 1 :=
let t := add_div_right 0 H in by rwa [zero_add, nat.zero_div] at t
theorem add_mul_div_left (x z : ℕ) {y : ℕ} (H : y > 0) : (x + y * z) / y = x / y + z :=
by {induction z with z ih, simp, rw [mul_succ, ← add_assoc, add_div_right _ H, ih]}
theorem add_mul_div_right (x y : ℕ) {z : ℕ} (H : z > 0) : (x + y * z) / z = x / z + y :=
by rw [mul_comm, add_mul_div_left _ _ H]
protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m :=
let t := add_mul_div_right 0 m H in by rwa [zero_add, nat.zero_div, zero_add] at t
protected theorem mul_div_cancel_left (m : ℕ) {n : ℕ} (H : n > 0) : n * m / n = m :=
by rw [mul_comm, nat.mul_div_cancel _ H]
protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : n > 0) (H2 : m = k * n) :
m / n = k :=
by rw [H2, nat.mul_div_cancel _ H1]
protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : n > 0) (H2 : m = n * k) :
m / n = k :=
by rw [H2, nat.mul_div_cancel_left _ H1]
protected theorem div_eq_of_lt_le {m n k : ℕ}
(lo : k * n ≤ m) (hi : m < succ k * n) :
m / n = k :=
have npos : n > 0, from (eq_zero_or_pos _).resolve_left $ λ hn,
by rw [hn, mul_zero] at hi lo; exact absurd lo (not_le_of_gt hi),
le_antisymm
(le_of_lt_succ ((nat.div_lt_iff_lt_mul _ _ npos).2 hi))
((nat.le_div_iff_mul_le _ _ npos).2 lo)
theorem mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) :=
begin
have npos : n > 0 := (eq_zero_or_pos _).resolve_left (λ n0,
by rw [n0, zero_mul] at h₁; exact not_lt_zero _ h₁),
apply nat.div_eq_of_lt_le,
{ rw [nat.mul_sub_right_distrib, mul_comm],
apply nat.sub_le_sub_left,
exact (div_lt_iff_lt_mul _ _ npos).1 (lt_succ_self _) },
{ change succ (pred (n * p - x)) ≤ (succ (pred (p - x / n))) * n,
rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁),
succ_pred_eq_of_pos (nat.sub_pos_of_lt _)],
{ rw [nat.mul_sub_right_distrib, mul_comm],
apply nat.sub_le_sub_left, apply div_mul_le_self },
{ apply (div_lt_iff_lt_mul _ _ npos).2, rwa mul_comm } }
end
protected theorem div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) :=
begin
cases eq_zero_or_pos k with k0 kpos, {rw [k0, mul_zero, nat.div_zero, nat.div_zero]},
cases eq_zero_or_pos n with n0 npos, {rw [n0, zero_mul, nat.div_zero, nat.zero_div]},
apply le_antisymm,
{ apply (le_div_iff_mul_le _ _ (mul_pos npos kpos)).2,
rw [mul_comm n k, ← mul_assoc],
apply (le_div_iff_mul_le _ _ npos).1,
apply (le_div_iff_mul_le _ _ kpos).1,
refl },
{ apply (le_div_iff_mul_le _ _ kpos).2,
apply (le_div_iff_mul_le _ _ npos).2,
rw [mul_assoc, mul_comm n k],
apply (le_div_iff_mul_le _ _ (mul_pos kpos npos)).1,
refl }
end
protected theorem mul_div_mul {m : ℕ} (n k : ℕ) (H : m > 0) : m * n / (m * k) = n / k :=
by rw [← nat.div_div_eq_div_mul, nat.mul_div_cancel_left _ H]
/- dvd -/
protected theorem dvd_add_iff_right {k m n : ℕ} (h : k ∣ m) : k ∣ n ↔ k ∣ m + n :=
⟨dvd_add h, dvd.elim h $ λd hd, match m, hd with
| ._, rfl := λh₂, dvd.elim h₂ $ λe he, ⟨e - d,
by rw [nat.mul_sub_left_distrib, ← he, nat.add_sub_cancel_left]⟩
end⟩
protected theorem dvd_add_iff_left {k m n : ℕ} (h : k ∣ n) : k ∣ m ↔ k ∣ m + n :=
by rw add_comm; exact nat.dvd_add_iff_right h
theorem dvd_sub {k m n : ℕ} (H : n ≤ m) (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n :=
(nat.dvd_add_iff_left h₂).2 $ by rw nat.sub_add_cancel H; exact h₁
theorem dvd_mod_iff {k m n : ℕ} (h : k ∣ n) : k ∣ m % n ↔ k ∣ m :=
let t := @nat.dvd_add_iff_left _ (m % n) _ (dvd_trans h (dvd_mul_right n (m / n))) in
by rwa mod_add_div at t
theorem le_of_dvd {m n : ℕ} (h : n > 0) : m ∣ n → m ≤ n :=
λ⟨k, e⟩, by {
revert h, rw e, refine k.cases_on _ _,
exact λhn, absurd hn (lt_irrefl _),
exact λk _, let t := mul_le_mul_left m (succ_pos k) in by rwa mul_one at t }
theorem dvd_antisymm : Π {m n : ℕ}, m ∣ n → n ∣ m → m = n
| m 0 h₁ h₂ := eq_zero_of_zero_dvd h₂
| 0 n h₁ h₂ := (eq_zero_of_zero_dvd h₁).symm
| (succ m) (succ n) h₁ h₂ := le_antisymm (le_of_dvd (succ_pos _) h₁) (le_of_dvd (succ_pos _) h₂)
theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : n > 0) : m > 0 :=
nat.pos_of_ne_zero $ λm0, by rw m0 at H1; rw eq_zero_of_zero_dvd H1 at H2; exact lt_irrefl _ H2
theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 :=
le_antisymm (le_of_dvd dec_trivial H) (pos_of_dvd_of_pos H dec_trivial)
theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n :=
dvd.intro (n / m) $ let t := mod_add_div n m in by simp [H] at t; exact t
theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 :=
dvd.elim H (λ z H1, by rw [H1, mul_mod_right])
theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n % m = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
instance decidable_dvd : @decidable_rel ℕ (∣) :=
λm n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm
protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m :=
let t := mod_add_div m n in by rwa [mod_eq_zero_of_dvd H, zero_add] at t
protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m :=
by rw [mul_comm, nat.mul_div_cancel' H]
protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) :=
or.elim (eq_zero_or_pos k)
(λh, by rw [h, nat.div_zero, nat.div_zero, mul_zero])
(λh, have m * n / k = m * (n / k * k) / k, by rw nat.div_mul_cancel H,
by rw[this, ← mul_assoc, nat.mul_div_cancel _ h])
theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : k > 0) (H : k * m ∣ k * n) : m ∣ n :=
dvd.elim H (λl H1, by rw mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left kpos H1⟩)
theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : k > 0) (H : m * k ∣ n * k) : m ∣ n :=
by rw [mul_comm m k, mul_comm n k] at H; exact dvd_of_mul_dvd_mul_left kpos H
/- pow -/
@[simp] theorem pow_one (b : ℕ) : b^1 = b := by simp [pow_succ]
theorem pow_le_pow_of_le_left {x y : ℕ} (H : x ≤ y) : ∀ i, x^i ≤ y^i
| 0 := le_refl _
| (succ i) := mul_le_mul (pow_le_pow_of_le_left i) H (zero_le _) (zero_le _)
theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i} : ∀ {j}, i ≤ j → x^i ≤ x^j
| 0 h := by rw eq_zero_of_le_zero h; apply le_refl
| (succ j) h := (lt_or_eq_of_le h).elim
(λhl, by rw [pow_succ, ← mul_one (x^i)]; exact
mul_le_mul (pow_le_pow_of_le_right $ le_of_lt_succ hl) H (zero_le _) (zero_le _))
(λe, by rw e; refl)
theorem pos_pow_of_pos {b : ℕ} (n : ℕ) (h : 0 < b) : 0 < b^n :=
pow_le_pow_of_le_right h (zero_le _)
theorem zero_pow {n : ℕ} (h : 0 < n) : 0^n = 0 :=
by rw [← succ_pred_eq_of_pos h, pow_succ, mul_zero]
theorem pow_lt_pow_of_lt_left {x y : ℕ} (H : x < y) {i} (h : i > 0) : x^i < y^i :=
begin
cases i with i, { exact absurd h (not_lt_zero _) },
rw [pow_succ, pow_succ],
exact mul_lt_mul' (pow_le_pow_of_le_left (le_of_lt H) _) H (zero_le _)
(pos_pow_of_pos _ $ lt_of_le_of_lt (zero_le _) H)
end
theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i j} (h : i < j) : x^i < x^j :=
begin
have xpos := lt_of_succ_lt H,
refine lt_of_lt_of_le _ (pow_le_pow_of_le_right xpos h),
rw [← mul_one (x^i), pow_succ],
exact nat.mul_lt_mul_of_pos_left H (pos_pow_of_pos _ xpos)
end
/- mod / div / pow -/
theorem mod_pow_succ {b : ℕ} (b_pos : b > 0) (w m : ℕ)
: m % (b^succ w) = b * (m/b % b^w) + m % b :=
begin
apply nat.strong_induction_on m,
clear m,
intros p IH,
cases lt_or_ge p (b^succ w) with h₁ h₁,
-- base case: p < b^succ w
{ have h₂ : p / b < b^w,
{ rw [div_lt_iff_lt_mul p _ b_pos],
simp [pow_succ] at h₁,
simp [h₁] },
rw [mod_eq_of_lt h₁, mod_eq_of_lt h₂],
simp [mod_add_div] },
-- step: p ≥ b^succ w
{ -- Generate condiition for induction principal
have h₂ : p - b^succ w < p,
{ apply sub_lt_of_pos_le _ _ (pos_pow_of_pos _ b_pos) h₁ },
-- Apply induction
rw [mod_eq_sub_mod h₁, IH _ h₂],
-- Normalize goal and h1
simp [pow_succ],
simp [ge, pow_succ] at h₁,
-- Pull subtraction outside mod and div
rw [sub_mul_mod _ _ _ h₁, sub_mul_div _ _ _ h₁],
-- Cancel subtraction inside mod b^w
have p_b_ge : b^w ≤ p / b,
{ rw [le_div_iff_mul_le _ _ b_pos],
simp [h₁] },
rw [eq.symm (mod_eq_sub_mod p_b_ge)] }
end
end nat
|
b92262cc31cad2fa93eb3f473335cd3dcaf9c3d4 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/lie/solvable.lean | ec058f075296a61b30a42f06a56e281d4e0ef05b | [
"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 | 13,819 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.abelian
import algebra.lie.ideal_operations
import order.hom.basic
/-!
# Solvable Lie algebras
Like groups, Lie algebras admit a natural concept of solvability. We define this here via the
derived series and prove some related results. We also define the radical of a Lie algebra and
prove that it is solvable when the Lie algebra is Noetherian.
## Main definitions
* `lie_algebra.derived_series_of_ideal`
* `lie_algebra.derived_series`
* `lie_algebra.is_solvable`
* `lie_algebra.is_solvable_add`
* `lie_algebra.radical`
* `lie_algebra.radical_is_solvable`
* `lie_algebra.derived_length_of_ideal`
* `lie_algebra.derived_length`
* `lie_algebra.derived_abelian_of_ideal`
## Tags
lie algebra, derived series, derived length, solvable, radical
-/
universes u v w w₁ w₂
variables (R : Type u) (L : Type v) (M : Type w) {L' : Type w₁}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L']
variables (I J : lie_ideal R L) {f : L' →ₗ⁅R⁆ L}
namespace lie_algebra
/-- A generalisation of the derived series of a Lie algebra, whose zeroth term is a specified ideal.
It can be more convenient to work with this generalisation when considering the derived series of
an ideal since it provides a type-theoretic expression of the fact that the terms of the ideal's
derived series are also ideals of the enclosing algebra.
See also `lie_ideal.derived_series_eq_derived_series_of_ideal_comap` and
`lie_ideal.derived_series_eq_derived_series_of_ideal_map` below. -/
def derived_series_of_ideal (k : ℕ) : lie_ideal R L → lie_ideal R L := (λ I, ⁅I, I⁆)^[k]
@[simp] lemma derived_series_of_ideal_zero :
derived_series_of_ideal R L 0 I = I := rfl
@[simp] lemma derived_series_of_ideal_succ (k : ℕ) :
derived_series_of_ideal R L (k + 1) I =
⁅derived_series_of_ideal R L k I, derived_series_of_ideal R L k I⁆ :=
function.iterate_succ_apply' (λ I, ⁅I, I⁆) k I
/-- The derived series of Lie ideals of a Lie algebra. -/
abbreviation derived_series (k : ℕ) : lie_ideal R L := derived_series_of_ideal R L k ⊤
lemma derived_series_def (k : ℕ) :
derived_series R L k = derived_series_of_ideal R L k ⊤ := rfl
variables {R L}
local notation `D` := derived_series_of_ideal R L
lemma derived_series_of_ideal_add (k l : ℕ) : D (k + l) I = D k (D l I) :=
begin
induction k with k ih,
{ rw [zero_add, derived_series_of_ideal_zero], },
{ rw [nat.succ_add k l, derived_series_of_ideal_succ, derived_series_of_ideal_succ, ih], },
end
@[mono] lemma derived_series_of_ideal_le {I J : lie_ideal R L} {k l : ℕ} (h₁ : I ≤ J) (h₂ : l ≤ k) :
D k I ≤ D l J :=
begin
revert l, induction k with k ih; intros l h₂,
{ rw le_zero_iff at h₂, rw [h₂, derived_series_of_ideal_zero], exact h₁, },
{ have h : l = k.succ ∨ l ≤ k, by rwa [le_iff_eq_or_lt, nat.lt_succ_iff] at h₂,
cases h,
{ rw [h, derived_series_of_ideal_succ, derived_series_of_ideal_succ],
exact lie_submodule.mono_lie _ _ _ _ (ih (le_refl k)) (ih (le_refl k)), },
{ rw derived_series_of_ideal_succ, exact le_trans (lie_submodule.lie_le_left _ _) (ih h), }, },
end
lemma derived_series_of_ideal_succ_le (k : ℕ) : D (k + 1) I ≤ D k I :=
derived_series_of_ideal_le (le_refl I) k.le_succ
lemma derived_series_of_ideal_le_self (k : ℕ) : D k I ≤ I :=
derived_series_of_ideal_le (le_refl I) (zero_le k)
lemma derived_series_of_ideal_mono {I J : lie_ideal R L} (h : I ≤ J) (k : ℕ) : D k I ≤ D k J :=
derived_series_of_ideal_le h (le_refl k)
lemma derived_series_of_ideal_antitone {k l : ℕ} (h : l ≤ k) : D k I ≤ D l I :=
derived_series_of_ideal_le (le_refl I) h
lemma derived_series_of_ideal_add_le_add (J : lie_ideal R L) (k l : ℕ) :
D (k + l) (I + J) ≤ (D k I) + (D l J) :=
begin
let D₁ : lie_ideal R L →o lie_ideal R L :=
{ to_fun := λ I, ⁅I, I⁆,
monotone' := λ I J h, lie_submodule.mono_lie I J I J h h, },
have h₁ : ∀ (I J : lie_ideal R L), D₁ (I ⊔ J) ≤ (D₁ I) ⊔ J,
{ simp [lie_submodule.lie_le_right, lie_submodule.lie_le_left, le_sup_of_le_right], },
rw ← D₁.iterate_sup_le_sup_iff at h₁,
exact h₁ k l I J,
end
lemma derived_series_of_bot_eq_bot (k : ℕ) : derived_series_of_ideal R L k ⊥ = ⊥ :=
by { rw eq_bot_iff, exact derived_series_of_ideal_le_self ⊥ k, }
lemma abelian_iff_derived_one_eq_bot : is_lie_abelian I ↔ derived_series_of_ideal R L 1 I = ⊥ :=
by rw [derived_series_of_ideal_succ, derived_series_of_ideal_zero,
lie_submodule.lie_abelian_iff_lie_self_eq_bot]
lemma abelian_iff_derived_succ_eq_bot (I : lie_ideal R L) (k : ℕ) :
is_lie_abelian (derived_series_of_ideal R L k I) ↔ derived_series_of_ideal R L (k + 1) I = ⊥ :=
by rw [add_comm, derived_series_of_ideal_add I 1 k, abelian_iff_derived_one_eq_bot]
end lie_algebra
namespace lie_ideal
open lie_algebra
variables {R L}
lemma derived_series_eq_derived_series_of_ideal_comap (k : ℕ) :
derived_series R I k = (derived_series_of_ideal R L k I).comap I.incl :=
begin
induction k with k ih,
{ simp only [derived_series_def, comap_incl_self, derived_series_of_ideal_zero], },
{ simp only [derived_series_def, derived_series_of_ideal_succ] at ⊢ ih, rw ih,
exact comap_bracket_incl_of_le I
(derived_series_of_ideal_le_self I k) (derived_series_of_ideal_le_self I k), },
end
lemma derived_series_eq_derived_series_of_ideal_map (k : ℕ) :
(derived_series R I k).map I.incl = derived_series_of_ideal R L k I :=
by { rw [derived_series_eq_derived_series_of_ideal_comap, map_comap_incl, inf_eq_right],
apply derived_series_of_ideal_le_self, }
lemma derived_series_eq_bot_iff (k : ℕ) :
derived_series R I k = ⊥ ↔ derived_series_of_ideal R L k I = ⊥ :=
by rw [← derived_series_eq_derived_series_of_ideal_map, map_eq_bot_iff, ker_incl, eq_bot_iff]
lemma derived_series_add_eq_bot {k l : ℕ} {I J : lie_ideal R L}
(hI : derived_series R I k = ⊥) (hJ : derived_series R J l = ⊥) :
derived_series R ↥(I + J) (k + l) = ⊥ :=
begin
rw lie_ideal.derived_series_eq_bot_iff at hI hJ ⊢,
rw ← le_bot_iff,
let D := derived_series_of_ideal R L, change D k I = ⊥ at hI, change D l J = ⊥ at hJ,
calc D (k + l) (I + J) ≤ (D k I) + (D l J) : derived_series_of_ideal_add_le_add I J k l
... ≤ ⊥ : by { rw [hI, hJ], simp, },
end
lemma derived_series_map_le (k : ℕ) :
(derived_series R L' k).map f ≤ derived_series R L k :=
begin
induction k with k ih,
{ simp only [derived_series_def, derived_series_of_ideal_zero, le_top], },
{ simp only [derived_series_def, derived_series_of_ideal_succ] at ih ⊢,
exact le_trans (map_bracket_le f) (lie_submodule.mono_lie _ _ _ _ ih ih), },
end
lemma derived_series_map_eq (k : ℕ) (h : function.surjective f) :
(derived_series R L' k).map f = derived_series R L k :=
begin
induction k with k ih,
{ change (⊤ : lie_ideal R L').map f = ⊤,
rw ←f.ideal_range_eq_map,
exact f.ideal_range_eq_top_of_surjective h, },
{ simp only [derived_series_def, map_bracket_eq f h, ih, derived_series_of_ideal_succ], },
end
end lie_ideal
namespace lie_algebra
/-- A Lie algebra is solvable if its derived series reaches 0 (in a finite number of steps). -/
class is_solvable : Prop :=
(solvable : ∃ k, derived_series R L k = ⊥)
instance is_solvable_bot : is_solvable R ↥(⊥ : lie_ideal R L) :=
⟨⟨0, subsingleton.elim _ ⊥⟩⟩
instance is_solvable_add {I J : lie_ideal R L} [hI : is_solvable R I] [hJ : is_solvable R J] :
is_solvable R ↥(I + J) :=
begin
obtain ⟨k, hk⟩ := id hI, obtain ⟨l, hl⟩ := id hJ,
exact ⟨⟨k+l, lie_ideal.derived_series_add_eq_bot hk hl⟩⟩,
end
end lie_algebra
variables {R L}
namespace function
open lie_algebra
lemma injective.lie_algebra_is_solvable [h₁ : is_solvable R L] (h₂ : injective f) :
is_solvable R L' :=
begin
obtain ⟨k, hk⟩ := id h₁,
use k,
apply lie_ideal.bot_of_map_eq_bot h₂, rw [eq_bot_iff, ← hk],
apply lie_ideal.derived_series_map_le,
end
lemma surjective.lie_algebra_is_solvable [h₁ : is_solvable R L'] (h₂ : surjective f) :
is_solvable R L :=
begin
obtain ⟨k, hk⟩ := id h₁,
use k,
rw [← lie_ideal.derived_series_map_eq k h₂, hk],
simp only [lie_ideal.map_eq_bot_iff, bot_le],
end
end function
lemma lie_hom.is_solvable_range (f : L' →ₗ⁅R⁆ L) [h : lie_algebra.is_solvable R L'] :
lie_algebra.is_solvable R f.range :=
f.surjective_range_restrict.lie_algebra_is_solvable
namespace lie_algebra
lemma solvable_iff_equiv_solvable (e : L' ≃ₗ⁅R⁆ L) : is_solvable R L' ↔ is_solvable R L :=
begin
split; introsI h,
{ exact e.symm.injective.lie_algebra_is_solvable, },
{ exact e.injective.lie_algebra_is_solvable, },
end
lemma le_solvable_ideal_solvable {I J : lie_ideal R L} (h₁ : I ≤ J) (h₂ : is_solvable R J) :
is_solvable R I :=
(lie_ideal.hom_of_le_injective h₁).lie_algebra_is_solvable
variables (R L)
@[priority 100]
instance of_abelian_is_solvable [is_lie_abelian L] : is_solvable R L :=
begin
use 1,
rw [← abelian_iff_derived_one_eq_bot, lie_abelian_iff_equiv_lie_abelian lie_ideal.top_equiv],
apply_instance,
end
/-- The (solvable) radical of Lie algebra is the `Sup` of all solvable ideals. -/
def radical := Sup { I : lie_ideal R L | is_solvable R I }
/-- The radical of a Noetherian Lie algebra is solvable. -/
instance radical_is_solvable [is_noetherian R L] : is_solvable R (radical R L) :=
begin
have hwf := lie_submodule.well_founded_of_noetherian R L L,
rw ← complete_lattice.is_sup_closed_compact_iff_well_founded at hwf,
refine hwf { I : lie_ideal R L | is_solvable R I } ⟨⊥, _⟩ (λ I hI J hJ, _),
{ exact lie_algebra.is_solvable_bot R L, },
{ apply lie_algebra.is_solvable_add R L, exacts [hI, hJ] },
end
/-- The `→` direction of this lemma is actually true without the `is_noetherian` assumption. -/
lemma lie_ideal.solvable_iff_le_radical [is_noetherian R L] (I : lie_ideal R L) :
is_solvable R I ↔ I ≤ radical R L :=
⟨λ h, le_Sup h, λ h, le_solvable_ideal_solvable h infer_instance⟩
lemma center_le_radical : center R L ≤ radical R L :=
have h : is_solvable R (center R L), { apply_instance, }, le_Sup h
/-- Given a solvable Lie ideal `I` with derived series `I = D₀ ≥ D₁ ≥ ⋯ ≥ Dₖ = ⊥`, this is the
natural number `k` (the number of inclusions).
For a non-solvable ideal, the value is 0. -/
noncomputable def derived_length_of_ideal (I : lie_ideal R L) : ℕ :=
Inf {k | derived_series_of_ideal R L k I = ⊥}
/-- The derived length of a Lie algebra is the derived length of its 'top' Lie ideal.
See also `lie_algebra.derived_length_eq_derived_length_of_ideal`. -/
noncomputable abbreviation derived_length : ℕ := derived_length_of_ideal R L ⊤
lemma derived_series_of_derived_length_succ (I : lie_ideal R L) (k : ℕ) :
derived_length_of_ideal R L I = k + 1 ↔
is_lie_abelian (derived_series_of_ideal R L k I) ∧ derived_series_of_ideal R L k I ≠ ⊥ :=
begin
rw abelian_iff_derived_succ_eq_bot,
let s := {k | derived_series_of_ideal R L k I = ⊥}, change Inf s = k + 1 ↔ k + 1 ∈ s ∧ k ∉ s,
have hs : ∀ (k₁ k₂ : ℕ), k₁ ≤ k₂ → k₁ ∈ s → k₂ ∈ s,
{ intros k₁ k₂ h₁₂ h₁,
suffices : derived_series_of_ideal R L k₂ I ≤ ⊥, { exact eq_bot_iff.mpr this, },
change derived_series_of_ideal R L k₁ I = ⊥ at h₁, rw ← h₁,
exact derived_series_of_ideal_antitone I h₁₂, },
exact nat.Inf_upward_closed_eq_succ_iff hs k,
end
lemma derived_length_eq_derived_length_of_ideal (I : lie_ideal R L) :
derived_length R I = derived_length_of_ideal R L I :=
begin
let s₁ := {k | derived_series R I k = ⊥},
let s₂ := {k | derived_series_of_ideal R L k I = ⊥},
change Inf s₁ = Inf s₂,
congr, ext k, exact I.derived_series_eq_bot_iff k,
end
variables {R L}
/-- Given a solvable Lie ideal `I` with derived series `I = D₀ ≥ D₁ ≥ ⋯ ≥ Dₖ = ⊥`, this is the
`k-1`th term in the derived series (and is therefore an Abelian ideal contained in `I`).
For a non-solvable ideal, this is the zero ideal, `⊥`. -/
noncomputable def derived_abelian_of_ideal (I : lie_ideal R L) : lie_ideal R L :=
match derived_length_of_ideal R L I with
| 0 := ⊥
| k + 1 := derived_series_of_ideal R L k I
end
lemma abelian_derived_abelian_of_ideal (I : lie_ideal R L) :
is_lie_abelian (derived_abelian_of_ideal I) :=
begin
dunfold derived_abelian_of_ideal,
cases h : derived_length_of_ideal R L I with k,
{ exact is_lie_abelian_bot R L, },
{ rw derived_series_of_derived_length_succ at h, exact h.1, },
end
lemma derived_length_zero (I : lie_ideal R L) [hI : is_solvable R I] :
derived_length_of_ideal R L I = 0 ↔ I = ⊥ :=
begin
let s := {k | derived_series_of_ideal R L k I = ⊥}, change Inf s = 0 ↔ _,
have hne : s ≠ ∅,
{ rw set.ne_empty_iff_nonempty,
obtain ⟨k, hk⟩ := id hI, use k,
rw [derived_series_def, lie_ideal.derived_series_eq_bot_iff] at hk, exact hk, },
simp [hne],
end
lemma abelian_of_solvable_ideal_eq_bot_iff (I : lie_ideal R L) [h : is_solvable R I] :
derived_abelian_of_ideal I = ⊥ ↔ I = ⊥ :=
begin
dunfold derived_abelian_of_ideal,
cases h : derived_length_of_ideal R L I with k,
{ rw derived_length_zero at h, rw h, refl, },
{ obtain ⟨h₁, h₂⟩ := (derived_series_of_derived_length_succ R L I k).mp h,
have h₃ : I ≠ ⊥, { intros contra, apply h₂, rw contra, apply derived_series_of_bot_eq_bot, },
change derived_series_of_ideal R L k I = ⊥ ↔ I = ⊥,
split; contradiction, },
end
end lie_algebra
|
3692461da98662451976c78bdbd8ba31adf68799 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/geometry/manifold/cont_mdiff_map.lean | 73697d2b7a292dee41faaa89e3f6a73ca3457b24 | [
"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 | 3,854 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nicolò Cavalleri
-/
import geometry.manifold.cont_mdiff_mfderiv
import topology.continuous_function.basic
/-!
# Smooth bundled map
In this file we define the type `cont_mdiff_map` of `n` times continuously differentiable
bundled maps.
-/
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E']
{H : Type*} [topological_space H]
{H' : Type*} [topological_space H']
(I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H')
(M : Type*) [topological_space M] [charted_space H M]
(M' : Type*) [topological_space M'] [charted_space H' M']
{E'' : Type*} [normed_add_comm_group E''] [normed_space 𝕜 E'']
{H'' : Type*} [topological_space H'']
{I'' : model_with_corners 𝕜 E'' H''}
{M'' : Type*} [topological_space M''] [charted_space H'' M'']
(n : ℕ∞)
/-- Bundled `n` times continuously differentiable maps. -/
@[protect_proj]
structure cont_mdiff_map :=
(to_fun : M → M')
(cont_mdiff_to_fun : cont_mdiff I I' n to_fun)
/-- Bundled smooth maps. -/
@[reducible] def smooth_map := cont_mdiff_map I I' M M' ⊤
localized "notation (name := cont_mdiff_map) `C^` n `⟮` I `, ` M `; ` I' `, ` M' `⟯` :=
cont_mdiff_map I I' M M' n" in manifold
localized "notation (name := cont_mdiff_map.self) `C^` n `⟮` I `, ` M `; ` k `⟯` :=
cont_mdiff_map I (model_with_corners_self k k) M k n" in manifold
open_locale manifold
namespace cont_mdiff_map
variables {I} {I'} {M} {M'} {n}
instance : has_coe_to_fun C^n⟮I, M; I', M'⟯ (λ _, M → M') := ⟨cont_mdiff_map.to_fun⟩
instance : has_coe C^n⟮I, M; I', M'⟯ C(M, M') :=
⟨λ f, ⟨f, f.cont_mdiff_to_fun.continuous⟩⟩
attribute [to_additive_ignore_args 21] cont_mdiff_map
cont_mdiff_map.has_coe_to_fun cont_mdiff_map.continuous_map.has_coe
variables {f g : C^n⟮I, M; I', M'⟯}
@[simp] lemma coe_fn_mk (f : M → M') (hf : cont_mdiff I I' n f) :
(mk f hf : M → M') = f :=
rfl
protected lemma cont_mdiff (f : C^n⟮I, M; I', M'⟯) :
cont_mdiff I I' n f := f.cont_mdiff_to_fun
protected lemma smooth (f : C^∞⟮I, M; I', M'⟯) :
smooth I I' f := f.cont_mdiff_to_fun
protected lemma mdifferentiable' (f : C^n⟮I, M; I', M'⟯) (hn : 1 ≤ n) :
mdifferentiable I I' f :=
f.cont_mdiff.mdifferentiable hn
protected lemma mdifferentiable (f : C^∞⟮I, M; I', M'⟯) :
mdifferentiable I I' f :=
f.cont_mdiff.mdifferentiable le_top
protected lemma mdifferentiable_at (f : C^∞⟮I, M; I', M'⟯) {x} :
mdifferentiable_at I I' f x :=
f.mdifferentiable x
lemma coe_inj ⦃f g : C^n⟮I, M; I', M'⟯⦄ (h : (f : M → M') = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext] theorem ext (h : ∀ x, f x = g x) : f = g :=
by cases f; cases g; congr'; exact funext h
/-- The identity as a smooth map. -/
def id : C^n⟮I, M; I, M⟯ := ⟨id, cont_mdiff_id⟩
/-- The composition of smooth maps, as a smooth map. -/
def comp (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) : C^n⟮I, M; I'', M''⟯ :=
{ to_fun := λ a, f (g a),
cont_mdiff_to_fun := f.cont_mdiff_to_fun.comp g.cont_mdiff_to_fun, }
@[simp] lemma comp_apply (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) (x : M) :
f.comp g x = f (g x) := rfl
instance [inhabited M'] : inhabited C^n⟮I, M; I', M'⟯ :=
⟨⟨λ _, default, cont_mdiff_const⟩⟩
/-- Constant map as a smooth map -/
def const (y : M') : C^n⟮I, M; I', M'⟯ := ⟨λ x, y, cont_mdiff_const⟩
end cont_mdiff_map
instance continuous_linear_map.has_coe_to_cont_mdiff_map :
has_coe (E →L[𝕜] E') C^n⟮𝓘(𝕜, E), E; 𝓘(𝕜, E'), E'⟯ :=
⟨λ f, ⟨f.to_fun, f.cont_mdiff⟩⟩
|
b8a9c088add1f4d2702b0db40dc6116d910d01d9 | 5e3548e65f2c037cb94cd5524c90c623fbd6d46a | /src_icannos_totilas/aops/2020_CAMO_Problem_1.lean | 507b33133eee9168f79681d2c1a1b3078e0217c0 | [] | 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 | 299 | lean | import data.real.basic
import data.real.nnreal
import analysis.special_functions.pow
theorem CAMOProblemsProblem1_2020 (f : nnreal -> nnreal) :
(∀ x y : nnreal, f(x)*f(y)*f(x+y) = f(x)+f(y) - f(x+y)) →
(∃ a : nnreal, (a > 1 ∧ ∀ x : nnreal, f(x) = (a.rpow x -1) / (a.rpow x +1))):= sorry |
5744a151249331f5ac95569ffa7bed0aa4cb8206 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/artinian.lean | c64f5903be5761fba5c7f6cefeea41bf49bb8590 | [
"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 | 19,081 | lean | /-
Copyright (c) 2021 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import ring_theory.nakayama
import data.set_like.fintype
/-!
# Artinian rings and modules
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A module satisfying these equivalent conditions is said to be an *Artinian* R-module
if every decreasing chain of submodules is eventually constant, or equivalently,
if the relation `<` on submodules is well founded.
A ring is said to be left (or right) Artinian if it is Artinian as a left (or right) module over
itself, or simply Artinian if it is both left and right Artinian.
## Main definitions
Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`.
* `is_artinian R M` is the proposition that `M` is a Artinian `R`-module. It is a class,
implemented as the predicate that the `<` relation on submodules is well founded.
* `is_artinian_ring R` is the proposition that `R` is a left Artinian ring.
## References
* [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald]
* [samuel]
## Tags
Artinian, artinian, Artinian ring, Artinian module, artinian ring, artinian module
-/
open set
open_locale big_operators pointwise
/--
`is_artinian R M` is the proposition that `M` is an Artinian `R`-module,
implemented as the well-foundedness of submodule inclusion.
-/
class is_artinian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop :=
(well_founded_submodule_lt [] : well_founded ((<) : submodule R M → submodule R M → Prop))
section
variables {R M P N : Type*}
variables [ring R] [add_comm_group M] [add_comm_group P] [add_comm_group N]
variables [module R M] [module R P] [module R N]
open is_artinian
include R
theorem is_artinian_of_injective (f : M →ₗ[R] P) (h : function.injective f)
[is_artinian R P] : is_artinian R M :=
⟨subrelation.wf
(λ A B hAB, show A.map f < B.map f,
from submodule.map_strict_mono_of_injective h hAB)
(inv_image.wf (submodule.map f) (is_artinian.well_founded_submodule_lt R P))⟩
instance is_artinian_submodule' [is_artinian R M] (N : submodule R M) : is_artinian R N :=
is_artinian_of_injective N.subtype subtype.val_injective
lemma is_artinian_of_le {s t : submodule R M} [ht : is_artinian R t]
(h : s ≤ t) : is_artinian R s :=
is_artinian_of_injective (submodule.of_le h) (submodule.of_le_injective h)
variable (M)
theorem is_artinian_of_surjective (f : M →ₗ[R] P) (hf : function.surjective f)
[is_artinian R M] : is_artinian R P :=
⟨subrelation.wf
(λ A B hAB, show A.comap f < B.comap f,
from submodule.comap_strict_mono_of_surjective hf hAB)
(inv_image.wf (submodule.comap f) (is_artinian.well_founded_submodule_lt _ _))⟩
variable {M}
theorem is_artinian_of_linear_equiv (f : M ≃ₗ[R] P)
[is_artinian R M] : is_artinian R P :=
is_artinian_of_surjective _ f.to_linear_map f.to_equiv.surjective
theorem is_artinian_of_range_eq_ker
[is_artinian R M] [is_artinian R P]
(f : M →ₗ[R] N) (g : N →ₗ[R] P)
(hf : function.injective f)
(hg : function.surjective g)
(h : f.range = g.ker) :
is_artinian R N :=
⟨well_founded_lt_exact_sequence
(is_artinian.well_founded_submodule_lt _ _)
(is_artinian.well_founded_submodule_lt _ _)
f.range
(submodule.map f)
(submodule.comap f)
(submodule.comap g)
(submodule.map g)
(submodule.gci_map_comap hf)
(submodule.gi_map_comap hg)
(by simp [submodule.map_comap_eq, inf_comm])
(by simp [submodule.comap_map_eq, h])⟩
instance is_artinian_prod [is_artinian R M]
[is_artinian R P] : is_artinian R (M × P) :=
is_artinian_of_range_eq_ker
(linear_map.inl R M P)
(linear_map.snd R M P)
linear_map.inl_injective
linear_map.snd_surjective
(linear_map.range_inl R M P)
@[priority 100]
instance is_artinian_of_finite [finite M] : is_artinian R M :=
⟨finite.well_founded_of_trans_of_irrefl _⟩
local attribute [elab_as_eliminator] finite.induction_empty_option
instance is_artinian_pi {R ι : Type*} [finite ι] : Π {M : ι → Type*} [ring R]
[Π i, add_comm_group (M i)], by exactI Π [Π i, module R (M i)],
by exactI Π [∀ i, is_artinian R (M i)], is_artinian R (Π i, M i) :=
finite.induction_empty_option
(begin
introsI α β e hα M _ _ _ _,
exact is_artinian_of_linear_equiv
(linear_equiv.Pi_congr_left R M e)
end)
(by { introsI M _ _ _ _, apply_instance })
(begin
introsI α _ ih M _ _ _ _,
exact is_artinian_of_linear_equiv
(linear_equiv.pi_option_equiv_prod R).symm,
end)
ι
/-- A version of `is_artinian_pi` for non-dependent functions. We need this instance because
sometimes Lean fails to apply the dependent version in non-dependent settings (e.g., it fails to
prove that `ι → ℝ` is finite dimensional over `ℝ`). -/
instance is_artinian_pi' {R ι M : Type*} [ring R] [add_comm_group M] [module R M] [finite ι]
[is_artinian R M] : is_artinian R (ι → M) :=
is_artinian_pi
end
open is_artinian submodule function
section ring
variables {R M : Type*} [ring R] [add_comm_group M] [module R M]
theorem is_artinian_iff_well_founded :
is_artinian R M ↔ well_founded ((<) : submodule R M → submodule R M → Prop) :=
⟨λ h, h.1, is_artinian.mk⟩
variables {R M}
lemma is_artinian.finite_of_linear_independent [nontrivial R] [is_artinian R M]
{s : set M} (hs : linear_independent R (coe : s → M)) : s.finite :=
begin
refine classical.by_contradiction (λ hf, (rel_embedding.well_founded_iff_no_descending_seq.1
(well_founded_submodule_lt R M)).elim' _),
have f : ℕ ↪ s, from set.infinite.nat_embedding s hf,
have : ∀ n, (coe ∘ f) '' {m | n ≤ m} ⊆ s,
{ rintros n x ⟨y, hy₁, rfl⟩, exact (f y).2 },
have : ∀ a b : ℕ, a ≤ b ↔
span R ((coe ∘ f) '' {m | b ≤ m}) ≤ span R ((coe ∘ f) '' {m | a ≤ m}),
{ assume a b,
rw [span_le_span_iff hs (this b) (this a),
set.image_subset_image_iff (subtype.coe_injective.comp f.injective),
set.subset_def],
simp only [set.mem_set_of_eq],
exact ⟨λ hab x, le_trans hab, λ h, (h _ le_rfl)⟩ },
exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | n ≤ m}),
λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩,
begin
intros a b,
conv_rhs { rw [gt, lt_iff_le_not_le, this, this, ← lt_iff_le_not_le] },
simp
end⟩
end
/-- A module is Artinian iff every nonempty set of submodules has a minimal submodule among them.
-/
theorem set_has_minimal_iff_artinian :
(∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, ¬ I < M') ↔ is_artinian R M :=
by rw [is_artinian_iff_well_founded, well_founded.well_founded_iff_has_min]
theorem is_artinian.set_has_minimal [is_artinian R M] (a : set $ submodule R M) (ha : a.nonempty) :
∃ M' ∈ a, ∀ I ∈ a, ¬ I < M' :=
set_has_minimal_iff_artinian.mpr ‹_› a ha
/-- A module is Artinian iff every decreasing chain of submodules stabilizes. -/
theorem monotone_stabilizes_iff_artinian :
(∀ (f : ℕ →o (submodule R M)ᵒᵈ), ∃ n, ∀ m, n ≤ m → f n = f m) ↔ is_artinian R M :=
by { rw is_artinian_iff_well_founded, exact well_founded.monotone_chain_condition.symm }
namespace is_artinian
variables [is_artinian R M]
theorem monotone_stabilizes (f : ℕ →o (submodule R M)ᵒᵈ) : ∃ n, ∀ m, n ≤ m → f n = f m :=
monotone_stabilizes_iff_artinian.mpr ‹_› f
/-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/
lemma induction {P : submodule R M → Prop} (hgt : ∀ I, (∀ J < I, P J) → P I) (I : submodule R M) :
P I :=
(well_founded_submodule_lt R M).recursion I hgt
/--
For any endomorphism of a Artinian module, there is some nontrivial iterate
with disjoint kernel and range.
-/
theorem exists_endomorphism_iterate_ker_sup_range_eq_top (f : M →ₗ[R] M) :
∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊔ (f ^ n).range = ⊤ :=
begin
obtain ⟨n, w⟩ := monotone_stabilizes (f.iterate_range.comp ⟨λ n, n+1, λ n m w, by linarith⟩),
specialize w ((n + 1) + n) (by linarith),
dsimp at w,
refine ⟨n + 1, nat.succ_ne_zero _, _⟩,
simp_rw [eq_top_iff', mem_sup],
intro x,
have : (f^(n + 1)) x ∈ (f ^ ((n + 1) + n + 1)).range,
{ rw ← w, exact mem_range_self _ },
rcases this with ⟨y, hy⟩,
use x - (f ^ (n+1)) y,
split,
{ rw [linear_map.mem_ker, linear_map.map_sub, ← hy, sub_eq_zero, pow_add],
simp [iterate_add_apply], },
{ use (f^ (n+1)) y,
simp }
end
/-- Any injective endomorphism of an Artinian module is surjective. -/
theorem surjective_of_injective_endomorphism (f : M →ₗ[R] M) (s : injective f) : surjective f :=
begin
obtain ⟨n, ne, w⟩ := exists_endomorphism_iterate_ker_sup_range_eq_top f,
rw [linear_map.ker_eq_bot.mpr (linear_map.iterate_injective s n), bot_sup_eq,
linear_map.range_eq_top] at w,
exact linear_map.surjective_of_iterate_surjective ne w,
end
/-- Any injective endomorphism of an Artinian module is bijective. -/
theorem bijective_of_injective_endomorphism (f : M →ₗ[R] M) (s : injective f) : bijective f :=
⟨s, surjective_of_injective_endomorphism f s⟩
/--
A sequence `f` of submodules of a artinian module,
with the supremum `f (n+1)` and the infinum of `f 0`, ..., `f n` being ⊤,
is eventually ⊤.
-/
lemma disjoint_partial_infs_eventually_top (f : ℕ → submodule R M)
(h : ∀ n, disjoint (partial_sups (order_dual.to_dual ∘ f) n) (order_dual.to_dual (f (n+1)))) :
∃ n : ℕ, ∀ m, n ≤ m → f m = ⊤ :=
begin
-- A little off-by-one cleanup first:
rsuffices ⟨n, w⟩ : ∃ n : ℕ, ∀ m, n ≤ m → order_dual.to_dual f (m+1) = ⊤,
{ use n+1,
rintros (_|m) p,
{ cases p, },
{ apply w,
exact nat.succ_le_succ_iff.mp p }, },
obtain ⟨n, w⟩ := monotone_stabilizes (partial_sups (order_dual.to_dual ∘ f)),
refine ⟨n, λ m p, _⟩,
exact (h m).eq_bot_of_ge (sup_eq_left.1 $ (w (m + 1) $ le_add_right p).symm.trans $ w m p)
end
end is_artinian
end ring
section comm_ring
variables {R : Type*} (M : Type*) [comm_ring R] [add_comm_group M] [module R M] [is_artinian R M]
namespace is_artinian
lemma range_smul_pow_stabilizes (r : R) : ∃ n : ℕ, ∀ m, n ≤ m →
(r^n • linear_map.id : M →ₗ[R] M).range = (r^m • linear_map.id : M →ₗ[R] M).range :=
monotone_stabilizes
⟨λ n, (r^n • linear_map.id : M →ₗ[R] M).range,
λ n m h x ⟨y, hy⟩, ⟨r ^ (m - n) • y,
by { dsimp at ⊢ hy, rw [←smul_assoc, smul_eq_mul, ←pow_add, ←hy, add_tsub_cancel_of_le h] }⟩⟩
variables {M}
lemma exists_pow_succ_smul_dvd (r : R) (x : M) :
∃ (n : ℕ) (y : M), r ^ n.succ • y = r ^ n • x :=
begin
obtain ⟨n, hn⟩ := is_artinian.range_smul_pow_stabilizes M r,
simp_rw [set_like.ext_iff] at hn,
exact ⟨n, by simpa using hn n.succ n.le_succ (r ^ n • x)⟩,
end
end is_artinian
end comm_ring
-- TODO: Prove this for artinian modules
-- /--
-- If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial.
-- -/
-- universe w
-- variables {N : Type w} [add_comm_group N] [module R N]
-- noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M]
-- (f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} :=
-- begin
-- apply nonempty.some,
-- obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i)
-- (f.tailings_disjoint_tailing i),
-- specialize w n (le_refl n),
-- apply nonempty.intro,
-- refine (f.tailing_linear_equiv i n).symm.trans _,
-- rw w,
-- exact submodule.bot_equiv_punit,
-- end
/-- A ring is Artinian if it is Artinian as a module over itself.
Strictly speaking, this should be called `is_left_artinian_ring` but we omit the `left_` for
convenience in the commutative case. For a right Artinian ring, use `is_artinian Rᵐᵒᵖ R`. -/
@[reducible] def is_artinian_ring (R) [ring R] := is_artinian R R
theorem is_artinian_ring_iff {R} [ring R] : is_artinian_ring R ↔ is_artinian R R :=
iff.rfl
theorem ring.is_artinian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_artinian_ring R :=
have _ := subsingleton_of_zero_eq_one h01, by exactI infer_instance
theorem is_artinian_of_submodule_of_artinian (R M) [ring R] [add_comm_group M] [module R M]
(N : submodule R M) (h : is_artinian R M) : is_artinian R N :=
by apply_instance
theorem is_artinian_of_quotient_of_artinian (R) [ring R] (M) [add_comm_group M] [module R M]
(N : submodule R M) (h : is_artinian R M) : is_artinian R (M ⧸ N) :=
is_artinian_of_surjective M (submodule.mkq N) (submodule.quotient.mk_surjective N)
/-- If `M / S / R` is a scalar tower, and `M / R` is Artinian, then `M / S` is
also Artinian. -/
theorem is_artinian_of_tower (R) {S M} [comm_ring R] [ring S]
[add_comm_group M] [algebra R S] [module S M] [module R M] [is_scalar_tower R S M]
(h : is_artinian R M) : is_artinian S M :=
begin
rw is_artinian_iff_well_founded at h ⊢,
refine (submodule.restrict_scalars_embedding R S M).well_founded h
end
theorem is_artinian_of_fg_of_artinian {R M} [ring R] [add_comm_group M] [module R M]
(N : submodule R M) [is_artinian_ring R] (hN : N.fg) : is_artinian R N :=
let ⟨s, hs⟩ := hN in
begin
haveI := classical.dec_eq M,
haveI := classical.dec_eq R,
have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx,
refine @@is_artinian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _)
_ _ _ is_artinian_pi,
{ fapply linear_map.mk,
{ exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ },
{ intros f g, apply subtype.eq,
change ∑ i in s.attach, (f i + g i) • _ = _,
simp only [add_smul, finset.sum_add_distrib], refl },
{ intros c f, apply subtype.eq,
change ∑ i in s.attach, (c • f i) • _ = _,
simp only [smul_eq_mul, mul_smul],
exact finset.smul_sum.symm } },
rintro ⟨n, hn⟩, change n ∈ N at hn,
rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn,
rcases hn with ⟨l, hl1, hl2⟩,
refine ⟨λ x, l x, subtype.ext _⟩,
change ∑ i in s.attach, l i • (i : M) = n,
rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2,
finsupp.total_apply, finsupp.sum, eq_comm],
refine finset.sum_subset hl1 (λ x _ hx, _),
rw [finsupp.not_mem_support_iff.1 hx, zero_smul]
end
lemma is_artinian_of_fg_of_artinian' {R M} [ring R] [add_comm_group M] [module R M]
[is_artinian_ring R] (h : (⊤ : submodule R M).fg) : is_artinian R M :=
have is_artinian R (⊤ : submodule R M), from is_artinian_of_fg_of_artinian _ h,
by exactI is_artinian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl)
/-- In a module over a artinian ring, the submodule generated by finitely many vectors is
artinian. -/
theorem is_artinian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M]
[is_artinian_ring R] {A : set M} (hA : A.finite) : is_artinian R (submodule.span R A) :=
is_artinian_of_fg_of_artinian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩)
theorem function.surjective.is_artinian_ring {R} [ring R] {S} [ring S] {F} [ring_hom_class F R S]
{f : F} (hf : function.surjective f) [H : is_artinian_ring R] : is_artinian_ring S :=
begin
rw [is_artinian_ring_iff, is_artinian_iff_well_founded] at H ⊢,
exact (ideal.order_embedding_of_surjective f hf).well_founded H,
end
instance is_artinian_ring_range {R} [ring R] {S} [ring S] (f : R →+* S) [is_artinian_ring R] :
is_artinian_ring f.range :=
f.range_restrict_surjective.is_artinian_ring
namespace is_artinian_ring
open is_artinian
variables {R : Type*} [comm_ring R] [is_artinian_ring R]
lemma is_nilpotent_jacobson_bot : is_nilpotent (ideal.jacobson (⊥ : ideal R)) :=
begin
let Jac := ideal.jacobson (⊥ : ideal R),
let f : ℕ →o (ideal R)ᵒᵈ := ⟨λ n, Jac ^ n, λ _ _ h, ideal.pow_le_pow h⟩,
obtain ⟨n, hn⟩ : ∃ n, ∀ m, n ≤ m → Jac ^ n = Jac ^ m := is_artinian.monotone_stabilizes f,
refine ⟨n, _⟩,
let J : ideal R := annihilator (Jac ^ n),
suffices : J = ⊤,
{ have hJ : J • Jac ^ n = ⊥ := annihilator_smul (Jac ^ n),
simpa only [this, top_smul, ideal.zero_eq_bot] using hJ },
by_contradiction hJ, change J ≠ ⊤ at hJ,
rcases is_artinian.set_has_minimal {J' : ideal R | J < J'} ⟨⊤, hJ.lt_top⟩
with ⟨J', hJJ' : J < J', hJ' : ∀ I, J < I → ¬ I < J'⟩,
rcases set_like.exists_of_lt hJJ' with ⟨x, hxJ', hxJ⟩,
obtain rfl : J ⊔ ideal.span {x} = J',
{ apply eq_of_le_of_not_lt _ (hJ' (J ⊔ ideal.span {x}) _),
{ exact (sup_le hJJ'.le (span_le.2 (singleton_subset_iff.2 hxJ'))) },
{ rw set_like.lt_iff_le_and_exists,
exact ⟨le_sup_left, ⟨x, mem_sup_right (mem_span_singleton_self x), hxJ⟩⟩ } },
have : J ⊔ Jac • ideal.span {x} ≤ J ⊔ ideal.span {x},
from sup_le_sup_left (smul_le.2 (λ _ _ _, submodule.smul_mem _ _)) _,
have : Jac * ideal.span {x} ≤ J, --Need version 4 of Nakayamas lemma on Stacks
{ classical, by_contradiction H,
refine H (smul_sup_le_of_le_smul_of_le_jacobson_bot
(fg_span_singleton _) le_rfl (this.eq_of_not_lt (hJ' _ _)).ge),
exact lt_of_le_of_ne le_sup_left (λ h, H $ h.symm ▸ le_sup_right) },
have : ideal.span {x} * Jac ^ (n + 1) ≤ ⊥,
calc ideal.span {x} * Jac ^ (n + 1) = ideal.span {x} * Jac * Jac ^ n :
by rw [pow_succ, ← mul_assoc]
... ≤ J * Jac ^ n : mul_le_mul (by rwa mul_comm) le_rfl
... = ⊥ : by simp [J],
refine hxJ (mem_annihilator.2 (λ y hy, (mem_bot R).1 _)),
refine this (mul_mem_mul (mem_span_singleton_self x) _),
rwa [← hn (n + 1) (nat.le_succ _)]
end
section localization
variables (S : submonoid R) (L : Type*) [comm_ring L] [algebra R L] [is_localization S L]
include S
/-- Localizing an artinian ring can only reduce the amount of elements. -/
theorem localization_surjective : function.surjective (algebra_map R L) :=
begin
intro r',
obtain ⟨r₁, s, rfl⟩ := is_localization.mk'_surjective S r',
obtain ⟨r₂, h⟩ : ∃ r : R, is_localization.mk' L 1 s = algebra_map R L r,
swap, { exact ⟨r₁ * r₂, by rw [is_localization.mk'_eq_mul_mk'_one, map_mul, h]⟩ },
obtain ⟨n, r, hr⟩ := is_artinian.exists_pow_succ_smul_dvd (s : R) (1 : R),
use r,
rw [smul_eq_mul, smul_eq_mul, pow_succ', mul_assoc] at hr,
apply_fun algebra_map R L at hr,
simp only [map_mul, ←submonoid.coe_pow] at hr,
rw [←is_localization.mk'_one L, is_localization.mk'_eq_iff_eq, mul_one, submonoid.coe_one,
←(is_localization.map_units L (s ^ n)).mul_left_cancel hr, map_mul],
end
lemma localization_artinian : is_artinian_ring L :=
(localization_surjective S L).is_artinian_ring
/-- `is_artinian_ring.localization_artinian` can't be made an instance, as it would make `S` + `R`
into metavariables. However, this is safe. -/
instance : is_artinian_ring (localization S) := localization_artinian S _
end localization
end is_artinian_ring
|
4f91596da5906cf939a5c9b73d9ec9e4e08e4ebe | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/inseparable.lean | 0d8200d603bbf34e10441bdac8c1b521a8496505 | [
"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 | 20,130 | lean | /-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang, Yury G. Kudryashov
-/
import topology.continuous_on
import data.setoid.basic
import tactic.tfae
/-!
# Inseparable points in a topological space
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define
* `specializes` (notation: `x ⤳ y`) : a relation saying that `𝓝 x ≤ 𝓝 y`;
* `inseparable`: a relation saying that two points in a topological space have the same
neighbourhoods; equivalently, they can't be separated by an open set;
* `inseparable_setoid X`: same relation, as a `setoid`;
* `separation_quotient X`: the quotient of `X` by its `inseparable_setoid`.
We also prove various basic properties of the relation `inseparable`.
## Notations
- `x ⤳ y`: notation for `specializes x y`;
- `x ~ y` is used as a local notation for `inseparable x y`;
- `𝓝 x` is the neighbourhoods filter `nhds x` of a point `x`, defined elsewhere.
## Tags
topological space, separation setoid
-/
open set filter function
open_locale topology filter
variables {X Y Z α ι : Type*} {π : ι → Type*} [topological_space X] [topological_space Y]
[topological_space Z] [∀ i, topological_space (π i)] {x y z : X} {s : set X} {f : X → Y}
/-!
### `specializes` relation
-/
/-- `x` specializes to `y` (notation: `x ⤳ y`) if either of the following equivalent properties
hold:
* `𝓝 x ≤ 𝓝 y`; this property is used as the definition;
* `pure x ≤ 𝓝 y`; in other words, any neighbourhood of `y` contains `x`;
* `y ∈ closure {x}`;
* `closure {y} ⊆ closure {x}`;
* for any closed set `s` we have `x ∈ s → y ∈ s`;
* for any open set `s` we have `y ∈ s → x ∈ s`;
* `y` is a cluster point of the filter `pure x = 𝓟 {x}`.
This relation defines a `preorder` on `X`. If `X` is a T₀ space, then this preorder is a partial
order. If `X` is a T₁ space, then this partial order is trivial : `x ⤳ y ↔ x = y`. -/
def specializes (x y : X) : Prop := 𝓝 x ≤ 𝓝 y
infix ` ⤳ `:300 := specializes
/-- A collection of equivalent definitions of `x ⤳ y`. The public API is given by `iff` lemmas
below. -/
lemma specializes_tfae (x y : X) :
tfae [x ⤳ y,
pure x ≤ 𝓝 y,
∀ s : set X, is_open s → y ∈ s → x ∈ s,
∀ s : set X, is_closed s → x ∈ s → y ∈ s,
y ∈ closure ({x} : set X),
closure ({y} : set X) ⊆ closure {x},
cluster_pt y (pure x)] :=
begin
tfae_have : 1 → 2, from (pure_le_nhds _).trans,
tfae_have : 2 → 3, from λ h s hso hy, h (hso.mem_nhds hy),
tfae_have : 3 → 4, from λ h s hsc hx, of_not_not $ λ hy, h sᶜ hsc.is_open_compl hy hx,
tfae_have : 4 → 5, from λ h, h _ is_closed_closure (subset_closure $ mem_singleton _),
tfae_have : 6 ↔ 5, from is_closed_closure.closure_subset_iff.trans singleton_subset_iff,
tfae_have : 5 ↔ 7, by rw [mem_closure_iff_cluster_pt, principal_singleton],
tfae_have : 5 → 1,
{ refine λ h, (nhds_basis_opens _).ge_iff.2 _,
rintro s ⟨hy, ho⟩,
rcases mem_closure_iff.1 h s ho hy with ⟨z, hxs, (rfl : z = x)⟩,
exact ho.mem_nhds hxs },
tfae_finish
end
lemma specializes_iff_nhds : x ⤳ y ↔ 𝓝 x ≤ 𝓝 y := iff.rfl
lemma specializes_iff_pure : x ⤳ y ↔ pure x ≤ 𝓝 y := (specializes_tfae x y).out 0 1
alias specializes_iff_nhds ↔ specializes.nhds_le_nhds _
alias specializes_iff_pure ↔ specializes.pure_le_nhds _
lemma specializes_iff_forall_open : x ⤳ y ↔ ∀ s : set X, is_open s → y ∈ s → x ∈ s :=
(specializes_tfae x y).out 0 2
lemma specializes.mem_open (h : x ⤳ y) (hs : is_open s) (hy : y ∈ s) : x ∈ s :=
specializes_iff_forall_open.1 h s hs hy
lemma is_open.not_specializes (hs : is_open s) (hx : x ∉ s) (hy : y ∈ s) : ¬ x ⤳ y :=
λ h, hx $ h.mem_open hs hy
lemma specializes_iff_forall_closed : x ⤳ y ↔ ∀ s : set X, is_closed s → x ∈ s → y ∈ s :=
(specializes_tfae x y).out 0 3
lemma specializes.mem_closed (h : x ⤳ y) (hs : is_closed s) (hx : x ∈ s) : y ∈ s :=
specializes_iff_forall_closed.1 h s hs hx
lemma is_closed.not_specializes (hs : is_closed s) (hx : x ∈ s) (hy : y ∉ s) : ¬ x ⤳ y :=
λ h, hy $ h.mem_closed hs hx
lemma specializes_iff_mem_closure : x ⤳ y ↔ y ∈ closure ({x} : set X) :=
(specializes_tfae x y).out 0 4
alias specializes_iff_mem_closure ↔ specializes.mem_closure _
lemma specializes_iff_closure_subset :
x ⤳ y ↔ closure ({y} : set X) ⊆ closure {x} :=
(specializes_tfae x y).out 0 5
alias specializes_iff_closure_subset ↔ specializes.closure_subset _
lemma filter.has_basis.specializes_iff {ι} {p : ι → Prop} {s : ι → set X}
(h : (𝓝 y).has_basis p s) :
x ⤳ y ↔ ∀ i, p i → x ∈ s i :=
specializes_iff_pure.trans h.ge_iff
lemma specializes_rfl : x ⤳ x := le_rfl
@[refl] lemma specializes_refl (x : X) : x ⤳ x := specializes_rfl
@[trans] lemma specializes.trans : x ⤳ y → y ⤳ z → x ⤳ z := le_trans
lemma specializes_of_eq (e : x = y) : x ⤳ y := e ▸ specializes_refl x
lemma specializes_of_nhds_within (h₁ : 𝓝[s] x ≤ 𝓝[s] y) (h₂ : x ∈ s) : x ⤳ y :=
specializes_iff_pure.2 $
calc pure x ≤ 𝓝[s] x : le_inf (pure_le_nhds _) (le_principal_iff.2 h₂)
... ≤ 𝓝[s] y : h₁
... ≤ 𝓝 y : inf_le_left
lemma specializes.map_of_continuous_at (h : x ⤳ y) (hy : continuous_at f y) : f x ⤳ f y :=
specializes_iff_pure.2 $ λ s hs, mem_pure.2 $ mem_preimage.1 $ mem_of_mem_nhds $ hy.mono_left h hs
lemma specializes.map (h : x ⤳ y) (hf : continuous f) : f x ⤳ f y :=
h.map_of_continuous_at hf.continuous_at
lemma inducing.specializes_iff (hf : inducing f) : f x ⤳ f y ↔ x ⤳ y :=
by simp only [specializes_iff_mem_closure, hf.closure_eq_preimage_closure_image, image_singleton,
mem_preimage]
lemma subtype_specializes_iff {p : X → Prop} (x y : subtype p) : x ⤳ y ↔ (x : X) ⤳ y :=
inducing_coe.specializes_iff.symm
@[simp] lemma specializes_prod {x₁ x₂ : X} {y₁ y₂ : Y} :
(x₁, y₁) ⤳ (x₂, y₂) ↔ x₁ ⤳ x₂ ∧ y₁ ⤳ y₂ :=
by simp only [specializes, nhds_prod_eq, prod_le_prod]
lemma specializes.prod {x₁ x₂ : X} {y₁ y₂ : Y} (hx : x₁ ⤳ x₂) (hy : y₁ ⤳ y₂) :
(x₁, y₁) ⤳ (x₂, y₂) :=
specializes_prod.2 ⟨hx, hy⟩
@[simp] lemma specializes_pi {f g : Π i, π i} : f ⤳ g ↔ ∀ i, f i ⤳ g i :=
by simp only [specializes, nhds_pi, pi_le_pi]
lemma not_specializes_iff_exists_open : ¬ x ⤳ y ↔ ∃ (S : set X), is_open S ∧ y ∈ S ∧ x ∉ S :=
by { rw [specializes_iff_forall_open], push_neg, refl }
lemma not_specializes_iff_exists_closed : ¬ x ⤳ y ↔ ∃ (S : set X), is_closed S ∧ x ∈ S ∧ y ∉ S :=
by { rw [specializes_iff_forall_closed], push_neg, refl }
variable (X)
/-- Specialization forms a preorder on the topological space. -/
def specialization_preorder : preorder X :=
{ le := λ x y, y ⤳ x,
lt := λ x y, y ⤳ x ∧ ¬(x ⤳ y),
.. preorder.lift (order_dual.to_dual ∘ 𝓝) }
variable {X}
/-- A continuous function is monotone with respect to the specialization preorders on the domain and
the codomain. -/
lemma continuous.specialization_monotone (hf : continuous f) :
@monotone _ _ (specialization_preorder X) (specialization_preorder Y) f :=
λ x y h, h.map hf
/-!
### `inseparable` relation
-/
/-- Two points `x` and `y` in a topological space are `inseparable` if any of the following
equivalent properties hold:
- `𝓝 x = 𝓝 y`; we use this property as the definition;
- for any open set `s`, `x ∈ s ↔ y ∈ s`, see `inseparable_iff_open`;
- for any closed set `s`, `x ∈ s ↔ y ∈ s`, see `inseparable_iff_closed`;
- `x ∈ closure {y}` and `y ∈ closure {x}`, see `inseparable_iff_mem_closure`;
- `closure {x} = closure {y}`, see `inseparable_iff_closure_eq`.
-/
def inseparable (x y : X) : Prop := 𝓝 x = 𝓝 y
local infix ` ~ ` := inseparable
lemma inseparable_def : x ~ y ↔ 𝓝 x = 𝓝 y := iff.rfl
lemma inseparable_iff_specializes_and : x ~ y ↔ x ⤳ y ∧ y ⤳ x := le_antisymm_iff
lemma inseparable.specializes (h : x ~ y) : x ⤳ y := h.le
lemma inseparable.specializes' (h : x ~ y) : y ⤳ x := h.ge
lemma specializes.antisymm (h₁ : x ⤳ y) (h₂ : y ⤳ x) : x ~ y := le_antisymm h₁ h₂
lemma inseparable_iff_forall_open : x ~ y ↔ ∀ s : set X, is_open s → (x ∈ s ↔ y ∈ s) :=
by simp only [inseparable_iff_specializes_and, specializes_iff_forall_open, ← forall_and_distrib,
← iff_def, iff.comm]
lemma not_inseparable_iff_exists_open : ¬(x ~ y) ↔ ∃ s : set X, is_open s ∧ xor (x ∈ s) (y ∈ s) :=
by simp [inseparable_iff_forall_open, ← xor_iff_not_iff]
lemma inseparable_iff_forall_closed : x ~ y ↔ ∀ s : set X, is_closed s → (x ∈ s ↔ y ∈ s) :=
by simp only [inseparable_iff_specializes_and, specializes_iff_forall_closed, ← forall_and_distrib,
← iff_def]
lemma inseparable_iff_mem_closure :
x ~ y ↔ x ∈ closure ({y} : set X) ∧ y ∈ closure ({x} : set X) :=
inseparable_iff_specializes_and.trans $ by simp only [specializes_iff_mem_closure, and_comm]
lemma inseparable_iff_closure_eq : x ~ y ↔ closure ({x} : set X) = closure {y} :=
by simp only [inseparable_iff_specializes_and, specializes_iff_closure_subset,
← subset_antisymm_iff, eq_comm]
lemma inseparable_of_nhds_within_eq (hx : x ∈ s) (hy : y ∈ s) (h : 𝓝[s] x = 𝓝[s] y) : x ~ y :=
(specializes_of_nhds_within h.le hx).antisymm (specializes_of_nhds_within h.ge hy)
lemma inducing.inseparable_iff (hf : inducing f) : f x ~ f y ↔ x ~ y :=
by simp only [inseparable_iff_specializes_and, hf.specializes_iff]
lemma subtype_inseparable_iff {p : X → Prop} (x y : subtype p) : x ~ y ↔ (x : X) ~ y :=
inducing_coe.inseparable_iff.symm
@[simp] lemma inseparable_prod {x₁ x₂ : X} {y₁ y₂ : Y} :
(x₁, y₁) ~ (x₂, y₂) ↔ x₁ ~ x₂ ∧ y₁ ~ y₂ :=
by simp only [inseparable, nhds_prod_eq, prod_inj]
lemma inseparable.prod {x₁ x₂ : X} {y₁ y₂ : Y} (hx : x₁ ~ x₂) (hy : y₁ ~ y₂) :
(x₁, y₁) ~ (x₂, y₂) :=
inseparable_prod.2 ⟨hx, hy⟩
@[simp] lemma inseparable_pi {f g : Π i, π i} : f ~ g ↔ ∀ i, f i ~ g i :=
by simp only [inseparable, nhds_pi, funext_iff, pi_inj]
namespace inseparable
@[refl] lemma refl (x : X) : x ~ x := eq.refl (𝓝 x)
lemma rfl : x ~ x := refl x
lemma of_eq (e : x = y) : inseparable x y := e ▸ refl x
@[symm] lemma symm (h : x ~ y) : y ~ x := h.symm
@[trans] lemma trans (h₁ : x ~ y) (h₂ : y ~ z) : x ~ z := h₁.trans h₂
lemma nhds_eq (h : x ~ y) : 𝓝 x = 𝓝 y := h
lemma mem_open_iff (h : x ~ y) (hs : is_open s) : x ∈ s ↔ y ∈ s :=
inseparable_iff_forall_open.1 h s hs
lemma mem_closed_iff (h : x ~ y) (hs : is_closed s) : x ∈ s ↔ y ∈ s :=
inseparable_iff_forall_closed.1 h s hs
lemma map_of_continuous_at (h : x ~ y) (hx : continuous_at f x) (hy : continuous_at f y) :
f x ~ f y :=
(h.specializes.map_of_continuous_at hy).antisymm (h.specializes'.map_of_continuous_at hx)
lemma map (h : x ~ y) (hf : continuous f) : f x ~ f y :=
h.map_of_continuous_at hf.continuous_at hf.continuous_at
end inseparable
lemma is_closed.not_inseparable (hs : is_closed s) (hx : x ∈ s) (hy : y ∉ s) : ¬x ~ y :=
λ h, hy $ (h.mem_closed_iff hs).1 hx
lemma is_open.not_inseparable (hs : is_open s) (hx : x ∈ s) (hy : y ∉ s) : ¬x ~ y :=
λ h, hy $ (h.mem_open_iff hs).1 hx
/-!
### Separation quotient
In this section we define the quotient of a topological space by the `inseparable` relation.
-/
variable (X)
/-- A `setoid` version of `inseparable`, used to define the `separation_quotient`. -/
def inseparable_setoid : setoid X :=
{ r := (~),
.. setoid.comap 𝓝 ⊥ }
/-- The quotient of a topological space by its `inseparable_setoid`. This quotient is guaranteed to
be a T₀ space. -/
@[derive topological_space]
def separation_quotient := quotient (inseparable_setoid X)
variables {X} {t : set (separation_quotient X)}
namespace separation_quotient
/-- The natural map from a topological space to its separation quotient. -/
def mk : X → separation_quotient X := quotient.mk'
lemma quotient_map_mk : quotient_map (mk : X → separation_quotient X) :=
quotient_map_quot_mk
lemma continuous_mk : continuous (mk : X → separation_quotient X) :=
continuous_quot_mk
@[simp] lemma mk_eq_mk : mk x = mk y ↔ x ~ y := quotient.eq'
lemma surjective_mk : surjective (mk : X → separation_quotient X) :=
surjective_quot_mk _
@[simp] lemma range_mk : range (mk : X → separation_quotient X) = univ :=
surjective_mk.range_eq
instance [nonempty X] : nonempty (separation_quotient X) := nonempty.map mk ‹_›
instance [inhabited X] : inhabited (separation_quotient X) := ⟨mk default⟩
instance [subsingleton X] : subsingleton (separation_quotient X) := surjective_mk.subsingleton
lemma preimage_image_mk_open (hs : is_open s) : mk ⁻¹' (mk '' s) = s :=
begin
refine subset.antisymm _ (subset_preimage_image _ _),
rintro x ⟨y, hys, hxy⟩,
exact ((mk_eq_mk.1 hxy).mem_open_iff hs).1 hys
end
lemma is_open_map_mk : is_open_map (mk : X → separation_quotient X) :=
λ s hs, quotient_map_mk.is_open_preimage.1 $ by rwa preimage_image_mk_open hs
lemma preimage_image_mk_closed (hs : is_closed s) : mk ⁻¹' (mk '' s) = s :=
begin
refine subset.antisymm _ (subset_preimage_image _ _),
rintro x ⟨y, hys, hxy⟩,
exact ((mk_eq_mk.1 hxy).mem_closed_iff hs).1 hys
end
lemma inducing_mk : inducing (mk : X → separation_quotient X) :=
⟨le_antisymm (continuous_iff_le_induced.1 continuous_mk)
(λ s hs, ⟨mk '' s, is_open_map_mk s hs, preimage_image_mk_open hs⟩)⟩
lemma is_closed_map_mk : is_closed_map (mk : X → separation_quotient X) :=
inducing_mk.is_closed_map $ by { rw [range_mk], exact is_closed_univ }
@[simp] lemma comap_mk_nhds_mk : comap mk (𝓝 (mk x)) = 𝓝 x :=
(inducing_mk.nhds_eq_comap _).symm
@[simp] lemma comap_mk_nhds_set_image : comap mk (𝓝ˢ (mk '' s)) = 𝓝ˢ s :=
(inducing_mk.nhds_set_eq_comap _).symm
lemma map_mk_nhds : map mk (𝓝 x) = 𝓝 (mk x) :=
by rw [← comap_mk_nhds_mk, map_comap_of_surjective surjective_mk]
lemma map_mk_nhds_set : map mk (𝓝ˢ s) = 𝓝ˢ (mk '' s) :=
by rw [← comap_mk_nhds_set_image, map_comap_of_surjective surjective_mk]
lemma comap_mk_nhds_set : comap mk (𝓝ˢ t) = 𝓝ˢ (mk ⁻¹' t) :=
by conv_lhs { rw [← image_preimage_eq t surjective_mk, comap_mk_nhds_set_image] }
lemma preimage_mk_closure : mk ⁻¹' (closure t) = closure (mk ⁻¹' t) :=
is_open_map_mk.preimage_closure_eq_closure_preimage continuous_mk t
lemma preimage_mk_interior : mk ⁻¹' (interior t) = interior (mk ⁻¹' t) :=
is_open_map_mk.preimage_interior_eq_interior_preimage continuous_mk t
lemma preimage_mk_frontier : mk ⁻¹' (frontier t) = frontier (mk ⁻¹' t) :=
is_open_map_mk.preimage_frontier_eq_frontier_preimage continuous_mk t
lemma image_mk_closure : mk '' closure s = closure (mk '' s) :=
(image_closure_subset_closure_image continuous_mk).antisymm $
is_closed_map_mk.closure_image_subset _
lemma map_prod_map_mk_nhds (x : X) (y : Y) : map (prod.map mk mk) (𝓝 (x, y)) = 𝓝 (mk x, mk y) :=
by rw [nhds_prod_eq, ← prod_map_map_eq', map_mk_nhds, map_mk_nhds, nhds_prod_eq]
lemma map_mk_nhds_within_preimage (s : set (separation_quotient X)) (x : X) :
map mk (𝓝[mk ⁻¹' s] x) = 𝓝[s] (mk x) :=
by rw [nhds_within, ← comap_principal, filter.push_pull, nhds_within, map_mk_nhds]
/-- Lift a map `f : X → α` such that `inseparable x y → f x = f y` to a map
`separation_quotient X → α`. -/
def lift (f : X → α) (hf : ∀ x y, x ~ y → f x = f y) : separation_quotient X → α :=
λ x, quotient.lift_on' x f hf
@[simp] lemma lift_mk {f : X → α} (hf : ∀ x y, x ~ y → f x = f y) (x : X) :
lift f hf (mk x) = f x := rfl
@[simp] lemma lift_comp_mk {f : X → α} (hf : ∀ x y, x ~ y → f x = f y) : lift f hf ∘ mk = f := rfl
@[simp] lemma tendsto_lift_nhds_mk {f : X → α} {hf : ∀ x y, x ~ y → f x = f y} {x : X}
{l : filter α} : tendsto (lift f hf) (𝓝 $ mk x) l ↔ tendsto f (𝓝 x) l :=
by simp only [← map_mk_nhds, tendsto_map'_iff, lift_comp_mk]
@[simp] lemma tendsto_lift_nhds_within_mk {f : X → α} {hf : ∀ x y, x ~ y → f x = f y} {x : X}
{s : set (separation_quotient X)} {l : filter α} :
tendsto (lift f hf) (𝓝[s] (mk x)) l ↔ tendsto f (𝓝[mk ⁻¹' s] x) l :=
by simp only [← map_mk_nhds_within_preimage, tendsto_map'_iff, lift_comp_mk]
@[simp] lemma continuous_at_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y} {x : X} :
continuous_at (lift f hf) (mk x) ↔ continuous_at f x :=
tendsto_lift_nhds_mk
@[simp] lemma continuous_within_at_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y}
{s : set (separation_quotient X)} {x : X} :
continuous_within_at (lift f hf) s (mk x) ↔ continuous_within_at f (mk ⁻¹' s) x :=
tendsto_lift_nhds_within_mk
@[simp] lemma continuous_on_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y}
{s : set (separation_quotient X)} :
continuous_on (lift f hf) s ↔ continuous_on f (mk ⁻¹' s) :=
by simp only [continuous_on, surjective_mk.forall, continuous_within_at_lift, mem_preimage]
@[simp] lemma continuous_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y} :
continuous (lift f hf) ↔ continuous f :=
by simp only [continuous_iff_continuous_on_univ, continuous_on_lift, preimage_univ]
/-- Lift a map `f : X → Y → α` such that `inseparable a b → inseparable c d → f a c = f b d` to a
map `separation_quotient X → separation_quotient Y → α`. -/
def lift₂ (f : X → Y → α) (hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d) :
separation_quotient X → separation_quotient Y → α :=
λ x y, quotient.lift_on₂' x y f hf
@[simp] lemma lift₂_mk {f : X → Y → α} (hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d) (x : X)
(y : Y) : lift₂ f hf (mk x) (mk y) = f x y :=
rfl
@[simp] lemma tendsto_lift₂_nhds {f : X → Y → α} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d}
{x : X} {y : Y} {l : filter α} :
tendsto (uncurry $ lift₂ f hf) (𝓝 (mk x, mk y)) l ↔ tendsto (uncurry f) (𝓝 (x, y)) l :=
by { rw [← map_prod_map_mk_nhds, tendsto_map'_iff], refl }
@[simp] lemma tendsto_lift₂_nhds_within {f : X → Y → α}
{hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} {x : X} {y : Y}
{s : set (separation_quotient X × separation_quotient Y)} {l : filter α} :
tendsto (uncurry $ lift₂ f hf) (𝓝[s] (mk x, mk y)) l ↔
tendsto (uncurry f) (𝓝[prod.map mk mk ⁻¹' s] (x, y)) l :=
by { rw [nhds_within, ← map_prod_map_mk_nhds, ← filter.push_pull, comap_principal], refl }
@[simp] lemma continuous_at_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d}
{x : X} {y : Y} :
continuous_at (uncurry $ lift₂ f hf) (mk x, mk y) ↔ continuous_at (uncurry f) (x, y) :=
tendsto_lift₂_nhds
@[simp] lemma continuous_within_at_lift₂ {f : X → Y → Z}
{hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d}
{s : set (separation_quotient X × separation_quotient Y)} {x : X} {y : Y} :
continuous_within_at (uncurry $ lift₂ f hf) s (mk x, mk y) ↔
continuous_within_at (uncurry f) (prod.map mk mk ⁻¹' s) (x, y) :=
tendsto_lift₂_nhds_within
@[simp] lemma continuous_on_lift₂ {f : X → Y → Z}
{hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d}
{s : set (separation_quotient X × separation_quotient Y)} :
continuous_on (uncurry $ lift₂ f hf) s ↔ continuous_on (uncurry f) (prod.map mk mk ⁻¹' s) :=
begin
simp_rw [continuous_on, (surjective_mk.prod_map surjective_mk).forall, prod.forall, prod.map,
continuous_within_at_lift₂],
refl
end
@[simp] lemma continuous_lift₂ {f : X → Y → Z}
{hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} :
continuous (uncurry $ lift₂ f hf) ↔ continuous (uncurry f) :=
by simp only [continuous_iff_continuous_on_univ, continuous_on_lift₂, preimage_univ]
end separation_quotient
|
a8dddf22dd0a029458c2347ec88c1b14bc75eb35 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/algebra/group_power.lean | ee802d8fd12a791cff41a2ae727416a214bd14aa | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 37,029 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
-/
import algebra.opposites
import data.list.basic
import data.int.cast
import data.equiv.basic
import deprecated.ring
/-!
# Power operations on monoids and groups
The power operation on monoids and groups.
We separate this from group, because it depends on `ℕ`,
which in turn depends on other parts of algebra.
## Notation
The class `has_pow α β` provides the notation `a^b` for powers.
We define instances of `has_pow M ℕ`, for monoids `M`, and `has_pow G ℤ` for groups `G`.
We also define infix operators `•ℕ` and `•ℤ` for scalar multiplication by a natural and an integer
numbers, respectively.
## Implementation details
We adopt the convention that `0^0 = 1`.
-/
universes u v w x y z u₁ u₂
variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z}
{R : Type u₁} {S : Type u₂}
/-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/
def monoid.pow [has_mul M] [has_one M] (a : M) : ℕ → M
| 0 := 1
| (n+1) := a * monoid.pow n
/-- The scalar multiplication in an additive monoid.
`n •ℕ a = a+a+...+a` n times. -/
def nsmul [has_add A] [has_zero A] (n : ℕ) (a : A) : A :=
@monoid.pow (multiplicative A) _ { one := (0 : A) } a n
infix ` •ℕ `:70 := nsmul
@[priority 5] instance monoid.has_pow [monoid M] : has_pow M ℕ := ⟨monoid.pow⟩
/-!
### Commutativity
First we prove some facts about `semiconj_by` and `commute`. They do not require any theory about
`pow` and/or `nsmul` and will be useful later in this file.
-/
namespace semiconj_by
variables [monoid M]
@[simp] lemma pow_right {a x y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x^n) (y^n) :=
nat.rec_on n (one_right a) $ λ n ihn, h.mul_right ihn
end semiconj_by
namespace commute
variables [monoid M] {a b : M}
@[simp] theorem pow_right (h : commute a b) (n : ℕ) : commute a (b ^ n) := h.pow_right n
@[simp] theorem pow_left (h : commute a b) (n : ℕ) : commute (a ^ n) b := (h.symm.pow_right n).symm
@[simp] theorem pow_pow (h : commute a b) (m n : ℕ) : commute (a ^ m) (b ^ n) :=
(h.pow_left m).pow_right n
@[simp] theorem self_pow (a : M) (n : ℕ) : commute a (a ^ n) := (commute.refl a).pow_right n
@[simp] theorem pow_self (a : M) (n : ℕ) : commute (a ^ n) a := (commute.refl a).pow_left n
@[simp] theorem pow_pow_self (a : M) (m n : ℕ) : commute (a ^ m) (a ^ n) :=
(commute.refl a).pow_pow m n
end commute
/-!
### (Additive) monoid
-/
section monoid
variables [monoid M] [monoid N] [add_monoid A] [add_monoid B]
@[simp] theorem pow_zero (a : M) : a^0 = 1 := rfl
@[simp] theorem zero_nsmul (a : A) : 0 •ℕ a = 0 := rfl
theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := rfl
theorem succ_nsmul (a : A) (n : ℕ) : (n+1) •ℕ a = a + n •ℕ a := rfl
@[simp] theorem pow_one (a : M) : a^1 = a := mul_one _
@[simp] theorem one_nsmul (a : A) : 1 •ℕ a = a := add_zero _
@[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) :
a ^ (if P then b else c) = if P then a ^ b else a ^ c :=
by split_ifs; refl
@[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) :
(if P then a else b) ^ c = if P then a ^ c else b ^ c :=
by split_ifs; refl
@[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) :
a ^ (if P then 1 else 0) = if P then a else 1 :=
by simp
theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := commute.pow_self a n
theorem nsmul_add_comm' : ∀ (a : A) (n : ℕ), n •ℕ a + a = a + n •ℕ a :=
@pow_mul_comm' (multiplicative A) _
theorem pow_succ' (a : M) (n : ℕ) : a^(n+1) = a^n * a :=
by rw [pow_succ, pow_mul_comm']
theorem succ_nsmul' (a : A) (n : ℕ) : (n+1) •ℕ a = n •ℕ a + a :=
@pow_succ' (multiplicative A) _ _ _
theorem pow_two (a : M) : a^2 = a * a :=
show a*(a*1)=a*a, by rw mul_one
theorem two_nsmul (a : A) : 2 •ℕ a = a + a :=
@pow_two (multiplicative A) _ a
theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n :=
by induction n with n ih; [rw [add_zero, pow_zero, mul_one],
rw [pow_succ', ← mul_assoc, ← ih, ← pow_succ', add_assoc]]
theorem add_nsmul : ∀ (a : A) (m n : ℕ), (m + n) •ℕ a = m •ℕ a + n •ℕ a :=
@pow_add (multiplicative A) _
@[simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 :=
by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]]
@[simp] theorem nsmul_zero (n : ℕ) : n •ℕ (0 : A) = 0 :=
by induction n with n ih; [refl, rw [succ_nsmul, ih, zero_add]]
theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n :=
by induction n with n ih; [rw mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl
theorem mul_nsmul' : ∀ (a : A) (m n : ℕ), m * n •ℕ a = n •ℕ (m •ℕ a) :=
@pow_mul (multiplicative A) _
theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m :=
by rw [mul_comm, pow_mul]
theorem mul_nsmul (a : A) (m n : ℕ) : m * n •ℕ a = m •ℕ (n •ℕ a) :=
@pow_mul' (multiplicative A) _ a m n
@[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n •ℕ (1 : A) = n :=
add_monoid_hom.eq_nat_cast
⟨λ n, n •ℕ (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩
(one_nsmul _)
theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _
theorem bit0_nsmul (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ a + n •ℕ a := add_nsmul _ _ _
theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a :=
by rw [bit1, pow_succ', pow_bit0]
theorem bit1_nsmul : ∀ (a : A) (n : ℕ), bit1 n •ℕ a = n •ℕ a + n •ℕ a + a :=
@pow_bit1 (multiplicative A) _
theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m :=
commute.pow_pow_self a m n
theorem nsmul_add_comm : ∀ (a : A) (m n : ℕ), m •ℕ a + n •ℕ a = n •ℕ a + m •ℕ a :=
@pow_mul_comm (multiplicative A) _
@[simp, priority 500]
theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n :=
begin
induction n with n ih,
{ refl },
{ rw [list.repeat_succ, list.prod_cons, ih], refl, }
end
@[simp, priority 500]
theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n •ℕ a :=
@list.prod_repeat (multiplicative A) _
theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n
| 0 := f.map_one
| (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow]
theorem add_monoid_hom.map_nsmul (f : A →+ B) (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a :=
f.to_multiplicative.map_pow a n
theorem is_monoid_hom.map_pow (f : M → N) [is_monoid_hom f] (a : M) :
∀(n : ℕ), f (a ^ n) = (f a) ^ n :=
(monoid_hom.of f).map_pow a
theorem is_add_monoid_hom.map_nsmul (f : A → B) [is_add_monoid_hom f] (a : A) (n : ℕ) :
f (n •ℕ a) = n •ℕ f a :=
(add_monoid_hom.of f).map_nsmul a n
@[simp, norm_cast] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n :=
(units.coe_hom M).map_pow u n
lemma commute.mul_pow {a b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n :=
nat.rec_on n (by simp) $ λ n ihn,
by simp only [pow_succ, ihn, ← mul_assoc, (h.pow_left n).right_comm]
theorem neg_pow [ring R] (a : R) (n : ℕ) : (- a) ^ n = (-1) ^ n * a ^ n :=
(neg_one_mul a) ▸ (commute.neg_one_left a).mul_pow n
end monoid
@[simp] theorem nat.pow_eq_pow (p q : ℕ) :
@has_pow.pow _ _ monoid.has_pow p q = p ^ q :=
by induction q with q ih; [refl, rw [nat.pow_succ, pow_succ', ih]]
theorem nat.nsmul_eq_mul (m n : ℕ) : m •ℕ n = m * n :=
by induction m with m ih; [rw [zero_nsmul, zero_mul],
rw [succ_nsmul', ih, nat.succ_mul]]
/-!
### Commutative (additive) monoid
-/
section comm_monoid
variables [comm_monoid M] [add_comm_monoid A]
theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n :=
(commute.all a b).mul_pow n
theorem nsmul_add : ∀ (a b : A) (n : ℕ), n •ℕ (a + b) = n •ℕ a + n •ℕ b :=
@mul_pow (multiplicative A) _
instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : M → M) :=
{ map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ }
instance nsmul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (nsmul n : A → A) :=
{ map_add := λ _ _, nsmul_add _ _ _, map_zero := nsmul_zero _ }
end comm_monoid
section group
variables [group G] [group H] [add_group A] [add_group B]
section nat
@[simp] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ :=
by induction n with n ih; [exact one_inv.symm,
rw [pow_succ', pow_succ, ih, mul_inv_rev]]
@[simp] theorem neg_nsmul : ∀ (a : A) (n : ℕ), n •ℕ (-a) = -(n •ℕ a) :=
@inv_pow (multiplicative A) _
theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ :=
have h1 : m - n + n = m, from nat.sub_add_cancel h,
have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1],
eq_mul_inv_of_mul_eq h2
theorem nsmul_sub : ∀ (a : A) {m n : ℕ}, n ≤ m → (m - n) •ℕ a = m •ℕ a - n •ℕ a :=
@pow_sub (multiplicative A) _
theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m :=
(commute.refl a).inv_left.pow_pow m n
theorem nsmul_neg_comm : ∀ (a : A) (m n : ℕ), m •ℕ (-a) + n •ℕ a = n •ℕ a + m •ℕ (-a) :=
@pow_inv_comm (multiplicative A) _
end nat
open int
/--
The power operation in a group. This extends `monoid.pow` to negative integers
with the definition `a^(-n) = (a^n)⁻¹`.
-/
def gpow (a : G) : ℤ → G
| (of_nat n) := a^n
| -[1+n] := (a^(nat.succ n))⁻¹
/--
The scalar multiplication by integers on an additive group.
This extends `nsmul` to negative integers
with the definition `(-n) •ℤ a = -(n •ℕ a)`.
-/
def gsmul (n : ℤ) (a : A) : A :=
@gpow (multiplicative A) _ a n
@[priority 10] instance group.has_pow : has_pow G ℤ := ⟨gpow⟩
infix ` •ℤ `:70 := gsmul
@[simp] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl
@[simp] theorem gsmul_coe_nat (a : A) (n : ℕ) : n •ℤ a = n •ℕ a := rfl
theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := rfl
theorem gsmul_of_nat (a : A) (n : ℕ) : of_nat n •ℤ a = n •ℕ a := rfl
@[simp] theorem gpow_neg_succ_of_nat (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl
@[simp] theorem gsmul_neg_succ_of_nat (a : A) (n : ℕ) : -[1+n] •ℤ a = - (n.succ •ℕ a) := rfl
local attribute [ematch] le_of_lt
open nat
@[simp] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := rfl
@[simp] theorem zero_gsmul (a : A) : (0:ℤ) •ℤ a = 0 := rfl
@[simp] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := pow_one a
@[simp] theorem one_gsmul (a : A) : (1:ℤ) •ℤ a = a := add_zero _
@[simp] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1
| (n : ℕ) := one_pow _
| -[1+ n] := show _⁻¹=(1:G), by rw [_root_.one_pow, one_inv]
@[simp] theorem gsmul_zero : ∀ (n : ℤ), n •ℤ (0 : A) = 0 :=
@one_gpow (multiplicative A) _
@[simp] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹
| (n+1:ℕ) := rfl
| 0 := one_inv.symm
| -[1+ n] := (inv_inv _).symm
lemma mul_gpow_neg_one (a b : G) : (a*b)^(-(1:ℤ)) = b^(-(1:ℤ))*a^(-(1:ℤ)) :=
by simp only [mul_inv_rev, gpow_one, gpow_neg]
@[simp] theorem neg_gsmul : ∀ (a : A) (n : ℤ), -n •ℤ a = -(n •ℤ a) :=
@gpow_neg (multiplicative A) _
theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x
theorem neg_one_gsmul (x : A) : (-1:ℤ) •ℤ x = -x := congr_arg has_neg.neg $ one_nsmul x
theorem gsmul_one [has_one A] (n : ℤ) : n •ℤ (1 : A) = n :=
by cases n; simp
theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹
| (n : ℕ) := inv_pow a n
| -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1)
theorem gsmul_neg (a : A) (n : ℤ) : gsmul n (- a) = - gsmul n a :=
@inv_gpow (multiplicative A) _ a n
lemma gpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a
| (of_nat n) := by simp [← int.coe_nat_succ, pow_succ']
| -[1+0] := by simp [int.neg_succ_of_nat_eq]
| -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg,
← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, _root_.pow_succ _ (n + 1), mul_inv_rev,
inv_mul_cancel_right]
theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) •ℤ a = i •ℤ a + a :=
@gpow_add_one (multiplicative A) _
lemma gpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ :=
calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm
... = a^n * a⁻¹ : by rw [← gpow_add_one, sub_add_cancel]
lemma gpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n :=
begin
induction n using int.induction_on with n ihn n ihn,
case hz : { simp },
{ simp only [← add_assoc, gpow_add_one, ihn, mul_assoc] },
{ rw [gpow_sub_one, ← mul_assoc, ← ihn, ← gpow_sub_one, add_sub_assoc] }
end
lemma mul_self_gpow (b : G) (m : ℤ) : b*b^m = b^(m+1) :=
by { conv_lhs {congr, rw ← gpow_one b }, rw [← gpow_add, add_comm] }
lemma mul_gpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) :=
by { conv_lhs {congr, skip, rw ← gpow_one b }, rw [← gpow_add, add_comm] }
theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) •ℤ a = i •ℤ a + j •ℤ a :=
@gpow_add (multiplicative A) _
lemma gpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ :=
by rw [sub_eq_add_neg, gpow_add, gpow_neg]
lemma sub_gsmul (m n : ℤ) (a : A) : (m - n) •ℤ a = m •ℤ a - n •ℤ a :=
@gpow_sub (multiplicative A) _ _ _ _
theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i :=
by rw [gpow_add, gpow_one]
theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) •ℤ a = a + i •ℤ a :=
@gpow_one_add (multiplicative A) _
theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i :=
by rw [← gpow_add, ← gpow_add, add_comm]
theorem gsmul_add_comm : ∀ (a : A) (i j), i •ℤ a + j •ℤ a = j •ℤ a + i •ℤ a :=
@gpow_mul_comm (multiplicative A) _
theorem gpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n :=
int.induction_on n (by simp) (λ n ihn, by simp [mul_add, gpow_add, ihn])
(λ n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one])
theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n •ℤ a = n •ℤ (m •ℤ a) :=
@gpow_mul (multiplicative A) _
theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m :=
by rw [mul_comm, gpow_mul]
theorem gsmul_mul (a : A) (m n : ℤ) : m * n •ℤ a = m •ℤ (n •ℤ a) :=
by rw [mul_comm, gsmul_mul']
theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _
theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n •ℤ a = n •ℤ a + n •ℤ a := gpow_add _ _ _
theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a :=
by rw [bit1, gpow_add]; simp [gpow_bit0]
theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n •ℤ a = n •ℤ a + n •ℤ a + a :=
@gpow_bit1 (multiplicative A) _
theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n :=
by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)]
theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n •ℤ a) = n •ℤ f a :=
f.to_multiplicative.map_gpow a n
@[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n :=
(units.coe_hom G).map_gpow u n
theorem commute.mul_gpow {a b : G} (h : commute a b) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n
| (n : ℕ) := h.mul_pow n
| -[1+n] := by simp [h.mul_pow, (h.pow_pow n.succ n.succ).inv_inv.symm.eq]
end group
section comm_group
variables [comm_group G] [add_comm_group A]
theorem mul_gpow (a b : G) (n : ℤ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_gpow n
theorem gsmul_add : ∀ (a b : A) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b :=
@mul_gpow (multiplicative A) _
theorem gsmul_sub (a b : A) (n : ℤ) : gsmul n (a - b) = gsmul n a - gsmul n b :=
by simp only [gsmul_add, gsmul_neg, sub_eq_add_neg]
instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : G → G) :=
{ map_mul := λ _ _, mul_gpow _ _ n }
instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : A → A) :=
{ map_add := λ _ _, gsmul_add _ _ n }
end comm_group
@[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) :
((nsmul n a : A) : with_bot A) = nsmul n a :=
add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n
theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n •ℕ a = a * n :=
by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero],
rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]]
@[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n •ℕ a = n * a :=
by rw [nsmul_eq_mul', (n.cast_commute a).eq]
theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = a * (n •ℕ b) :=
by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc]
theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = n •ℕ a * b :=
by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc]
lemma zero_pow [semiring R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0
| (n+1) _ := zero_mul _
@[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m :=
by induction m with m ih; [exact nat.cast_one, rw [nat.pow_succ, pow_succ', nat.cast_mul, ih]]
@[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m :=
by induction m with m ih; [exact int.coe_nat_one, rw [nat.pow_succ, pow_succ', int.coe_nat_mul, ih]]
theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k :=
by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, nat.pow_succ, ih]]
namespace ring_hom
variables [semiring R] [semiring S]
@[simp] lemma map_pow (f : R →+* S) (a) :
∀ n : ℕ, f (a ^ n) = (f a) ^ n :=
f.to_monoid_hom.map_pow a
end ring_hom
lemma is_semiring_hom.map_pow [semiring R] [semiring S] (f : R → S) [is_semiring_hom f] (a) :
∀ n : ℕ, f (a ^ n) = (f a) ^ n :=
is_monoid_hom.map_pow f a
theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1
| 0 := or.inl rfl
| (n+1) := (neg_one_pow_eq_or n).swap.imp
(λ h, by rw [pow_succ, h, neg_one_mul, neg_neg])
(λ h, by rw [pow_succ, h, mul_one])
lemma pow_dvd_pow [comm_semiring R] (a : R) {m n : ℕ} (h : m ≤ n) :
a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_sub_cancel' h]⟩
theorem pow_dvd_pow_of_dvd [comm_semiring R] {a b : R} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n
| 0 := dvd_refl _
| (n+1) := mul_dvd_mul h (pow_dvd_pow_of_dvd n)
lemma pow_two_sub_pow_two {R : Type*} [comm_ring R] (a b : R) :
a ^ 2 - b ^ 2 = (a + b) * (a - b) :=
by simp only [pow_two, mul_sub, add_mul, sub_sub, add_sub, mul_comm, sub_add_cancel]
lemma eq_or_eq_neg_of_pow_two_eq_pow_two [integral_domain R] (a b : R) (h : a ^ 2 = b ^ 2) :
a = b ∨ a = -b :=
by rwa [← add_eq_zero_iff_eq_neg, ← sub_eq_zero, or_comm, ← mul_eq_zero,
← pow_two_sub_pow_two a b, sub_eq_zero]
-- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression.
-- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`.
lemma bit0_mul [ring R] {n r : R} : bit0 n * r = gsmul 2 (n * r) :=
by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], }
lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = gsmul 2 (r * n) :=
by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], }
lemma bit1_mul [ring R] {n r : R} : bit1 n * r = gsmul 2 (n * r) + r :=
by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], }
lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = gsmul 2 (r * n) + r :=
by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], }
@[simp] theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a
| (n : ℕ) := nsmul_eq_mul _ _
| -[1+ n] := show -(_ •ℕ _)=-_*_, by rw [neg_mul_eq_neg_mul_symm, nsmul_eq_mul, nat.cast_succ]
theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n :=
by rw [gsmul_eq_mul, (n.cast_commute a).eq]
theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) :=
by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc]
theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b :=
by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc]
@[simp]
lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul]
lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp
@[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m :=
by induction m with m ih; [exact int.cast_one,
rw [pow_succ, pow_succ, int.cast_mul, ih]]
lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) :=
by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two]
theorem sq_sub_sq [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) :=
by rw [pow_two, pow_two, mul_self_sub_mul_self]
theorem pow_eq_zero [domain R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 :=
begin
induction n with n ih,
{ rw pow_zero at H,
rw [← mul_one x, H, mul_zero] },
exact or.cases_on (mul_eq_zero.1 H) id ih
end
@[field_simps] theorem pow_ne_zero [domain R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 :=
mt pow_eq_zero h
theorem nsmul_nonneg [ordered_add_comm_monoid R] {a : R} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n •ℕ a
| 0 := le_refl _
| (n+1) := add_nonneg H (nsmul_nonneg n)
lemma pow_abs [decidable_linear_ordered_comm_ring R] (a : R) (n : ℕ) : (abs a)^n = abs (a^n) :=
by induction n with n ih; [exact (abs_one).symm,
rw [pow_succ, pow_succ, ih, abs_mul]]
lemma abs_neg_one_pow [decidable_linear_ordered_comm_ring R] (n : ℕ) : abs ((-1 : R)^n) = 1 :=
by rw [←pow_abs, abs_neg, abs_one, one_pow]
section add_monoid
variable [ordered_add_comm_monoid A]
theorem nsmul_le_nsmul {a : A} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℕ a ≤ m •ℕ a :=
let ⟨k, hk⟩ := nat.le.dest h in
calc n •ℕ a = n •ℕ a + 0 : (add_zero _).symm
... ≤ n •ℕ a + k •ℕ a : add_le_add_left (nsmul_nonneg ha _) _
... = m •ℕ a : by rw [← hk, add_nsmul]
lemma nsmul_le_nsmul_of_le_right {a b : A} (hab : a ≤ b) : ∀ i : ℕ, i •ℕ a ≤ i •ℕ b
| 0 := by simp
| (k+1) := add_le_add hab (nsmul_le_nsmul_of_le_right _)
end add_monoid
namespace canonically_ordered_semiring
variable [canonically_ordered_comm_semiring R]
theorem pow_pos {a : R} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n
| 0 := canonically_ordered_semiring.zero_lt_one
| (n+1) := canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩
lemma pow_le_pow_of_le_left {a b : R} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i
| 0 := by simp
| (k+1) := canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k)
theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n :=
by simpa only [one_pow] using pow_le_pow_of_le_left H n
theorem pow_le_one {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:=
by simpa only [one_pow] using pow_le_pow_of_le_left H n
end canonically_ordered_semiring
section linear_ordered_semiring
variable [linear_ordered_semiring R]
theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n
| 0 := zero_lt_one
| (n+1) := mul_pos H (pow_pos _)
theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n
| 0 := zero_le_one
| (n+1) := mul_nonneg H (pow_nonneg _)
theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) :
x ^ n < y ^ n :=
begin
cases lt_or_eq_of_le Hxpos,
{ rw ←nat.sub_add_cancel Hnpos,
induction (n - 1), { simpa only [pow_one] },
rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one],
apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) },
{ rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),}
end
theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n)
(Hxyn : x ^ n = y ^ n) : x = y :=
begin
rcases lt_trichotomy x y with hxy | rfl | hyx,
{ exact absurd Hxyn (ne_of_lt (pow_lt_pow_of_lt_left hxy Hxpos Hnpos)) },
{ refl },
{ exact absurd Hxyn (ne_of_gt (pow_lt_pow_of_lt_left hyx Hypos Hnpos)) },
end
theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n
| 0 := le_refl _
| (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n)
zero_le_one (le_trans zero_le_one H)
/-- Bernoulli's inequality. This version works for semirings but requires
an additional hypothesis `0 ≤ a * a`. -/
theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (H : 0 ≤ 1 + a) :
∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n
| 0 := le_of_eq $ add_zero _
| (n+1) :=
calc 1 + (n + 1) •ℕ a ≤ (1 + a) * (1 + n •ℕ a) :
by simpa [succ_nsmul, mul_add, add_mul, mul_nsmul_left, add_comm, add_left_comm]
using nsmul_nonneg Hsqr n
... ≤ (1 + a)^(n+1) : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) H
theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m :=
let ⟨k, hk⟩ := nat.le.dest h in
calc a ^ n = a ^ n * 1 : (mul_one _).symm
... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left
(one_le_pow_of_one_le ha _)
(pow_nonneg (le_trans zero_le_one ha) _)
... = a ^ m : by rw [←hk, pow_add]
lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m :=
begin
have h' : 1 ≤ a := le_of_lt h,
have h'' : 0 < a := lt_trans zero_lt_one h,
cases m, cases h2, rw [pow_succ, ←one_mul (a ^ n)],
exact mul_lt_mul h (pow_le_pow h' (nat.le_of_lt_succ h2)) (pow_pos h'' _) (le_of_lt h'')
end
lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i
| 0 := by simp
| (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab)
lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b :=
lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h
private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) :
∀ k : ℕ, a ^ (i + k + 1) < a ^ i
| 0 :=
begin
simp only [add_zero],
rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one
end
| (k+1) :=
begin
rw ←one_mul (a^i),
apply mul_lt_mul ha _ _ zero_le_one,
{ apply le_of_lt, apply pow_lt_pow_of_lt_one_aux },
{ show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h }
end
private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) :
∀ k : ℕ, a ^ (i + k) ≤ a ^ i
| 0 := by simp
| (k+1) := by rw [←add_assoc, ←one_mul (a^i)];
exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one
lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1)
{i j : ℕ} (hij : i < j) : a ^ j < a ^ i :=
let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in
by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _
lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1)
{i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i :=
let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in
by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _
lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1
| 0 h0 h1 := le_refl (1 : R)
| (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1)
end linear_ordered_semiring
theorem pow_two_nonneg [linear_ordered_ring R] (a : R) : 0 ≤ a ^ 2 :=
by { rw pow_two, exact mul_self_nonneg _ }
theorem pow_two_pos_of_ne_zero [linear_ordered_ring R] (a : R) (h : a ≠ 0) : 0 < a ^ 2 :=
lt_of_le_of_ne (pow_two_nonneg a) (pow_ne_zero 2 h).symm
/-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/
theorem one_add_mul_le_pow [linear_ordered_ring R] {a : R} (H : -2 ≤ a) :
∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n
| 0 := le_of_eq $ add_zero _
| 1 := by simp
| (n+2) :=
have H' : 0 ≤ 2 + a,
from neg_le_iff_add_nonneg.1 H,
have 0 ≤ n •ℕ (a * a * (2 + a)) + a * a,
from add_nonneg (nsmul_nonneg (mul_nonneg (mul_self_nonneg a) H') n)
(mul_self_nonneg a),
calc 1 + (n + 2) •ℕ a ≤ 1 + (n + 2) •ℕ a + (n •ℕ (a * a * (2 + a)) + a * a) :
(le_add_iff_nonneg_right _).2 this
... = (1 + a) * (1 + a) * (1 + n •ℕ a) :
by { simp only [add_mul, mul_add, mul_two, mul_one, one_mul, succ_nsmul, nsmul_add,
mul_nsmul_assoc, (mul_nsmul_left _ _ _).symm],
ac_refl }
... ≤ (1 + a) * (1 + a) * (1 + a)^n :
mul_le_mul_of_nonneg_left (one_add_mul_le_pow n) (mul_self_nonneg (1 + a))
... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc]
/-- Bernoulli's inequality reformulated to estimate `a^n`. -/
theorem one_add_sub_mul_le_pow [linear_ordered_ring R]
{a : R} (H : -1 ≤ a) (n : ℕ) : 1 + n •ℕ (a - 1) ≤ a ^ n :=
have -2 ≤ a - 1, by { rw [bit0, neg_add], exact sub_le_sub_right H 1 },
by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n
namespace int
lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 :=
(units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl)
lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) :=
by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one]
@[simp] lemma nat_abs_pow_two (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 :=
by rw [pow_two, int.nat_abs_mul_self', pow_two]
end int
@[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 :=
by simp [pow, monoid.pow]
lemma of_add_nsmul [add_monoid A] (x : A) (n : ℕ) :
multiplicative.of_add (n •ℕ x) = (multiplicative.of_add x)^n := rfl
lemma of_add_gsmul [add_group A] (x : A) (n : ℤ) :
multiplicative.of_add (n •ℤ x) = (multiplicative.of_add x)^n := rfl
variables (M G A)
/-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image
of `multiplicative.of_add 1`. -/
def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) :=
{ to_fun := λ x, ⟨λ n, x ^ n.to_add, pow_zero x, λ m n, pow_add x m n⟩,
inv_fun := λ f, f (multiplicative.of_add 1),
left_inv := pow_one,
right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } }
/-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image
of `multiplicative.of_add 1`. -/
def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) :=
{ to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩,
inv_fun := λ f, f (multiplicative.of_add 1),
left_inv := gpow_one,
right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← of_add_gsmul ] } }
/-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/
def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) :=
{ to_fun := λ x, ⟨λ n, n •ℕ x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩,
inv_fun := λ f, f 1,
left_inv := one_nsmul,
right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) }
/-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/
def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) :=
{ to_fun := λ x, ⟨λ n, n •ℤ x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩,
inv_fun := λ f, f 1,
left_inv := one_gsmul,
right_inv := λ f, add_monoid_hom.ext_int $ one_gsmul (f 1) }
variables {M G A}
@[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) :
powers_hom M x n = x ^ n.to_add := rfl
@[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) :
(powers_hom M).symm f = f (multiplicative.of_add 1) := rfl
lemma mnat_monoid_hom_eq [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) :
f n = (f (multiplicative.of_add 1)) ^ n.to_add :=
by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply]
lemma mnat_monoid_hom_ext [monoid M] ⦃f g : multiplicative ℕ →* M⦄
(h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g :=
monoid_hom.ext $ λ n, by rw [mnat_monoid_hom_eq f, mnat_monoid_hom_eq g, h]
/-!
### Commutativity (again)
Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer
multiplication equals semiring multiplication.
-/
namespace semiconj_by
section
variables [semiring R] {a x y : R}
@[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) :=
semiconj_by.mul_right (nat.commute_cast _ _) h
@[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y :=
semiconj_by.mul_left (nat.cast_commute _ _) h
@[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) :
semiconj_by ((m : R) * a) (n * x) (n * y) :=
(h.cast_nat_mul_left m).cast_nat_mul_right n
end
variables [monoid M] [group G] [ring R]
@[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) :
∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m))
| (n : ℕ) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right]
| -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right]
@[simp] lemma gpow_right {a x y : G} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (x^m) (y^m)
| (n : ℕ) := h.pow_right n
| -[1+n] := (h.pow_right n.succ).inv_right
variables {a b x y x' y' : R}
@[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) :
semiconj_by a ((m : ℤ) * x) (m * y) :=
semiconj_by.mul_right (int.commute_cast _ _) h
@[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y :=
semiconj_by.mul_left (int.cast_commute _ _) h
@[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) :
semiconj_by ((m : R) * a) (n * x) (n * y) :=
(h.cast_int_mul_left m).cast_int_mul_right n
end semiconj_by
namespace commute
section
variables [semiring R] {a b : R}
@[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) :=
h.cast_nat_mul_right n
@[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b :=
h.cast_nat_mul_left n
@[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) :
commute ((m : R) * a) (n * b) :=
h.cast_nat_mul_cast_nat_mul m n
@[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) :=
(commute.refl a).cast_nat_mul_right n
@[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a :=
(commute.refl a).cast_nat_mul_left n
@[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) :=
(commute.refl a).cast_nat_mul_cast_nat_mul m n
end
variables [monoid M] [group G] [ring R]
@[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) :
commute a (↑(u^m)) :=
h.units_gpow_right m
@[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) :
commute (↑(u^m)) a :=
(h.symm.units_gpow_right m).symm
section
variables {a b : G}
@[simp] lemma gpow_right (h : commute a b) (m : ℤ) : commute a (b^m) :=
h.gpow_right m
@[simp] lemma gpow_left (h : commute a b) (m : ℤ) : commute (a^m) b :=
(h.symm.gpow_right m).symm
lemma gpow_gpow (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.gpow_left m).gpow_right n
variables (a) (m n : ℕ)
@[simp] theorem self_gpow : commute a (a ^ n) := (commute.refl a).gpow_right n
@[simp] theorem gpow_self : commute (a ^ n) a := (commute.refl a).gpow_left n
@[simp] theorem gpow_gpow_self : commute (a ^ m) (a ^ n) := (commute.refl a).gpow_gpow m n
end
variables {a b : R}
@[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) :=
h.cast_int_mul_right m
@[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b :=
h.cast_int_mul_left m
lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) :=
h.cast_int_mul_cast_int_mul m n
variables (a) (m n : ℤ)
@[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n
@[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n
theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) :=
(commute.refl a).cast_int_mul_cast_int_mul m n
end commute
namespace units
variables [monoid M]
lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) :=
(divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm
lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:=
(u⁻¹).conj_pow x n
open opposite
/-- Moving to the opposite monoid commutes with taking powers. -/
@[simp] lemma op_pow (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n :=
begin
induction n with n h,
{ simp },
{ rw [pow_succ', op_mul, h, pow_succ] }
end
@[simp] lemma unop_pow (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n :=
begin
induction n with n h,
{ simp },
{ rw [pow_succ', unop_mul, h, pow_succ] }
end
end units
|
bcdc61d314064f4bb4dfaf4077bfbbcff16767ac | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/mv_polynomial/basic.lean | eff152a5f063bb176ef7e0ab9be73914f8fae7c3 | [
"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 | 48,167 | 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, Johan Commelin, Mario Carneiro
-/
import ring_theory.adjoin.basic
import data.finsupp.antidiagonal
import algebra.monoid_algebra.basic
import order.symm_diff
/-!
# Multivariate polynomials
This file defines polynomial rings over a base ring (or even semiring),
with variables from a general type `σ` (which could be infinite).
## Important definitions
Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary
type. This file creates the type `mv_polynomial σ R`, which mathematicians
might denote $R[X_i : i \in σ]$. It is the type of multivariate
(a.k.a. multivariable) polynomials, with variables
corresponding to the terms in `σ`, and coefficients in `R`.
### Notation
In the definitions below, we use the following notation:
+ `σ : Type*` (indexing the variables)
+ `R : Type*` `[comm_semiring R]` (the coefficients)
+ `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set.
This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s`
+ `a : R`
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : mv_polynomial σ R`
### Definitions
* `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients
in the commutative semiring `R`
* `monomial s a` : the monomial which mathematically would be denoted `a * X^s`
* `C a` : the constant polynomial with value `a`
* `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`.
* `coeff s p` : the coefficient of `s` in `p`.
* `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another
semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`.
Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested
that sticking to `eval` and `map` might make the code less brittle.
* `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation,
returning a term of type `R`
* `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of
coefficient semiring corresponding to `f`
## Implementation notes
Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite
support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`.
The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all
monomials in the variables, and the function to `R` sends a monomial to its coefficient in
the polynomial being represented.
## Tags
polynomial, multivariate polynomial, multivariable polynomial
-/
noncomputable theory
open_locale classical big_operators
open set function finsupp add_monoid_algebra
open_locale big_operators
universes u v w x
variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x}
/-- Multivariate polynomial, where `σ` is the index set of the variables and
`R` is the coefficient ring -/
def mv_polynomial (σ : Type*) (R : Type*) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ)
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section comm_semiring
section instances
instance decidable_eq_mv_polynomial [comm_semiring R] [decidable_eq σ] [decidable_eq R] :
decidable_eq (mv_polynomial σ R) := finsupp.decidable_eq
instance [comm_semiring R] : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring
instance [comm_semiring R] : inhabited (mv_polynomial σ R) := ⟨0⟩
instance [monoid R] [comm_semiring S₁] [distrib_mul_action R S₁] :
distrib_mul_action R (mv_polynomial σ S₁) :=
add_monoid_algebra.distrib_mul_action
instance [monoid R] [comm_semiring S₁] [distrib_mul_action R S₁] [has_faithful_scalar R S₁] :
has_faithful_scalar R (mv_polynomial σ S₁) :=
add_monoid_algebra.has_faithful_scalar
instance [semiring R] [comm_semiring S₁] [module R S₁] : module R (mv_polynomial σ S₁) :=
add_monoid_algebra.module
instance [monoid R] [monoid S₁] [comm_semiring S₂]
[has_scalar R S₁] [distrib_mul_action R S₂] [distrib_mul_action S₁ S₂] [is_scalar_tower R S₁ S₂] :
is_scalar_tower R S₁ (mv_polynomial σ S₂) :=
add_monoid_algebra.is_scalar_tower
instance [monoid R] [monoid S₁][comm_semiring S₂]
[distrib_mul_action R S₂] [distrib_mul_action S₁ S₂] [smul_comm_class R S₁ S₂] :
smul_comm_class R S₁ (mv_polynomial σ S₂) :=
add_monoid_algebra.smul_comm_class
instance [monoid R] [comm_semiring S₁] [distrib_mul_action R S₁] [distrib_mul_action Rᵐᵒᵖ S₁]
[is_central_scalar R S₁] :
is_central_scalar R (mv_polynomial σ S₁) :=
add_monoid_algebra.is_central_scalar
instance [comm_semiring R] [comm_semiring S₁] [algebra R S₁] : algebra R (mv_polynomial σ S₁) :=
add_monoid_algebra.algebra
-- Register with high priority to avoid timeout in `data.mv_polynomial.pderiv`
instance is_scalar_tower' [comm_semiring R] [comm_semiring S₁] [algebra R S₁] :
is_scalar_tower R (mv_polynomial σ S₁) (mv_polynomial σ S₁) :=
is_scalar_tower.right
-- TODO[gh-6025]: make this an instance once safe to do so
/-- If `R` is a subsingleton, then `mv_polynomial σ R` has a unique element -/
protected def unique [comm_semiring R] [subsingleton R] : unique (mv_polynomial σ R) :=
add_monoid_algebra.unique
end instances
variables [comm_semiring R] [comm_semiring S₁] {p q : mv_polynomial σ R}
/-- `monomial s a` is the monomial with coefficient `a` and exponents given by `s` -/
def monomial (s : σ →₀ ℕ) : R →ₗ[R] mv_polynomial σ R := lsingle s
lemma single_eq_monomial (s : σ →₀ ℕ) (a : R) : single s a = monomial s a := rfl
lemma mul_def : (p * q) = p.sum (λ m a, q.sum $ λ n b, monomial (m + n) (a * b)) := rfl
/-- `C a` is the constant polynomial with value `a` -/
def C : R →+* mv_polynomial σ R :=
{ to_fun := monomial 0, ..single_zero_ring_hom }
variables (R σ)
theorem algebra_map_eq : algebra_map R (mv_polynomial σ R) = C := rfl
variables {R σ}
/-- `X n` is the degree `1` monomial $X_n$. -/
def X (n : σ) : mv_polynomial σ R := monomial (single n 1) 1
lemma C_apply : (C a : mv_polynomial σ R) = monomial 0 a := rfl
@[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ R) := by simp [C_apply, monomial]
@[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ R) := rfl
lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') :=
by simp [C_apply, monomial, single_mul_single]
@[simp] lemma C_add : (C (a + a') : mv_polynomial σ R) = C a + C a' := single_add
@[simp] lemma C_mul : (C (a * a') : mv_polynomial σ R) = C a * C a' := C_mul_monomial.symm
@[simp] lemma C_pow (a : R) (n : ℕ) : (C (a^n) : mv_polynomial σ R) = (C a)^n :=
by induction n; simp [pow_succ, *]
lemma C_injective (σ : Type*) (R : Type*) [comm_semiring R] :
function.injective (C : R → mv_polynomial σ R) :=
finsupp.single_injective _
lemma C_surjective {R : Type*} [comm_semiring R] (σ : Type*) [is_empty σ] :
function.surjective (C : R → mv_polynomial σ R) :=
begin
refine λ p, ⟨p.to_fun 0, finsupp.ext (λ a, _)⟩,
simpa [(finsupp.ext is_empty_elim : a = 0), C_apply, monomial],
end
@[simp] lemma C_inj {σ : Type*} (R : Type*) [comm_semiring R] (r s : R) :
(C r : mv_polynomial σ R) = C s ↔ r = s :=
(C_injective σ R).eq_iff
instance infinite_of_infinite (σ : Type*) (R : Type*) [comm_semiring R] [infinite R] :
infinite (mv_polynomial σ R) :=
infinite.of_injective C (C_injective _ _)
instance infinite_of_nonempty (σ : Type*) (R : Type*) [nonempty σ] [comm_semiring R]
[nontrivial R] :
infinite (mv_polynomial σ R) :=
infinite.of_injective ((λ s : σ →₀ ℕ, monomial s 1) ∘ single (classical.arbitrary σ)) $
function.injective.comp
(λ m n, (finsupp.single_left_inj one_ne_zero).mp) (finsupp.single_injective _)
lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ R) = n :=
by induction n; simp [nat.succ_eq_add_one, *]
theorem C_mul' : mv_polynomial.C a * p = a • p :=
(algebra.smul_def a p).symm
lemma smul_eq_C_mul (p : mv_polynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm
lemma C_eq_smul_one : (C a : mv_polynomial σ R) = a • 1 :=
by rw [← C_mul', mul_one]
lemma monomial_pow : monomial s a ^ e = monomial (e • s) (a ^ e) :=
add_monoid_algebra.single_pow e
@[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : R} :
monomial s a * monomial s' b = monomial (s + s') (a * b) :=
add_monoid_algebra.single_mul_single
variables (σ R)
/-- `λ s, monomial s 1` as a homomorphism. -/
def monomial_one_hom : multiplicative (σ →₀ ℕ) →* mv_polynomial σ R :=
add_monoid_algebra.of _ _
variables {σ R}
@[simp] lemma monomial_one_hom_apply :
monomial_one_hom R σ s = (monomial s 1 : mv_polynomial σ R) := rfl
lemma X_pow_eq_monomial : X n ^ e = monomial (single n e) (1 : R) :=
by simp [X, monomial_pow]
lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) :=
by rw [X_pow_eq_monomial, monomial_mul, mul_one]
lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) :=
by rw [X_pow_eq_monomial, monomial_mul, one_mul]
lemma monomial_eq_C_mul_X {s : σ} {a : R} {n : ℕ} :
monomial (single s n) a = C a * (X s)^n :=
by rw [← zero_add (single s n), monomial_add_single, C_apply]
@[simp] lemma monomial_zero {s : σ →₀ ℕ} : monomial s (0 : R) = 0 :=
single_zero
@[simp] lemma monomial_zero' : (monomial (0 : σ →₀ ℕ) : R → mv_polynomial σ R) = C := rfl
@[simp] lemma monomial_eq_zero {s : σ →₀ ℕ} {b : R} : monomial s b = 0 ↔ b = 0 :=
finsupp.single_eq_zero
@[simp] lemma sum_monomial_eq {A : Type*} [add_comm_monoid A]
{u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) :
sum (monomial u r) b = b u r :=
sum_single_index w
@[simp] lemma sum_C {A : Type*} [add_comm_monoid A]
{b : (σ →₀ ℕ) → R → A} (w : b 0 0 = 0) :
sum (C a) b = b 0 a :=
sum_monomial_eq w
lemma monomial_sum_one {α : Type*} (s : finset α) (f : α → (σ →₀ ℕ)) :
(monomial (∑ i in s, f i) 1 : mv_polynomial σ R) = ∏ i in s, monomial (f i) 1 :=
(monomial_one_hom R σ).map_prod (λ i, multiplicative.of_add (f i)) s
lemma monomial_sum_index {α : Type*} (s : finset α) (f : α → (σ →₀ ℕ)) (a : R) :
(monomial (∑ i in s, f i) a) = C a * ∏ i in s, monomial (f i) 1 :=
by rw [← monomial_sum_one, C_mul', ← (monomial _).map_smul, smul_eq_mul, mul_one]
lemma monomial_finsupp_sum_index {α β : Type*} [has_zero β] (f : α →₀ β)
(g : α → β → (σ →₀ ℕ)) (a : R) :
(monomial (f.sum g) a) = C a * f.prod (λ a b, monomial (g a b) 1) :=
monomial_sum_index _ _ _
lemma monomial_eq_monomial_iff {α : Type*} (a₁ a₂ : α →₀ ℕ) (b₁ b₂ : R) :
monomial a₁ b₁ = monomial a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ ∨ b₁ = 0 ∧ b₂ = 0 :=
finsupp.single_eq_single_iff _ _ _ _
lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ R) :=
by simp only [X_pow_eq_monomial, ← monomial_finsupp_sum_index, finsupp.sum_single]
lemma induction_on_monomial {M : mv_polynomial σ R → Prop} (h_C : ∀ a, M (C a))
(h_X : ∀ p n, M p → M (p * X n)) : ∀ s a, M (monomial s a) :=
begin
assume s a,
apply @finsupp.induction σ ℕ _ _ s,
{ show M (monomial 0 a), from h_C a, },
{ assume n e p hpn he ih,
have : ∀e:ℕ, M (monomial p a * X n ^ e),
{ intro e,
induction e,
{ simp [ih] },
{ simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } },
simp [add_comm, monomial_add_single, this] }
end
/-- Analog of `polynomial.induction_on'`.
To prove something about mv_polynomials,
it suffices to show the condition is closed under taking sums,
and it holds for monomials. -/
attribute [elab_as_eliminator]
theorem induction_on' {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R)
(h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a))
(h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p :=
finsupp.induction p (suffices P (monomial 0 0), by rwa monomial_zero at this,
show P (monomial 0 0), from h1 0 0)
(λ a b f ha hb hPf, h2 _ _ (h1 _ _) hPf)
/-- Similar to `mv_polynomial.induction_on` but only a weak form of `h_add` is required.-/
lemma induction_on''' {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀ a, M (C a))
(h_add_weak : ∀ (a : σ →₀ ℕ) (b : R) (f : (σ →₀ ℕ) →₀ R),
a ∉ f.support → b ≠ 0 → M f → M (monomial a b + f)) : M p :=
finsupp.induction p (C_0.rec $ h_C 0) h_add_weak
/-- Similar to `mv_polynomial.induction_on` but only a yet weaker form of `h_add` is required.-/
lemma induction_on'' {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀ a, M (C a))
(h_add_weak : ∀ (a : σ →₀ ℕ) (b : R) (f : (σ →₀ ℕ) →₀ R),
a ∉ f.support → b ≠ 0 → M f → M (monomial a b) → M (monomial a b + f))
(h_X : ∀ (p : mv_polynomial σ R) (n : σ), M p → M (p * mv_polynomial.X n)): M p :=
induction_on''' p h_C (λ a b f ha hb hf,
h_add_weak a b f ha hb hf $ induction_on_monomial h_C h_X a b)
/-- Analog of `polynomial.induction_on`.-/
@[recursor 5]
lemma induction_on {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R)
(h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) :
M p :=
induction_on'' p h_C (λ a b f ha hb hf hm, h_add (monomial a b) f hm hf) h_X
lemma ring_hom_ext {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A}
(hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) :
f = g :=
by { ext, exacts [hC _, hX _] }
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma ring_hom_ext' {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A}
(hC : f.comp C = g.comp C) (hX : ∀ i, f (X i) = g (X i)) :
f = g :=
ring_hom_ext (ring_hom.ext_iff.1 hC) hX
lemma hom_eq_hom [semiring S₂]
(f g : mv_polynomial σ R →+* S₂)
(hC : f.comp C = g.comp C) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ R) :
f p = g p :=
ring_hom.congr_fun (ring_hom_ext' hC hX) p
lemma is_id (f : mv_polynomial σ R →+* mv_polynomial σ R)
(hC : f.comp C = C) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ R) :
f p = p :=
hom_eq_hom f (ring_hom.id _) hC hX p
@[ext] lemma alg_hom_ext' {A B : Type*} [comm_semiring A] [comm_semiring B]
[algebra R A] [algebra R B] {f g : mv_polynomial σ A →ₐ[R] B}
(h₁ : f.comp (is_scalar_tower.to_alg_hom R A (mv_polynomial σ A)) =
g.comp (is_scalar_tower.to_alg_hom R A (mv_polynomial σ A)))
(h₂ : ∀ i, f (X i) = g (X i)) : f = g :=
alg_hom.coe_ring_hom_injective (mv_polynomial.ring_hom_ext'
(congr_arg alg_hom.to_ring_hom h₁) h₂)
@[ext] lemma alg_hom_ext {A : Type*} [semiring A] [algebra R A]
{f g : mv_polynomial σ R →ₐ[R] A} (hf : ∀ i : σ, f (X i) = g (X i)) :
f = g :=
add_monoid_algebra.alg_hom_ext' (mul_hom_ext' (λ (x : σ), monoid_hom.ext_mnat (hf x)))
@[simp] lemma alg_hom_C (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (r : R) :
f (C r) = C r :=
f.commutes r
@[simp] lemma adjoin_range_X : algebra.adjoin R (range (X : σ → mv_polynomial σ R)) = ⊤ :=
begin
set S := algebra.adjoin R (range (X : σ → mv_polynomial σ R)),
refine top_unique (λ p hp, _), clear hp,
induction p using mv_polynomial.induction_on,
case h_C : { exact S.algebra_map_mem _ },
case h_add : p q hp hq { exact S.add_mem hp hq },
case h_X : p i hp { exact S.mul_mem hp (algebra.subset_adjoin $ mem_range_self _) }
end
@[ext] lemma linear_map_ext {M : Type*} [add_comm_monoid M] [module R M]
{f g : mv_polynomial σ R →ₗ[R] M} (h : ∀ s, f ∘ₗ monomial s = g ∘ₗ monomial s) :
f = g :=
finsupp.lhom_ext' h
section support
/--
The finite set of all `m : σ →₀ ℕ` such that `X^m` has a non-zero coefficient.
-/
def support (p : mv_polynomial σ R) : finset (σ →₀ ℕ) :=
p.support
lemma finsupp_support_eq_support (p : mv_polynomial σ R) : finsupp.support p = p.support := rfl
lemma support_monomial [decidable (a = 0)] : (monomial s a).support = if a = 0 then ∅ else {s} :=
by convert rfl
lemma support_monomial_subset : (monomial s a).support ⊆ {s} :=
support_single_subset
lemma support_add : (p + q).support ⊆ p.support ∪ q.support := finsupp.support_add
lemma support_X [nontrivial R] : (X n : mv_polynomial σ R).support = {single n 1} :=
by rw [X, support_monomial, if_neg]; exact one_ne_zero
lemma support_X_pow [nontrivial R] (s : σ) (n : ℕ) :
(X s ^ n : mv_polynomial σ R).support = {finsupp.single s n} :=
by rw [X_pow_eq_monomial, support_monomial, if_neg (@one_ne_zero R _ _)]
@[simp] lemma support_zero : (0 : mv_polynomial σ R).support = ∅ := rfl
lemma support_sum {α : Type*} {s : finset α} {f : α → mv_polynomial σ R} :
(∑ x in s, f x).support ⊆ s.bUnion (λ x, (f x).support) := finsupp.support_finset_sum
end support
section coeff
/-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/
def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R :=
@coe_fn _ _ (monoid_algebra.has_coe_to_fun _ _) p m
@[simp] lemma mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} :
m ∈ p.support ↔ p.coeff m ≠ 0 :=
by simp [support, coeff]
lemma not_mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} :
m ∉ p.support ↔ p.coeff m = 0 :=
by simp
lemma sum_def {A} [add_comm_monoid A] {p : mv_polynomial σ R} {b : (σ →₀ ℕ) → R → A} :
p.sum b = ∑ m in p.support, b m (p.coeff m) :=
by simp [support, finsupp.sum, coeff]
lemma support_mul (p q : mv_polynomial σ R) :
(p * q).support ⊆ p.support.bUnion (λ a, q.support.bUnion $ λ b, {a + b}) :=
by convert add_monoid_algebra.support_mul p q; ext; convert iff.rfl
@[ext] lemma ext (p q : mv_polynomial σ R) :
(∀ m, coeff m p = coeff m q) → p = q := ext
lemma ext_iff (p q : mv_polynomial σ R) :
p = q ↔ (∀ m, coeff m p = coeff m q) :=
⟨ λ h m, by rw h, ext p q⟩
@[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ R) :
coeff m (p + q) = coeff m p + coeff m q := add_apply p q m
@[simp] lemma coeff_smul {S₁ : Type*} [monoid S₁] [distrib_mul_action S₁ R]
(m : σ →₀ ℕ) (c : S₁) (p : mv_polynomial σ R) :
coeff m (c • p) = c • coeff m p := smul_apply c p m
@[simp] lemma coeff_zero (m : σ →₀ ℕ) :
coeff m (0 : mv_polynomial σ R) = 0 := rfl
@[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ R) = 0 :=
single_eq_of_ne (λ h, by cases single_eq_zero.1 h)
/-- `mv_polynomial.coeff m` but promoted to an `add_monoid_hom`. -/
@[simps] def coeff_add_monoid_hom (m : σ →₀ ℕ) : mv_polynomial σ R →+ R :=
{ to_fun := coeff m,
map_zero' := coeff_zero m,
map_add' := coeff_add m }
lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) :
coeff m (∑ x in s, f x) = ∑ x in s, coeff m (f x) :=
(coeff_add_monoid_hom _).map_sum _ s
lemma monic_monomial_eq (m) : monomial m (1:R) = (m.prod $ λn e, X n ^ e : mv_polynomial σ R) :=
by simp [monomial_eq]
@[simp] lemma coeff_monomial [decidable_eq σ] (m n) (a) :
coeff m (monomial n a : mv_polynomial σ R) = if n = m then a else 0 :=
single_apply
@[simp] lemma coeff_C [decidable_eq σ] (m) (a) :
coeff m (C a : mv_polynomial σ R) = if 0 = m then a else 0 :=
single_apply
lemma coeff_one [decidable_eq σ] (m) :
coeff m (1 : mv_polynomial σ R) = if 0 = m then 1 else 0 :=
coeff_C m 1
@[simp] lemma coeff_zero_C (a) : coeff 0 (C a : mv_polynomial σ R) = a :=
single_eq_same
@[simp] lemma coeff_zero_one : coeff 0 (1 : mv_polynomial σ R) = 1 :=
coeff_zero_C 1
lemma coeff_X_pow [decidable_eq σ] (i : σ) (m) (k : ℕ) :
coeff m (X i ^ k : mv_polynomial σ R) = if single i k = m then 1 else 0 :=
begin
have := coeff_monomial m (finsupp.single i k) (1:R),
rwa [@monomial_eq _ _ (1:R) (finsupp.single i k) _,
C_1, one_mul, finsupp.prod_single_index] at this,
exact pow_zero _
end
lemma coeff_X' [decidable_eq σ] (i : σ) (m) :
coeff m (X i : mv_polynomial σ R) = if single i 1 = m then 1 else 0 :=
by rw [← coeff_X_pow, pow_one]
@[simp] lemma coeff_X (i : σ) :
coeff (single i 1) (X i : mv_polynomial σ R) = 1 :=
by rw [coeff_X', if_pos rfl]
@[simp] lemma coeff_C_mul (m) (a : R) (p : mv_polynomial σ R) :
coeff m (C a * p) = a * coeff m p :=
begin
rw [mul_def, sum_C],
{ simp [sum_def, coeff_sum] {contextual := tt} },
simp
end
lemma coeff_mul (p q : mv_polynomial σ R) (n : σ →₀ ℕ) :
coeff n (p * q) = ∑ x in antidiagonal n, coeff x.1 p * coeff x.2 q :=
add_monoid_algebra.mul_apply_antidiagonal p q _ _ $ λ p, mem_antidiagonal
@[simp] lemma coeff_mul_monomial (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff (m + s) (p * monomial s r) = coeff m p * r :=
(add_monoid_algebra.mul_single_apply_aux p _ _ _ _ (λ a, add_left_inj _))
@[simp] lemma coeff_monomial_mul (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff (s + m) (monomial s r * p) = r * coeff m p :=
(add_monoid_algebra.single_mul_apply_aux p _ _ _ _ (λ a, add_right_inj _))
@[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ R) :
coeff (m + single s 1) (p * X s) = coeff m p :=
(coeff_mul_monomial _ _ _ _).trans (mul_one _)
@[simp] lemma coeff_X_mul (m) (s : σ) (p : mv_polynomial σ R) :
coeff (single s 1 + m) (X s * p) = coeff m p :=
(coeff_monomial_mul _ _ _ _).trans (one_mul _)
@[simp] lemma support_mul_X (s : σ) (p : mv_polynomial σ R) :
(p * X s).support = p.support.map (add_right_embedding (single s 1)) :=
add_monoid_algebra.support_mul_single p _ (by simp) _
@[simp] lemma support_X_mul (s : σ) (p : mv_polynomial σ R) :
(X s * p).support = p.support.map (add_left_embedding (single s 1)) :=
add_monoid_algebra.support_single_mul p _ (by simp) _
lemma support_sdiff_support_subset_support_add [decidable_eq σ] (p q : mv_polynomial σ R) :
p.support \ q.support ⊆ (p + q).support :=
begin
intros m hm,
simp only [not_not, mem_support_iff, finset.mem_sdiff, ne.def] at hm,
simp [hm.2, hm.1],
end
lemma support_symm_diff_support_subset_support_add [decidable_eq σ] (p q : mv_polynomial σ R) :
p.support ∆ q.support ⊆ (p + q).support :=
begin
rw [symm_diff_def, finset.sup_eq_union],
apply finset.union_subset,
{ exact support_sdiff_support_subset_support_add p q, },
{ rw add_comm,
exact support_sdiff_support_subset_support_add q p, },
end
lemma coeff_mul_monomial' (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff m (p * monomial s r) = if s ≤ m then coeff (m - s) p * r else 0 :=
begin
obtain rfl | hr := eq_or_ne r 0,
{ simp only [monomial_zero, coeff_zero, mul_zero, if_t_t], },
haveI : nontrivial R := nontrivial_of_ne _ _ hr,
split_ifs with h h,
{ conv_rhs {rw ← coeff_mul_monomial _ s},
congr' with t,
rw tsub_add_cancel_of_le h, },
{ rw ← not_mem_support_iff, intro hm, apply h,
have H := support_mul _ _ hm, simp only [finset.mem_bUnion] at H,
rcases H with ⟨j, hj, i', hi', H⟩,
rw [support_monomial, if_neg hr, finset.mem_singleton] at hi', subst i',
rw finset.mem_singleton at H, subst m,
exact le_add_left le_rfl, }
end
lemma coeff_monomial_mul' (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff m (monomial s r * p) = if s ≤ m then r * coeff (m - s) p else 0 :=
begin
-- note that if we allow `R` to be non-commutative we will have to duplicate the proof above.
rw [mul_comm, mul_comm r],
exact coeff_mul_monomial' _ _ _ _
end
lemma coeff_mul_X' [decidable_eq σ] (m) (s : σ) (p : mv_polynomial σ R) :
coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 :=
begin
refine (coeff_mul_monomial' _ _ _ _).trans _,
simp_rw [finsupp.single_le_iff, finsupp.mem_support_iff, nat.succ_le_iff, pos_iff_ne_zero,
mul_one],
end
lemma coeff_X_mul' [decidable_eq σ] (m) (s : σ) (p : mv_polynomial σ R) :
coeff m (X s * p) = if s ∈ m.support then coeff (m - single s 1) p else 0 :=
begin
refine (coeff_monomial_mul' _ _ _ _).trans _,
simp_rw [finsupp.single_le_iff, finsupp.mem_support_iff, nat.succ_le_iff, pos_iff_ne_zero,
one_mul],
end
lemma eq_zero_iff {p : mv_polynomial σ R} :
p = 0 ↔ ∀ d, coeff d p = 0 :=
by { rw ext_iff, simp only [coeff_zero], }
lemma ne_zero_iff {p : mv_polynomial σ R} :
p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 :=
by { rw [ne.def, eq_zero_iff], push_neg, }
lemma exists_coeff_ne_zero {p : mv_polynomial σ R} (h : p ≠ 0) :
∃ d, coeff d p ≠ 0 :=
ne_zero_iff.mp h
lemma C_dvd_iff_dvd_coeff (r : R) (φ : mv_polynomial σ R) :
C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i :=
begin
split,
{ rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right },
{ intro h,
choose c hc using h,
classical,
let c' : (σ →₀ ℕ) → R := λ i, if i ∈ φ.support then c i else 0,
let ψ : mv_polynomial σ R := ∑ i in φ.support, monomial i (c' i),
use ψ,
apply mv_polynomial.ext, intro i,
simp only [coeff_C_mul, coeff_sum, coeff_monomial, finset.sum_ite_eq', c'],
split_ifs with hi hi,
{ rw hc },
{ rw not_mem_support_iff at hi, rwa mul_zero } },
end
end coeff
section constant_coeff
/--
`constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`.
This is a ring homomorphism.
-/
def constant_coeff : mv_polynomial σ R →+* R :=
{ to_fun := coeff 0,
map_one' := by simp [coeff, add_monoid_algebra.one_def],
map_mul' := by simp [coeff_mul, finsupp.support_single_ne_zero],
map_zero' := coeff_zero _,
map_add' := coeff_add _ }
lemma constant_coeff_eq : (constant_coeff : mv_polynomial σ R → R) = coeff 0 := rfl
@[simp]
lemma constant_coeff_C (r : R) :
constant_coeff (C r : mv_polynomial σ R) = r :=
by simp [constant_coeff_eq]
@[simp]
lemma constant_coeff_X (i : σ) :
constant_coeff (X i : mv_polynomial σ R) = 0 :=
by simp [constant_coeff_eq]
lemma constant_coeff_monomial [decidable_eq σ] (d : σ →₀ ℕ) (r : R) :
constant_coeff (monomial d r) = if d = 0 then r else 0 :=
by rw [constant_coeff_eq, coeff_monomial]
variables (σ R)
@[simp] lemma constant_coeff_comp_C :
constant_coeff.comp (C : R →+* mv_polynomial σ R) = ring_hom.id R :=
by { ext, apply constant_coeff_C }
@[simp] lemma constant_coeff_comp_algebra_map :
constant_coeff.comp (algebra_map R (mv_polynomial σ R)) = ring_hom.id R :=
constant_coeff_comp_C _ _
end constant_coeff
section as_sum
@[simp] lemma support_sum_monomial_coeff (p : mv_polynomial σ R) :
∑ v in p.support, monomial v (coeff v p) = p :=
finsupp.sum_single p
lemma as_sum (p : mv_polynomial σ R) : p = ∑ v in p.support, monomial v (coeff v p) :=
(support_sum_monomial_coeff p).symm
end as_sum
section eval₂
variables (f : R →+* S₁) (g : σ → S₁)
/-- Evaluate a polynomial `p` given a valuation `g` of all the variables
and a ring hom `f` from the scalar ring to the target -/
def eval₂ (p : mv_polynomial σ R) : S₁ :=
p.sum (λs a, f a * s.prod (λn e, g n ^ e))
lemma eval₂_eq (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) :
f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i in d.support, x i ^ d i :=
rfl
lemma eval₂_eq' [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) :
f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i, x i ^ d i :=
by { simp only [eval₂_eq, ← finsupp.prod_pow], refl }
@[simp] lemma eval₂_zero : (0 : mv_polynomial σ R).eval₂ f g = 0 :=
finsupp.sum_zero_index
section
@[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g :=
finsupp.sum_add_index
(by simp [f.map_zero])
(by simp [add_mul, f.map_add])
@[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) :=
finsupp.sum_single_index (by simp [f.map_zero])
@[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a :=
by rw [C_apply, eval₂_monomial, prod_zero_index, mul_one]
@[simp] lemma eval₂_one : (1 : mv_polynomial σ R).eval₂ f g = 1 :=
(eval₂_C _ _ _).trans f.map_one
@[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n :=
by simp [eval₂_monomial, f.map_one, X, prod_single_index, pow_one]
lemma eval₂_mul_monomial :
∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) :=
begin
apply mv_polynomial.induction_on p,
{ assume a' s a,
simp [C_mul_monomial, eval₂_monomial, f.map_mul] },
{ assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] },
{ assume p n ih s a,
from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g :
by rw [monomial_single_add, pow_one, mul_assoc]
... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) :
by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm,
f.map_one, -add_comm] }
end
lemma eval₂_mul_C : (p * C a).eval₂ f g = p.eval₂ f g * f a :=
(eval₂_mul_monomial _ _).trans $ by simp
@[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g :=
begin
apply mv_polynomial.induction_on q,
{ simp [eval₂_C, eval₂_mul_C] },
{ simp [mul_add, eval₂_add] {contextual := tt} },
{ simp [X, eval₂_monomial, eval₂_mul_monomial, ← mul_assoc] { contextual := tt} }
end
@[simp] lemma eval₂_pow {p:mv_polynomial σ R} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n
| 0 := by { rw [pow_zero, pow_zero], exact eval₂_one _ _ }
| (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow]
/-- `mv_polynomial.eval₂` as a `ring_hom`. -/
def eval₂_hom (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ :=
{ to_fun := eval₂ f g,
map_one' := eval₂_one _ _,
map_mul' := λ p q, eval₂_mul _ _,
map_zero' := eval₂_zero _ _,
map_add' := λ p q, eval₂_add _ _ }
@[simp] lemma coe_eval₂_hom (f : R →+* S₁) (g : σ → S₁) :
⇑(eval₂_hom f g) = eval₂ f g := rfl
lemma eval₂_hom_congr {f₁ f₂ : R →+* S₁} {g₁ g₂ : σ → S₁} {p₁ p₂ : mv_polynomial σ R} :
f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ :=
by rintros rfl rfl rfl; refl
end
@[simp] lemma eval₂_hom_C (f : R →+* S₁) (g : σ → S₁) (r : R) :
eval₂_hom f g (C r) = f r := eval₂_C f g r
@[simp] lemma eval₂_hom_X' (f : R →+* S₁) (g : σ → S₁) (i : σ) :
eval₂_hom f g (X i) = g i := eval₂_X f g i
@[simp] lemma comp_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) :
φ.comp (eval₂_hom f g) = (eval₂_hom (φ.comp f) (λ i, φ (g i))) :=
begin
apply mv_polynomial.ring_hom_ext,
{ intro r, rw [ring_hom.comp_apply, eval₂_hom_C, eval₂_hom_C, ring_hom.comp_apply] },
{ intro i, rw [ring_hom.comp_apply, eval₂_hom_X', eval₂_hom_X'] }
end
lemma map_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
φ (eval₂_hom f g p) = (eval₂_hom (φ.comp f) (λ i, φ (g i)) p) :=
by { rw ← comp_eval₂_hom, refl }
lemma eval₂_hom_monomial (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) :
eval₂_hom f g (monomial d r) = f r * d.prod (λ i k, g i ^ k) :=
by simp only [monomial_eq, ring_hom.map_mul, eval₂_hom_C, finsupp.prod,
ring_hom.map_prod, ring_hom.map_pow, eval₂_hom_X']
section
lemma eval₂_comp_left {S₂} [comm_semiring S₂]
(k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁)
(p) : k (eval₂ f g p) = eval₂ (k.comp f) (k ∘ g) p :=
by apply mv_polynomial.induction_on p; simp [
eval₂_add, k.map_add,
eval₂_mul, k.map_mul] {contextual := tt}
end
@[simp] lemma eval₂_eta (p : mv_polynomial σ R) : eval₂ C X p = p :=
by apply mv_polynomial.induction_on p;
simp [eval₂_add, eval₂_mul] {contextual := tt}
lemma eval₂_congr (g₁ g₂ : σ → S₁)
(h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) :
p.eval₂ f g₁ = p.eval₂ f g₂ :=
begin
apply finset.sum_congr rfl,
intros c hc, dsimp, congr' 1,
apply finset.prod_congr rfl,
intros i hi, dsimp, congr' 1,
apply h hi,
rwa finsupp.mem_support_iff at hc
end
@[simp] lemma eval₂_prod (s : finset S₂) (p : S₂ → mv_polynomial σ R) :
eval₂ f g (∏ x in s, p x) = ∏ x in s, eval₂ f g (p x) :=
(eval₂_hom f g).map_prod _ s
@[simp] lemma eval₂_sum (s : finset S₂) (p : S₂ → mv_polynomial σ R) :
eval₂ f g (∑ x in s, p x) = ∑ x in s, eval₂ f g (p x) :=
(eval₂_hom f g).map_sum _ s
attribute [to_additive] eval₂_prod
lemma eval₂_assoc (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) :
eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) :=
begin
show _ = eval₂_hom f g (eval₂ C q p),
rw eval₂_comp_left (eval₂_hom f g), congr' with a, simp,
end
end eval₂
section eval
variables {f : σ → R}
/-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/
def eval (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id _) f
lemma eval_eq (x : σ → R) (f : mv_polynomial σ R) :
eval x f = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i :=
rfl
lemma eval_eq' [fintype σ] (x : σ → R) (f : mv_polynomial σ R) :
eval x f = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i :=
eval₂_eq' (ring_hom.id R) x f
lemma eval_monomial : eval f (monomial s a) = a * s.prod (λn e, f n ^ e) :=
eval₂_monomial _ _
@[simp] lemma eval_C : ∀ a, eval f (C a) = a := eval₂_C _ _
@[simp] lemma eval_X : ∀ n, eval f (X n) = f n := eval₂_X _ _
@[simp] lemma smul_eval (x) (p : mv_polynomial σ R) (s) : eval x (s • p) = s * eval x p :=
by rw [smul_eq_C_mul, (eval x).map_mul, eval_C]
lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) :
eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) :=
(eval g).map_sum _ _
@[to_additive]
lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) :
eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) :=
(eval g).map_prod _ _
theorem eval_assoc {τ}
(f : σ → mv_polynomial τ R) (g : τ → R)
(p : mv_polynomial σ R) :
eval (eval g ∘ f) p = eval g (eval₂ C f p) :=
begin
rw eval₂_comp_left (eval g),
unfold eval, simp only [coe_eval₂_hom],
congr' with a, simp
end
end eval
section map
variables (f : R →+* S₁)
/-- `map f p` maps a polynomial `p` across a ring hom `f` -/
def map : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (C.comp f) X
@[simp] theorem map_monomial (s : σ →₀ ℕ) (a : R) : map f (monomial s a) = monomial s (f a) :=
(eval₂_monomial _ _).trans monomial_eq.symm
@[simp] theorem map_C : ∀ (a : R), map f (C a : mv_polynomial σ R) = C (f a) := map_monomial _ _
@[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ R) = X n := eval₂_X _ _
theorem map_id : ∀ (p : mv_polynomial σ R), map (ring_hom.id R) p = p := eval₂_eta
theorem map_map [comm_semiring S₂]
(g : S₁ →+* S₂)
(p : mv_polynomial σ R) :
map g (map f p) = map (g.comp f) p :=
(eval₂_comp_left (map g) (C.comp f) X p).trans $
begin
congr,
{ ext1 a, simp only [map_C, comp_app, ring_hom.coe_comp], },
{ ext1 n, simp only [map_X, comp_app], }
end
theorem eval₂_eq_eval_map (g : σ → S₁) (p : mv_polynomial σ R) :
p.eval₂ f g = eval g (map f p) :=
begin
unfold map eval, simp only [coe_eval₂_hom],
have h := eval₂_comp_left (eval₂_hom _ g),
dsimp at h,
rw h,
congr,
{ ext1 a, simp only [coe_eval₂_hom, ring_hom.id_apply, comp_app, eval₂_C, ring_hom.coe_comp], },
{ ext1 n, simp only [comp_app, eval₂_X], },
end
lemma eval₂_comp_right {S₂} [comm_semiring S₂]
(k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁)
(p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, k.map_add, (map f).map_add, eval₂_add, hp, hq] },
{ intros p s hp,
rw [eval₂_mul, k.map_mul, (map f).map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] }
end
lemma map_eval₂ (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) :
map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, (map f).map_add, hp, hq, (map f).map_add, eval₂_add] },
{ intros p s hp,
rw [eval₂_mul, (map f).map_mul, hp, (map f).map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] }
end
lemma coeff_map (p : mv_polynomial σ R) : ∀ (m : σ →₀ ℕ), coeff m (map f p) = f (coeff m p) :=
begin
apply mv_polynomial.induction_on p; clear p,
{ intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw f.map_zero },
{ intros p q hp hq m, simp only [hp, hq, (map f).map_add, coeff_add], rw f.map_add },
{ intros p i hp m, simp only [hp, (map f).map_mul, map_X],
simp only [hp, mem_support_iff, coeff_mul_X'],
split_ifs, {refl},
rw f.map_zero }
end
lemma map_injective (hf : function.injective f) :
function.injective (map f : mv_polynomial σ R → mv_polynomial σ S₁) :=
begin
intros p q h,
simp only [ext_iff, coeff_map] at h ⊢,
intro m,
exact hf (h m),
end
lemma map_surjective (hf : function.surjective f) :
function.surjective (map f : mv_polynomial σ R → mv_polynomial σ S₁) :=
λ p, begin
induction p using mv_polynomial.induction_on' with i fr a b ha hb,
{ obtain ⟨r, rfl⟩ := hf fr,
exact ⟨monomial i r, map_monomial _ _ _⟩, },
{ obtain ⟨a, rfl⟩ := ha,
obtain ⟨b, rfl⟩ := hb,
exact ⟨a + b, ring_hom.map_add _ _ _⟩ },
end
/-- If `f` is a left-inverse of `g` then `map f` is a left-inverse of `map g`. -/
lemma map_left_inverse {f : R →+* S₁} {g : S₁ →+* R} (hf : function.left_inverse f g) :
function.left_inverse (map f : mv_polynomial σ R → mv_polynomial σ S₁) (map g) :=
λ x, by rw [map_map, (ring_hom.ext hf : f.comp g = ring_hom.id _), map_id]
/-- If `f` is a right-inverse of `g` then `map f` is a right-inverse of `map g`. -/
lemma map_right_inverse {f : R →+* S₁} {g : S₁ →+* R} (hf : function.right_inverse f g) :
function.right_inverse (map f : mv_polynomial σ R → mv_polynomial σ S₁) (map g) :=
(map_left_inverse hf.left_inverse).right_inverse
@[simp] lemma eval_map (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) :
eval g (map f p) = eval₂ f g p :=
by { apply mv_polynomial.induction_on p; { simp { contextual := tt } } }
@[simp] lemma eval₂_map [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
eval₂ φ g (map f p) = eval₂ (φ.comp f) g p :=
by { rw [← eval_map, ← eval_map, map_map], }
@[simp] lemma eval₂_hom_map_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
eval₂_hom φ g (map f p) = eval₂_hom (φ.comp f) g p :=
eval₂_map f g φ p
@[simp] lemma constant_coeff_map (f : R →+* S₁) (φ : mv_polynomial σ R) :
constant_coeff (mv_polynomial.map f φ) = f (constant_coeff φ) :=
coeff_map f φ 0
lemma constant_coeff_comp_map (f : R →+* S₁) :
(constant_coeff : mv_polynomial σ S₁ →+* S₁).comp (mv_polynomial.map f) = f.comp constant_coeff :=
by { ext; simp }
lemma support_map_subset (p : mv_polynomial σ R) : (map f p).support ⊆ p.support :=
begin
intro x,
simp only [mem_support_iff],
contrapose!,
change p.coeff x = 0 → (map f p).coeff x = 0,
rw coeff_map,
intro hx,
rw hx,
exact ring_hom.map_zero f
end
lemma support_map_of_injective (p : mv_polynomial σ R) {f : R →+* S₁} (hf : injective f) :
(map f p).support = p.support :=
begin
apply finset.subset.antisymm,
{ exact mv_polynomial.support_map_subset _ _ },
intros x hx,
rw mem_support_iff,
contrapose! hx,
simp only [not_not, mem_support_iff],
change (map f p).coeff x = 0 at hx,
rw [coeff_map, ← f.map_zero] at hx,
exact hf hx
end
lemma C_dvd_iff_map_hom_eq_zero
(q : R →+* S₁) (r : R) (hr : ∀ r' : R, q r' = 0 ↔ r ∣ r')
(φ : mv_polynomial σ R) :
C r ∣ φ ↔ map q φ = 0 :=
begin
rw [C_dvd_iff_dvd_coeff, mv_polynomial.ext_iff],
simp only [coeff_map, coeff_zero, hr],
end
lemma map_map_range_eq_iff (f : R →+* S₁) (g : S₁ → R) (hg : g 0 = 0) (φ : mv_polynomial σ S₁) :
map f (finsupp.map_range g hg φ) = φ ↔ ∀ d, f (g (coeff d φ)) = coeff d φ :=
begin
rw mv_polynomial.ext_iff,
apply forall_congr, intro m,
rw [coeff_map],
apply eq_iff_eq_cancel_right.mpr,
refl
end
/-- If `f : S₁ →ₐ[R] S₂` is a morphism of `R`-algebras, then so is `mv_polynomial.map f`. -/
@[simps]
def map_alg_hom [comm_semiring S₂] [algebra R S₁] [algebra R S₂] (f : S₁ →ₐ[R] S₂) :
mv_polynomial σ S₁ →ₐ[R] mv_polynomial σ S₂ :=
{ to_fun := map ↑f,
commutes' := λ r, begin
have h₁ : algebra_map R (mv_polynomial σ S₁) r = C (algebra_map R S₁ r) := rfl,
have h₂ : algebra_map R (mv_polynomial σ S₂) r = C (algebra_map R S₂ r) := rfl,
rw [h₁, h₂, map, eval₂_hom_C, ring_hom.comp_apply, alg_hom.coe_to_ring_hom, alg_hom.commutes],
end,
..map ↑f }
@[simp] lemma map_alg_hom_id [algebra R S₁] :
map_alg_hom (alg_hom.id R S₁) = alg_hom.id R (mv_polynomial σ S₁) :=
alg_hom.ext map_id
@[simp] lemma map_alg_hom_coe_ring_hom [comm_semiring S₂] [algebra R S₁] [algebra R S₂]
(f : S₁ →ₐ[R] S₂) :
↑(map_alg_hom f : _ →ₐ[R] mv_polynomial σ S₂) =
(map ↑f : mv_polynomial σ S₁ →+* mv_polynomial σ S₂) :=
ring_hom.mk_coe _ _ _ _ _
end map
section aeval
/-! ### The algebra of multivariate polynomials -/
variables [algebra R S₁] [comm_semiring S₂]
variables (f : σ → S₁)
/-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism
from multivariate polynomials over `σ` to `S₁`. -/
def aeval : mv_polynomial σ R →ₐ[R] S₁ :=
{ commutes' := λ r, eval₂_C _ _ _
.. eval₂_hom (algebra_map R S₁) f }
theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R S₁) f p := rfl
lemma aeval_eq_eval₂_hom (p : mv_polynomial σ R) :
aeval f p = eval₂_hom (algebra_map R S₁) f p := rfl
@[simp] lemma aeval_X (s : σ) : aeval f (X s : mv_polynomial _ R) = f s := eval₂_X _ _ _
@[simp] lemma aeval_C (r : R) : aeval f (C r) = algebra_map R S₁ r := eval₂_C _ _ _
theorem aeval_unique (φ : mv_polynomial σ R →ₐ[R] S₁) :
φ = aeval (φ ∘ X) :=
by { ext i, simp }
lemma comp_aeval {B : Type*} [comm_semiring B] [algebra R B]
(φ : S₁ →ₐ[R] B) :
φ.comp (aeval f) = aeval (λ i, φ (f i)) :=
by { ext i, simp }
@[simp] lemma map_aeval {B : Type*} [comm_semiring B]
(g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) :
φ (aeval g p) = (eval₂_hom (φ.comp (algebra_map R S₁)) (λ i, φ (g i)) p) :=
by { rw ← comp_eval₂_hom, refl }
@[simp] lemma eval₂_hom_zero (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂_hom f (0 : σ → S₂) p = f (constant_coeff p) :=
begin
suffices : eval₂_hom f (0 : σ → S₂) = f.comp constant_coeff,
from ring_hom.congr_fun this p,
ext; simp
end
@[simp] lemma eval₂_hom_zero' (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂_hom f (λ _, 0 : σ → S₂) p = f (constant_coeff p) :=
eval₂_hom_zero f p
@[simp] lemma aeval_zero (p : mv_polynomial σ R) :
aeval (0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) :=
eval₂_hom_zero (algebra_map R S₁) p
@[simp] lemma aeval_zero' (p : mv_polynomial σ R) :
aeval (λ _, 0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) :=
aeval_zero p
lemma aeval_monomial (g : σ → S₁) (d : σ →₀ ℕ) (r : R) :
aeval g (monomial d r) = algebra_map _ _ r * d.prod (λ i k, g i ^ k) :=
eval₂_hom_monomial _ _ _ _
lemma eval₂_hom_eq_zero (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R)
(h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, g i = 0) :
eval₂_hom f g φ = 0 :=
begin
rw [φ.as_sum, ring_hom.map_sum, finset.sum_eq_zero],
intros d hd,
obtain ⟨i, hi, hgi⟩ : ∃ i ∈ d.support, g i = 0 := h d (finsupp.mem_support_iff.mp hd),
rw [eval₂_hom_monomial, finsupp.prod, finset.prod_eq_zero hi, mul_zero],
rw [hgi, zero_pow],
rwa [pos_iff_ne_zero, ← finsupp.mem_support_iff]
end
lemma aeval_eq_zero [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R)
(h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, f i = 0) :
aeval f φ = 0 :=
eval₂_hom_eq_zero _ _ _ h
lemma aeval_sum {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) :
aeval f (∑ i in s, φ i) = ∑ i in s, aeval f (φ i) :=
(mv_polynomial.aeval f).map_sum _ _
@[to_additive]
lemma aeval_prod {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) :
aeval f (∏ i in s, φ i) = ∏ i in s, aeval f (φ i) :=
(mv_polynomial.aeval f).map_prod _ _
variable (R)
lemma _root_.algebra.adjoin_range_eq_range_aeval :
algebra.adjoin R (set.range f) = (mv_polynomial.aeval f).range :=
by simp only [← algebra.map_top, ← mv_polynomial.adjoin_range_X, alg_hom.map_adjoin,
← set.range_comp, (∘), mv_polynomial.aeval_X]
theorem _root_.algebra.adjoin_eq_range (s : set S₁) :
algebra.adjoin R s = (mv_polynomial.aeval (coe : s → S₁)).range :=
by rw [← algebra.adjoin_range_eq_range_aeval, subtype.range_coe]
end aeval
section aeval_tower
variables {S A B : Type*} [comm_semiring S] [comm_semiring A] [comm_semiring B]
variables [algebra S R] [algebra S A] [algebra S B]
/-- Version of `aeval` for defining algebra homs out of `mv_polynomial σ R` over a smaller base ring
than `R`. -/
def aeval_tower (f : R →ₐ[S] A) (x : σ → A) : mv_polynomial σ R →ₐ[S] A :=
{ commutes' := λ r,
by simp [is_scalar_tower.algebra_map_eq S R (mv_polynomial σ R), algebra_map_eq],
..eval₂_hom ↑f x }
variables (g : R →ₐ[S] A) (y : σ → A)
@[simp] lemma aeval_tower_X (i : σ): aeval_tower g y (X i) = y i := eval₂_X _ _ _
@[simp] lemma aeval_tower_C (x : R) : aeval_tower g y (C x) = g x := eval₂_C _ _ _
@[simp] lemma aeval_tower_comp_C : ((aeval_tower g y : mv_polynomial σ R →+* A).comp C) = g :=
ring_hom.ext $ aeval_tower_C _ _
@[simp] lemma aeval_tower_algebra_map (x : R) :
aeval_tower g y (algebra_map R (mv_polynomial σ R) x) = g x := eval₂_C _ _ _
@[simp] lemma aeval_tower_comp_algebra_map :
(aeval_tower g y : mv_polynomial σ R →+* A).comp (algebra_map R (mv_polynomial σ R)) = g :=
aeval_tower_comp_C _ _
lemma aeval_tower_to_alg_hom (x : R) :
aeval_tower g y (is_scalar_tower.to_alg_hom S R (mv_polynomial σ R) x) = g x :=
aeval_tower_algebra_map _ _ _
@[simp] lemma aeval_tower_comp_to_alg_hom :
(aeval_tower g y).comp (is_scalar_tower.to_alg_hom S R (mv_polynomial σ R)) = g :=
alg_hom.coe_ring_hom_injective $ aeval_tower_comp_algebra_map _ _
@[simp] lemma aeval_tower_id : aeval_tower (alg_hom.id S S) =
(aeval : (σ → S) → (mv_polynomial σ S →ₐ[S] S)) :=
by { ext, simp only [aeval_tower_X, aeval_X] }
@[simp] lemma aeval_tower_of_id : aeval_tower (algebra.of_id S A) =
(aeval : (σ → A) → (mv_polynomial σ S →ₐ[S] A)) :=
by { ext, simp only [aeval_X, aeval_tower_X] }
end aeval_tower
end comm_semiring
end mv_polynomial
|
c48f6c4b9114e64ec83c6d1e490c386f10bf7e07 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Lean/Meta/Tactic/Replace.lean | 6d50ac8f760cea79f988c097a2b55a9c3980e0d5 | [
"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 | 5,397 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.ForEachExpr
import Lean.Meta.AppBuilder
import Lean.Meta.MatchUtil
import Lean.Meta.Tactic.Util
import Lean.Meta.Tactic.Revert
import Lean.Meta.Tactic.Intro
import Lean.Meta.Tactic.Clear
import Lean.Meta.Tactic.Assert
namespace Lean.Meta
/--
Convert the given goal `Ctx |- target` into `Ctx |- targetNew` using an equality proof `eqProof : target = targetNew`.
It assumes `eqProof` has type `target = targetNew` -/
def replaceTargetEq (mvarId : MVarId) (targetNew : Expr) (eqProof : Expr) : MetaM MVarId :=
withMVarContext mvarId do
checkNotAssigned mvarId `replaceTarget
let tag ← getMVarTag mvarId
let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag
let target ← getMVarType mvarId
let u ← getLevel target
let eq ← mkEq target targetNew
let newProof ← mkExpectedTypeHint eqProof eq
let val := mkAppN (Lean.mkConst `Eq.mpr [u]) #[target, targetNew, eqProof, mvarNew]
assignExprMVar mvarId val
pure mvarNew.mvarId!
/--
Convert the given goal `Ctx | target` into `Ctx |- targetNew`. It assumes the goals are definitionally equal.
We use the proof term
```
@id target mvarNew
```
to create a checkpoint. -/
def replaceTargetDefEq (mvarId : MVarId) (targetNew : Expr) : MetaM MVarId :=
withMVarContext mvarId do
checkNotAssigned mvarId `change
let target ← getMVarType mvarId
if target == targetNew then pure mvarId
else
let tag ← getMVarTag mvarId
let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag
let newVal ← mkExpectedTypeHint mvarNew target
assignExprMVar mvarId mvarNew
pure mvarNew.mvarId!
/--
Replace type of the local declaration with id `fvarId` with one with the same user-facing name, but with type `typeNew`.
This method assumes `eqProof` is a proof that type of `fvarId` is equal to `typeNew`.
This tactic actually adds a new declaration and (try to) clear the old one.
If the old one cannot be cleared, then at least its user-facing name becomes inaccessible.
Remark: the new declaration is added immediately after `fvarId`.
`typeNew` must be well-formed at `fvarId`, but `eqProof` may contain variables declared after `fvarId`. -/
def replaceLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (eqProof : Expr) : MetaM AssertAfterResult :=
withMVarContext mvarId do
let localDecl ← getLocalDecl fvarId
let typeNewPr ← mkEqMP eqProof (mkFVar fvarId)
-- `typeNew` may contain variables that occur after `fvarId`.
-- Thus, we use the auxiliary function `findMaxFVar` to ensure `typeNew` is well-formed at the position we are inserting it.
let (_, localDecl') ← findMaxFVar typeNew |>.run localDecl
let result ← assertAfter mvarId localDecl'.fvarId localDecl.userName typeNew typeNewPr
(do let mvarIdNew ← clear result.mvarId fvarId
pure { result with mvarId := mvarIdNew })
<|> pure result
where
findMaxFVar (e : Expr) : StateRefT LocalDecl MetaM Unit :=
e.forEach' fun e => do
if e.isFVar then
let localDecl' ← getLocalDecl e.fvarId!
modify fun localDecl => if localDecl'.index > localDecl.index then localDecl' else localDecl
return false
else
return e.hasFVar
def change (mvarId : MVarId) (targetNew : Expr) (checkDefEq := true) : MetaM MVarId := withMVarContext mvarId do
let target ← getMVarType mvarId
if checkDefEq then
unless (← isDefEq target targetNew) do
throwTacticEx `change mvarId m!"given type{indentExpr targetNew}\nis not definitionally equal to{indentExpr target}"
replaceTargetDefEq mvarId targetNew
def changeLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (checkDefEq := true) : MetaM MVarId := do
checkNotAssigned mvarId `changeLocalDecl
let (xs, mvarId) ← revert mvarId #[fvarId] true
withMVarContext mvarId do
let numReverted := xs.size
let target ← getMVarType mvarId
let check (typeOld : Expr) : MetaM Unit := do
if checkDefEq then
unless (← isDefEq typeNew typeOld) do
throwTacticEx `changeHypothesis mvarId m!"given type{indentExpr typeNew}\nis not definitionally equal to{indentExpr typeOld}"
let finalize (targetNew : Expr) : MetaM MVarId := do
let mvarId ← replaceTargetDefEq mvarId targetNew
let (_, mvarId) ← introNP mvarId numReverted
pure mvarId
match target with
| Expr.forallE n d b c => do check d; finalize (mkForall n c.binderInfo typeNew b)
| Expr.letE n t v b _ => do check t; finalize (mkLet n typeNew v b)
| _ => throwTacticEx `changeHypothesis mvarId "unexpected auxiliary target"
def modifyTarget (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do
withMVarContext mvarId do
checkNotAssigned mvarId `modifyTarget
change mvarId (← f (← getMVarType mvarId)) (checkDefEq := false)
def modifyTargetEqLHS (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do
modifyTarget mvarId fun target => do
if let some (_, lhs, rhs) ← matchEq? target then
mkEq (← f lhs) rhs
else
throwTacticEx `modifyTargetEqLHS mvarId m!"equality expected{indentExpr target}"
end Lean.Meta
|
76fec54174f5a7fb8c8e93d6da2a9c7767daf45f | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/beginend3.lean | 01335cd5cdd289be7be5799305682d1d6abfda0b | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 285 | lean | import tools.tactic logic
open tactic
theorem foo (A : Type) (a b c : A) : a = b → b = c → a = c ∧ c = a :=
begin
intros (Hab, Hbc),
apply and.intro,
apply eq.trans,
rotate 2,
apply eq.trans,
apply (eq.symm Hbc),
apply (eq.symm Hab),
apply Hab,
apply Hbc,
end
|
492679958ed74eab7152d1e227b7b5e6063ab418 | b9d8165d695e844c92d9d4cdcac7b5ab9efe09f7 | /src/analysis/calculus/tangent_cone.lean | 36e1308f2d06a0702676cfe9ba16bea562506049 | [
"Apache-2.0"
] | permissive | spapinistarkware/mathlib | e917d9c44bf85ef51db18e7a11615959f714efc5 | 0a9a1ff463a1f26e27d7c391eb7f6334f0d90383 | refs/heads/master | 1,606,808,129,547 | 1,577,478,369,000 | 1,577,478,369,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,515 | 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.convex analysis.normed_space.bounded_linear_maps analysis.specific_limits
/-!
# Tangent cone
In this file, we define two predicates `unique_diff_within_at 𝕜 s x` and `unique_diff_on 𝕜 s`
ensuring that, if a function has two derivatives, then they have to coincide. As a direct
definition of this fact (quantifying on all target types and all functions) would depend on
universes, we use a more intrinsic definition: if all the possible tangent directions to the set
`s` at the point `x` span a dense subset of the whole subset, it is easy to check that the
derivative has to be unique.
Therefore, we introduce the set of all tangent directions, named `tangent_cone_at`,
and express `unique_diff_within_at` and `unique_diff_on` in terms of it.
One should however think of this definition as an implementation detail: the only reason to
introduce the predicates `unique_diff_within_at` and `unique_diff_on` is to ensure the uniqueness
of the derivative. This is why their names reflect their uses, and not how they are defined.
## Implementation details
Note that this file is imported by `deriv.lean`. Hence, derivatives are not defined yet. The
property of uniqueness of the derivative is therefore proved in `deriv.lean`, but based on the
properties of the tangent cone we prove here.
-/
variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F]
variables {G : Type*} [normed_group G] [normed_space ℝ G]
set_option class.instance_max_depth 50
open filter set
open_locale topological_space
/-- The set of all tangent directions to the set `s` at the point `x`. -/
def tangent_cone_at (s : set E) (x : E) : set E :=
{y : E | ∃(c : ℕ → 𝕜) (d : ℕ → E), {n:ℕ | x + d n ∈ s} ∈ (at_top : filter ℕ) ∧
(tendsto (λn, ∥c n∥) at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))}
/-- A property ensuring that the tangent cone to `s` at `x` spans a dense subset of the whole space.
The main role of this property is to ensure that the differential within `s` at `x` is unique,
hence this name. The uniqueness it asserts is proved in `unique_diff_within_at.eq` in `deriv.lean`.
To avoid pathologies in dimension 0, we also require that `x` belongs to the closure of `s` (which
is automatic when `E` is not `0`-dimensional).
-/
def unique_diff_within_at (s : set E) (x : E) : Prop :=
closure ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E) = univ ∧ x ∈ closure s
/-- A property ensuring that the tangent cone to `s` at any of its points spans a dense subset of
the whole space. The main role of this property is to ensure that the differential along `s` is
unique, hence this name. The uniqueness it asserts is proved in `unique_diff_on.eq` in
`deriv.lean`. -/
def unique_diff_on (s : set E) : Prop :=
∀x ∈ s, unique_diff_within_at 𝕜 s x
variables {𝕜} {x y : E} {s t : set E}
section tangent_cone
/- This section is devoted to the properties of the tangent cone. -/
open normed_field
lemma tangent_cone_univ : tangent_cone_at 𝕜 univ x = univ :=
begin
refine univ_subset_iff.1 (λy hy, _),
rcases exists_one_lt_norm 𝕜 with ⟨w, hw⟩,
refine ⟨λn, w^n, λn, (w^n)⁻¹ • y, univ_mem_sets' (λn, mem_univ _), _, _⟩,
{ simp only [norm_pow],
exact tendsto_pow_at_top_at_top_of_gt_1 hw },
{ convert tendsto_const_nhds,
ext n,
have : w ^ n * (w ^ n)⁻¹ = 1,
{ apply mul_inv_cancel,
apply pow_ne_zero,
simpa [norm_eq_zero] using (ne_of_lt (lt_trans zero_lt_one hw)).symm },
rw [smul_smul, this, one_smul] }
end
lemma tangent_cone_mono (h : s ⊆ t) :
tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x :=
begin
rintros y ⟨c, d, ds, ctop, clim⟩,
exact ⟨c, d, mem_sets_of_superset ds (λn hn, h hn), ctop, clim⟩
end
/-- Auxiliary lemma ensuring that, under the assumptions defining the tangent cone,
the sequence `d` tends to 0 at infinity. -/
lemma tangent_cone_at.lim_zero {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E}
(hc : tendsto (λn, ∥c n∥) l at_top) (hd : tendsto (λn, c n • d n) l (𝓝 y)) :
tendsto d l (𝓝 0) :=
begin
have A : tendsto (λn, ∥c n∥⁻¹) l (𝓝 0) :=
tendsto_inverse_at_top_nhds_0.comp hc,
have B : tendsto (λn, ∥c n • d n∥) l (𝓝 ∥y∥) :=
(continuous_norm.tendsto _).comp hd,
have C : tendsto (λn, ∥c n∥⁻¹ * ∥c n • d n∥) l (𝓝 (0 * ∥y∥)) := A.mul B,
rw zero_mul at C,
have : {n | ∥c n∥⁻¹ * ∥c n • d n∥ = ∥d n∥} ∈ l,
{ apply mem_sets_of_superset (ne_mem_of_tendsto_norm_at_top hc 0) (λn hn, _),
rw [mem_set_of_eq, norm_smul, ← mul_assoc, inv_mul_cancel, one_mul],
rwa [ne.def, norm_eq_zero] },
have D : tendsto (λ n, ∥d n∥) l (𝓝 0) :=
tendsto.congr' this C,
rw tendsto_zero_iff_norm_tendsto_zero,
exact D
end
/-- Intersecting with a neighborhood of the point does not change the tangent cone. -/
lemma tangent_cone_inter_nhds (ht : t ∈ 𝓝 x) :
tangent_cone_at 𝕜 (s ∩ t) x = tangent_cone_at 𝕜 s x :=
begin
refine subset.antisymm (tangent_cone_mono (inter_subset_left _ _)) _,
rintros y ⟨c, d, ds, ctop, clim⟩,
refine ⟨c, d, _, ctop, clim⟩,
have : {n : ℕ | x + d n ∈ t} ∈ at_top,
{ have : tendsto (λn, x + d n) at_top (𝓝 (x + 0)) :=
tendsto_const_nhds.add (tangent_cone_at.lim_zero at_top ctop clim),
rw add_zero at this,
exact mem_map.1 (this ht) },
exact inter_mem_sets ds this
end
/-- The tangent cone of a product contains the tangent cone of its left factor. -/
lemma subset_tangent_cone_prod_left {t : set F} {y : F} (ht : y ∈ closure t) :
set.prod (tangent_cone_at 𝕜 s x) {(0 : F)} ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) :=
begin
rintros ⟨v, w⟩ ⟨⟨c, d, hd, hc, hy⟩, hw⟩,
have : w = 0, by simpa using hw,
rw this,
have : ∀n, ∃d', y + d' ∈ t ∧ ∥c n • d'∥ ≤ ((1:ℝ)/2)^n,
{ assume n,
have c_pos : 0 < 1 + ∥c n∥ :=
add_pos_of_pos_of_nonneg zero_lt_one (norm_nonneg _),
rcases metric.mem_closure_iff'.1 ht ((1 + ∥c n∥)⁻¹ * (1/2)^n) _ with ⟨z, z_pos, hz⟩,
refine ⟨z - y, _, _⟩,
{ convert z_pos, abel },
{ rw [norm_smul, ← dist_eq_norm, dist_comm],
calc ∥c n∥ * dist y z ≤ (1 + ∥c n∥) * ((1 + ∥c n∥)⁻¹ * (1/2)^n) :
begin
apply mul_le_mul _ (le_of_lt hz) dist_nonneg (le_of_lt c_pos),
simp only [zero_le_one, le_add_iff_nonneg_left]
end
... = (1/2)^n :
begin
rw [← mul_assoc, mul_inv_cancel, one_mul],
exact ne_of_gt c_pos
end },
{ apply mul_pos (inv_pos c_pos) (pow_pos _ _),
norm_num } },
choose d' hd' using this,
refine ⟨c, λn, (d n, d' n), _, hc, _⟩,
show {n : ℕ | (x, y) + (d n, d' n) ∈ set.prod s t} ∈ at_top,
{ apply filter.mem_sets_of_superset hd,
assume n hn,
simp at hn,
simp [hn, (hd' n).1] },
{ apply tendsto_prod_mk_nhds hy,
change tendsto (λ (n : ℕ), c n • d' n) at_top (𝓝 0),
rw tendsto_zero_iff_norm_tendsto_zero,
refine squeeze_zero (λn, norm_nonneg _) (λn, (hd' n).2) _,
apply tendsto_pow_at_top_nhds_0_of_lt_1; norm_num }
end
/-- The tangent cone of a product contains the tangent cone of its right factor. -/
lemma subset_tangent_cone_prod_right {t : set F} {y : F}
(hs : x ∈ closure s) :
set.prod {(0 : E)} (tangent_cone_at 𝕜 t y) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) :=
begin
rintros ⟨v, w⟩ ⟨hv, ⟨c, d, hd, hc, hy⟩⟩,
have : v = 0, by simpa using hv,
rw this,
have : ∀n, ∃d', x + d' ∈ s ∧ ∥c n • d'∥ ≤ ((1:ℝ)/2)^n,
{ assume n,
have c_pos : 0 < 1 + ∥c n∥ :=
add_pos_of_pos_of_nonneg zero_lt_one (norm_nonneg _),
rcases metric.mem_closure_iff'.1 hs ((1 + ∥c n∥)⁻¹ * (1/2)^n) _ with ⟨z, z_pos, hz⟩,
refine ⟨z - x, _, _⟩,
{ convert z_pos, abel },
{ rw [norm_smul, ← dist_eq_norm, dist_comm],
calc ∥c n∥ * dist x z ≤ (1 + ∥c n∥) * ((1 + ∥c n∥)⁻¹ * (1/2)^n) :
begin
apply mul_le_mul _ (le_of_lt hz) dist_nonneg (le_of_lt c_pos),
simp only [zero_le_one, le_add_iff_nonneg_left]
end
... = (1/2)^n :
begin
rw [← mul_assoc, mul_inv_cancel, one_mul],
exact ne_of_gt c_pos
end },
{ apply mul_pos (inv_pos c_pos) (pow_pos _ _),
norm_num } },
choose d' hd' using this,
refine ⟨c, λn, (d' n, d n), _, hc, _⟩,
show {n : ℕ | (x, y) + (d' n, d n) ∈ set.prod s t} ∈ at_top,
{ apply filter.mem_sets_of_superset hd,
assume n hn,
simp at hn,
simp [hn, (hd' n).1] },
{ apply tendsto_prod_mk_nhds _ hy,
change tendsto (λ (n : ℕ), c n • d' n) at_top (𝓝 0),
rw tendsto_zero_iff_norm_tendsto_zero,
refine squeeze_zero (λn, norm_nonneg _) (λn, (hd' n).2) _,
apply tendsto_pow_at_top_nhds_0_of_lt_1; norm_num }
end
/-- If a subset of a real vector space contains a segment, then the direction of this
segment belongs to the tangent cone at its endpoints. -/
lemma mem_tangent_cone_of_segment_subset {s : set G} {x y : G} (h : segment x y ⊆ s) :
y - x ∈ tangent_cone_at ℝ s x :=
begin
let w : ℝ := 2,
let c := λn:ℕ, (2:ℝ)^n,
let d := λn:ℕ, (c n)⁻¹ • (y-x),
refine ⟨c, d, filter.univ_mem_sets' (λn, h _), _, _⟩,
show x + d n ∈ segment x y,
{ refine ⟨(c n)⁻¹, ⟨_, _⟩, _⟩,
{ rw inv_nonneg, apply pow_nonneg, norm_num },
{ apply inv_le_one, apply one_le_pow_of_one_le, norm_num },
{ simp only [d], abel } },
show filter.tendsto (λ (n : ℕ), ∥c n∥) filter.at_top filter.at_top,
{ have : (λ (n : ℕ), ∥c n∥) = c,
by { ext n, exact abs_of_nonneg (pow_nonneg (by norm_num) _) },
rw this,
exact tendsto_pow_at_top_at_top_of_gt_1 (by norm_num) },
show filter.tendsto (λ (n : ℕ), c n • d n) filter.at_top (𝓝 (y - x)),
{ have : (λ (n : ℕ), c n • d n) = (λn, y - x),
{ ext n,
simp only [d, smul_smul],
rw [mul_inv_cancel, one_smul],
exact pow_ne_zero _ (by norm_num) },
rw this,
apply tendsto_const_nhds }
end
end tangent_cone
section unique_diff
/- This section is devoted to properties of the predicates `unique_diff_within_at` and
`unique_diff_on`. -/
lemma unique_diff_within_at_univ : unique_diff_within_at 𝕜 univ x :=
by { rw [unique_diff_within_at, tangent_cone_univ], simp }
lemma unique_diff_on_univ : unique_diff_on 𝕜 (univ : set E) :=
λx hx, unique_diff_within_at_univ
lemma unique_diff_within_at.mono (h : unique_diff_within_at 𝕜 s x) (st : s ⊆ t) :
unique_diff_within_at 𝕜 t x :=
begin
unfold unique_diff_within_at at *,
rw [← univ_subset_iff, ← h.1],
exact ⟨closure_mono (submodule.span_mono (tangent_cone_mono st)), closure_mono st h.2⟩
end
lemma unique_diff_within_at_inter (ht : t ∈ 𝓝 x) :
unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x :=
begin
have : x ∈ closure (s ∩ t) ↔ x ∈ closure s,
{ split,
{ assume h, exact closure_mono (inter_subset_left _ _) h },
{ assume h,
rw mem_closure_iff_nhds at ⊢ h,
assume u hu,
rw [inter_comm s t, ← inter_assoc],
exact h _ (filter.inter_mem_sets hu ht) } },
rw [unique_diff_within_at, unique_diff_within_at, tangent_cone_inter_nhds ht, this]
end
lemma unique_diff_within_at.inter (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝 x) :
unique_diff_within_at 𝕜 (s ∩ t) x :=
(unique_diff_within_at_inter ht).2 hs
lemma unique_diff_within_at_inter' (ht : t ∈ nhds_within x s) :
unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x :=
begin
split,
{ exact λH, H.mono (inter_subset_left _ _) },
{ assume H,
rw mem_nhds_within at ht,
rcases ht with ⟨u, u_open, xu, us⟩,
have : u ∈ 𝓝 x := mem_nhds_sets u_open xu,
rw ← unique_diff_within_at_inter this at H,
apply H.mono,
exact λ p ⟨ps, pu⟩, ⟨ps, us ⟨pu, ps⟩⟩ }
end
lemma unique_diff_within_at.inter' (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ nhds_within x s) :
unique_diff_within_at 𝕜 (s ∩ t) x :=
(unique_diff_within_at_inter' ht).2 hs
lemma is_open.unique_diff_within_at (hs : is_open s) (xs : x ∈ s) : unique_diff_within_at 𝕜 s x :=
begin
have := unique_diff_within_at_univ.inter (mem_nhds_sets hs xs),
rwa univ_inter at this
end
lemma unique_diff_on.inter (hs : unique_diff_on 𝕜 s) (ht : is_open t) : unique_diff_on 𝕜 (s ∩ t) :=
λx hx, (hs x hx.1).inter (mem_nhds_sets ht hx.2)
lemma is_open.unique_diff_on (hs : is_open s) : unique_diff_on 𝕜 s :=
λx hx, is_open.unique_diff_within_at hs hx
/-- The product of two sets of unique differentiability at points `x` and `y` has unique
differentiability at `(x, y)`. -/
lemma unique_diff_within_at.prod {t : set F} {y : F}
(hs : unique_diff_within_at 𝕜 s x) (ht : unique_diff_within_at 𝕜 t y) :
unique_diff_within_at 𝕜 (set.prod s t) (x, y) :=
begin
rw [unique_diff_within_at, ← univ_subset_iff] at ⊢ hs ht,
split,
{ assume v _,
rw metric.mem_closure_iff',
assume ε ε_pos,
rcases v with ⟨v₁, v₂⟩,
rcases metric.mem_closure_iff'.1 (hs.1 (mem_univ v₁)) ε ε_pos with ⟨w₁, w₁_mem, h₁⟩,
rcases metric.mem_closure_iff'.1 (ht.1 (mem_univ v₂)) ε ε_pos with ⟨w₂, w₂_mem, h₂⟩,
have I₁ : (w₁, (0 : F)) ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 (set.prod s t) (x, y)),
{ apply submodule.span_induction w₁_mem,
{ assume w hw,
have : (w, (0 : F)) ∈ (set.prod (tangent_cone_at 𝕜 s x) {(0 : F)}),
{ rw mem_prod,
simp [hw],
apply mem_insert },
have : (w, (0 : F)) ∈ tangent_cone_at 𝕜 (set.prod s t) (x, y) :=
subset_tangent_cone_prod_left ht.2 this,
exact submodule.subset_span this },
{ exact submodule.zero_mem _ },
{ assume a b ha hb,
have : (a, (0 : F)) + (b, (0 : F)) = (a + b, (0 : F)), by simp,
rw ← this,
exact submodule.add_mem _ ha hb },
{ assume c a ha,
have : c • (0 : F) = (0 : F), by simp,
rw ← this,
exact submodule.smul_mem _ _ ha } },
have I₂ : ((0 : E), w₂) ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 (set.prod s t) (x, y)),
{ apply submodule.span_induction w₂_mem,
{ assume w hw,
have : ((0 : E), w) ∈ (set.prod {(0 : E)} (tangent_cone_at 𝕜 t y)),
{ rw mem_prod,
simp [hw],
apply mem_insert },
have : ((0 : E), w) ∈ tangent_cone_at 𝕜 (set.prod s t) (x, y) :=
subset_tangent_cone_prod_right hs.2 this,
exact submodule.subset_span this },
{ exact submodule.zero_mem _ },
{ assume a b ha hb,
have : ((0 : E), a) + ((0 : E), b) = ((0 : E), a + b), by simp,
rw ← this,
exact submodule.add_mem _ ha hb },
{ assume c a ha,
have : c • (0 : E) = (0 : E), by simp,
rw ← this,
exact submodule.smul_mem _ _ ha } },
have I : (w₁, w₂) ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 (set.prod s t) (x, y)),
{ have : (w₁, (0 : F)) + ((0 : E), w₂) = (w₁, w₂), by simp,
rw ← this,
exact submodule.add_mem _ I₁ I₂ },
refine ⟨(w₁, w₂), I, _⟩,
simp [dist, h₁, h₂] },
{ simp [closure_prod_eq, mem_prod_iff, hs.2, ht.2] }
end
/-- The product of two sets of unique differentiability is a set of unique differentiability. -/
lemma unique_diff_on.prod {t : set F} (hs : unique_diff_on 𝕜 s) (ht : unique_diff_on 𝕜 t) :
unique_diff_on 𝕜 (set.prod s t) :=
λ ⟨x, y⟩ h, unique_diff_within_at.prod (hs x h.1) (ht y h.2)
/-- In a real vector space, a convex set with nonempty interior is a set of unique
differentiability. -/
theorem unique_diff_on_convex {s : set G} (conv : convex s) (hs : interior s ≠ ∅) :
unique_diff_on ℝ s :=
begin
assume x xs,
have A : ∀v, ∃a∈ tangent_cone_at ℝ s x, ∃b∈ tangent_cone_at ℝ s x, ∃δ>(0:ℝ), δ • v = b-a,
{ assume v,
rcases ne_empty_iff_exists_mem.1 hs with ⟨y, hy⟩,
have ys : y ∈ s := interior_subset hy,
have : ∃(δ : ℝ), 0<δ ∧ y + δ • v ∈ s,
{ by_cases h : ∥v∥ = 0,
{ exact ⟨1, zero_lt_one, by simp [(norm_eq_zero _).1 h, ys]⟩ },
{ rcases mem_interior.1 hy with ⟨u, us, u_open, yu⟩,
rcases metric.is_open_iff.1 u_open y yu with ⟨ε, εpos, hε⟩,
let δ := (ε/2) / ∥v∥,
have δpos : 0 < δ := div_pos (half_pos εpos) (lt_of_le_of_ne (norm_nonneg _) (ne.symm h)),
have : y + δ • v ∈ s,
{ apply us (hε _),
rw [metric.mem_ball, dist_eq_norm],
calc ∥(y + δ • v) - y ∥ = ∥δ • v∥ : by {congr' 1, abel }
... = ∥δ∥ * ∥v∥ : norm_smul _ _
... = δ * ∥v∥ : by simp only [norm, abs_of_nonneg (le_of_lt δpos)]
... = ε /2 : div_mul_cancel _ h
... < ε : half_lt_self εpos },
exact ⟨δ, δpos, this⟩ } },
rcases this with ⟨δ, δpos, hδ⟩,
refine ⟨y-x, _, (y + δ • v) - x, _, δ, δpos, by abel⟩,
exact mem_tangent_cone_of_segment_subset (convex_segment_iff.1 conv x y xs ys),
exact mem_tangent_cone_of_segment_subset (convex_segment_iff.1 conv x _ xs hδ) },
have B : ∀v:G, v ∈ submodule.span ℝ (tangent_cone_at ℝ s x),
{ assume v,
rcases A v with ⟨a, ha, b, hb, δ, hδ, h⟩,
have : v = δ⁻¹ • (b - a),
by { rw [← h, smul_smul, inv_mul_cancel, one_smul], exact (ne_of_gt hδ) },
rw this,
exact submodule.smul_mem _ _
(submodule.sub_mem _ (submodule.subset_span hb) (submodule.subset_span ha)) },
refine ⟨univ_subset_iff.1 (λv hv, subset_closure (B v)), subset_closure xs⟩
end
/-- The real interval `[0, 1]` is a set of unique differentiability. -/
lemma unique_diff_on_Icc_zero_one : unique_diff_on ℝ (Icc (0:ℝ) 1) :=
begin
apply unique_diff_on_convex (convex_Icc 0 1),
have : (1/(2:ℝ)) ∈ interior (Icc (0:ℝ) 1) :=
mem_interior.2 ⟨Ioo (0:ℝ) 1, Ioo_subset_Icc_self, is_open_Ioo, by norm_num, by norm_num⟩,
exact ne_empty_of_mem this,
end
end unique_diff
|
b6625fbaa2d6115f7cc43e4c1298eeacb40d5815 | d9ed0fce1c218297bcba93e046cb4e79c83c3af8 | /library/init/meta/declaration.lean | 7f1c8a582b7b42c7e6d8fdfba7ea5ebe0d4d77b3 | [
"Apache-2.0"
] | permissive | leodemoura/lean_clone | 005c63aa892a6492f2d4741ee3c2cb07a6be9d7f | cc077554b584d39bab55c360bc12a6fe7957afe6 | refs/heads/master | 1,610,506,475,484 | 1,482,348,354,000 | 1,482,348,543,000 | 77,091,586 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,032 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.expr init.meta.name init.meta.task
/-
Reducibility hints are used in the convertibility checker.
When trying to solve a constraint such a
(f ...) =?= (g ...)
where f and g are definitions, the checker has to decide which one will be unfolded.
If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque,
Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev,
Else if f and g are regular, then we unfold the one with the biggest definitional height.
Otherwise both are unfolded.
The arguments of the `regular` constructor are: the definitional height and the flag `self_opt`.
The definitional height is by default computed by the kernel. It only takes into account
other regular definitions used in a definition. When creating declarations using meta-programming,
we can specify the definitional depth manually.
For definitions marked as regular, we also have a hint for constraints such as
(f a) =?= (f b)
if self_opt == true, then checker will first try to solve (a =?= b), only if it fails,
it unfolds f.
Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a
declaration during type checking.
Remark: the reducibility_hints are not related to the attributes: reducible/irrelevance/semireducible.
These attributes are used by the elaborator. The reducibility_hints are used by the kernel (and elaborator).
Moreover, the reducibility_hints cannot be changed after a declaration is added to the kernel.
-/
inductive reducibility_hints
| opaque : reducibility_hints
| abbrev : reducibility_hints
| regular : nat → bool → reducibility_hints
/- Reflect a C++ declaration object. The VM replaces it with the C++ implementation. -/
meta inductive declaration
/- definition: name, list universe parameters, type, value, is_trusted -/
| defn : name → list name → expr → expr → reducibility_hints → bool → declaration
/- theorem: name, list universe parameters, type, value (remark: theorems are always trusted) -/
| thm : name → list name → expr → task expr → declaration
/- constant assumption: name, list universe parameters, type, is_trusted -/
| cnst : name → list name → expr → bool → declaration
/- axiom : name → list universe parameters, type (remark: axioms are always trusted) -/
| ax : name → list name → expr → declaration
meta def declaration.to_name : declaration → name
| (declaration.defn n ls t v h tr) := n
| (declaration.thm n ls t v) := n
| (declaration.cnst n ls t tr) := n
| (declaration.ax n ls t) := n
meta def declaration.univ_params : declaration → list name
| (declaration.defn n ls t v h tr) := ls
| (declaration.thm n ls t v) := ls
| (declaration.cnst n ls t tr) := ls
| (declaration.ax n ls t) := ls
meta def declaration.type : declaration → expr
| (declaration.defn n ls t v h tr) := t
| (declaration.thm n ls t v) := t
| (declaration.cnst n ls t tr) := t
| (declaration.ax n ls t) := t
meta def declaration.value : declaration → expr
| (declaration.defn n ls t v h tr) := v
| (declaration.thm n ls t v) := v^.get
| _ := default expr
meta def declaration.update_type : declaration → expr → declaration
| (declaration.defn n ls t v h tr) new_t := declaration.defn n ls new_t v h tr
| (declaration.thm n ls t v) new_t := declaration.thm n ls new_t v
| (declaration.cnst n ls t tr) new_t := declaration.cnst n ls new_t tr
| (declaration.ax n ls t) new_t := declaration.ax n ls new_t
meta def declaration.update_name : declaration → name → declaration
| (declaration.defn n ls t v h tr) new_n := declaration.defn new_n ls t v h tr
| (declaration.thm n ls t v) new_n := declaration.thm new_n ls t v
| (declaration.cnst n ls t tr) new_n := declaration.cnst new_n ls t tr
| (declaration.ax n ls t) new_n := declaration.ax new_n ls t
meta def declaration.update_value : declaration → expr → declaration
| (declaration.defn n ls t v h tr) new_v := declaration.defn n ls t new_v h tr
| (declaration.thm n ls t v) new_v := declaration.thm n ls t (task.pure new_v)
| d new_v := d
meta def declaration.to_definition : declaration → declaration
| (declaration.cnst n ls t tr) := declaration.defn n ls t (default expr) reducibility_hints.abbrev tr
| (declaration.ax n ls t) := declaration.thm n ls t (task.pure (default expr))
| d := d
/- Instantiate a universe polymorphic declaration type with the given universes. -/
meta constant declaration.instantiate_type_univ_params : declaration → list level → option expr
/- Instantiate a universe polymorphic declaration value with the given universes. -/
meta constant declaration.instantiate_value_univ_params : declaration → list level → option expr |
43c26c38fbd9bb49ec1739e839bb30650390185d | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/extra/show_goal.lean | a5489e1a3265a18f848c7152a3cc83484bc101a8 | [
"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 | 570 | lean | import data.nat
open nat algebra
example (a b c d : nat) : a + b = 0 → b = 0 → c + 1 + a = 1 → d = c - 1 → d = 0 :=
begin
intro h₁ h₂,
have aeq0 : a = 0, begin
rewrite h₂ at h₁,
exact h₁
end,
intro h₃ h₄,
have deq0 : d = 0, begin
have ceq : c = 0, begin
rewrite aeq0 at h₃,
rewrite add_zero at h₃,
krewrite add_succ at h₃,
krewrite add_zero at h₃,
injection h₃, exact a_1
end,
rewrite ceq at h₄,
repeat (esimp [sub, pred] at h₄),
exact h₄
end,
exact deq0
end
|
b6d1b0cac7188b9fd08dbf9fb2e5429dac13f151 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/representation_theory/maschke.lean | 5d1bb5d276fd4f72fd04fc6d375323ce06216291 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 5,920 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Scott Morrison
-/
import data.monoid_algebra
import ring_theory.algebra
import algebra.invertible
import algebra.char_p
import linear_algebra.basis
/-!
# Maschke's theorem
We prove Maschke's theorem for finite groups,
in the formulation that every submodule of a `k[G]` module has a complement,
when `k` is a field with `¬(ring_char k ∣ fintype.card G)`.
We do the core computation in greater generality.
For any `[comm_ring k]` in which `[invertible (fintype.card G : k)]`,
and a `k[G]`-linear map `i : V → W` which admits a `k`-linear retraction `π`,
we produce a `k[G]`-linear retraction by
taking the average over `G` of the conjugates of `π`.
## Future work
It's not so far to give the usual statement, that every finite dimensional representation
of a finite group is semisimple (i.e. a direct sum of irreducibles).
-/
universes u
noncomputable theory
open semimodule
open monoid_algebra
open_locale big_operators
section
-- At first we work with any `[comm_ring k]`, and add the assumption that
-- `[invertible (fintype.card G : k)]` when it is required.
variables {k : Type u} [comm_ring k] {G : Type u} [group G]
variables {V : Type u} [add_comm_group V] [module (monoid_algebra k G) V]
variables {W : Type u} [add_comm_group W] [module (monoid_algebra k G) W]
/-!
We now do the key calculation in Maschke's theorem.
Given `V → W`, an inclusion of `k[G]` modules,,
assume we have some retraction `π` (i.e. `∀ v, π (i v) = v`),
just as a `k`-linear map.
(When `k` is a field, this will be available cheaply, by choosing a basis.)
We now construct a retraction of the inclusion as a `k[G]`-linear map,
by the formula
$$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$
-/
variables (π : (restrict_scalars k (monoid_algebra k G) W) →ₗ[k]
(restrict_scalars k (monoid_algebra k G) V))
include π
/--
We define the conjugate of `π` by `g`, as a `k`-linear map.
-/
def conjugate (g : G) :
(restrict_scalars k (monoid_algebra k G) W) →ₗ[k] (restrict_scalars k (monoid_algebra k G) V) :=
((group_smul.linear_map k V g⁻¹).comp π).comp (group_smul.linear_map k W g)
variables (i : V →ₗ[monoid_algebra k G] W) (h : ∀ v : V, π (i v) = v)
section
include h
lemma conjugate_i (g : G) (v : V) : (conjugate π g) (i v) = v :=
begin
dsimp [conjugate],
simp only [←i.map_smul, h, ←mul_smul, single_mul_single, mul_one, mul_left_inv],
change (1 : monoid_algebra k G) • v = v,
simp,
end
end
variables [fintype G]
/--
The sum of the conjugates of `π` by each element `g : G`, as a `k`-linear map.
(We postpone dividing by the size of the group as long as possible.)
-/
def sum_of_conjugates :
(restrict_scalars k (monoid_algebra k G) W) →ₗ[k] (restrict_scalars k (monoid_algebra k G) V) :=
∑ g : G, conjugate π g
/--
In fact, the sum over `g : G` of the conjugate of `π` by `g` is a `k[G]`-linear map.
-/
def sum_of_conjugates_equivariant :
W →ₗ[monoid_algebra k G] V :=
monoid_algebra.equivariant_of_linear_of_comm (sum_of_conjugates π) (λ g v,
begin
dsimp [sum_of_conjugates],
simp only [linear_map.sum_apply, finset.smul_sum],
dsimp [conjugate],
conv_lhs {
rw [←finset.univ_map_embedding (mul_right_embedding g⁻¹)],
simp only [mul_right_embedding],
},
simp only [←mul_smul, single_mul_single, mul_inv_rev, mul_one, function.embedding.coe_fn_mk,
finset.sum_map, inv_inv, inv_mul_cancel_right],
end)
section
variables [inv : invertible (fintype.card G : k)]
include inv
section
local attribute [instance] linear_map_algebra_module
/--
We construct our `k[G]`-linear retraction of `i` as
$$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$
-/
def equivariant_projection :
W →ₗ[monoid_algebra k G] V :=
⅟(fintype.card G : k) • (sum_of_conjugates_equivariant π)
end
include h
lemma equivariant_projection_condition (v : V) : (equivariant_projection π) (i v) = v :=
begin
rw [equivariant_projection, linear_map_algebra_module.smul_apply, sum_of_conjugates_equivariant,
equivariant_of_linear_of_comm_apply, sum_of_conjugates],
rw [linear_map.sum_apply],
simp only [conjugate_i π i h],
rw [finset.sum_const, finset.card_univ,
@semimodule.nsmul_eq_smul k _
(restrict_scalars k (monoid_algebra k G) V) _ _ (fintype.card G) v,
←mul_smul, invertible.inv_of_mul_self, one_smul],
end
end
end
-- Now we work over a `[field k]`, and replace the assumption `[invertible (fintype.card G : k)]`
-- with `¬(ring_char k ∣ fintype.card G)`.
variables {k : Type u} [field k] {G : Type u} [fintype G] [group G]
variables {V : Type u} [add_comm_group V] [module (monoid_algebra k G) V]
variables {W : Type u} [add_comm_group W] [module (monoid_algebra k G) W]
lemma monoid_algebra.exists_left_inverse_of_injective
(not_dvd : ¬(ring_char k ∣ fintype.card G))
(f : V →ₗ[monoid_algebra k G] W) (hf_inj : f.ker = ⊥) :
∃ (g : W →ₗ[monoid_algebra k G] V), g.comp f = linear_map.id :=
begin
let E := linear_map.exists_left_inverse_of_injective
(by convert f.restrict_scalars k) (by simp [hf_inj]),
fsplit,
haveI : invertible (fintype.card G : k) :=
invertible_of_ring_char_not_dvd not_dvd,
exact equivariant_projection (classical.some E),
{ ext v,
apply equivariant_projection_condition,
intro v,
have := classical.some_spec E,
have := congr_arg linear_map.to_fun this,
exact congr_fun this v, }
end
lemma monoid_algebra.submodule.exists_is_compl
(not_dvd : ¬(ring_char k ∣ fintype.card G)) (p : submodule (monoid_algebra k G) V) :
∃ q : submodule (monoid_algebra k G) V, is_compl p q :=
let ⟨f, hf⟩ := monoid_algebra.exists_left_inverse_of_injective not_dvd p.subtype p.ker_subtype in
⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩
|
01701e639efb2b644c4aba64c6de99aa72137b69 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/analysis/seminorm.lean | f5c61f465c0e1b9170a94fb8e51f4927cefeecae | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 38,759 | lean | /-
Copyright (c) 2019 Jean Lo. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jean Lo, Yaël Dillies, Moritz Doll
-/
import analysis.locally_convex.basic
import data.real.pointwise
import data.real.sqrt
import topology.algebra.filter_basis
import topology.algebra.module.locally_convex
/-!
# Seminorms
This file defines seminorms.
A seminorm is a function to the reals which is positive-semidefinite, absolutely homogeneous, and
subadditive. They are closely related to convex sets and a topological vector space is locally
convex if and only if its topology is induced by a family of seminorms.
## Main declarations
* `add_group_seminorm`: A function `f` from an additive group `G` to the reals that preserves zero,
takes nonnegative values, is subadditive and such that `f (-x) = f x` for all `x`.
* `group_seminorm`: A function `f` from a group `G` to the reals that sends one to zero, takes
nonnegative values, is submultiplicative and such that `f x⁻¹ = f x` for all `x`.
For a module over a normed ring:
* `seminorm`: A function to the reals that is positive-semidefinite, absolutely homogeneous, and
subadditive.
* `norm_seminorm 𝕜 E`: The norm on `E` as a seminorm.
## References
* [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966]
## Tags
seminorm, locally convex, LCTVS
-/
set_option old_structure_cmd true
open normed_field set
open_locale big_operators nnreal pointwise topological_space
variables {R R' 𝕜 E F G ι : Type*}
/-- A seminorm on an additive group `G` is a function `f : G → ℝ` that preserves zero, takes
nonnegative values, is subadditive and such that `f (-x) = f x` for all `x ∈ G`. -/
structure add_group_seminorm (G : Type*) [add_group G]
extends zero_hom G ℝ :=
(nonneg' : ∀ r, 0 ≤ to_fun r)
(add_le' : ∀ r s, to_fun (r + s) ≤ to_fun r + to_fun s)
(neg' : ∀ r, to_fun (- r) = to_fun r)
/-- A seminorm on a group `G` is a function `f : G → ℝ` that preserves zero, takes nonnegative
values, is submultiplicative and such that `f x⁻¹ = f x` for all `x`. -/
@[to_additive] structure group_seminorm (G : Type*) [group G] :=
(to_fun : G → ℝ)
(map_one' : to_fun 1 = 0)
(nonneg' : ∀ x, 0 ≤ to_fun x)
(mul_le' : ∀ x y, to_fun (x * y) ≤ to_fun x + to_fun y)
(inv' : ∀ x, to_fun x⁻¹ = to_fun x)
attribute [nolint doc_blame] add_group_seminorm.to_zero_hom
namespace group_seminorm
section group
variables [group E] [group F] [group G]
@[to_additive] instance fun_like : fun_like (group_seminorm E) E (λ _, ℝ) :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by cases f; cases g; congr' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`. -/
@[to_additive "Helper instance for when there's too many metavariables to apply
`fun_like.has_coe_to_fun`. "]
instance : has_coe_to_fun (group_seminorm E) (λ _, E → ℝ) := ⟨to_fun⟩
@[ext, to_additive] lemma ext {p q : group_seminorm E} : (∀ x, (p : E → ℝ) x = q x) → p = q :=
fun_like.ext p q
variables (p q : group_seminorm E) (x y : E) (r : ℝ)
@[to_additive] protected lemma nonneg : 0 ≤ p x := p.nonneg' _
@[simp, to_additive] protected lemma map_one : p 1 = 0 := p.map_one'
@[to_additive] protected lemma mul_le : p (x * y) ≤ p x + p y := p.mul_le' _ _
@[simp, to_additive] protected lemma inv : p x⁻¹ = p x := p.inv' _
@[to_additive] protected lemma div_le : p (x / y) ≤ p x + p y :=
by { rw [div_eq_mul_inv, ←p.inv y], exact p.mul_le _ _ }
@[to_additive] lemma div_rev : p (x / y) = p (y / x) := by rw [←inv_div, p.inv]
@[to_additive] instance : partial_order (group_seminorm E) :=
partial_order.lift _ fun_like.coe_injective
@[to_additive] lemma le_def : p ≤ q ↔ (p : E → ℝ) ≤ q := iff.rfl
@[to_additive] lemma lt_def : p < q ↔ (p : E → ℝ) < q := iff.rfl
variables {p q}
@[simp, to_additive] lemma coe_le_coe : (p : E → ℝ) ≤ q ↔ p ≤ q := iff.rfl
@[simp, to_additive] lemma coe_lt_coe : (p : E → ℝ) < q ↔ p < q := iff.rfl
variables (p q) (f : F →* E)
@[to_additive] instance : has_zero (group_seminorm E) :=
⟨{ to_fun := 0,
nonneg' := λ r, le_rfl,
map_one' := pi.zero_apply _,
mul_le' := λ _ _, (zero_add _).ge,
inv' := λ x, rfl}⟩
@[simp, to_additive] lemma coe_zero : ⇑(0 : group_seminorm E) = 0 := rfl
@[simp, to_additive] lemma zero_apply (x : E) : (0 : group_seminorm E) x = 0 := rfl
@[to_additive] instance : inhabited (group_seminorm E) := ⟨0⟩
@[to_additive] instance : has_add (group_seminorm E) :=
{ add := λ p q,
{ to_fun := λ x, p x + q x,
nonneg' := λ x, add_nonneg (p.nonneg _) (q.nonneg _),
map_one' := by rw [p.map_one, q.map_one, zero_add],
mul_le' := λ _ _, (add_le_add (p.mul_le _ _) $ q.mul_le _ _).trans_eq $
add_add_add_comm _ _ _ _,
inv' := λ x, by rw [p.inv, q.inv] }}
@[simp, to_additive] lemma coe_add : ⇑(p + q) = p + q := rfl
@[simp, to_additive] lemma add_apply (x : E) : (p + q) x = p x + q x := rfl
-- TODO: define `has_Sup` too, from the skeleton at
-- https://github.com/leanprover-community/mathlib/pull/11329#issuecomment-1008915345
@[to_additive] noncomputable instance : has_sup (group_seminorm E) :=
{ sup := λ p q,
{ to_fun := p ⊔ q,
nonneg' := λ x, le_sup_of_le_left $ p.nonneg _,
map_one' := by rw [pi.sup_apply, ←p.map_one, sup_eq_left, p.map_one, q.map_one],
mul_le' := λ x y, sup_le
((p.mul_le x y).trans $ add_le_add le_sup_left le_sup_left)
((q.mul_le x y).trans $ add_le_add le_sup_right le_sup_right),
inv' := λ x, by rw [pi.sup_apply, pi.sup_apply, p.inv, q.inv] }}
@[simp, to_additive] lemma coe_sup : ⇑(p ⊔ q) = p ⊔ q := rfl
@[simp, to_additive] lemma sup_apply (x : E) : (p ⊔ q) x = p x ⊔ q x := rfl
@[to_additive] noncomputable instance : semilattice_sup (group_seminorm E) :=
fun_like.coe_injective.semilattice_sup _ coe_sup
/-- Composition of a group seminorm with a monoid homomorphism as a group seminorm. -/
@[to_additive "Composition of an additive group seminorm with an additive monoid homomorphism as an
additive group seminorm."]
def comp (p : group_seminorm E) (f : F →* E) : group_seminorm F :=
{ to_fun := λ x, p (f x),
nonneg' := λ x, p.nonneg _,
map_one' := by rw [f.map_one, p.map_one],
mul_le' := λ _ _, (congr_arg p $ f.map_mul _ _).trans_le $ p.mul_le _ _,
inv' := λ x, by rw [map_inv, p.inv] }
@[simp, to_additive] lemma coe_comp : ⇑(p.comp f) = p ∘ f := rfl
@[simp, to_additive] lemma comp_apply (x : F) : (p.comp f) x = p (f x) := rfl
@[simp, to_additive] lemma comp_id : p.comp (monoid_hom.id _) = p := ext $ λ _, rfl
@[simp, to_additive] lemma comp_zero : p.comp (1 : F →* E) = 0 := ext $ λ _, p.map_one
@[simp, to_additive] lemma zero_comp : (0 : group_seminorm E).comp f = 0 := ext $ λ _, rfl
@[to_additive] lemma comp_assoc (g : F →* E) (f : G →* F) : p.comp (g.comp f) = (p.comp g).comp f :=
ext $ λ _, rfl
@[to_additive] lemma add_comp (f : F →* E) : (p + q).comp f = p.comp f + q.comp f := ext $ λ _, rfl
variables {p q}
@[to_additive] lemma comp_mono (hp : p ≤ q) : p.comp f ≤ q.comp f := λ _, hp _
end group
section comm_group
variables [comm_group E] [comm_group F] (p q : group_seminorm E) (x y : E)
/-- The direct path from `1` to `y` is shorter than the path with `x` "inserted" in between. -/
@[to_additive "The direct path from `0` to `y` is shorter than the path with `x` \"inserted\" in
between."]
lemma le_insert : p y ≤ p x + p (x / y) :=
calc p y = p (x / (x / y)) : by rw div_div_cancel
... ≤ p x + p (x / y) : p.div_le _ _
/-- The direct path from 0 to x is shorter than the path with y "inserted" in between. -/
@[to_additive "The direct path from 0 to x is shorter than the path with y \"inserted\" in
between."]
lemma le_insert' : p x ≤ p y + p (x / y) := by { rw div_rev, exact le_insert _ _ _ }
@[to_additive] lemma comp_mul_le (f g : F →* E) : p.comp (f * g) ≤ p.comp f + p.comp g :=
λ _, p.mul_le _ _
@[to_additive] private lemma mul_bdd_below_range_add {p q : group_seminorm E} {x : E} :
bdd_below (range (λ y, p y + q (x / y))) :=
⟨0, by { rintro _ ⟨x, rfl⟩, exact add_nonneg (p.nonneg _) (q.nonneg _) }⟩
@[to_additive] noncomputable instance : has_inf (group_seminorm E) :=
{ inf := λ p q,
{ to_fun := λ x, ⨅ y, p y + q (x / y),
nonneg' := λ x, le_cinfi $ λ x, add_nonneg (p.nonneg _) (q.nonneg _),
map_one' := cinfi_eq_of_forall_ge_of_forall_gt_exists_lt
(λ x, add_nonneg (p.nonneg _) (q.nonneg _))
(λ r hr, ⟨1, by rwa [div_one, p.map_one, q.map_one, add_zero]⟩),
mul_le' := λ x y, le_cinfi_add_cinfi $ λ u v, begin
apply cinfi_le_of_le mul_bdd_below_range_add (u * v),
dsimp,
rw [mul_div_mul_comm, add_add_add_comm],
exact add_le_add (p.mul_le _ _) (q.mul_le _ _),
end,
inv' := λ x, (inv_surjective.infi_comp _).symm.trans $ by simp_rw [p.inv, ←inv_div', q.inv] }}
@[simp, to_additive] lemma inf_apply : (p ⊓ q) x = ⨅ y, p y + q (x / y) := rfl
@[to_additive] noncomputable instance : lattice (group_seminorm E) :=
{ inf := (⊓),
inf_le_left := λ p q x, cinfi_le_of_le mul_bdd_below_range_add x $
by rw [div_self', q.map_one, add_zero],
inf_le_right := λ p q x, cinfi_le_of_le mul_bdd_below_range_add (1 : E) $
by simp only [div_one, p.map_one, zero_add],
le_inf := λ a b c hb hc x, le_cinfi $ λ u, (a.le_insert' _ _).trans $ add_le_add (hb _) (hc _),
..group_seminorm.semilattice_sup }
end comm_group
end group_seminorm
namespace add_group_seminorm
variables [add_group E] (p : add_group_seminorm E) (x y : E) (r : ℝ)
instance zero_hom_class : zero_hom_class (add_group_seminorm E) E ℝ :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by cases f; cases g; congr',
map_zero := λ f, f.map_zero' }
/- TODO: All the following ought to be automated using `to_additive`. The problem is that it doesn't
see that `has_smul R ℝ` should be fixed because `ℝ` is fixed. -/
/-- Any action on `ℝ` which factors through `ℝ≥0` applies to an `add_group_seminorm`. -/
instance [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
has_smul R (add_group_seminorm E) :=
{ smul := λ r p,
{ to_fun := λ x, r • p x,
nonneg' := λ x, begin
simp only [←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul],
exact mul_nonneg (nnreal.coe_nonneg _) (p.nonneg _)
end,
map_zero' := by simp only [←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul,
p.map_zero, mul_zero],
add_le' := λ _ _, begin
simp only [←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul],
exact (mul_le_mul_of_nonneg_left (p.add_le _ _) (nnreal.coe_nonneg _)).trans_eq
(mul_add _ _ _),
end,
neg' := λ x, by rw p.neg }}
instance [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
[has_smul R' ℝ] [has_smul R' ℝ≥0] [is_scalar_tower R' ℝ≥0 ℝ]
[has_smul R R'] [is_scalar_tower R R' ℝ] :
is_scalar_tower R R' (add_group_seminorm E) :=
{ smul_assoc := λ r a p, ext $ λ x, smul_assoc r a (p x) }
@[simp] lemma coe_smul [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p : add_group_seminorm E) : ⇑(r • p) = r • p := rfl
@[simp] lemma smul_apply [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p : add_group_seminorm E) (x : E) : (r • p) x = r • p x := rfl
lemma smul_sup [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p q : add_group_seminorm E) :
r • (p ⊔ q) = r • p ⊔ r • q :=
have real.smul_max : ∀ x y : ℝ, r • max x y = max (r • x) (r • y),
from λ x y, by simpa only [←smul_eq_mul, ←nnreal.smul_def, smul_one_smul ℝ≥0 r (_ : ℝ)]
using mul_max_of_nonneg x y (r • 1 : ℝ≥0).prop,
ext $ λ x, real.smul_max _ _
end add_group_seminorm
namespace group_seminorm
variables [group E] [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
/-- Any action on `ℝ` which factors through `ℝ≥0` applies to an `add_group_seminorm`. -/
@[to_additive add_group_seminorm.has_smul] instance : has_smul R (group_seminorm E) :=
⟨λ r p,
{ to_fun := λ x, r • p x,
nonneg' := λ x, begin
simp only [←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul],
exact mul_nonneg (nnreal.coe_nonneg _) (p.nonneg _)
end,
map_one' := by simp only [←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul,
p.map_one, mul_zero],
mul_le' := λ _ _, begin
simp only [←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul],
exact (mul_le_mul_of_nonneg_left (p.mul_le _ _) $ nnreal.coe_nonneg _).trans_eq
(mul_add _ _ _),
end,
inv' := λ x, by rw p.inv }⟩
@[to_additive add_group_seminorm.is_scalar_tower]
instance [has_smul R' ℝ] [has_smul R' ℝ≥0] [is_scalar_tower R' ℝ≥0 ℝ] [has_smul R R']
[is_scalar_tower R R' ℝ] : is_scalar_tower R R' (group_seminorm E) :=
⟨λ r a p, ext $ λ x, smul_assoc r a $ p x⟩
@[simp, to_additive add_group_seminorm.coe_smul]
lemma coe_smul (r : R) (p : group_seminorm E) : ⇑(r • p) = r • p := rfl
@[simp, to_additive add_group_seminorm.smul_apply]
lemma smul_apply (r : R) (p : group_seminorm E) (x : E) : (r • p) x = r • p x := rfl
@[to_additive add_group_seminorm.smul_sup]
lemma smul_sup (r : R) (p q : group_seminorm E) : r • (p ⊔ q) = r • p ⊔ r • q :=
have real.smul_max : ∀ x y : ℝ, r • max x y = max (r • x) (r • y),
from λ x y, by simpa only [←smul_eq_mul, ←nnreal.smul_def, smul_one_smul ℝ≥0 r (_ : ℝ)]
using mul_max_of_nonneg x y (r • 1 : ℝ≥0).prop,
ext $ λ x, real.smul_max _ _
end group_seminorm
/-- A seminorm on a module over a normed ring is a function to the reals that is positive
semidefinite, positive homogeneous, and subadditive. -/
structure seminorm (𝕜 : Type*) (E : Type*) [semi_normed_ring 𝕜] [add_group E] [has_smul 𝕜 E]
extends add_group_seminorm E :=
(smul' : ∀ (a : 𝕜) (x : E), to_fun (a • x) = ∥a∥ * to_fun x)
attribute [nolint doc_blame] seminorm.to_add_group_seminorm
private lemma map_zero.of_smul {𝕜 : Type*} {E : Type*} [semi_normed_ring 𝕜] [add_group E]
[smul_with_zero 𝕜 E] {f : E → ℝ} (smul : ∀ (a : 𝕜) (x : E), f (a • x) = ∥a∥ * f x) : f 0 = 0 :=
calc f 0 = f ((0 : 𝕜) • 0) : by rw zero_smul
... = 0 : by rw [smul, norm_zero, zero_mul]
private lemma neg.of_smul {𝕜 : Type*} {E : Type*} [semi_normed_ring 𝕜] [add_comm_group E]
[module 𝕜 E] {f : E → ℝ} (smul : ∀ (a : 𝕜) (x : E), f (a • x) = ∥a∥ * f x) (x : E) :
f (-x) = f x :=
by rw [←neg_one_smul 𝕜, smul, norm_neg, ← smul, one_smul]
private lemma nonneg.of {𝕜 : Type*} {E : Type*} [semi_normed_ring 𝕜] [add_comm_group E] [module 𝕜 E]
{f : E → ℝ} (add_le : ∀ (x y : E), f (x + y) ≤ f x + f y)
(smul : ∀ (a : 𝕜) (x : E), f (a • x) = ∥a∥ * f x) (x : E) : 0 ≤ f x :=
have h: 0 ≤ 2 * f x, from
calc 0 = f (x + (- x)) : by rw [add_neg_self, map_zero.of_smul smul]
... ≤ f x + f (-x) : add_le _ _
... = 2 * f x : by rw [neg.of_smul smul, two_mul],
nonneg_of_mul_nonneg_right h zero_lt_two
/-- Alternative constructor for a `seminorm` on an `add_comm_group E` that is a module over a
`semi_norm_ring 𝕜`. -/
def seminorm.of {𝕜 : Type*} {E : Type*} [semi_normed_ring 𝕜] [add_comm_group E] [module 𝕜 E]
(f : E → ℝ) (add_le : ∀ (x y : E), f (x + y) ≤ f x + f y)
(smul : ∀ (a : 𝕜) (x : E), f (a • x) = ∥a∥ * f x) : seminorm 𝕜 E :=
{ to_fun := f,
map_zero' := map_zero.of_smul smul,
nonneg' := nonneg.of add_le smul,
add_le' := add_le,
smul' := smul,
neg' := neg.of_smul smul }
namespace seminorm
section semi_normed_ring
variables [semi_normed_ring 𝕜]
section add_group
variables [add_group E]
section has_smul
variables [has_smul 𝕜 E]
instance zero_hom_class : zero_hom_class (seminorm 𝕜 E) E ℝ :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by cases f; cases g; congr',
map_zero := λ f, f.map_zero' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`. -/
instance : has_coe_to_fun (seminorm 𝕜 E) (λ _, E → ℝ) := ⟨λ p, p.to_fun⟩
@[ext] lemma ext {p q : seminorm 𝕜 E} (h : ∀ x, (p : E → ℝ) x = q x) : p = q := fun_like.ext p q h
instance : has_zero (seminorm 𝕜 E) :=
⟨{ smul' := λ _ _, (mul_zero _).symm,
..add_group_seminorm.has_zero.zero }⟩
@[simp] lemma coe_zero : ⇑(0 : seminorm 𝕜 E) = 0 := rfl
@[simp] lemma zero_apply (x : E) : (0 : seminorm 𝕜 E) x = 0 := rfl
instance : inhabited (seminorm 𝕜 E) := ⟨0⟩
variables (p : seminorm 𝕜 E) (c : 𝕜) (x y : E) (r : ℝ)
protected lemma nonneg : 0 ≤ p x := p.nonneg' _
protected lemma map_zero : p 0 = 0 := p.map_zero'
protected lemma smul : p (c • x) = ∥c∥ * p x := p.smul' _ _
protected lemma add_le : p (x + y) ≤ p x + p y := p.add_le' _ _
/-- Any action on `ℝ` which factors through `ℝ≥0` applies to a seminorm. -/
instance [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
has_smul R (seminorm 𝕜 E) :=
{ smul := λ r p,
{ to_fun := λ x, r • p x,
smul' := λ _ _, begin
simp only [←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul],
rw [p.smul, mul_left_comm],
end,
..(r • p.to_add_group_seminorm) }}
instance [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
[has_smul R' ℝ] [has_smul R' ℝ≥0] [is_scalar_tower R' ℝ≥0 ℝ]
[has_smul R R'] [is_scalar_tower R R' ℝ] :
is_scalar_tower R R' (seminorm 𝕜 E) :=
{ smul_assoc := λ r a p, ext $ λ x, smul_assoc r a (p x) }
lemma coe_smul [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p : seminorm 𝕜 E) : ⇑(r • p) = r • p := rfl
@[simp] lemma smul_apply [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p : seminorm 𝕜 E) (x : E) : (r • p) x = r • p x := rfl
instance : has_add (seminorm 𝕜 E) :=
{ add := λ p q,
{ to_fun := λ x, p x + q x,
smul' := λ a x, by simp only [p.smul, q.smul, mul_add],
..(p.to_add_group_seminorm + q.to_add_group_seminorm) }}
lemma coe_add (p q : seminorm 𝕜 E) : ⇑(p + q) = p + q := rfl
@[simp] lemma add_apply (p q : seminorm 𝕜 E) (x : E) : (p + q) x = p x + q x := rfl
instance : add_monoid (seminorm 𝕜 E) :=
fun_like.coe_injective.add_monoid _ rfl coe_add (λ p n, coe_smul n p)
instance : ordered_cancel_add_comm_monoid (seminorm 𝕜 E) :=
fun_like.coe_injective.ordered_cancel_add_comm_monoid _ rfl coe_add (λ p n, coe_smul n p)
instance [monoid R] [mul_action R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
mul_action R (seminorm 𝕜 E) :=
fun_like.coe_injective.mul_action _ coe_smul
variables (𝕜 E)
/-- `coe_fn` as an `add_monoid_hom`. Helper definition for showing that `seminorm 𝕜 E` is
a module. -/
@[simps]
def coe_fn_add_monoid_hom : add_monoid_hom (seminorm 𝕜 E) (E → ℝ) := ⟨coe_fn, coe_zero, coe_add⟩
lemma coe_fn_add_monoid_hom_injective : function.injective (coe_fn_add_monoid_hom 𝕜 E) :=
show @function.injective (seminorm 𝕜 E) (E → ℝ) coe_fn, from fun_like.coe_injective
variables {𝕜 E}
instance [monoid R] [distrib_mul_action R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
distrib_mul_action R (seminorm 𝕜 E) :=
(coe_fn_add_monoid_hom_injective 𝕜 E).distrib_mul_action _ coe_smul
instance [semiring R] [module R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
module R (seminorm 𝕜 E) :=
(coe_fn_add_monoid_hom_injective 𝕜 E).module R _ coe_smul
-- TODO: define `has_Sup` too, from the skeleton at
-- https://github.com/leanprover-community/mathlib/pull/11329#issuecomment-1008915345
noncomputable instance : has_sup (seminorm 𝕜 E) :=
{ sup := λ p q,
{ to_fun := p ⊔ q,
smul' := λ x v, (congr_arg2 max (p.smul x v) (q.smul x v)).trans $
(mul_max_of_nonneg _ _ $ norm_nonneg x).symm,
..(p.to_add_group_seminorm ⊔ q.to_add_group_seminorm) } }
@[simp] lemma coe_sup (p q : seminorm 𝕜 E) : ⇑(p ⊔ q) = p ⊔ q := rfl
lemma sup_apply (p q : seminorm 𝕜 E) (x : E) : (p ⊔ q) x = p x ⊔ q x := rfl
lemma smul_sup [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p q : seminorm 𝕜 E) :
r • (p ⊔ q) = r • p ⊔ r • q :=
have real.smul_max : ∀ x y : ℝ, r • max x y = max (r • x) (r • y),
from λ x y, by simpa only [←smul_eq_mul, ←nnreal.smul_def, smul_one_smul ℝ≥0 r (_ : ℝ)]
using mul_max_of_nonneg x y (r • 1 : ℝ≥0).prop,
ext $ λ x, real.smul_max _ _
instance : partial_order (seminorm 𝕜 E) :=
partial_order.lift _ fun_like.coe_injective
lemma le_def (p q : seminorm 𝕜 E) : p ≤ q ↔ (p : E → ℝ) ≤ q := iff.rfl
lemma lt_def (p q : seminorm 𝕜 E) : p < q ↔ (p : E → ℝ) < q := iff.rfl
noncomputable instance : semilattice_sup (seminorm 𝕜 E) :=
function.injective.semilattice_sup _ fun_like.coe_injective coe_sup
end has_smul
end add_group
section module
variables [add_comm_group E] [add_comm_group F] [add_comm_group G]
variables [module 𝕜 E] [module 𝕜 F] [module 𝕜 G]
variables [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
/-- Composition of a seminorm with a linear map is a seminorm. -/
def comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : seminorm 𝕜 E :=
{ to_fun := λ x, p (f x),
smul' := λ _ _, (congr_arg p (f.map_smul _ _)).trans (p.smul _ _),
..(p.to_add_group_seminorm.comp f.to_add_monoid_hom) }
lemma coe_comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : ⇑(p.comp f) = p ∘ f := rfl
@[simp] lemma comp_apply (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (x : E) : (p.comp f) x = p (f x) := rfl
@[simp] lemma comp_id (p : seminorm 𝕜 E) : p.comp linear_map.id = p :=
ext $ λ _, rfl
@[simp] lemma comp_zero (p : seminorm 𝕜 F) : p.comp (0 : E →ₗ[𝕜] F) = 0 :=
ext $ λ _, map_zero p
@[simp] lemma zero_comp (f : E →ₗ[𝕜] F) : (0 : seminorm 𝕜 F).comp f = 0 :=
ext $ λ _, rfl
lemma comp_comp (p : seminorm 𝕜 G) (g : F →ₗ[𝕜] G) (f : E →ₗ[𝕜] F) :
p.comp (g.comp f) = (p.comp g).comp f :=
ext $ λ _, rfl
lemma add_comp (p q : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : (p + q).comp f = p.comp f + q.comp f :=
ext $ λ _, rfl
lemma comp_add_le (p : seminorm 𝕜 F) (f g : E →ₗ[𝕜] F) : p.comp (f + g) ≤ p.comp f + p.comp g :=
λ _, p.add_le _ _
lemma smul_comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (c : R) : (c • p).comp f = c • (p.comp f) :=
ext $ λ _, rfl
lemma comp_mono {p : seminorm 𝕜 F} {q : seminorm 𝕜 F} (f : E →ₗ[𝕜] F) (hp : p ≤ q) :
p.comp f ≤ q.comp f := λ _, hp _
/-- The composition as an `add_monoid_hom`. -/
@[simps] def pullback (f : E →ₗ[𝕜] F) : add_monoid_hom (seminorm 𝕜 F) (seminorm 𝕜 E) :=
⟨λ p, p.comp f, zero_comp f, λ p q, add_comp p q f⟩
section
variables (p : seminorm 𝕜 E)
@[simp]
protected lemma neg (x : E) : p (-x) = p x :=
by rw [←neg_one_smul 𝕜, seminorm.smul, norm_neg, ←seminorm.smul, one_smul]
protected lemma sub_le (x y : E) : p (x - y) ≤ p x + p y :=
calc
p (x - y)
= p (x + -y) : by rw sub_eq_add_neg
... ≤ p x + p (-y) : p.add_le x (-y)
... = p x + p y : by rw p.neg
lemma sub_rev (x y : E) : p (x - y) = p (y - x) := by rw [←neg_sub, p.neg]
/-- The direct path from 0 to y is shorter than the path with x "inserted" in between. -/
lemma le_insert (x y : E) : p y ≤ p x + p (x - y) :=
calc p y = p (x - (x - y)) : by rw sub_sub_cancel
... ≤ p x + p (x - y) : p.sub_le _ _
/-- The direct path from 0 to x is shorter than the path with y "inserted" in between. -/
lemma le_insert' (x y : E) : p x ≤ p y + p (x - y) := by { rw sub_rev, exact le_insert _ _ _ }
end
instance : order_bot (seminorm 𝕜 E) := ⟨0, seminorm.nonneg⟩
@[simp] lemma coe_bot : ⇑(⊥ : seminorm 𝕜 E) = 0 := rfl
lemma bot_eq_zero : (⊥ : seminorm 𝕜 E) = 0 := rfl
lemma smul_le_smul {p q : seminorm 𝕜 E} {a b : ℝ≥0} (hpq : p ≤ q) (hab : a ≤ b) :
a • p ≤ b • q :=
begin
simp_rw [le_def, pi.le_def, coe_smul],
intros x,
simp_rw [pi.smul_apply, nnreal.smul_def, smul_eq_mul],
exact mul_le_mul hab (hpq x) (p.nonneg x) (nnreal.coe_nonneg b),
end
lemma finset_sup_apply (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) :
s.sup p x = ↑(s.sup (λ i, ⟨p i x, (p i).nonneg x⟩) : ℝ≥0) :=
begin
induction s using finset.cons_induction_on with a s ha ih,
{ rw [finset.sup_empty, finset.sup_empty, coe_bot, _root_.bot_eq_zero, pi.zero_apply,
nonneg.coe_zero] },
{ rw [finset.sup_cons, finset.sup_cons, coe_sup, sup_eq_max, pi.sup_apply, sup_eq_max,
nnreal.coe_max, subtype.coe_mk, ih] }
end
lemma finset_sup_le_sum (p : ι → seminorm 𝕜 E) (s : finset ι) : s.sup p ≤ ∑ i in s, p i :=
begin
classical,
refine finset.sup_le_iff.mpr _,
intros i hi,
rw [finset.sum_eq_sum_diff_singleton_add hi, le_add_iff_nonneg_left],
exact bot_le,
end
lemma finset_sup_apply_le {p : ι → seminorm 𝕜 E} {s : finset ι} {x : E} {a : ℝ} (ha : 0 ≤ a)
(h : ∀ i, i ∈ s → p i x ≤ a) : s.sup p x ≤ a :=
begin
lift a to ℝ≥0 using ha,
rw [finset_sup_apply, nnreal.coe_le_coe],
exact finset.sup_le h,
end
lemma finset_sup_apply_lt {p : ι → seminorm 𝕜 E} {s : finset ι} {x : E} {a : ℝ} (ha : 0 < a)
(h : ∀ i, i ∈ s → p i x < a) : s.sup p x < a :=
begin
lift a to ℝ≥0 using ha.le,
rw [finset_sup_apply, nnreal.coe_lt_coe, finset.sup_lt_iff],
{ exact h },
{ exact nnreal.coe_pos.mpr ha },
end
end module
end semi_normed_ring
section semi_normed_comm_ring
variables [semi_normed_comm_ring 𝕜] [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F]
lemma comp_smul (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (c : 𝕜) :
p.comp (c • f) = ∥c∥₊ • p.comp f :=
ext $ λ _, by rw [comp_apply, smul_apply, linear_map.smul_apply, p.smul, nnreal.smul_def,
coe_nnnorm, smul_eq_mul, comp_apply]
lemma comp_smul_apply (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (c : 𝕜) (x : E) :
p.comp (c • f) x = ∥c∥ * p (f x) := p.smul _ _
end semi_normed_comm_ring
section normed_field
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E]
private lemma bdd_below_range_add (x : E) (p q : seminorm 𝕜 E) :
bdd_below (range (λ (u : E), p u + q (x - u))) :=
by { use 0, rintro _ ⟨x, rfl⟩, exact add_nonneg (p.nonneg _) (q.nonneg _) }
noncomputable instance : has_inf (seminorm 𝕜 E) :=
{ inf := λ p q,
{ to_fun := λ x, ⨅ u : E, p u + q (x-u),
smul' :=
begin
intros a x,
obtain rfl | ha := eq_or_ne a 0,
{ rw [norm_zero, zero_mul, zero_smul],
refine cinfi_eq_of_forall_ge_of_forall_gt_exists_lt
(λ i, add_nonneg (p.nonneg _) (q.nonneg _))
(λ x hx, ⟨0, by rwa [map_zero, sub_zero, map_zero, add_zero]⟩) },
simp_rw [real.mul_infi_of_nonneg (norm_nonneg a), mul_add, ←p.smul, ←q.smul, smul_sub],
refine function.surjective.infi_congr ((•) a⁻¹ : E → E) (λ u, ⟨a • u, inv_smul_smul₀ ha u⟩)
(λ u, _),
rw smul_inv_smul₀ ha
end,
..(p.to_add_group_seminorm ⊓ q.to_add_group_seminorm) }}
@[simp] lemma inf_apply (p q : seminorm 𝕜 E) (x : E) : (p ⊓ q) x = ⨅ u : E, p u + q (x-u) := rfl
noncomputable instance : lattice (seminorm 𝕜 E) :=
{ inf := (⊓),
inf_le_left := λ p q x, begin
apply cinfi_le_of_le (bdd_below_range_add _ _ _) x,
simp only [sub_self, map_zero, add_zero],
end,
inf_le_right := λ p q x, begin
apply cinfi_le_of_le (bdd_below_range_add _ _ _) (0:E),
simp only [sub_self, map_zero, zero_add, sub_zero],
end,
le_inf := λ a b c hab hac x,
le_cinfi $ λ u, le_trans (a.le_insert' _ _) (add_le_add (hab _) (hac _)),
..seminorm.semilattice_sup }
lemma smul_inf [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p q : seminorm 𝕜 E) :
r • (p ⊓ q) = r • p ⊓ r • q :=
begin
ext,
simp_rw [smul_apply, inf_apply, smul_apply, ←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def,
smul_eq_mul, real.mul_infi_of_nonneg (subtype.prop _), mul_add],
end
end normed_field
/-! ### Seminorm ball -/
section semi_normed_ring
variables [semi_normed_ring 𝕜]
section add_comm_group
variables [add_comm_group E]
section has_smul
variables [has_smul 𝕜 E] (p : seminorm 𝕜 E)
/-- The ball of radius `r` at `x` with respect to seminorm `p` is the set of elements `y` with
`p (y - x) < `r`. -/
def ball (x : E) (r : ℝ) := { y : E | p (y - x) < r }
variables {x y : E} {r : ℝ}
@[simp] lemma mem_ball : y ∈ ball p x r ↔ p (y - x) < r := iff.rfl
lemma mem_ball_zero : y ∈ ball p 0 r ↔ p y < r := by rw [mem_ball, sub_zero]
lemma ball_zero_eq : ball p 0 r = { y : E | p y < r } := set.ext $ λ x, p.mem_ball_zero
@[simp] lemma ball_zero' (x : E) (hr : 0 < r) : ball (0 : seminorm 𝕜 E) x r = set.univ :=
begin
rw [set.eq_univ_iff_forall, ball],
simp [hr],
end
lemma ball_smul (p : seminorm 𝕜 E) {c : nnreal} (hc : 0 < c) (r : ℝ) (x : E) :
(c • p).ball x r = p.ball x (r / c) :=
by { ext, rw [mem_ball, mem_ball, smul_apply, nnreal.smul_def, smul_eq_mul, mul_comm,
lt_div_iff (nnreal.coe_pos.mpr hc)] }
lemma ball_sup (p : seminorm 𝕜 E) (q : seminorm 𝕜 E) (e : E) (r : ℝ) :
ball (p ⊔ q) e r = ball p e r ∩ ball q e r :=
by simp_rw [ball, ←set.set_of_and, coe_sup, pi.sup_apply, sup_lt_iff]
lemma ball_finset_sup' (p : ι → seminorm 𝕜 E) (s : finset ι) (H : s.nonempty) (e : E) (r : ℝ) :
ball (s.sup' H p) e r = s.inf' H (λ i, ball (p i) e r) :=
begin
induction H using finset.nonempty.cons_induction with a a s ha hs ih,
{ classical, simp },
{ rw [finset.sup'_cons hs, finset.inf'_cons hs, ball_sup, inf_eq_inter, ih] },
end
lemma ball_mono {p : seminorm 𝕜 E} {r₁ r₂ : ℝ} (h : r₁ ≤ r₂) : p.ball x r₁ ⊆ p.ball x r₂ :=
λ _ (hx : _ < _), hx.trans_le h
lemma ball_antitone {p q : seminorm 𝕜 E} (h : q ≤ p) : p.ball x r ⊆ q.ball x r :=
λ _, (h _).trans_lt
lemma ball_add_ball_subset (p : seminorm 𝕜 E) (r₁ r₂ : ℝ) (x₁ x₂ : E):
p.ball (x₁ : E) r₁ + p.ball (x₂ : E) r₂ ⊆ p.ball (x₁ + x₂) (r₁ + r₂) :=
begin
rintros x ⟨y₁, y₂, hy₁, hy₂, rfl⟩,
rw [mem_ball, add_sub_add_comm],
exact (p.add_le _ _).trans_lt (add_lt_add hy₁ hy₂),
end
end has_smul
section module
variables [module 𝕜 E]
variables [add_comm_group F] [module 𝕜 F]
lemma ball_comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (x : E) (r : ℝ) :
(p.comp f).ball x r = f ⁻¹' (p.ball (f x) r) :=
begin
ext,
simp_rw [ball, mem_preimage, comp_apply, set.mem_set_of_eq, map_sub],
end
variables (p : seminorm 𝕜 E)
lemma ball_zero_eq_preimage_ball {r : ℝ} :
p.ball 0 r = p ⁻¹' (metric.ball 0 r) :=
begin
ext x,
simp only [mem_ball, sub_zero, mem_preimage, mem_ball_zero_iff],
rw real.norm_of_nonneg,
exact p.nonneg _,
end
@[simp] lemma ball_bot {r : ℝ} (x : E) (hr : 0 < r) :
ball (⊥ : seminorm 𝕜 E) x r = set.univ :=
ball_zero' x hr
/-- Seminorm-balls at the origin are balanced. -/
lemma balanced_ball_zero (r : ℝ) : balanced 𝕜 (ball p 0 r) :=
begin
rintro a ha x ⟨y, hy, hx⟩,
rw [mem_ball_zero, ←hx, p.smul],
calc _ ≤ p y : mul_le_of_le_one_left (p.nonneg _) ha
... < r : by rwa mem_ball_zero at hy,
end
lemma ball_finset_sup_eq_Inter (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) {r : ℝ} (hr : 0 < r) :
ball (s.sup p) x r = ⋂ (i ∈ s), ball (p i) x r :=
begin
lift r to nnreal using hr.le,
simp_rw [ball, Inter_set_of, finset_sup_apply, nnreal.coe_lt_coe,
finset.sup_lt_iff (show ⊥ < r, from hr), ←nnreal.coe_lt_coe, subtype.coe_mk],
end
lemma ball_finset_sup (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) {r : ℝ} (hr : 0 < r) :
ball (s.sup p) x r = s.inf (λ i, ball (p i) x r) :=
begin
rw finset.inf_eq_infi,
exact ball_finset_sup_eq_Inter _ _ _ hr,
end
lemma ball_smul_ball (p : seminorm 𝕜 E) (r₁ r₂ : ℝ) :
metric.ball (0 : 𝕜) r₁ • p.ball 0 r₂ ⊆ p.ball 0 (r₁ * r₂) :=
begin
rw set.subset_def,
intros x hx,
rw set.mem_smul at hx,
rcases hx with ⟨a, y, ha, hy, hx⟩,
rw [←hx, mem_ball_zero, seminorm.smul],
exact mul_lt_mul'' (mem_ball_zero_iff.mp ha) (p.mem_ball_zero.mp hy) (norm_nonneg a) (p.nonneg y),
end
@[simp] lemma ball_eq_emptyset (p : seminorm 𝕜 E) {x : E} {r : ℝ} (hr : r ≤ 0) : p.ball x r = ∅ :=
begin
ext,
rw [seminorm.mem_ball, set.mem_empty_eq, iff_false, not_lt],
exact hr.trans (p.nonneg _),
end
end module
end add_comm_group
end semi_normed_ring
section normed_field
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] (p : seminorm 𝕜 E) {A B : set E}
{a : 𝕜} {r : ℝ} {x : E}
lemma smul_ball_zero {p : seminorm 𝕜 E} {k : 𝕜} {r : ℝ} (hk : 0 < ∥k∥) :
k • p.ball 0 r = p.ball 0 (∥k∥ * r) :=
begin
ext,
rw [set.mem_smul_set, seminorm.mem_ball_zero],
split; intro h,
{ rcases h with ⟨y, hy, h⟩,
rw [←h, seminorm.smul],
rw seminorm.mem_ball_zero at hy,
exact (mul_lt_mul_left hk).mpr hy },
refine ⟨k⁻¹ • x, _, _⟩,
{ rw [seminorm.mem_ball_zero, seminorm.smul, norm_inv, ←(mul_lt_mul_left hk),
←mul_assoc, ←(div_eq_mul_inv ∥k∥ ∥k∥), div_self (ne_of_gt hk), one_mul],
exact h},
rw [←smul_assoc, smul_eq_mul, ←div_eq_mul_inv, div_self (norm_pos_iff.mp hk), one_smul],
end
lemma ball_zero_absorbs_ball_zero (p : seminorm 𝕜 E) {r₁ r₂ : ℝ} (hr₁ : 0 < r₁) :
absorbs 𝕜 (p.ball 0 r₁) (p.ball 0 r₂) :=
begin
by_cases hr₂ : r₂ ≤ 0,
{ rw ball_eq_emptyset p hr₂, exact absorbs_empty },
rw [not_le] at hr₂,
rcases exists_between hr₁ with ⟨r, hr, hr'⟩,
refine ⟨r₂/r, div_pos hr₂ hr, _⟩,
simp_rw set.subset_def,
intros a ha x hx,
have ha' : 0 < ∥a∥ := lt_of_lt_of_le (div_pos hr₂ hr) ha,
rw [smul_ball_zero ha', p.mem_ball_zero],
rw p.mem_ball_zero at hx,
rw div_le_iff hr at ha,
exact hx.trans (lt_of_le_of_lt ha ((mul_lt_mul_left ha').mpr hr')),
end
/-- Seminorm-balls at the origin are absorbent. -/
protected lemma absorbent_ball_zero (hr : 0 < r) : absorbent 𝕜 (ball p (0 : E) r) :=
begin
rw absorbent_iff_nonneg_lt,
rintro x,
have hxr : 0 ≤ p x/r := div_nonneg (p.nonneg _) hr.le,
refine ⟨p x/r, hxr, λ a ha, _⟩,
have ha₀ : 0 < ∥a∥ := hxr.trans_lt ha,
refine ⟨a⁻¹ • x, _, smul_inv_smul₀ (norm_pos_iff.1 ha₀) x⟩,
rwa [mem_ball_zero, p.smul, norm_inv, inv_mul_lt_iff ha₀, ←div_lt_iff hr],
end
/-- Seminorm-balls containing the origin are absorbent. -/
protected lemma absorbent_ball (hpr : p x < r) : absorbent 𝕜 (ball p x r) :=
begin
refine (p.absorbent_ball_zero $ sub_pos.2 hpr).subset (λ y hy, _),
rw p.mem_ball_zero at hy,
exact p.mem_ball.2 ((p.sub_le _ _).trans_lt $ add_lt_of_lt_sub_right hy),
end
lemma symmetric_ball_zero (r : ℝ) (hx : x ∈ ball p 0 r) : -x ∈ ball p 0 r :=
balanced_ball_zero p r (-1) (by rw [norm_neg, norm_one]) ⟨x, hx, by rw [neg_smul, one_smul]⟩
@[simp]
lemma neg_ball (p : seminorm 𝕜 E) (r : ℝ) (x : E) :
-ball p x r = ball p (-x) r :=
by { ext, rw [mem_neg, mem_ball, mem_ball, ←neg_add', sub_neg_eq_add, p.neg], }
@[simp]
lemma smul_ball_preimage (p : seminorm 𝕜 E) (y : E) (r : ℝ) (a : 𝕜) (ha : a ≠ 0) :
((•) a) ⁻¹' p.ball y r = p.ball (a⁻¹ • y) (r / ∥a∥) :=
set.ext $ λ _, by rw [mem_preimage, mem_ball, mem_ball,
lt_div_iff (norm_pos_iff.mpr ha), mul_comm, ←p.smul, smul_sub, smul_inv_smul₀ ha]
end normed_field
section convex
variables [normed_field 𝕜] [add_comm_group E] [normed_space ℝ 𝕜] [module 𝕜 E]
section has_smul
variables [has_smul ℝ E] [is_scalar_tower ℝ 𝕜 E] (p : seminorm 𝕜 E)
/-- A seminorm is convex. Also see `convex_on_norm`. -/
protected lemma convex_on : convex_on ℝ univ p :=
begin
refine ⟨convex_univ, λ x y _ _ a b ha hb hab, _⟩,
calc p (a • x + b • y) ≤ p (a • x) + p (b • y) : p.add_le _ _
... = ∥a • (1 : 𝕜)∥ * p x + ∥b • (1 : 𝕜)∥ * p y
: by rw [←p.smul, ←p.smul, smul_one_smul, smul_one_smul]
... = a * p x + b * p y
: by rw [norm_smul, norm_smul, norm_one, mul_one, mul_one, real.norm_of_nonneg ha,
real.norm_of_nonneg hb],
end
end has_smul
section module
variables [module ℝ E] [is_scalar_tower ℝ 𝕜 E] (p : seminorm 𝕜 E) (x : E) (r : ℝ)
/-- Seminorm-balls are convex. -/
lemma convex_ball : convex ℝ (ball p x r) :=
begin
convert (p.convex_on.translate_left (-x)).convex_lt r,
ext y,
rw [preimage_univ, sep_univ, p.mem_ball, sub_eq_add_neg],
refl,
end
end module
end convex
end seminorm
/-! ### The norm as a seminorm -/
section norm_seminorm
variables (𝕜) (E) [normed_field 𝕜] [seminormed_add_comm_group E] [normed_space 𝕜 E] {r : ℝ}
/-- The norm of a seminormed group as an add_monoid seminorm. -/
def norm_add_group_seminorm : add_group_seminorm E :=
⟨norm, norm_zero, norm_nonneg, norm_add_le, norm_neg⟩
@[simp] lemma coe_norm_add_group_seminorm : ⇑(norm_add_group_seminorm E) = norm := rfl
/-- The norm of a seminormed group as a seminorm. -/
def norm_seminorm : seminorm 𝕜 E :=
{ smul' := norm_smul,
..(norm_add_group_seminorm E)}
@[simp] lemma coe_norm_seminorm : ⇑(norm_seminorm 𝕜 E) = norm := rfl
@[simp] lemma ball_norm_seminorm : (norm_seminorm 𝕜 E).ball = metric.ball :=
by { ext x r y, simp only [seminorm.mem_ball, metric.mem_ball, coe_norm_seminorm, dist_eq_norm] }
variables {𝕜 E} {x : E}
/-- Balls at the origin are absorbent. -/
lemma absorbent_ball_zero (hr : 0 < r) : absorbent 𝕜 (metric.ball (0 : E) r) :=
by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).absorbent_ball_zero hr }
/-- Balls containing the origin are absorbent. -/
lemma absorbent_ball (hx : ∥x∥ < r) : absorbent 𝕜 (metric.ball x r) :=
by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).absorbent_ball hx }
/-- Balls at the origin are balanced. -/
lemma balanced_ball_zero : balanced 𝕜 (metric.ball (0 : E) r) :=
by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).balanced_ball_zero r }
end norm_seminorm
|
87dc6be04dc40d0bdb07708ce225a9b9acea7e91 | 8b8ab1eba67c5c35b51ab27fcf8151aab660e44d | /src/demo.lean | b4d04778c1b284349876f113640cf58254897961 | [] | no_license | PatrickMassot/lean-scratchpad | ab5e89b69034cc699bf234852822acf74b50f2b9 | 03eec3bfabfc218b79dcbe7c7712bfa024a02625 | refs/heads/master | 1,626,995,046,509 | 1,538,577,853,000 | 1,538,577,853,000 | 115,135,779 | 1 | 2 | null | 1,522,993,992,000 | 1,513,962,994,000 | Lean | UTF-8 | Lean | false | false | 1,816 | lean | import algebra.group
import data.set.basic
import analysis.real
import tactic.norm_num
import .choice
set_option pp.beta true
example (P Q R : Prop) : ((P ∨ Q → R) ∧ P) → R :=
begin
rintro ⟨hyp1, hyp2⟩,
apply hyp1,
left,
assumption,
end
example (P Q R : Prop) : ((P ∨ Q → R) ∧ P) → R :=
by finish
example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) :=
begin
ext x,
split,
{ rintro ⟨x_1, x_B | x_C⟩,
{ left,
apply and.intro,
{ assumption },
{ assumption } },
{ right,
apply and.intro,
{ assumption },
{ assumption } } },
{ rintro (⟨x_A, x_B⟩|⟨x_A, x_C⟩),
{ apply and.intro,
{ assumption },
{ left,
assumption } },
{ apply and.intro,
{ assumption },
{ right,
assumption } } }
end
example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) :=
by ext x; split; finish
example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) :=
set.inter_distrib_left _ _ _
example (X Y : Type) (f : X → Y) :
(∀ y : Y, ∃ x : X, f(x) = y) ↔ (∃ g : Y → X, f ∘ g = id) :=
begin
split,
{ intro hyp,
choice hyp with g H,
existsi g,
exact funext H, },
{ rintros ⟨g, f_rond_g⟩ y,
existsi g y,
exact congr_fun f_rond_g y }
end
example (G H : Type) [group G] [group H] (f : G → H)
(Hyp : ∀ a b : G, f (a*b) = f a * f b) : f 1 = 1 :=
begin
have clef := calc
f 1 = f (1*1) : by simp
... = f 1 * f 1 : Hyp 1 1,
exact mul_self_iff_eq_one.1 (eq.symm clef)
end
example (u : ℕ → ℝ) (H : ∀ n, u (n+1) = 2*u n) (H' : u 0 > 0) :
∀ n, u n > 0 :=
begin
intro n,
induction n with n IH,
{ exact H' },
{ rw H,
apply mul_pos,
norm_num,
exact IH }
end |
76936aef2f8de9257a38aae2e6c927ed4ed72fbe | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/simp20.lean | 4ece305a8eed7aefd35e742f8aae04bef8d19ca4 | [
"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 | 365 | lean | rewrite_set simple
set_option pp::implicit true
universe M >= 1
definition TypeM := (Type M)
variable g : TypeM → TypeM
variable B : Type
variable B' : Type
axiom H : B = B'
add_rewrite H : simple
(*
local t = parse_lean([[ g B ]])
print(t)
print("===>")
local t2, pr = simplify(t, "simple")
print(t2)
print(pr)
print(get_environment():type_check(pr))
*) |
3dacc32ba9723d304459b1abb220616240c36786 | 0845ae2ca02071debcfd4ac24be871236c01784f | /library/init/control/alternative.lean | 243990110ed6080e941154a67a22a33e5c9c51ef | [
"Apache-2.0"
] | permissive | GaloisInc/lean4 | 74c267eb0e900bfaa23df8de86039483ecbd60b7 | 228ddd5fdcd98dd4e9c009f425284e86917938aa | refs/heads/master | 1,643,131,356,301 | 1,562,715,572,000 | 1,562,715,572,000 | 192,390,898 | 0 | 0 | null | 1,560,792,750,000 | 1,560,792,749,000 | null | UTF-8 | Lean | false | false | 1,284 | 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.core init.control.applicative
universes u v
class Alternative (f : Type u → Type v) extends Applicative f : Type (max (u+1) v) :=
(failure : ∀ {α : Type u}, f α)
(orelse : ∀ {α : Type u}, f α → f α → f α)
instance alternativeHasOrelse (f : Type u → Type v) (α : Type u) [Alternative f] : HasOrelse (f α) :=
⟨Alternative.orelse⟩
section
variables {f : Type u → Type v} [Alternative f] {α : Type u}
@[inline] def failure : f α :=
Alternative.failure f
@[inline] def guard {f : Type → Type v} [Alternative f] (p : Prop) [Decidable p] : f Unit :=
if p then pure () else failure
@[inline] def assert {f : Type → Type v} [Alternative f] (p : Prop) [Decidable p] : f (Inhabited p) :=
if h : p then pure ⟨h⟩ else failure
/- Later we define a coercion from Bool to Prop, but this version will still be useful.
Given (t : tactic Bool), we can write t >>= guardb -/
@[inline] def guardb {f : Type → Type v} [Alternative f] : Bool → f Unit
| true := pure ()
| false := failure
@[inline] def optional (x : f α) : f (Option α) :=
some <$> x <|> pure none
end
|
68d8ecc728a201b41ea512d46233d98ea5c4d983 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/Load/Manifest.lean | eb4d87e8373fad1a9c0f91d88bf1341b7abace1f | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 4,458 | lean | /-
Copyright (c) 2022 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone, Gabriel Ebner
-/
import Lean.Data.Json
import Lake.Util.Log
open System Lean
namespace Lake
instance [ToJson α] : ToJson (NameMap α) where
toJson m := Json.obj <| m.fold (fun n k v => n.insert compare k.toString (toJson v)) .leaf
instance [FromJson α] : FromJson (NameMap α) where
fromJson? j := do
(← j.getObj?).foldM (init := {}) fun m k v =>
let k := k.toName
if k.isAnonymous then
throw "expected name"
else
return m.insert k (← fromJson? v)
/-- Current version of the manifest format. -/
def Manifest.version : Nat := 5
/-- An entry for a package stored in the manifest. -/
inductive PackageEntry
| /--
A local filesystem package. `dir` is relative to the package directory
of the package containing the manifest.
-/
path (name : Name) (opts : NameMap String) (inherited : Bool) (dir : FilePath)
| /-- A remote Git package. -/
git (name : Name) (opts : NameMap String) (inherited : Bool) (url : String) (rev : String)
(inputRev? : Option String) (subDir? : Option FilePath)
deriving FromJson, ToJson, Inhabited
namespace PackageEntry
@[inline] protected def name : PackageEntry → Name
| .path name .. | .git name .. => name
@[inline] protected def opts : PackageEntry → NameMap String
| .path _ opts .. | .git _ opts .. => opts
@[inline] protected def inherited : PackageEntry → Bool
| .path _ _ inherited .. | .git _ _ inherited .. => inherited
def setInherited : PackageEntry → PackageEntry
| .path name opts _ dir => .path name opts true dir
| .git name opts _ url rev inputRev? subDir? => .git name opts true url rev inputRev? subDir?
def inDirectory (pkgDir : FilePath) : PackageEntry → PackageEntry
| .path name opts inherited dir => .path name opts inherited (pkgDir / dir)
| entry => entry
end PackageEntry
/-- Manifest file format. -/
structure Manifest where
packagesDir? : Option FilePath := none
entryMap : NameMap PackageEntry := {}
namespace Manifest
def empty : Manifest := {}
def isEmpty (self : Manifest) : Bool :=
self.entryMap.isEmpty
def entryArray (self : Manifest) : Array PackageEntry :=
self.entryMap.fold (fun a _ v => a.push v) #[]
def contains (packageName : Name) (self : Manifest) : Bool :=
self.entryMap.contains packageName
def find? (packageName : Name) (self : Manifest) : Option PackageEntry :=
self.entryMap.find? packageName
def insert (entry : PackageEntry) (self : Manifest) : Manifest :=
{self with entryMap := self.entryMap.insert entry.name entry}
instance : ForIn m Manifest PackageEntry where
forIn self init f := self.entryMap.forIn init (f ·.2)
protected def toJson (self : Manifest) : Json :=
Json.mkObj [
("version", version),
("packagesDir", toJson self.packagesDir?),
("packages", toJson self.entryArray)
]
instance : ToJson Manifest := ⟨Manifest.toJson⟩
protected def fromJson? (json : Json) : Except String Manifest := do
let ver ← (← json.getObjVal? "version").getNat?
if ver = 5 then
let packagesDir? ← do
match json.getObjVal? "packagesDir" with
| .ok path => fromJson? path
| .error _ => pure none
let entries : Array PackageEntry ← fromJson? (← json.getObjVal? "packages")
return {
packagesDir?,
entryMap := entries.foldl (fun map entry => map.insert entry.name entry) {}
}
else if ver < 5 then
throw s!"incompatible manifest version `{ver}`"
else
throw s!"unknown manifest version `{ver}`"
instance : FromJson Manifest := ⟨Manifest.fromJson?⟩
def loadFromFile (file : FilePath) : IO Manifest := do
let contents ← IO.FS.readFile file
match Json.parse contents with
| .ok json =>
match fromJson? json with
| .ok manifest =>
return manifest
| .error e =>
throw <| IO.userError <| s!"improperly formatted manifest: {e}"
| .error e =>
throw <| IO.userError <| s!"invalid JSON in manifest: {e}"
def loadOrEmpty (file : FilePath) : LogIO Manifest := do
match (← loadFromFile file |>.toBaseIO) with
| .ok a => return a
| .error e =>
unless e matches .noFileOrDirectory .. do
logWarning (toString e)
return {}
def saveToFile (self : Manifest) (manifestFile : FilePath) : IO PUnit := do
let jsonString := Json.pretty self.toJson
IO.FS.writeFile manifestFile <| jsonString.push '\n'
|
c0e66b6ada3ecac62dd00d30aac7fbeef034e148 | 853df553b1d6ca524e3f0a79aedd32dde5d27ec3 | /src/category_theory/limits/cones.lean | f1e283db5a8ef4612659e63f61bd70efdc804a85 | [
"Apache-2.0"
] | permissive | DanielFabian/mathlib | efc3a50b5dde303c59eeb6353ef4c35a345d7112 | f520d07eba0c852e96fe26da71d85bf6d40fcc2a | refs/heads/master | 1,668,739,922,971 | 1,595,201,756,000 | 1,595,201,756,000 | 279,469,476 | 0 | 0 | null | 1,594,696,604,000 | 1,594,696,604,000 | null | UTF-8 | Lean | false | false | 17,031 | 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
universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation
open category_theory
variables {J : Type v} [small_category J]
variables {C : Type u} [category.{v} C]
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)
/--
Functorially associated to each functor `J ⥤ C`, we have the `C`-presheaf consisting of
cones with a given cone point.
-/
@[simps] def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) :=
{ obj := functor.cones,
map := λ F G f, whisker_left (const J).op (yoneda.map f) }
/--
Contravariantly associated to each functor `J ⥤ C`, we have the `C`-copresheaf consisting of
cocones with a given cocone point.
-/
@[simps] def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) :=
{ obj := λ F, functor.cocones (unop F),
map := λ F G f, whisker_left (const J) (coyoneda.map f) }
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, via `cone.equiv` below, 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, via `cone.equiv` below, 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
def equiv (F : J ⥤ C) : cone F ≅ Σ X, F.cones.obj X :=
{ hom := λ c, ⟨op c.X, c.π⟩,
inv := λ c, { X := unop c.1, π := c.2 },
hom_inv_id' := begin ext, cases x, refl, end,
inv_hom_id' := begin ext, cases x, refl, end }
@[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
@[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) :=
{ X := c.X,
π := whisker_left E c.π }
end cone
namespace cocone
def equiv (F : J ⥤ C) : cocone F ≅ Σ X, F.cocones.obj X :=
{ hom := λ c, ⟨c.X, c.ι⟩,
inv := λ c, { X := c.1, ι := c.2 },
hom_inv_id' := begin ext, cases x, refl, end,
inv_hom_id' := begin ext, cases x, refl, end }
@[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
@[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) :=
{ X := c.X,
ι := whisker_left E c.ι }
end cocone
@[ext] 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
@[simps] instance cone.category : category.{v} (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
/-- To give an isomorphism between cones, it suffices to give an
isomorphism between their vertices which commutes with the cone
maps. -/
@[ext, simps] 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) } }
@[simps] 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] } }
def postcompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) :
postcompose (α ≫ β) ≅ postcompose α ⋙ postcompose β :=
nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy)
def postcompose_id : postcompose (𝟙 F) ≅ 𝟭 (cone F) :=
nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy)
@[simps]
def postcompose_equivalence {G : J ⥤ C} (α : F ≅ G) : cone F ≌ cone G :=
{ functor := postcompose α.hom,
inverse := postcompose α.inv,
unit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy),
counit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) }
/--
Whiskering on the left by `E : K ⥤ J` gives a functor from `cone F` to `cone (E ⋙ F)`.
-/
@[simps]
def whiskering {K : Type v} [small_category K] (E : K ⥤ J) : cone F ⥤ cone (E ⋙ F) :=
{ obj := λ c, c.whisker E,
map := λ c c' f, { hom := f.hom, } }
/--
Whiskering by an equivalence gives an equivalence between categories of cones.
-/
@[simps]
def whiskering_equivalence {K : Type v} [small_category K] (e : K ≌ J) :
cone F ≌ cone (e.functor ⋙ F) :=
{ functor := whiskering e.functor,
inverse := whiskering e.inverse ⋙
postcompose ((functor.associator _ _ _).inv ≫ (whisker_right (e.counit_iso).hom F) ≫
(functor.left_unitor F).hom),
unit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy),
counit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _)
(begin
intro k,
have t := s.π.naturality (e.unit_inv.app k),
dsimp at t,
simp only [←e.counit_functor k, id_comp] at t,
dsimp,
simp [t],
end)) (by tidy), }
/--
The categories of cones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic
(possibly after changing the indexing category by an equivalence).
-/
def equivalence_of_reindexing {K : Type v} [small_category K] {G : K ⥤ C}
(e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cone F ≌ cone G :=
(whiskering_equivalence e).trans (postcompose_equivalence α)
@[simp]
lemma equivalence_of_reindexing_functor_obj {K : Type v} [small_category K] {G : K ⥤ C}
(e : K ≌ J) (α : e.functor ⋙ F ≅ G) (c : cone F) :
(equivalence_of_reindexing e α).functor.obj c =
(postcompose α.hom).obj (cone.whisker e.functor c) :=
rfl
section
variable (F)
@[simps]
def forget : cone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
variables {D : Type u'} [category.{v} D] (G : C ⥤ D)
@[simps] def functoriality : 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] } }
instance functoriality_full [full G] [faithful G] : full (functoriality F G) :=
{ preimage := λ X Y t,
{ hom := G.preimage t.hom,
w' := λ j, G.map_injective (by simpa using t.w j) } }
instance functoriality_faithful [faithful G] : faithful (cones.functoriality F G) :=
{ map_injective' := λ X Y f g e, by { ext1, injection e, apply G.map_injective h_1 } }
end
end cones
@[ext] 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
@[simps] instance cocone.category : category.{v} (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
/-- To give an isomorphism between cocones, it suffices to give an
isomorphism between their vertices which commutes with the cocone
maps. -/
@[ext, simps] 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 } }
@[simps] def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G :=
{ obj := λ c, { X := c.X, ι := α ≫ c.ι },
map := λ c₁ c₂ f, { hom := f.hom } }
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) ≅ 𝟭 (cocone F) :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
@[simps]
def precompose_equivalence {G : J ⥤ C} (α : G ≅ F) : cocone F ≌ cocone G :=
{ functor := precompose α.hom,
inverse := precompose α.inv,
unit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy),
counit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) }
/--
Whiskering on the left by `E : K ⥤ J` gives a functor from `cocone F` to `cocone (E ⋙ F)`.
-/
@[simps]
def whiskering {K : Type v} [small_category K] (E : K ⥤ J) : cocone F ⥤ cocone (E ⋙ F) :=
{ obj := λ c, c.whisker E,
map := λ c c' f, { hom := f.hom, } }
/--
Whiskering by an equivalence gives an equivalence between categories of cones.
-/
@[simps]
def whiskering_equivalence {K : Type v} [small_category K] (e : K ≌ J) :
cocone F ≌ cocone (e.functor ⋙ F) :=
{ functor := whiskering e.functor,
inverse := whiskering e.inverse ⋙
precompose ((functor.left_unitor F).inv ≫ (whisker_right (e.counit_iso).inv F) ≫ (functor.associator _ _ _).inv),
unit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy),
counit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _)
(begin
intro k,
have t := s.ι.naturality (e.unit.app k),
dsimp at t,
simp only [e.functor_unit k, comp_id] at t,
dsimp,
simp [t],
end)) (by tidy), }
/--
The categories of cocones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic
(possibly after changing the indexing category by an equivalence).
-/
def equivalence_of_reindexing {K : Type v} [small_category K] {G : K ⥤ C}
(e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cocone F ≌ cocone G :=
(whiskering_equivalence e).trans (precompose_equivalence α.symm)
@[simp]
lemma equivalence_of_reindexing_functor_obj {K : Type v} [small_category K] {G : K ⥤ C}
(e : K ≌ J) (α : e.functor ⋙ F ≅ G) (c : cocone F) :
(equivalence_of_reindexing e α).functor.obj c =
(precompose α.inv).obj (cocone.whisker e.functor c) :=
rfl
section
variable (F)
@[simps]
def forget : cocone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
variables {D : Type u'} [category.{v} D] (G : C ⥤ D)
@[simps] def functoriality : 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] } }
instance functoriality_full [full G] [faithful G] : full (functoriality F G) :=
{ preimage := λ X Y t,
{ hom := G.preimage t.hom,
w' := λ j, G.map_injective (by simpa using t.w j) } }
instance functoriality_faithful [faithful G] : faithful (functoriality F G) :=
{ map_injective' := λ X Y f g e, by { ext1, injection e, apply G.map_injective h_1 } }
end
end cocones
end limits
namespace functor
variables {D : Type u'} [category.{v} 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 F 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 F 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
@[simps]
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.inv) : F ⋙ (H ⋙ inv H) ⟶ _) ≫ (functor.right_unitor _).hom in
{ X := t.X,
π := ((category_theory.cones J C).map α).app (op t.X) t.π }
def map_cone_morphism {c c' : cone F} (f : c ⟶ c') :
(H.map_cone c) ⟶ (H.map_cone c') := (cones.functoriality F H).map f
def map_cocone_morphism {c c' : cocone F} (f : c ⟶ c') :
(H.map_cocone c) ⟶ (H.map_cocone c') := (cocones.functoriality F 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
/-- `map_cone` is the left inverse to `map_cone_inv`. -/
def map_cone_map_cone_inv {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cone (F ⋙ H)) :
map_cone H (map_cone_inv H c) ≅ c :=
begin
apply cones.ext _ (λ j, _),
{ exact H.inv_fun_id.app c.X },
{ dsimp,
erw [comp_id, ← H.inv_fun_id.hom.naturality (c.π.app j), comp_map, H.map_comp],
congr' 1,
erw [← cancel_epi (H.inv_fun_id.inv.app (H.obj (F.obj j))), nat_iso.inv_hom_id_app,
← (functor.as_equivalence H).functor_unit _, ← H.map_comp, nat_iso.hom_inv_id_app,
H.map_id],
refl }
end
end functor
end category_theory
namespace category_theory.limits
variables {F : J ⥤ Cᵒᵖ}
-- Here and below we only automatically generate the `@[simp]` lemma for the `X` field,
-- as we can be a simpler `rfl` lemma for the components of the natural transformation by hand.
@[simps X] 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_π_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 }
@[simps X] 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_ι_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 }
@[simps X] 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_ι_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 }
@[simps X] 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_π_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
|
20a13a73d137703b051ceedff0e6d951691e5208 | e24425fbf75189e4b34ef6b29f5f274e70cd5011 | /src/week04.lean | 613878f0b513b1b6602ca9a13267c3cb61fafb16 | [] | no_license | UVM-M52/week04-chuyisun | a654ea18050ca25b2d2865cfcf568c89cde593dd | ed1dafaa43d33e878e71dbdac00535118afd3afc | refs/heads/master | 1,609,225,390,456 | 1,581,527,077,000 | 1,581,527,077,000 | 238,504,390 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,515 | lean | -- Math 52: Week 4
import .utils.int_refl
-- Lakins Definition 1.2.1:
definition is_even (n : ℤ) := ∃ (k : ℤ), n = 2 * k
definition is_odd (n : ℤ) := ∃ (k : ℤ), n = 2 * k + 1
-- Lakins Definition 2.1.1: Let a, b ∈ ℤ.
-- a divides b if there exists n ∈ ℤ such that b = an.
-- We write a ∣ b for "a divides b" and say that a is
-- a divisor of b.
definition divides (a b : ℤ) : Prop := ∃ (n : ℤ), a * n = b
-- The notation `a ∣ b` can be used for `divides a b`
local infix ∣ := divides
-- Lakins Example 2.1.2:
example : 3 ∣ 12 :=
begin
unfold divides,
existsi (4:ℤ),
refl,
end
-- Theorem: For every integer a, a ∣ a.
theorem divides_refl : ∀ (a : ℤ), a ∣ a :=
begin
intro a,
unfold divides,
existsi (1:ℤ),
calc a * 1 = a : by rw mul_one,
end
-- Proof: Let a ∈ ℤ be arbitrary. We must show that a ∣ a;
-- i.e., we must find an integer k such that a = a * k.
-- Since a = a * 1 and 1 is an integer, we see that
-- a ∣ a is true. □
-- Lakins Proposition 2.1.3: For all integers a, b, c,
-- if a ∣ b and b ∣ c, then a ∣ c.
theorem divides_trans : ∀ (a b c : ℤ), a ∣ b ∧ b ∣ c → a ∣ c :=
begin
intros a b c,
intro H,
cases H,
unfold divides,
unfold divides at H_left H_right,
cases H_left with n,
cases H_right with m,
existsi(n*m:ℤ),
symmetry,
calc c
=b*m : by rw H_right_h ...
=(a*n)*m : by rw H_left_h ...
=a*(n*m): by ac_refl,
end
-- Proof: Let a,b,c ∈ ℤ be arbitrary and assume that
-- a ∣ b and b ∣ c. We must show that a ∣ c; i.e., we
-- must find an integer k such that c = a * k.
--
-- Since a ∣ b, by Definition 2.1.1 we may fix n ∈ ℤ
-- such that b = a * n. Similarly, since b | c, we may
-- fix m ∈ ℤ such that c = b * m, again by Definition
-- 2.1.1. Then
-- c = b * m = (a * n) * m = a * (n * m),
-- since multiplication of integers is associative
-- (Basic Properties of Integers 1.2.3). Since
-- n * m ∈ ℤ, we have proved that a ∣ c, by
-- Definition 2.1.1, as desired.
-- Lakins Exercise 2.1.1: Let a,b, and c be integers.
-- For all integers m and n, if a ∣ b and a ∣ c, then
-- a ∣ (bm + cn).
theorem L211 : ∀ (a b c m n : ℤ), a ∣ b ∧ a ∣ c → a ∣ (b * m + c * n) :=
begin
sorry
end
-- Theorem: For every integer a, a is even if and only if 2 ∣ a.
theorem is_even_iff_two_divides : ∀ (a : ℤ), is_even a ↔ 2 ∣ a :=
begin
sorry
end
-- We will prove this fact later after we discuss induction.
-- For now we take it as an axiom, i.e., as statement that we
-- take as true without proof.
axiom even_or_odd (a : ℤ) : is_even a ∨ is_odd a
-- Lakins Theorem 2.1.9: For all integers a, a(a + 1) is even.
theorem even_product : ∀ (a : ℤ), is_even (a * (a + 1)) :=
begin
sorry
end
-- Proof: Let a ∈ ℤ. We show that a(a + 1) is even by
-- considering two cases.
--
-- Case I: a is even.
-- Then 2 ∣ a, by Definition 1.2.1. Since a ∣ a(a + 1)
-- by Definition 2.1.1, we have that 2 ∣ a(a + 1) since
-- the divisibility relation is transitive (Proposition
-- 2.1.3). Hence a(a + 1) is even.
--
-- Case II: a is not even.
-- Since a is not even, we know that a is odd. Then
-- a+1 is even by Exercise 1.2.2b. Then, using an
-- argument similar to that of Case I, we have that
-- 2 ∣ (a+1) and (a+1) ∣ a(a+1), and hence 2 ∣ a(a+1)
-- by Proposition 2.1.3. Thus a(a + 1) is even.
--
-- Hence, since we have considered all possible cases
-- for the integer a, we have proved that for all
-- integers a, a(a + 1) is even.
|
e4fd0338f5a9ecd250c68e883b272af1a18e736b | 1446f520c1db37e157b631385707cc28a17a595e | /stage0/src/Init/Lean/Elab/BuiltinNotation.lean | 1a46130d30bcfb0ace41559710c551b60e8439e7 | [
"Apache-2.0"
] | permissive | bdbabiak/lean4 | cab06b8a2606d99a168dd279efdd404edb4e825a | 3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac | refs/heads/master | 1,615,045,275,530 | 1,583,793,696,000 | 1,583,793,696,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,613 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Elab.Term
import Init.Lean.Elab.Quotation
namespace Lean
namespace Elab
namespace Term
@[builtinMacro Lean.Parser.Term.dollar] def expandDollar : Macro :=
fun stx => match_syntax stx with
| `($f $args* $ $a) => let args := args.push a; `($f $args*)
| `($f $ $a) => `($f $a)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.dollarProj] def expandDollarProj : Macro :=
fun stx => match_syntax stx with
| `($term $.$field) => `($(term).$field)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.if] def expandIf : Macro :=
fun stx => match_syntax stx with
| `(if $h : $cond then $t else $e) => `(dite $cond (fun $h:ident => $t) (fun $h:ident => $e))
| `(if $cond then $t else $e) => `(ite $cond $t $e)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.subtype] def expandSubtype : Macro :=
fun stx => match_syntax stx with
| `({ $x : $type // $p }) => `(Subtype (fun ($x:ident : $type) => $p))
| `({ $x // $p }) => `(Subtype (fun ($x:ident : _) => $p))
| _ => Macro.throwUnsupported
@[builtinTermElab anonymousCtor] def elabAnonymousCtor : TermElab :=
fun stx expectedType? => match_syntax stx with
| `(⟨$args*⟩) => do
let ref := stx;
tryPostponeIfNoneOrMVar expectedType?;
match expectedType? with
| some expectedType => do
expectedType ← instantiateMVars ref expectedType;
let expectedType := expectedType.consumeMData;
match expectedType.getAppFn with
| Expr.const constName _ _ => do
env ← getEnv;
match env.find? constName with
| some (ConstantInfo.inductInfo val) =>
match val.ctors with
| [ctor] => do
stx ← `($(mkCTermIdFrom ref ctor) $(args.getSepElems)*);
withMacroExpansion ref stx $ elabTerm stx expectedType?
| _ => throwError ref ("invalid constructor ⟨...⟩, '" ++ constName ++ "' must have only one constructor")
| _ => throwError ref ("invalid constructor ⟨...⟩, '" ++ constName ++ "' is not an inductive type")
| _ => throwError ref ("invalid constructor ⟨...⟩, expected type is not an inductive type " ++ indentExpr expectedType)
| none => throwError ref "invalid constructor ⟨...⟩, expected type must be known"
| _ => throwUnsupportedSyntax
@[builtinMacro Lean.Parser.Term.show] def expandShow : Macro :=
fun stx => match_syntax stx with
| `(show $type from $val) => let thisId := mkIdentFrom stx `this; `(let! $thisId : $type := $val; $thisId)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.have] def expandHave : Macro :=
fun stx => match_syntax stx with
| `(have $type from $val; $body) => let thisId := mkIdentFrom stx `this; `(let! $thisId : $type := $val; $body)
| `(have $type := $val; $body) => let thisId := mkIdentFrom stx `this; `(let! $thisId : $type := $val; $body)
| `(have $x : $type from $val; $body) => `(let! $x:ident : $type := $val; $body)
| `(have $x : $type := $val; $body) => `(let! $x:ident : $type := $val; $body)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.where] def expandWhere : Macro :=
fun stx => match_syntax stx with
| `($body where $decls:letDecl*) => do
let decls := decls.getEvenElems;
decls.foldrM
(fun decl body => `(let $decl:letDecl; $body))
body
| _ => Macro.throwUnsupported
@[builtinTermElab «parser!»] def elabParserMacro : TermElab :=
adaptExpander $ fun stx => match_syntax stx with
| `(parser! $e) => do
some declName ← getDeclName?
| throwError stx "invalid `parser!` macro, it must be used in definitions";
match extractMacroScopes declName with
| { name := Name.str _ s _, scopes := scps, .. } => do
let kind := quote declName;
let s := quote s;
p ← `(Lean.Parser.leadingNode $kind $e);
if scps == [] then
-- TODO simplify the following quotation as soon as we have coercions
`(HasOrelse.orelse (Lean.Parser.mkAntiquot $s (some $kind)) $p)
else
-- if the parser decl is hidden by hygiene, it doesn't make sense to provide an antiquotation kind
`(HasOrelse.orelse (Lean.Parser.mkAntiquot $s none) $p)
| _ => throwError stx "invalid `parser!` macro, unexpected declaration name"
| _ => throwUnsupportedSyntax
@[builtinTermElab «tparser!»] def elabTParserMacro : TermElab :=
adaptExpander $ fun stx => match_syntax stx with
| `(tparser! $e) => do
declName? ← getDeclName?;
match declName? with
| some declName => let kind := quote declName; `(Lean.Parser.trailingNode $kind $e)
| none => throwError stx "invalid `tparser!` macro, it must be used in definitions"
| _ => throwUnsupportedSyntax
def elabInfix (f : Syntax) : Macro :=
fun stx => do
-- term `op` term
let a := stx.getArg 0;
let b := stx.getArg 2;
pure (mkAppStx f #[a, b])
def elabInfixOp (op : Name) : Macro :=
fun stx => elabInfix (mkCTermIdFrom (stx.getArg 1) op) stx
@[builtinMacro Lean.Parser.Term.prod] def elabProd : Macro := elabInfixOp `Prod
@[builtinMacro Lean.Parser.Term.fcomp] def ElabFComp : Macro := elabInfixOp `Function.comp
@[builtinMacro Lean.Parser.Term.add] def elabAdd : Macro := elabInfixOp `HasAdd.add
@[builtinMacro Lean.Parser.Term.sub] def elabSub : Macro := elabInfixOp `HasSub.sub
@[builtinMacro Lean.Parser.Term.mul] def elabMul : Macro := elabInfixOp `HasMul.mul
@[builtinMacro Lean.Parser.Term.div] def elabDiv : Macro := elabInfixOp `HasDiv.div
@[builtinMacro Lean.Parser.Term.mod] def elabMod : Macro := elabInfixOp `HasMod.mod
@[builtinMacro Lean.Parser.Term.modN] def elabModN : Macro := elabInfixOp `HasModN.modn
@[builtinMacro Lean.Parser.Term.pow] def elabPow : Macro := elabInfixOp `HasPow.pow
@[builtinMacro Lean.Parser.Term.le] def elabLE : Macro := elabInfixOp `HasLessEq.LessEq
@[builtinMacro Lean.Parser.Term.ge] def elabGE : Macro := elabInfixOp `GreaterEq
@[builtinMacro Lean.Parser.Term.lt] def elabLT : Macro := elabInfixOp `HasLess.Less
@[builtinMacro Lean.Parser.Term.gt] def elabGT : Macro := elabInfixOp `Greater
@[builtinMacro Lean.Parser.Term.eq] def elabEq : Macro := elabInfixOp `Eq
@[builtinMacro Lean.Parser.Term.ne] def elabNe : Macro := elabInfixOp `Ne
@[builtinMacro Lean.Parser.Term.beq] def elabBEq : Macro := elabInfixOp `HasBeq.beq
@[builtinMacro Lean.Parser.Term.bne] def elabBNe : Macro := elabInfixOp `bne
@[builtinMacro Lean.Parser.Term.heq] def elabHEq : Macro := elabInfixOp `HEq
@[builtinMacro Lean.Parser.Term.equiv] def elabEquiv : Macro := elabInfixOp `HasEquiv.Equiv
@[builtinMacro Lean.Parser.Term.and] def elabAnd : Macro := elabInfixOp `And
@[builtinMacro Lean.Parser.Term.or] def elabOr : Macro := elabInfixOp `Or
@[builtinMacro Lean.Parser.Term.iff] def elabIff : Macro := elabInfixOp `Iff
@[builtinMacro Lean.Parser.Term.band] def elabBAnd : Macro := elabInfixOp `and
@[builtinMacro Lean.Parser.Term.bor] def elabBOr : Macro := elabInfixOp `or
@[builtinMacro Lean.Parser.Term.append] def elabAppend : Macro := elabInfixOp `HasAppend.append
@[builtinMacro Lean.Parser.Term.cons] def elabCons : Macro := elabInfixOp `List.cons
@[builtinMacro Lean.Parser.Term.andthen] def elabAndThen : Macro := elabInfixOp `HasAndthen.andthen
@[builtinMacro Lean.Parser.Term.bindOp] def elabBind : Macro := elabInfixOp `HasBind.bind
@[builtinMacro Lean.Parser.Term.seq] def elabseq : Macro := elabInfixOp `HasSeq.seq
@[builtinMacro Lean.Parser.Term.seqLeft] def elabseqLeft : Macro := elabInfixOp `HasSeqLeft.seqLeft
@[builtinMacro Lean.Parser.Term.seqRight] def elabseqRight : Macro := elabInfixOp `HasSeqRight.seqRight
@[builtinMacro Lean.Parser.Term.map] def elabMap : Macro := elabInfixOp `Functor.map
@[builtinMacro Lean.Parser.Term.mapRev] def elabMapRev : Macro := elabInfixOp `Functor.mapRev
@[builtinMacro Lean.Parser.Term.mapConst] def elabMapConst : Macro := elabInfixOp `Functor.mapConst
@[builtinMacro Lean.Parser.Term.mapConstRev] def elabMapConstRev : Macro := elabInfixOp `Functor.mapConstRev
@[builtinMacro Lean.Parser.Term.orelse] def elabOrElse : Macro := elabInfixOp `HasOrelse.orelse
@[builtinMacro Lean.Parser.Term.orM] def elabOrM : Macro := elabInfixOp `orM
@[builtinMacro Lean.Parser.Term.andM] def elabAndM : Macro := elabInfixOp `andM
/-
TODO
@[builtinTermElab] def elabsubst : TermElab := elabInfixOp infixR " ▸ " 75
-/
end Term
end Elab
end Lean
|
2b4d64db920e131b245088f92bab48420e36344b | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/combinatorics/hall/finite.lean | 1924706d8ef03039209b53a0e88506dc7449672d | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,645 | lean | /-
Copyright (c) 2021 Alena Gusakov, Bhavik Mehta, Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alena Gusakov, Bhavik Mehta, Kyle Miller
-/
import data.fintype.basic
import data.rel
import data.set.finite
/-!
# Hall's Marriage Theorem for finite index types
This module proves the basic form of Hall's theorem.
In constrast to the theorem described in `combinatorics.hall.basic`, this
version requires that the indexed family `t : ι → finset α` have `ι` be a `fintype`.
The `combinatorics.hall.basic` module applies a compactness argument to this version
to remove the `fintype` constraint on `ι`.
The modules are split like this since the generalized statement
depends on the topology and category theory libraries, but the finite
case in this module has few dependencies.
A description of this formalization is in [Gusakov2021].
## Main statements
* `finset.all_card_le_bUnion_card_iff_exists_injective'` is Hall's theorem with
a finite index set. This is elsewhere generalized to
`finset.all_card_le_bUnion_card_iff_exists_injective`.
## Tags
Hall's Marriage Theorem, indexed families
-/
open finset
universes u v
namespace hall_marriage_theorem
variables {ι : Type u} {α : Type v} [fintype ι]
theorem hall_hard_inductive_zero (t : ι → finset α) (hn : fintype.card ι = 0) :
∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x :=
begin
rw fintype.card_eq_zero_iff at hn,
exactI ⟨is_empty_elim, is_empty_elim, is_empty_elim⟩,
end
variables {t : ι → finset α} [decidable_eq α]
lemma hall_cond_of_erase {x : ι} (a : α)
(ha : ∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card)
(s' : finset {x' : ι | x' ≠ x}) :
s'.card ≤ (s'.bUnion (λ x', (t x').erase a)).card :=
begin
haveI := classical.dec_eq ι,
specialize ha (s'.image coe),
rw [nonempty.image_iff, finset.card_image_of_injective s' subtype.coe_injective] at ha,
by_cases he : s'.nonempty,
{ have ha' : s'.card < (s'.bUnion (λ x, t x)).card,
{ specialize ha he (λ h, by { have h' := mem_univ x, rw ←h at h', simpa using h' }),
convert ha using 2,
ext x,
simp only [mem_image, mem_bUnion, exists_prop, set_coe.exists,
exists_and_distrib_right, exists_eq_right, subtype.coe_mk], },
rw ←erase_bUnion,
by_cases hb : a ∈ s'.bUnion (λ x, t x),
{ rw card_erase_of_mem hb,
exact nat.le_pred_of_lt ha' },
{ rw erase_eq_of_not_mem hb,
exact nat.le_of_lt ha' }, },
{ rw [nonempty_iff_ne_empty, not_not] at he,
subst s',
simp },
end
/--
First case of the inductive step: assuming that
`∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card`
and that the statement of **Hall's Marriage Theorem** is true for all
`ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`.
-/
lemma hall_hard_inductive_step_A {n : ℕ} (hn : fintype.card ι = n + 1)
(ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card)
(ih : ∀ {ι' : Type u} [fintype ι'] (t' : ι' → finset α),
by exactI fintype.card ι' ≤ n →
(∀ (s' : finset ι'), s'.card ≤ (s'.bUnion t').card) →
∃ (f : ι' → α), function.injective f ∧ ∀ x, f x ∈ t' x)
(ha : ∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card) :
∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x :=
begin
haveI : nonempty ι := fintype.card_pos_iff.mp (hn.symm ▸ nat.succ_pos _),
haveI := classical.dec_eq ι,
/- Choose an arbitrary element `x : ι` and `y : t x`. -/
let x := classical.arbitrary ι,
have tx_ne : (t x).nonempty,
{ rw ←finset.card_pos,
apply nat.lt_of_lt_of_le nat.one_pos,
convert ht {x},
rw finset.singleton_bUnion, },
rcases classical.indefinite_description _ tx_ne with ⟨y, hy⟩,
/- Restrict to everything except `x` and `y`. -/
let ι' := {x' : ι | x' ≠ x},
let t' : ι' → finset α := λ x', (t x').erase y,
have card_ι' : fintype.card ι' = n,
{ convert congr_arg (λ m, m - 1) hn,
convert set.card_ne_eq _, },
rcases ih t' card_ι'.le (hall_cond_of_erase y ha) with ⟨f', hfinj, hfr⟩,
/- Extend the resulting function. -/
refine ⟨λ z, if h : z = x then y else f' ⟨z, h⟩, _, _⟩,
{ rintro z₁ z₂,
have key : ∀ {x}, y ≠ f' x,
{ intros x h,
specialize hfr x,
rw ←h at hfr,
simpa using hfr, },
by_cases h₁ : z₁ = x; by_cases h₂ : z₂ = x; simp [h₁, h₂, hfinj.eq_iff, key, key.symm], },
{ intro z,
split_ifs with hz,
{ rwa hz },
{ specialize hfr ⟨z, hz⟩,
rw mem_erase at hfr,
exact hfr.2, }, },
end
lemma hall_cond_of_restrict {ι : Type u} {t : ι → finset α} {s : finset ι}
(ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card)
(s' : finset (s : set ι)) :
s'.card ≤ (s'.bUnion (λ a', t a')).card :=
begin
haveI := classical.dec_eq ι,
convert ht (s'.image coe) using 1,
{ rw card_image_of_injective _ subtype.coe_injective, },
{ apply congr_arg,
ext y,
simp, },
end
lemma hall_cond_of_compl {ι : Type u} {t : ι → finset α} {s : finset ι}
(hus : s.card = (s.bUnion t).card)
(ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card)
(s' : finset (sᶜ : set ι)) :
s'.card ≤ (s'.bUnion (λ x', t x' \ s.bUnion t)).card :=
begin
haveI := classical.dec_eq ι,
have : s'.card = (s ∪ s'.image coe).card - s.card,
{ rw [card_disjoint_union, nat.add_sub_cancel_left,
card_image_of_injective _ subtype.coe_injective],
simp only [disjoint_left, not_exists, mem_image, exists_prop, set_coe.exists,
exists_and_distrib_right, exists_eq_right, subtype.coe_mk],
intros x hx hc h,
exact (hc hx).elim },
rw [this, hus],
apply (nat.sub_le_sub_right (ht _) _).trans _,
rw ← card_sdiff,
{ have : (s ∪ s'.image subtype.val).bUnion t \ s.bUnion t ⊆ s'.bUnion (λ x', t x' \ s.bUnion t),
{ intros t,
simp only [mem_bUnion, mem_sdiff, not_exists, mem_image, and_imp, mem_union,
exists_and_distrib_right, exists_imp_distrib],
rintro x (hx | ⟨x', hx', rfl⟩) rat hs,
{ exact (hs x hx rat).elim },
{ exact ⟨⟨x', hx', rat⟩, hs⟩, } },
exact (card_le_of_subset this).trans le_rfl, },
{ apply bUnion_subset_bUnion_of_subset_left,
apply subset_union_left }
end
/--
Second case of the inductive step: assuming that
`∃ (s : finset ι), s ≠ univ → s.card = (s.bUnion t).card`
and that the statement of Hall's Marriage Theorem is true for all
`ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`.
-/
lemma hall_hard_inductive_step_B {n : ℕ} (hn : fintype.card ι = n + 1)
(ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card)
(ih : ∀ {ι' : Type u} [fintype ι'] (t' : ι' → finset α),
by exactI fintype.card ι' ≤ n →
(∀ (s' : finset ι'), s'.card ≤ (s'.bUnion t').card) →
∃ (f : ι' → α), function.injective f ∧ ∀ x, f x ∈ t' x)
(s : finset ι)
(hs : s.nonempty)
(hns : s ≠ univ)
(hus : s.card = (s.bUnion t).card) :
∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x :=
begin
haveI := classical.dec_eq ι,
/- Restrict to `s` -/
let t' : s → finset α := λ x', t x',
rw nat.add_one at hn,
have card_ι'_le : fintype.card s ≤ n,
{ apply nat.le_of_lt_succ,
rw ←hn,
convert (card_lt_iff_ne_univ _).mpr hns,
convert fintype.card_coe _ },
rcases ih t' card_ι'_le (hall_cond_of_restrict ht) with ⟨f', hf', hsf'⟩,
/- Restrict to `sᶜ` in the domain and `(s.bUnion t)ᶜ` in the codomain. -/
set ι'' := (s : set ι)ᶜ with ι''_def,
let t'' : ι'' → finset α := λ a'', t a'' \ s.bUnion t,
have card_ι''_le : fintype.card ι'' ≤ n,
{ apply nat.le_of_lt_succ,
rw ←hn,
convert (card_compl_lt_iff_nonempty _).mpr hs,
convert fintype.card_coe (sᶜ),
exact (finset.coe_compl s).symm },
rcases ih t'' card_ι''_le (hall_cond_of_compl hus ht) with ⟨f'', hf'', hsf''⟩,
/- Put them together -/
have f'_mem_bUnion : ∀ {x'} (hx' : x' ∈ s), f' ⟨x', hx'⟩ ∈ s.bUnion t,
{ intros x' hx',
rw mem_bUnion,
exact ⟨x', hx', hsf' _⟩, },
have f''_not_mem_bUnion : ∀ {x''} (hx'' : ¬ x'' ∈ s), ¬ f'' ⟨x'', hx''⟩ ∈ s.bUnion t,
{ intros x'' hx'',
have h := hsf'' ⟨x'', hx''⟩,
rw mem_sdiff at h,
exact h.2, },
have im_disj : ∀ {x' x'' : ι} {hx' : x' ∈ s} {hx'' : ¬x'' ∈ s}, f' ⟨x', hx'⟩ ≠ f'' ⟨x'', hx''⟩,
{ intros _ _ hx' hx'' h,
apply f''_not_mem_bUnion hx'',
rw ←h,
apply f'_mem_bUnion, },
refine ⟨λ x, if h : x ∈ s then f' ⟨x, h⟩ else f'' ⟨x, h⟩, _, _⟩,
{ exact hf'.dite _ hf'' @im_disj },
{ intro x,
split_ifs,
{ exact hsf' ⟨x, h⟩ },
{ exact sdiff_subset _ _ (hsf'' ⟨x, h⟩) } }
end
/--
If `ι` has cardinality `n + 1` and the statement of Hall's Marriage Theorem
is true for all `ι'` of cardinality ≤ `n`, then it is true for `ι`.
-/
theorem hall_hard_inductive_step {n : ℕ} (hn : fintype.card ι = n + 1)
(ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card)
(ih : ∀ {ι' : Type u} [fintype ι'] (t' : ι' → finset α),
by exactI fintype.card ι' ≤ n →
(∀ (s' : finset ι'), s'.card ≤ (s'.bUnion t').card) →
∃ (f : ι' → α), function.injective f ∧ ∀ x, f x ∈ t' x) :
∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x :=
begin
by_cases h : ∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card,
{ exact hall_hard_inductive_step_A hn ht @ih h, },
{ push_neg at h,
rcases h with ⟨s, sne, snu, sle⟩,
have seq := nat.le_antisymm (ht _) sle,
exact hall_hard_inductive_step_B hn ht @ih s sne snu seq, },
end
/--
Here we combine the base case and the inductive step into
a full strong induction proof, thus completing the proof
of the second direction.
-/
theorem hall_hard_inductive {n : ℕ} (hn : fintype.card ι = n)
(ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) :
∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x :=
begin
tactic.unfreeze_local_instances,
revert ι,
refine nat.strong_induction_on n (λ n' ih, _),
intros _ _ t hn ht,
rcases n' with (_|_),
{ exact hall_hard_inductive_zero t hn },
{ apply hall_hard_inductive_step hn ht,
introsI ι' _ _ hι',
exact ih (fintype.card ι') (nat.lt_succ_of_le hι') rfl, },
end
end hall_marriage_theorem
/--
This is the version of **Hall's Marriage Theorem** in terms of indexed
families of finite sets `t : ι → finset α` with `ι` a `fintype`.
It states that there is a set of distinct representatives if and only
if every union of `k` of the sets has at least `k` elements.
See `finset.all_card_le_bUnion_card_iff_exists_injective` for a version
where the `fintype ι` constraint is removed.
-/
theorem finset.all_card_le_bUnion_card_iff_exists_injective'
{ι α : Type*} [fintype ι] [decidable_eq α] (t : ι → finset α) :
(∀ (s : finset ι), s.card ≤ (s.bUnion t).card) ↔
(∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x) :=
begin
split,
{ exact hall_marriage_theorem.hall_hard_inductive rfl },
{ rintro ⟨f, hf₁, hf₂⟩ s,
rw ←card_image_of_injective s hf₁,
apply card_le_of_subset,
intro _,
rw [mem_image, mem_bUnion],
rintros ⟨x, hx, rfl⟩,
exact ⟨x, hx, hf₂ x⟩, },
end
|
baf0c7f4075951a3b5e45b5d9b284e7d4387c718 | bdd56e6eb0f467437e368d613de75299495d4054 | /src/category_theory/limits/shapes/equalizers.lean | fbe98857da3d8a840b1a42b3b71c744dc6d28282 | [] | no_license | truong111000/formalabstracts | 49a04c268ccee136e48e24e9d5dcb6fedea4b53e | 93a89a5c05c6fbc23eb9b914b60dcc353e609cd2 | refs/heads/master | 1,589,551,767,824 | 1,555,708,723,000 | 1,555,708,723,000 | 182,326,292 | 0 | 0 | null | 1,555,708,332,000 | 1,555,708,331,000 | null | UTF-8 | Lean | false | false | 4,846 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import .pullbacks basic
open category_theory
namespace category_theory.limits
-- local attribute [tidy] tactic.case_bash
universes u v
@[derive decidable_eq] inductive walking_pair : Type v
| zero | one
open walking_pair
inductive walking_pair_hom : walking_pair → walking_pair → Type v
| left : walking_pair_hom zero one
| right : walking_pair_hom zero one
| id : Π X : walking_pair.{v}, walking_pair_hom X X
open walking_pair_hom
instance walking_pair_category : small_category walking_pair :=
{ hom := walking_pair_hom,
id := walking_pair_hom.id,
comp := λ X Y Z f g, match X, Y, Z, f, g with
| _, _ ,_, (id _), h := h
| _, _, _, left, (id one) := left
| _, _, _, right, (id one) := right
end,
id_comp' := omitted,
comp_id' := omitted,
assoc' := omitted}
lemma walking_pair_hom_id (X : walking_pair.{v}) : walking_pair_hom.id X = 𝟙 X := rfl
variables {C : Type u} [𝒞 : category.{v} C]
include 𝒞
variables {X Y : C}
def pair (f g : X ⟶ Y) : walking_pair.{v} ⥤ C :=
{ obj := λ x, match x with
| zero := X
| one := Y
end,
map := λ x y h, match x, y, h with
| a, b, (id c) := 𝟙 _
| a, b, left := f
| a, b, right := g
end,
map_id' := omitted,
map_comp' := by exact omitted } -- what the heck
@[simp] lemma pair_map_left (f g : X ⟶ Y) : (pair f g).map left = f := rfl
@[simp] lemma pair_map_right (f g : X ⟶ Y) : (pair f g).map right = g := rfl
@[simp] lemma pair_functor_obj {F : walking_pair.{v} ⥤ C} (j : walking_pair.{v}) :
(pair (F.map left) (F.map right)).obj j = F.obj j :=
begin
cases j; refl
end
def fork (f g : X ⟶ Y) := cone (pair f g)
def cofork (f g : X ⟶ Y) := cocone (pair f g)
variables {f g : X ⟶ Y}
attribute [simp] walking_pair_hom_id
def fork.of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork f g :=
{ X := P,
π :=
{ app := λ X, begin cases X, exact ι, exact ι ≫ f, end,
naturality' := λ X Y f,
begin
cases X; cases Y; cases f; dsimp; simp,
exact w
end }}
def cofork.of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork f g :=
{ X := P,
ι :=
{ app := λ X, begin cases X, exact f ≫ π, exact π, end,
naturality' := λ X Y f,
begin
cases X; cases Y; cases f; dsimp; simp,
exact eq.symm w
end }}
@[simp] lemma fork.of_ι_app_zero {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) :
(fork.of_ι ι w).π.app zero = ι := rfl
@[simp] lemma fork.of_ι_app_one {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) :
(fork.of_ι ι w).π.app one = ι ≫ f := rfl
def fork.ι (t : fork f g) := t.π.app zero
def cofork.π (t : cofork f g) := t.ι.app one
def fork.condition (t : fork f g) : (fork.ι t) ≫ f = (fork.ι t) ≫ g :=
begin
erw [t.w left, ← t.w right], refl
end
def cofork.condition (t : cofork f g) : f ≫ (cofork.π t) = g ≫ (cofork.π t) :=
begin
erw [t.w left, ← t.w right], refl
end
def cone.of_fork
{F : walking_pair.{v} ⥤ C} (t : fork (F.map left) (F.map right)) : cone F :=
{ X := t.X,
π :=
{ app := λ X, t.π.app X ≫ eq_to_hom (by tidy),
naturality' := λ j j' g,
begin
cases j; cases j'; cases g; dsimp; simp,
erw ← t.w left, refl,
erw ← t.w right, refl,
end } }.
def cocone.of_cofork
{F : walking_pair.{v} ⥤ C} (t : cofork (F.map left) (F.map right)) : cocone F :=
{ X := t.X,
ι :=
{ app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X,
naturality' := λ j j' g,
begin
cases j; cases j'; cases g; dsimp; simp,
erw ← t.w left, refl,
erw ← t.w right, refl,
end } }.
@[simp] lemma cone.of_fork_π
{F : walking_pair.{v} ⥤ C} (t : fork (F.map left) (F.map right)) (j):
(cone.of_fork t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
@[simp] lemma cocone.of_cofork_ι
{F : walking_pair.{v} ⥤ C} (t : cofork (F.map left) (F.map right)) (j):
(cocone.of_cofork t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
def fork.of_cone
{F : walking_pair.{v} ⥤ C} (t : cone F) : fork (F.map left) (F.map right) :=
{ X := t.X,
π := {app := λ X, t.π.app X ≫ eq_to_hom (by tidy),
naturality' := omitted } }
def cofork.of_cocone
{F : walking_pair.{v} ⥤ C} (t : cocone F) : cofork (F.map left) (F.map right) :=
{ X := t.X,
ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := omitted } }
@[simp] lemma fork.of_cone_π {F : walking_pair.{v} ⥤ C} (t : cone F) (j) :
(fork.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
@[simp] lemma cofork.of_cocone_ι {F : walking_pair.{v} ⥤ C} (t : cocone F) (j) :
(cofork.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
end category_theory.limits
|
686e1b3529b9350a505daa8a7d549d0ca15d0f78 | 7cdf3413c097e5d36492d12cdd07030eb991d394 | /src/game/world5/level8.lean | c533aaf73dd96742611d230a70f802d9840140d0 | [] | no_license | alreadydone/natural_number_game | 3135b9385a9f43e74cfbf79513fc37e69b99e0b3 | 1a39e693df4f4e871eb449890d3c7715a25c2ec9 | refs/heads/master | 1,599,387,390,105 | 1,573,200,587,000 | 1,573,200,691,000 | 220,397,084 | 0 | 0 | null | 1,573,192,734,000 | 1,573,192,733,000 | null | UTF-8 | Lean | false | false | 1,772 | lean | /-
# Function world.
## Level 8 : `(P → Q) → ((Q → empty) → (P → empty))`
Level 8 is the same as level 7, except we have replaced the
set $F$ with the empty set $\emptyset$. The same proof will work (after all, our
previous proof worked for all sets, and the empty set is a set).
But note that if you start with `intro f, intro h, intro p,`
(which can incidentally be shortened to `intros f h p`),
then the local context looks like this:
```
P Q : Type,
f : P → Q,
h : Q → empty,
p : P
⊢ empty
```
and your job is to construct an element of the empty set!
This on the face of it seems hard, but what is going on is that
our hypotheses (we have an element of $P$, and functions $P\to Q$
and $Q\to\emptyset$) are themselves contradictory, so
I guess we are doing some kind of proof by contradiction at this point? However,
if your next line is `apply h` then all of a sudden the goal
seems like it might be possible again. If this is confusing, note
that the proof of the previous world worked for all sets $F$, so in particular
it worked for the empty set, you just probably weren't really thinking about
this case explicitly beforehand. [Technical note to constructivists: I know
that we are not doing a proof by contradiction. But how else do you explain
to a classical mathematician that their goal is to prove something false
and this is OK because their hypotheses don't add up?]
-/
/- Lemma : no-side-bar
Whatever the sets $P$ and $Q$ are, we can always
make an element of $\operatorname{Hom}(\operatorname{Hom}(P,Q),
\operatorname{Hom}(\operatorname{Hom}(Q,\emptyset),\operatorname{Hom}(P,\emptyset)))$.
-/
example (P Q : Type) : (P → Q) → ((Q → empty) → (P → empty)) :=
begin
intros f h p,
apply h,
apply f,
exact p,
end
|
1e0b85d26d06a11d5b102f9d4fdce5853741da59 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/linear_algebra/free_module/pid.lean | 39cd1c498b6ae2fa8025ca88492af92a0af36d22 | [
"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 | 25,512 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import linear_algebra.dimension
import ring_theory.principal_ideal_domain
import ring_theory.finiteness
/-! # Free modules over PID
A free `R`-module `M` is a module with a basis over `R`,
equivalently it is an `R`-module linearly equivalent to `ι →₀ R` for some `ι`.
This file proves a submodule of a free `R`-module of finite rank is also
a free `R`-module of finite rank, if `R` is a principal ideal domain (PID),
i.e. we have instances `[is_domain R] [is_principal_ideal_ring R]`.
We express "free `R`-module of finite rank" as a module `M` which has a basis
`b : ι → R`, where `ι` is a `fintype`.
We call the cardinality of `ι` the rank of `M` in this file;
it would be equal to `finrank R M` if `R` is a field and `M` is a vector space.
## Main results
In this section, `M` is a free and finitely generated `R`-module, and
`N` is a submodule of `M`.
- `submodule.induction_on_rank`: if `P` holds for `⊥ : submodule R M` and if
`P N` follows from `P N'` for all `N'` that are of lower rank, then `P` holds
on all submodules
- `submodule.exists_basis_of_pid`: if `R` is a PID, then `N : submodule R M` is
free and finitely generated. This is the first part of the structure theorem
for modules.
- `submodule.smith_normal_form`: if `R` is a PID, then `M` has a basis
`bM` and `N` has a basis `bN` such that `bN i = a i • bM i`.
Equivalently, a linear map `f : M →ₗ M` with `range f = N` can be written as
a matrix in Smith normal form, a diagonal matrix with the coefficients `a i`
along the diagonal.
## Tags
free module, finitely generated module, rank, structure theorem
-/
open_locale big_operators
universes u v
section ring
variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M]
variables {ι : Type*} (b : basis ι R M)
open submodule.is_principal submodule
lemma eq_bot_of_generator_maximal_map_eq_zero (b : basis ι R M) {N : submodule R M}
{ϕ : M →ₗ[R] R} (hϕ : ∀ (ψ : M →ₗ[R] R), N.map ϕ ≤ N.map ψ → N.map ψ = N.map ϕ)
[(N.map ϕ).is_principal] (hgen : generator (N.map ϕ) = 0) : N = ⊥ :=
begin
rw submodule.eq_bot_iff,
intros x hx,
refine b.ext_elem (λ i, _),
rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ,
rw [linear_equiv.map_zero, finsupp.zero_apply],
exact (submodule.eq_bot_iff _).mp (hϕ ((finsupp.lapply i) ∘ₗ ↑b.repr) bot_le) _ ⟨x, hx, rfl⟩
end
lemma eq_bot_of_generator_maximal_submodule_image_eq_zero {N O : submodule R M} (b : basis ι R O)
(hNO : N ≤ O)
{ϕ : O →ₗ[R] R} (hϕ : ∀ (ψ : O →ₗ[R] R), ϕ.submodule_image N ≤ ψ.submodule_image N →
ψ.submodule_image N = ϕ.submodule_image N)
[(ϕ.submodule_image N).is_principal] (hgen : generator (ϕ.submodule_image N) = 0) :
N = ⊥ :=
begin
rw submodule.eq_bot_iff,
intros x hx,
refine congr_arg coe (show (⟨x, hNO hx⟩ : O) = 0, from b.ext_elem (λ i, _)),
rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ,
rw [linear_equiv.map_zero, finsupp.zero_apply],
refine (submodule.eq_bot_iff _).mp (hϕ ((finsupp.lapply i) ∘ₗ ↑b.repr) bot_le) _ _,
exact (linear_map.mem_submodule_image_of_le hNO).mpr ⟨x, hx, rfl⟩
end
end ring
section is_domain
variables {ι : Type*} {R : Type*} [comm_ring R] [is_domain R]
variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M}
open submodule.is_principal set submodule
lemma dvd_generator_iff {I : ideal R} [I.is_principal] {x : R} (hx : x ∈ I) :
x ∣ generator I ↔ I = ideal.span {x} :=
begin
conv_rhs { rw [← span_singleton_generator I] },
erw [ideal.span_singleton_eq_span_singleton, ← dvd_dvd_iff_associated, ← mem_iff_generator_dvd],
exact ⟨λ h, ⟨hx, h⟩, λ h, h.2⟩
end
end is_domain
section principal_ideal_domain
open submodule.is_principal set submodule
variables {ι : Type*} {R : Type*} [comm_ring R] [is_domain R] [is_principal_ideal_ring R]
variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M}
open submodule.is_principal
lemma generator_maximal_submodule_image_dvd {N O : submodule R M} (hNO : N ≤ O)
{ϕ : O →ₗ[R] R} (hϕ : ∀ (ψ : O →ₗ[R] R), ϕ.submodule_image N ≤ ψ.submodule_image N →
ψ.submodule_image N = ϕ.submodule_image N)
[(ϕ.submodule_image N).is_principal]
(y : M) (yN : y ∈ N) (ϕy_eq : ϕ ⟨y, hNO yN⟩ = generator (ϕ.submodule_image N))
(ψ : O →ₗ[R] R) : generator (ϕ.submodule_image N) ∣ ψ ⟨y, hNO yN⟩ :=
begin
let a : R := generator (ϕ.submodule_image N),
let d : R := is_principal.generator (submodule.span R {a, ψ ⟨y, hNO yN⟩}),
have d_dvd_left : d ∣ a := (mem_iff_generator_dvd _).mp
(subset_span (mem_insert _ _)),
have d_dvd_right : d ∣ ψ ⟨y, hNO yN⟩ := (mem_iff_generator_dvd _).mp
(subset_span (mem_insert_of_mem _ (mem_singleton _))),
refine dvd_trans _ d_dvd_right,
rw [dvd_generator_iff, ideal.span,
← span_singleton_generator (submodule.span R {a, ψ ⟨y, hNO yN⟩})],
obtain ⟨r₁, r₂, d_eq⟩ : ∃ r₁ r₂ : R, d = r₁ * a + r₂ * ψ ⟨y, hNO yN⟩,
{ obtain ⟨r₁, r₂', hr₂', hr₁⟩ := mem_span_insert.mp (is_principal.generator_mem
(submodule.span R {a, ψ ⟨y, hNO yN⟩})),
obtain ⟨r₂, rfl⟩ := mem_span_singleton.mp hr₂',
exact ⟨r₁, r₂, hr₁⟩ },
let ψ' : O →ₗ[R] R := r₁ • ϕ + r₂ • ψ,
have : span R {d} ≤ ψ'.submodule_image N,
{ rw [span_le, singleton_subset_iff, set_like.mem_coe, linear_map.mem_submodule_image_of_le hNO],
refine ⟨y, yN, _⟩,
change r₁ * ϕ ⟨y, hNO yN⟩ + r₂ * ψ ⟨y, hNO yN⟩ = d,
rw [d_eq, ϕy_eq] },
refine le_antisymm (this.trans (le_of_eq _))
(ideal.span_singleton_le_span_singleton.mpr d_dvd_left),
rw span_singleton_generator,
refine hϕ ψ' (le_trans _ this),
rw [← span_singleton_generator (ϕ.submodule_image N)],
exact ideal.span_singleton_le_span_singleton.mpr d_dvd_left,
{ exact subset_span (mem_insert _ _) }
end
/-- The induction hypothesis of `submodule.basis_of_pid` and `submodule.smith_normal_form`.
Basically, it says: let `N ≤ M` be a pair of submodules, then we can find a pair of
submodules `N' ≤ M'` of strictly smaller rank, whose basis we can extend to get a basis
of `N` and `M`. Moreover, if the basis for `M'` is up to scalars a basis for `N'`,
then the basis we find for `M` is up to scalars a basis for `N`.
For `basis_of_pid` we only need the first half and can fix `M = ⊤`,
for `smith_normal_form` we need the full statement,
but must also feed in a basis for `M` using `basis_of_pid` to keep the induction going.
-/
lemma submodule.basis_of_pid_aux [fintype ι] {O : Type*} [add_comm_group O] [module R O]
(M N : submodule R O) (b'M : basis ι R M) (N_bot : N ≠ ⊥) (N_le_M : N ≤ M) :
∃ (y ∈ M) (a : R) (hay : a • y ∈ N) (M' ≤ M) (N' ≤ N) (N'_le_M' : N' ≤ M')
(y_ortho_M' : ∀ (c : R) (z : O), z ∈ M' → c • y + z = 0 → c = 0)
(ay_ortho_N' : ∀ (c : R) (z : O), z ∈ N' → c • a • y + z = 0 → c = 0),
∀ (n') (bN' : basis (fin n') R N'), ∃ (bN : basis (fin (n' + 1)) R N),
∀ (m') (hn'm' : n' ≤ m') (bM' : basis (fin m') R M'),
∃ (hnm : (n' + 1) ≤ (m' + 1)) (bM : basis (fin (m' + 1)) R M),
∀ (as : fin n' → R) (h : ∀ (i : fin n'), (bN' i : O) = as i • (bM' (fin.cast_le hn'm' i) : O)),
∃ (as' : fin (n' + 1) → R),
∀ (i : fin (n' + 1)), (bN i : O) = as' i • (bM (fin.cast_le hnm i) : O) :=
begin
-- Let `ϕ` be a maximal projection of `M` onto `R`, in the sense that there is
-- no `ψ` whose image of `N` is larger than `ϕ`'s image of `N`.
have : ∃ ϕ : M →ₗ[R] R, ∀ (ψ : M →ₗ[R] R),
ϕ.submodule_image N ≤ ψ.submodule_image N → ψ.submodule_image N = ϕ.submodule_image N,
{ obtain ⟨P, P_eq, P_max⟩ := set_has_maximal_iff_noetherian.mpr
(infer_instance : is_noetherian R R) _
(show (set.range (λ ψ : M →ₗ[R] R, ψ.submodule_image N)).nonempty,
from ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩),
obtain ⟨ϕ, rfl⟩ := set.mem_range.mp P_eq,
exact ⟨ϕ, λ ψ hψ, P_max _ ⟨_, rfl⟩ hψ⟩ },
let ϕ := this.some,
have ϕ_max := this.some_spec,
-- Since `ϕ(N)` is a `R`-submodule of the PID `R`,
-- it is principal and generated by some `a`.
let a := generator (ϕ.submodule_image N),
have a_mem : a ∈ ϕ.submodule_image N := generator_mem _,
-- If `a` is zero, then the submodule is trivial. So let's assume `a ≠ 0`, `N ≠ ⊥`.
by_cases a_zero : a = 0,
{ have := eq_bot_of_generator_maximal_submodule_image_eq_zero b'M N_le_M ϕ_max a_zero,
contradiction },
-- We claim that `ϕ⁻¹ a = y` can be taken as basis element of `N`.
obtain ⟨y, yN, ϕy_eq⟩ := (linear_map.mem_submodule_image_of_le N_le_M).mp a_mem,
have ϕy_ne_zero : ϕ ⟨y, N_le_M yN⟩ ≠ 0 := λ h, a_zero (ϕy_eq.symm.trans h),
-- Write `y` as `a • y'` for some `y'`.
have hdvd : ∀ i, a ∣ b'M.coord i ⟨y, N_le_M yN⟩ :=
λ i, generator_maximal_submodule_image_dvd N_le_M ϕ_max y yN ϕy_eq (b'M.coord i),
choose c hc using hdvd,
let y' : O := ∑ i, c i • b'M i,
have y'M : y' ∈ M := M.sum_mem (λ i _, M.smul_mem (c i) (b'M i).2),
have mk_y' : (⟨y', y'M⟩ : M) = ∑ i, c i • b'M i :=
subtype.ext (show y' = M.subtype _,
by { simp only [linear_map.map_sum, linear_map.map_smul], refl }),
have a_smul_y' : a • y' = y,
{ refine congr_arg coe (show (a • ⟨y', y'M⟩ : M) = ⟨y, N_le_M yN⟩, from _),
rw [← b'M.sum_repr ⟨y, N_le_M yN⟩, mk_y', finset.smul_sum],
refine finset.sum_congr rfl (λ i _, _),
rw [← mul_smul, ← hc], refl },
-- We found an `y` and an `a`!
refine ⟨y', y'M, a, a_smul_y'.symm ▸ yN, _⟩,
have ϕy'_eq : ϕ ⟨y', y'M⟩ = 1 := mul_left_cancel₀ a_zero
(calc a • ϕ ⟨y', y'M⟩ = ϕ ⟨a • y', _⟩ : (ϕ.map_smul a ⟨y', y'M⟩).symm
... = ϕ ⟨y, N_le_M yN⟩ : by simp only [a_smul_y']
... = a : ϕy_eq
... = a * 1 : (mul_one a).symm),
have ϕy'_ne_zero : ϕ ⟨y', y'M⟩ ≠ 0 := by simpa only [ϕy'_eq] using one_ne_zero,
-- `M' := ker (ϕ : M → R)` is smaller than `M` and `N' := ker (ϕ : N → R)` is smaller than `N`.
let M' : submodule R O := ϕ.ker.map M.subtype,
let N' : submodule R O := (ϕ.comp (of_le N_le_M)).ker.map N.subtype,
have M'_le_M : M' ≤ M := M.map_subtype_le ϕ.ker,
have N'_le_M' : N' ≤ M',
{ intros x hx,
simp only [mem_map, linear_map.mem_ker] at hx ⊢,
obtain ⟨⟨x, xN⟩, hx, rfl⟩ := hx,
exact ⟨⟨x, N_le_M xN⟩, hx, rfl⟩ },
have N'_le_N : N' ≤ N := N.map_subtype_le (ϕ.comp (of_le N_le_M)).ker,
-- So fill in those results as well.
refine ⟨M', M'_le_M, N', N'_le_N, N'_le_M', _⟩,
-- Note that `y'` is orthogonal to `M'`.
have y'_ortho_M' : ∀ (c : R) z ∈ M', c • y' + z = 0 → c = 0,
{ intros c x xM' hc,
obtain ⟨⟨x, xM⟩, hx', rfl⟩ := submodule.mem_map.mp xM',
rw linear_map.mem_ker at hx',
have hc' : (c • ⟨y', y'M⟩ + ⟨x, xM⟩ : M) = 0 := subtype.coe_injective hc,
simpa only [linear_map.map_add, linear_map.map_zero, linear_map.map_smul, smul_eq_mul, add_zero,
mul_eq_zero, ϕy'_ne_zero, hx', or_false] using congr_arg ϕ hc' },
-- And `a • y'` is orthogonal to `N'`.
have ay'_ortho_N' : ∀ (c : R) z ∈ N', c • a • y' + z = 0 → c = 0,
{ intros c z zN' hc,
refine (mul_eq_zero.mp (y'_ortho_M' (a * c) z (N'_le_M' zN') _)).resolve_left a_zero,
rw [mul_comm, mul_smul, hc] },
-- So we can extend a basis for `N'` with `y`
refine ⟨y'_ortho_M', ay'_ortho_N', λ n' bN', ⟨_, _⟩⟩,
{ refine basis.mk_fin_cons_of_le y yN bN' N'_le_N _ _,
{ intros c z zN' hc,
refine ay'_ortho_N' c z zN' _,
rwa ← a_smul_y' at hc },
{ intros z zN,
obtain ⟨b, hb⟩ : _ ∣ ϕ ⟨z, N_le_M zN⟩ := generator_submodule_image_dvd_of_mem N_le_M ϕ zN,
refine ⟨-b, submodule.mem_map.mpr ⟨⟨_, N.sub_mem zN (N.smul_mem b yN)⟩, _, _⟩⟩,
{ refine linear_map.mem_ker.mpr (show ϕ (⟨z, N_le_M zN⟩ - b • ⟨y, N_le_M yN⟩) = 0, from _),
rw [linear_map.map_sub, linear_map.map_smul, hb, ϕy_eq, smul_eq_mul,
mul_comm, sub_self] },
{ simp only [sub_eq_add_neg, neg_smul], refl } } },
-- And extend a basis for `M'` with `y'`
intros m' hn'm' bM',
refine ⟨nat.succ_le_succ hn'm', _, _⟩,
{ refine basis.mk_fin_cons_of_le y' y'M bM' M'_le_M y'_ortho_M' _,
intros z zM,
refine ⟨-ϕ ⟨z, zM⟩, ⟨⟨z, zM⟩ - (ϕ ⟨z, zM⟩) • ⟨y', y'M⟩, linear_map.mem_ker.mpr _, _⟩⟩,
{ rw [linear_map.map_sub, linear_map.map_smul, ϕy'_eq, smul_eq_mul, mul_one, sub_self] },
{ rw [linear_map.map_sub, linear_map.map_smul, sub_eq_add_neg, neg_smul], refl } },
-- It remains to show the extended bases are compatible with each other.
intros as h,
refine ⟨fin.cons a as, _⟩,
intro i,
rw [basis.coe_mk_fin_cons_of_le, basis.coe_mk_fin_cons_of_le],
refine fin.cases _ (λ i, _) i,
{ simp only [fin.cons_zero, fin.cast_le_zero],
exact a_smul_y'.symm },
{ rw fin.cast_le_succ, simp only [fin.cons_succ, coe_of_le, h i] }
end
/-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank,
if `R` is a principal ideal domain.
This is a `lemma` to make the induction a bit easier. To actually access the basis,
see `submodule.basis_of_pid`.
See also the stronger version `submodule.smith_normal_form`.
-/
lemma submodule.nonempty_basis_of_pid {ι : Type*} [fintype ι]
(b : basis ι R M) (N : submodule R M) :
∃ (n : ℕ), nonempty (basis (fin n) R N) :=
begin
haveI := classical.dec_eq M,
refine N.induction_on_rank b _ _,
intros N ih,
let b' := (b.reindex (fintype.equiv_fin ι)).map (linear_equiv.of_top _ rfl).symm,
by_cases N_bot : N = ⊥,
{ subst N_bot, exact ⟨0, ⟨basis.empty _⟩⟩ },
obtain ⟨y, -, a, hay, M', -, N', N'_le_N, -, -, ay_ortho, h'⟩ :=
submodule.basis_of_pid_aux ⊤ N b' N_bot le_top,
obtain ⟨n', ⟨bN'⟩⟩ := ih N' N'_le_N _ hay ay_ortho,
obtain ⟨bN, hbN⟩ := h' n' bN',
exact ⟨n' + 1, ⟨bN⟩⟩
end
/-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank,
if `R` is a principal ideal domain.
See also the stronger version `submodule.smith_normal_form`.
-/
noncomputable def submodule.basis_of_pid {ι : Type*} [fintype ι]
(b : basis ι R M) (N : submodule R M) :
Σ (n : ℕ), (basis (fin n) R N) :=
⟨_, (N.nonempty_basis_of_pid b).some_spec.some⟩
lemma submodule.basis_of_pid_bot {ι : Type*} [fintype ι] (b : basis ι R M) :
submodule.basis_of_pid b ⊥ = ⟨0, basis.empty _⟩ :=
begin
obtain ⟨n, b'⟩ := submodule.basis_of_pid b ⊥,
let e : fin n ≃ fin 0 := b'.index_equiv (basis.empty _ : basis (fin 0) R (⊥ : submodule R M)),
have : n = 0 := by simpa using fintype.card_eq.mpr ⟨e⟩,
subst this,
exact sigma.eq rfl (basis.eq_of_apply_eq $ fin_zero_elim)
end
/-- A submodule inside a free `R`-submodule of finite rank is also a free `R`-module of finite rank,
if `R` is a principal ideal domain.
See also the stronger version `submodule.smith_normal_form_of_le`.
-/
noncomputable def submodule.basis_of_pid_of_le {ι : Type*} [fintype ι]
{N O : submodule R M} (hNO : N ≤ O) (b : basis ι R O) :
Σ (n : ℕ), basis (fin n) R N :=
let ⟨n, bN'⟩ := submodule.basis_of_pid b (N.comap O.subtype)
in ⟨n, bN'.map (submodule.comap_subtype_equiv_of_le hNO)⟩
/-- A submodule inside the span of a linear independent family is a free `R`-module of finite rank,
if `R` is a principal ideal domain. -/
noncomputable def submodule.basis_of_pid_of_le_span
{ι : Type*} [fintype ι] {b : ι → M} (hb : linear_independent R b)
{N : submodule R M} (le : N ≤ submodule.span R (set.range b)) :
Σ (n : ℕ), basis (fin n) R N :=
submodule.basis_of_pid_of_le le (basis.span hb)
variable {M}
/-- A finite type torsion free module over a PID is free. -/
noncomputable def module.free_of_finite_type_torsion_free [fintype ι] {s : ι → M}
(hs : span R (range s) = ⊤) [no_zero_smul_divisors R M] :
Σ (n : ℕ), basis (fin n) R M :=
begin
classical,
-- We define `N` as the submodule spanned by a maximal linear independent subfamily of `s`
have := exists_maximal_independent R s,
let I : set ι := this.some,
obtain ⟨indepI : linear_independent R (s ∘ coe : I → M),
hI : ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I)⟩ := this.some_spec,
let N := span R (range $ (s ∘ coe : I → M)), -- same as `span R (s '' I)` but more convenient
let sI : I → N := λ i, ⟨s i.1, subset_span (mem_range_self i)⟩, -- `s` restricted to `I`
let sI_basis : basis I R N, -- `s` restricted to `I` is a basis of `N`
from basis.span indepI,
-- Our first goal is to build `A ≠ 0` such that `A • M ⊆ N`
have exists_a : ∀ i : ι, ∃ a : R, a ≠ 0 ∧ a • s i ∈ N,
{ intro i,
by_cases hi : i ∈ I,
{ use [1, zero_ne_one.symm],
rw one_smul,
exact subset_span (mem_range_self (⟨i, hi⟩ : I)) },
{ simpa [image_eq_range s I] using hI i hi } },
choose a ha ha' using exists_a,
let A := ∏ i, a i,
have hA : A ≠ 0,
{ rw finset.prod_ne_zero_iff,
simpa using ha },
-- `M ≃ A • M` because `M` is torsion free and `A ≠ 0`
let φ : M →ₗ[R] M := linear_map.lsmul R M A,
have : φ.ker = ⊥,
from linear_map.ker_lsmul hA,
let ψ : M ≃ₗ[R] φ.range := linear_equiv.of_injective φ (linear_map.ker_eq_bot.mp this),
have : φ.range ≤ N, -- as announced, `A • M ⊆ N`
{ suffices : ∀ i, φ (s i) ∈ N,
{ rw [linear_map.range_eq_map, ← hs, φ.map_span_le],
rintros _ ⟨i, rfl⟩, apply this },
intro i,
calc (∏ j, a j) • s i = (∏ j in {i}ᶜ, a j) • a i • s i :
by rw [fintype.prod_eq_prod_compl_mul i, mul_smul]
... ∈ N : N.smul_mem _ (ha' i) },
-- Since a submodule of a free `R`-module is free, we get that `A • M` is free
obtain ⟨n, b : basis (fin n) R φ.range⟩ := submodule.basis_of_pid_of_le this sI_basis,
-- hence `M` is free.
exact ⟨n, b.map ψ.symm⟩
end
/-- A finite type torsion free module over a PID is free. -/
noncomputable def module.free_of_finite_type_torsion_free' [module.finite R M]
[no_zero_smul_divisors R M] :
Σ (n : ℕ), basis (fin n) R M :=
module.free_of_finite_type_torsion_free module.finite.exists_fin.some_spec.some_spec
section smith_normal
/-- A Smith normal form basis for a submodule `N` of a module `M` consists of
bases for `M` and `N` such that the inclusion map `N → M` can be written as a
(rectangular) matrix with `a` along the diagonal: in Smith normal form. -/
@[nolint has_inhabited_instance]
structure basis.smith_normal_form (N : submodule R M) (ι : Type*) (n : ℕ) :=
(bM : basis ι R M)
(bN : basis (fin n) R N)
(f : fin n ↪ ι)
(a : fin n → R)
(snf : ∀ i, (bN i : M) = a i • bM (f i))
/-- If `M` is finite free over a PID `R`, then any submodule `N` is free
and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix
in Smith normal form.
See `submodule.smith_normal_form_of_le` for a version of this theorem that returns
a `basis.smith_normal_form`.
This is a strengthening of `submodule.basis_of_pid_of_le`.
-/
theorem submodule.exists_smith_normal_form_of_le [fintype ι]
(b : basis ι R M) (N O : submodule R M) (N_le_O : N ≤ O) :
∃ (n o : ℕ) (hno : n ≤ o) (bO : basis (fin o) R O) (bN : basis (fin n) R N) (a : fin n → R),
∀ i, (bN i : M) = a i • bO (fin.cast_le hno i) :=
begin
revert N,
refine induction_on_rank b _ _ O,
intros M ih N N_le_M,
obtain ⟨m, b'M⟩ := M.basis_of_pid b,
by_cases N_bot : N = ⊥,
{ subst N_bot,
exact ⟨0, m, nat.zero_le _, b'M, basis.empty _, fin_zero_elim, fin_zero_elim⟩ },
obtain ⟨y, hy, a, hay, M', M'_le_M, N', N'_le_N, N'_le_M', y_ortho, ay_ortho, h⟩ :=
submodule.basis_of_pid_aux M N b'M N_bot N_le_M,
obtain ⟨n', m', hn'm', bM', bN', as', has'⟩ := ih M' M'_le_M y hy y_ortho N' N'_le_M',
obtain ⟨bN, h'⟩ := h n' bN',
obtain ⟨hmn, bM, h''⟩ := h' m' hn'm' bM',
obtain ⟨as, has⟩ := h'' as' has',
exact ⟨_, _, hmn, bM, bN, as, has⟩
end
/-- If `M` is finite free over a PID `R`, then any submodule `N` is free
and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix
in Smith normal form.
See `submodule.exists_smith_normal_form_of_le` for a version of this theorem that doesn't
need to map `N` into a submodule of `O`.
This is a strengthening of `submodule.basis_of_pid_of_le`.
-/
noncomputable def submodule.smith_normal_form_of_le [fintype ι]
(b : basis ι R M) (N O : submodule R M) (N_le_O : N ≤ O) :
Σ (o n : ℕ), basis.smith_normal_form (N.comap O.subtype) (fin o) n :=
begin
choose n o hno bO bN a snf using N.exists_smith_normal_form_of_le b O N_le_O,
refine ⟨o, n, bO, bN.map (comap_subtype_equiv_of_le N_le_O).symm, (fin.cast_le hno).to_embedding,
a, λ i, _⟩,
ext,
simp only [snf, basis.map_apply, submodule.comap_subtype_equiv_of_le_symm_apply_coe_coe,
submodule.coe_smul_of_tower, rel_embedding.coe_fn_to_embedding]
end
/-- If `M` is finite free over a PID `R`, then any submodule `N` is free
and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix
in Smith normal form.
This is a strengthening of `submodule.basis_of_pid`.
See also `ideal.smith_normal_form`, which moreover proves that the dimension of
an ideal is the same as the dimension of the whole ring.
-/
noncomputable def submodule.smith_normal_form [fintype ι] (b : basis ι R M) (N : submodule R M) :
Σ (n : ℕ), basis.smith_normal_form N ι n :=
let ⟨m, n, bM, bN, f, a, snf⟩ := N.smith_normal_form_of_le b ⊤ le_top,
bM' := bM.map (linear_equiv.of_top _ rfl),
e := bM'.index_equiv b in
⟨n, bM'.reindex e, bN.map (comap_subtype_equiv_of_le le_top), f.trans e.to_embedding, a,
λ i, by simp only [snf, basis.map_apply, linear_equiv.of_top_apply, submodule.coe_smul_of_tower,
submodule.comap_subtype_equiv_of_le_apply_coe, coe_coe, basis.reindex_apply,
equiv.to_embedding_apply, function.embedding.trans_apply,
equiv.symm_apply_apply]⟩
/-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module,
then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can
find a basis for `S` and `I` such that the inclusion map is a square diagonal
matrix.
See `ideal.exists_smith_normal_form` for a version of this theorem that doesn't
need to map `I` into a submodule of `R`.
This is a strengthening of `submodule.basis_of_pid`.
-/
noncomputable def ideal.smith_normal_form
[fintype ι] {S : Type*} [comm_ring S] [is_domain S] [algebra R S]
(b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) :
basis.smith_normal_form (I.restrict_scalars R) ι (fintype.card ι) :=
let ⟨n, bS, bI, f, a, snf⟩ := (I.restrict_scalars R).smith_normal_form b in
have eq : _ := ideal.rank_eq bS hI (bI.map ((restrict_scalars_equiv R S S I).restrict_scalars _)),
let e : fin n ≃ fin (fintype.card ι) := fintype.equiv_of_card_eq (by rw [eq, fintype.card_fin]) in
⟨bS, bI.reindex e, e.symm.to_embedding.trans f, a ∘ e.symm, λ i,
by simp only [snf, basis.coe_reindex, function.embedding.trans_apply, equiv.to_embedding_apply]⟩
/-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module,
then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can
find a basis for `S` and `I` such that the inclusion map is a square diagonal
matrix.
See also `ideal.smith_normal_form` for a version of this theorem that returns
a `basis.smith_normal_form`.
-/
theorem ideal.exists_smith_normal_form
[fintype ι] {S : Type*} [comm_ring S] [is_domain S] [algebra R S]
(b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) :
∃ (b' : basis ι R S) (a : ι → R) (ab' : basis ι R I),
∀ i, (ab' i : S) = a i • b' i :=
let ⟨bS, bI, f, a, snf⟩ := I.smith_normal_form b hI,
e : fin (fintype.card ι) ≃ ι := equiv.of_bijective f
((fintype.bijective_iff_injective_and_card f).mpr ⟨f.injective, fintype.card_fin _⟩) in
have fe : ∀ i, f (e.symm i) = i := e.apply_symm_apply,
⟨bS, a ∘ e.symm, (bI.reindex e).map ((restrict_scalars_equiv _ _ _ _).restrict_scalars R), λ i,
by simp only [snf, fe, basis.map_apply, linear_equiv.restrict_scalars_apply,
submodule.restrict_scalars_equiv_apply, basis.coe_reindex]⟩
end smith_normal
end principal_ideal_domain
/-- A set of linearly independent vectors in a module `M` over a semiring `S` is also linearly
independent over a subring `R` of `K`. -/
lemma linear_independent.restrict_scalars_algebras {R S M ι : Type*} [comm_semiring R] [semiring S]
[add_comm_monoid M] [algebra R S] [module R M] [module S M] [is_scalar_tower R S M]
(hinj : function.injective (algebra_map R S)) {v : ι → M} (li : linear_independent S v) :
linear_independent R v :=
linear_independent.restrict_scalars (by rwa algebra.algebra_map_eq_smul_one' at hinj) li
|
98cf5e8a0118c3c1dc8caa41e4bdae550475e28a | 7c92a46ce39266c13607ecdef7f228688f237182 | /src/for_mathlib/nonarchimedean/basic.lean | d8c78294cf664e98d3f417e9fa08c69129f314f5 | [
"Apache-2.0"
] | permissive | asym57/lean-perfectoid-spaces | 3217d01f6ddc0d13e9fb68651749469750420767 | 359187b429f254a946218af4411d45f08705c83e | refs/heads/master | 1,609,457,937,251 | 1,577,542,616,000 | 1,577,542,675,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,094 | lean | import topology.algebra.ring
import ring_theory.algebra
import ring_theory.ideal_operations
import tactic.abel tactic.chain
import for_mathlib.submodule
import for_mathlib.open_embeddings
import for_mathlib.rings
import topology.algebra.open_subgroup
local attribute [instance] set.pointwise_mul_semiring
local attribute [instance] set.pointwise_mul_action
/--A topological group is non-archimedean if every neighborhood of 1 contains an open subgroup.-/
definition topological_group.nonarchimedean (G : Type*)
[group G] [topological_space G] [topological_group G] : Prop :=
∀ U ∈ nhds (1 : G), ∃ V : open_subgroup G, (V : set G) ⊆ U
/--A topological additive group is non-archimedean if every neighborhood of 0 contains an
open subgroup.-/
definition topological_add_group.nonarchimedean (G : Type*)
[add_group G] [topological_space G] [topological_add_group G] : Prop :=
∀ U ∈ nhds (0 : G), ∃ V : open_add_subgroup G, (V : set G) ⊆ U
attribute [to_additive topological_add_group.nonarchimedean] topological_group.nonarchimedean
namespace topological_group
open function (hiding embedding) set
variables {G₀ : Type*} [group G₀] [topological_space G₀] [topological_group G₀]
variables {G : Type*} [group G] [topological_space G] [topological_group G]
variables (f : G₀ → G) [is_group_hom f]
@[to_additive topological_add_group.nonarchimedean_of_nonarchimedean_open_embedding]
lemma nonarchimedean_of_nonarchimedean_open_embedding
(emb : open_embedding f) (h : nonarchimedean G₀) :
nonarchimedean G :=
begin
intros U hU,
cases h (f ⁻¹' U) _ with V hV,
{ refine ⟨⟨f '' V, _, _⟩, _⟩,
{ exact emb.is_open_map _ V.is_open },
{ apply_instance },
{ rwa ← set.image_subset_iff at hV } },
{ apply emb.continuous.tendsto,
rwa is_group_hom.map_one f }
end
end topological_group
namespace topological_add_group
namespace nonarchimedean
open topological_ring
variables {R : Type*} [ring R] [topological_space R] [topological_ring R]
variables {S : Type*} [ring S] [topological_space S] [topological_ring S]
lemma left_mul_subset (h : nonarchimedean R) (U : open_add_subgroup R) (r : R) :
∃ V : open_add_subgroup R, r • (V : set R) ⊆ U :=
begin
let V : open_add_subgroup R := ⟨_, _, _⟩,
{ use V,
intros x hx,
rw set.mem_smul_set at hx,
rcases hx with ⟨y, hy, rfl⟩,
exact hy },
{ exact continuous_const.mul continuous_id U U.is_open },
{ refine {..}; intros,
{ show r * 0 ∈ U, simpa using U.zero_mem },
{ show r * (_ + _) ∈ U, rw left_distrib, apply U.add_mem, assumption' },
{ show r * _ ∈ U, rw mul_neg_eq_neg_mul_symm, apply U.neg_mem, assumption } },
end
lemma prod_subset (hR : nonarchimedean R) (hS : nonarchimedean S) :
∀ U ∈ nhds (0 : R × S), ∃ (V : open_add_subgroup R) (W : open_add_subgroup S),
(V : set R).prod (W : set S) ⊆ U :=
begin
intros U hU,
erw [nhds_prod_eq, filter.mem_prod_iff] at hU,
rcases hU with ⟨U₁, hU₁, U₂, hU₂, h⟩,
cases hR _ hU₁ with V hV,
cases hS _ hU₂ with W hW,
use [V, W, set.subset.trans (set.prod_mono hV hW) h]
end
lemma prod_self_subset (hR : nonarchimedean R) :
∀ U ∈ nhds (0 : R × R), ∃ (V : open_add_subgroup R), (V : set R).prod (V : set R) ⊆ U :=
begin
intros U hU,
rcases prod_subset hR hR U hU with ⟨V, W, h⟩,
use V ⊓ W,
refine set.subset.trans (set.prod_mono _ _) ‹_›; simp
end
lemma prod (hR : nonarchimedean R) (hS : nonarchimedean S) :
nonarchimedean (R × S) :=
begin
intros U hU,
rcases prod_subset hR hS U hU with ⟨V, W, h⟩,
refine ⟨V.sum W, ‹_›⟩
end
lemma mul_subset (h : nonarchimedean R) (U : open_add_subgroup R) :
∃ V : open_add_subgroup R, (V : set R) * V ⊆ U :=
begin
rcases prod_self_subset h _ _ with ⟨V, H⟩,
use V,
work_on_goal 0 {
rwa [set.pointwise_mul_eq_image, set.image_subset_iff] },
apply mem_nhds_sets (continuous_mul _ U.is_open),
simpa only [prod.fst_zero, prod.snd_zero, set.mem_preimage, mul_zero] using U.zero_mem
end
end nonarchimedean
end topological_add_group
|
dfb2e439b765d6b9a3c6354ac04fa360fbce8a09 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/fin_enum.lean | 338b1b1bb5db00c2819bf267e3fd946c7f325f53 | [
"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,850 | lean | /-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.monad.basic
import data.fintype.basic
import data.list.prod_sigma
/-!
Type class for finitely enumerable types. The property is stronger
than `fintype` in that it assigns each element a rank in a finite
enumeration.
-/
universes u v
open finset
/-- `fin_enum α` means that `α` is finite and can be enumerated in some order,
i.e. `α` has an explicit bijection with `fin n` for some n. -/
class fin_enum (α : Sort*) :=
(card : ℕ)
(equiv [] : α ≃ fin card)
[dec_eq : decidable_eq α]
attribute [instance, priority 100] fin_enum.dec_eq
namespace fin_enum
variables {α : Type u} {β : α → Type v}
/-- transport a `fin_enum` instance across an equivalence -/
def of_equiv (α) {β} [fin_enum α] (h : β ≃ α) : fin_enum β :=
{ card := card α,
equiv := h.trans (equiv α),
dec_eq := (h.trans (equiv _)).decidable_eq }
/-- create a `fin_enum` instance from an exhaustive list without duplicates -/
def of_nodup_list [decidable_eq α] (xs : list α) (h : ∀ x : α, x ∈ xs) (h' : list.nodup xs) :
fin_enum α :=
{ card := xs.length,
equiv := ⟨λ x, ⟨xs.index_of x,by rw [list.index_of_lt_length]; apply h⟩,
λ ⟨i,h⟩, xs.nth_le _ h,
λ x, by simp [of_nodup_list._match_1],
λ ⟨i,h⟩, by simp [of_nodup_list._match_1,*]; rw list.nth_le_index_of;
apply list.nodup_dedup ⟩ }
/-- create a `fin_enum` instance from an exhaustive list; duplicates are removed -/
def of_list [decidable_eq α] (xs : list α) (h : ∀ x : α, x ∈ xs) : fin_enum α :=
of_nodup_list xs.dedup (by simp *) (list.nodup_dedup _)
/-- create an exhaustive list of the values of a given type -/
def to_list (α) [fin_enum α] : list α :=
(list.fin_range (card α)).map (equiv α).symm
open function
@[simp] lemma mem_to_list [fin_enum α] (x : α) : x ∈ to_list α :=
by simp [to_list]; existsi equiv α x; simp
@[simp] lemma nodup_to_list [fin_enum α] : list.nodup (to_list α) :=
by simp [to_list]; apply list.nodup.map; [apply equiv.injective, apply list.nodup_fin_range]
/-- create a `fin_enum` instance using a surjection -/
def of_surjective {β} (f : β → α) [decidable_eq α] [fin_enum β] (h : surjective f) : fin_enum α :=
of_list ((to_list β).map f) (by intro; simp; exact h _)
/-- create a `fin_enum` instance using an injection -/
noncomputable def of_injective {α β} (f : α → β) [decidable_eq α] [fin_enum β] (h : injective f) :
fin_enum α :=
of_list ((to_list β).filter_map (partial_inv f))
begin
intro x,
simp only [mem_to_list, true_and, list.mem_filter_map],
use f x,
simp only [h, function.partial_inv_left],
end
instance pempty : fin_enum pempty :=
of_list [] (λ x, pempty.elim x)
instance empty : fin_enum empty :=
of_list [] (λ x, empty.elim x)
instance punit : fin_enum punit :=
of_list [punit.star] (λ x, by cases x; simp)
instance prod {β} [fin_enum α] [fin_enum β] : fin_enum (α × β) :=
of_list ( (to_list α).product (to_list β) ) (λ x, by cases x; simp)
instance sum {β} [fin_enum α] [fin_enum β] : fin_enum (α ⊕ β) :=
of_list ( (to_list α).map sum.inl ++ (to_list β).map sum.inr ) (λ x, by cases x; simp)
instance fin {n} : fin_enum (fin n) :=
of_list (list.fin_range _) (by simp)
instance quotient.enum [fin_enum α] (s : setoid α)
[decidable_rel ((≈) : α → α → Prop)] : fin_enum (quotient s) :=
fin_enum.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩))
/-- enumerate all finite sets of a given type -/
def finset.enum [decidable_eq α] : list α → list (finset α)
| [] := [∅]
| (x :: xs) :=
do r ← finset.enum xs,
[r,{x} ∪ r]
@[simp]lemma finset.mem_enum [decidable_eq α] (s : finset α) (xs : list α) :
s ∈ finset.enum xs ↔ ∀ x ∈ s, x ∈ xs :=
begin
induction xs generalizing s; simp [*,finset.enum],
{ simp [finset.eq_empty_iff_forall_not_mem,(∉)], refl },
{ split, rintro ⟨a,h,h'⟩ x hx,
cases h',
{ right, apply h, subst a, exact hx, },
{ simp only [h', mem_union, mem_singleton] at hx ⊢, cases hx,
{ exact or.inl hx },
{ exact or.inr (h _ hx) } },
intro h, existsi s \ ({xs_hd} : finset α),
simp only [and_imp, union_comm, mem_sdiff, mem_singleton],
simp only [or_iff_not_imp_left] at h,
existsi h,
by_cases xs_hd ∈ s,
{ have : {xs_hd} ⊆ s, simp only [has_subset.subset, *, forall_eq, mem_singleton],
simp only [union_sdiff_of_subset this, or_true, finset.union_sdiff_of_subset,
eq_self_iff_true], },
{ left, symmetry, simp only [sdiff_eq_self],
intro a, simp only [and_imp, mem_inter, mem_singleton, not_mem_empty],
rintro h₀ rfl, apply h h₀, } }
end
instance finset.fin_enum [fin_enum α] : fin_enum (finset α) :=
of_list (finset.enum (to_list α)) (by intro; simp)
instance subtype.fin_enum [fin_enum α] (p : α → Prop) [decidable_pred p] : fin_enum {x // p x} :=
of_list ((to_list α).filter_map $ λ x, if h : p x then some ⟨_,h⟩ else none)
(by rintro ⟨x,h⟩; simp; existsi x; simp *)
instance (β : α → Type v)
[fin_enum α] [∀ a, fin_enum (β a)] : fin_enum (sigma β) :=
of_list
((to_list α).bind $ λ a, (to_list (β a)).map $ sigma.mk a)
(by intro x; cases x; simp)
instance psigma.fin_enum [fin_enum α] [∀ a, fin_enum (β a)] :
fin_enum (Σ' a, β a) :=
fin_enum.of_equiv _ (equiv.psigma_equiv_sigma _)
instance psigma.fin_enum_prop_left {α : Prop} {β : α → Type v} [∀ a, fin_enum (β a)] [decidable α] :
fin_enum (Σ' a, β a) :=
if h : α then of_list ((to_list (β h)).map $ psigma.mk h) (λ ⟨a,Ba⟩, by simp)
else of_list [] (λ ⟨a,Ba⟩, (h a).elim)
instance psigma.fin_enum_prop_right {β : α → Prop} [fin_enum α] [∀ a, decidable (β a)] :
fin_enum (Σ' a, β a) :=
fin_enum.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩
instance psigma.fin_enum_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] :
fin_enum (Σ' a, β a) :=
if h : ∃ a, β a
then of_list [⟨h.fst,h.snd⟩] (by rintro ⟨⟩; simp)
else of_list [] (λ a, (h ⟨a.fst,a.snd⟩).elim)
@[priority 100]
instance [fin_enum α] : fintype α :=
{ elems := univ.map (equiv α).symm.to_embedding,
complete := by intros; simp; existsi (equiv α x); simp }
/-- For `pi.cons x xs y f` create a function where every `i ∈ xs` is mapped to `f i` and
`x` is mapped to `y` -/
def pi.cons [decidable_eq α] (x : α) (xs : list α) (y : β x)
(f : Π a, a ∈ xs → β a) :
Π a, a ∈ (x :: xs : list α) → β a
| b h :=
if h' : b = x then cast (by rw h') y
else f b (list.mem_of_ne_of_mem h' h)
/-- Given `f` a function whose domain is `x :: xs`, produce a function whose domain
is restricted to `xs`. -/
def pi.tail {x : α} {xs : list α} (f : Π a, a ∈ (x :: xs : list α) → β a) :
Π a, a ∈ xs → β a
| a h := f a (list.mem_cons_of_mem _ h)
/-- `pi xs f` creates the list of functions `g` such that, for `x ∈ xs`, `g x ∈ f x` -/
def pi {β : α → Type (max u v)} [decidable_eq α] : Π xs : list α, (Π a, list (β a)) →
list (Π a, a ∈ xs → β a)
| [] fs := [λ x h, h.elim]
| (x :: xs) fs :=
fin_enum.pi.cons x xs <$> fs x <*> pi xs fs
lemma mem_pi {β : α → Type (max u v)} [fin_enum α] [∀a, fin_enum (β a)] (xs : list α)
(f : Π a, a ∈ xs → β a) :
f ∈ pi xs (λ x, to_list (β x)) :=
begin
induction xs; simp [pi,-list.map_eq_map] with monad_norm functor_norm,
{ ext a ⟨ ⟩ },
{ existsi pi.cons xs_hd xs_tl (f _ (list.mem_cons_self _ _)),
split, exact ⟨_,rfl⟩,
existsi pi.tail f, split,
{ apply xs_ih, },
{ ext x h, simp [pi.cons], split_ifs, subst x, refl, refl }, }
end
/-- enumerate all functions whose domain and range are finitely enumerable -/
def pi.enum (β : α → Type (max u v)) [fin_enum α] [∀a, fin_enum (β a)] : list (Π a, β a) :=
(pi (to_list α) (λ x, to_list (β x))).map (λ f x, f x (mem_to_list _))
lemma pi.mem_enum {β : α → Type (max u v)} [fin_enum α] [∀a, fin_enum (β a)] (f : Π a, β a) :
f ∈ pi.enum β :=
by simp [pi.enum]; refine ⟨λ a h, f a, mem_pi _ _, rfl⟩
instance pi.fin_enum {β : α → Type (max u v)}
[fin_enum α] [∀a, fin_enum (β a)] : fin_enum (Πa, β a) :=
of_list (pi.enum _) (λ x, pi.mem_enum _)
instance pfun_fin_enum (p : Prop) [decidable p] (α : p → Type*)
[Π hp, fin_enum (α hp)] : fin_enum (Π hp : p, α hp) :=
if hp : p then of_list ( (to_list (α hp)).map $ λ x hp', x ) (by intro; simp; exact ⟨x hp,rfl⟩)
else of_list [λ hp', (hp hp').elim] (by intro; simp; ext hp'; cases hp hp')
end fin_enum
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.