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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26e14fe2b429d1353e19418e92b7153fe8d0abad | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/analysis/normed_space/mazur_ulam.lean | a13d4468f2d46ca6171781bb90d348bb0f701650 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 6,370 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import topology.instances.real_vector_space
import analysis.normed_space.add_torsor
import linear_algebra.affine_space.midpoint
import analysis.normed_space.linear_isometry
/-!
# Mazur-Ulam Theorem
Mazur-Ulam theorem states that an isometric bijection between two normed affine spaces over `ℝ` is
affine. We formalize it in three definitions:
* `isometric.to_real_linear_isometry_equiv_of_map_zero` : given `E ≃ᵢ F` sending `0` to `0`,
returns `E ≃ₗᵢ[ℝ] F` with the same `to_fun` and `inv_fun`;
* `isometric.to_real_linear_isometry_equiv` : given `f : E ≃ᵢ F`,
returns `g : E ≃ₗᵢ[ℝ] F` with `g x = f x - f 0`.
* `isometric.to_affine_equiv` : given `PE ≃ᵢ PF`, returns `g : PE ≃ᵃ[ℝ] PF` with the same
`to_equiv`.
The formalization is based on [Jussi Väisälä, *A Proof of the Mazur-Ulam Theorem*][Vaisala_2003].
## Tags
isometry, affine map, linear map
-/
variables
{E PE : Type*} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE]
{F PF : Type*} [normed_group F] [normed_space ℝ F] [metric_space PF] [normed_add_torsor F PF]
open set affine_map
noncomputable theory
namespace isometric
include E
/-- If an isometric self-homeomorphism of a normed vector space over `ℝ` fixes `x` and `y`,
then it fixes the midpoint of `[x, y]`. This is a lemma for a more general Mazur-Ulam theorem,
see below. -/
lemma midpoint_fixed {x y : PE} :
∀ e : PE ≃ᵢ PE, e x = x → e y = y → e (midpoint ℝ x y) = midpoint ℝ x y :=
begin
set z := midpoint ℝ x y,
-- Consider the set of `e : E ≃ᵢ E` such that `e x = x` and `e y = y`
set s := { e : PE ≃ᵢ PE | e x = x ∧ e y = y },
haveI : nonempty s := ⟨⟨isometric.refl PE, rfl, rfl⟩⟩,
-- On the one hand, `e` cannot send the midpoint `z` of `[x, y]` too far
have h_bdd : bdd_above (range $ λ e : s, dist (e z) z),
{ refine ⟨dist x z + dist x z, forall_range_iff.2 $ subtype.forall.2 _⟩,
rintro e ⟨hx, hy⟩,
calc dist (e z) z ≤ dist (e z) x + dist x z : dist_triangle (e z) x z
... = dist (e x) (e z) + dist x z : by rw [hx, dist_comm]
... = dist x z + dist x z : by erw [e.dist_eq x z] },
-- On the other hand, consider the map `f : (E ≃ᵢ E) → (E ≃ᵢ E)`
-- sending each `e` to `R ∘ e⁻¹ ∘ R ∘ e`, where `R` is the point reflection in the
-- midpoint `z` of `[x, y]`.
set R : PE ≃ᵢ PE := point_reflection z,
set f : (PE ≃ᵢ PE) → (PE ≃ᵢ PE) := λ e, ((e.trans R).trans e.symm).trans R,
-- Note that `f` doubles the value of ``dist (e z) z`
have hf_dist : ∀ e, dist (f e z) z = 2 * dist (e z) z,
{ intro e,
dsimp [f],
rw [dist_point_reflection_fixed, ← e.dist_eq, e.apply_symm_apply,
dist_point_reflection_self_real, dist_comm] },
-- Also note that `f` maps `s` to itself
have hf_maps_to : maps_to f s s,
{ rintros e ⟨hx, hy⟩,
split; simp [hx, hy, e.symm_apply_eq.2 hx.symm, e.symm_apply_eq.2 hy.symm], },
-- Therefore, `dist (e z) z = 0` for all `e ∈ s`.
set c := ⨆ e : s, dist (e z) z,
have : c ≤ c / 2,
{ apply csupr_le,
rintros ⟨e, he⟩,
simp only [coe_fn_coe_base, subtype.coe_mk, le_div_iff' (@zero_lt_two ℝ _ _), ← hf_dist],
exact le_csupr h_bdd ⟨f e, hf_maps_to he⟩ },
replace : c ≤ 0, { linarith },
refine λ e hx hy, dist_le_zero.1 (le_trans _ this),
exact le_csupr h_bdd ⟨e, hx, hy⟩
end
include F
/-- A bijective isometry sends midpoints to midpoints. -/
lemma map_midpoint (f : PE ≃ᵢ PF) (x y : PE) : f (midpoint ℝ x y) = midpoint ℝ (f x) (f y) :=
begin
set e : PE ≃ᵢ PE := ((f.trans $ point_reflection $ midpoint ℝ (f x) (f y)).trans f.symm).trans
(point_reflection $ midpoint ℝ x y),
have hx : e x = x, by simp,
have hy : e y = y, by simp,
have hm := e.midpoint_fixed hx hy,
simp only [e, trans_apply] at hm,
rwa [← eq_symm_apply, point_reflection_symm, point_reflection_self, symm_apply_eq,
point_reflection_fixed_iff ℝ] at hm,
apply_instance
end
/-!
Since `f : PE ≃ᵢ PF` sends midpoints to midpoints, it is an affine map.
We define a conversion to a `continuous_linear_equiv` first, then a conversion to an `affine_map`.
-/
/-- Mazur-Ulam Theorem: if `f` is an isometric bijection between two normed vector spaces
over `ℝ` and `f 0 = 0`, then `f` is a linear equivalence. -/
def to_real_linear_isometry_equiv_of_map_zero (f : E ≃ᵢ F) (h0 : f 0 = 0) :
E ≃ₗᵢ[ℝ] F :=
{ norm_map' := λ x, show ∥f x∥ = ∥x∥, by simp only [← dist_zero_right, ← h0, f.dist_eq],
.. ((add_monoid_hom.of_map_midpoint ℝ ℝ f h0 f.map_midpoint).to_real_linear_map f.continuous),
.. f }
@[simp] lemma coe_to_real_linear_equiv_of_map_zero (f : E ≃ᵢ F) (h0 : f 0 = 0) :
⇑(f.to_real_linear_isometry_equiv_of_map_zero h0) = f := rfl
@[simp] lemma coe_to_real_linear_equiv_of_map_zero_symm (f : E ≃ᵢ F) (h0 : f 0 = 0) :
⇑(f.to_real_linear_isometry_equiv_of_map_zero h0).symm = f.symm := rfl
/-- Mazur-Ulam Theorem: if `f` is an isometric bijection between two normed vector spaces
over `ℝ`, then `x ↦ f x - f 0` is a linear equivalence. -/
def to_real_linear_isometry_equiv (f : E ≃ᵢ F) : E ≃ₗᵢ[ℝ] F :=
(f.trans (isometric.add_right (f 0)).symm).to_real_linear_isometry_equiv_of_map_zero
(by simpa only [sub_eq_add_neg] using sub_self (f 0))
@[simp] lemma to_real_linear_equiv_apply (f : E ≃ᵢ F) (x : E) :
(f.to_real_linear_isometry_equiv : E → F) x = f x - f 0 :=
(sub_eq_add_neg (f x) (f 0)).symm
@[simp] lemma to_real_linear_isometry_equiv_symm_apply (f : E ≃ᵢ F) (y : F) :
(f.to_real_linear_isometry_equiv.symm : F → E) y = f.symm (y + f 0) := rfl
/-- Convert an isometric equivalence between two affine spaces to an `affine_map`. -/
def to_affine_equiv (f : PE ≃ᵢ PF) : PE ≃ᵃ[ℝ] PF :=
affine_equiv.mk' f.to_equiv
(((vadd_const (classical.arbitrary PE)).trans $ f.trans
(vadd_const (f $ classical.arbitrary PE)).symm).to_real_linear_isometry_equiv.to_linear_equiv)
(classical.arbitrary PE) (λ p, by simp)
@[simp] lemma coe_to_affine_equiv (f : PE ≃ᵢ PF) : ⇑f.to_affine_equiv = f := rfl
end isometric
|
85fb599ada131e94f0a562e9437281f008c38253 | 6772a11d96d69b3f90d6eeaf7f9accddf2a7691d | /functor.lean | 6e30de7690497c06715a8b8f3503dca8cb7ef10e | [] | no_license | lbordowitz/lean-category-theory | 5397361f0f81037d65762da48de2c16ec85a5e4b | 8c59893e44af3804eba4dbc5f7fa5928ed2e0ae6 | refs/heads/master | 1,611,310,752,156 | 1,487,070,172,000 | 1,487,070,172,000 | 82,003,141 | 0 | 0 | null | 1,487,118,553,000 | 1,487,118,553,000 | null | UTF-8 | Lean | false | false | 4,458 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import .category
open tqft.categories
namespace tqft.categories.functor
universe variables u1 v1 u2 v2
structure Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) :=
(onObjects : C^.Obj → D^.Obj)
(onMorphisms : Π { X Y : C^.Obj },
C^.Hom X Y → D^.Hom (onObjects X) (onObjects Y))
(identities : ∀ (X : C^.Obj),
onMorphisms (C^.identity X) = D^.identity (onObjects X))
(functoriality : ∀ { X Y Z : C^.Obj } (f : C^.Hom X Y) (g : C^.Hom Y Z),
onMorphisms (C^.compose f g) = D^.compose (onMorphisms f) (onMorphisms g))
attribute [simp] Functor.identities
attribute [simp] Functor.functoriality
-- We define a coercion so that we can write `F X` for the functor `F` applied to the object `X`.
-- One can still write out `onObjects F X` when needed.
instance Functor_to_onObjects { C D : Category }: has_coe_to_fun (Functor C D) :=
{ F := λ f, C^.Obj -> D^.Obj,
coe := Functor.onObjects }
/-
-- Unfortunately we haven't been able to set up similar notation for morphisms.
-- Instead we define notation so that `F <$> f` denotes the functor `F` applied to the morphism `f`.
-- One can still write out `onMorphisms F f` when needed, or even the very verbose `@Functor.onMorphisms C D F X Y f`.
--namespace notations
-- Lean complains about the use of local variables in
-- notation. There must be a way around that.
infix `<$>` :50 := λ {C : Category} {D : Category}
(F : Functor C D) {X Y : C^.Obj} (f : C^.Hom X Y),
Functor.onMorphisms F f
end notations
open notations
-/
-- This defines a coercion allowing us to write `F f` for `onMorphisms F f`
-- but sadly it doesn't work if to_onObjects is already in scope.
--instance Functor_to_onMorphisms { C D : Category } : has_coe_to_fun (Functor C D) :=
--{ F := λ f, Π ⦃X Y : C^.Obj⦄, C^.Hom X Y → D^.Hom (f X) (f Y), -- contrary to usual use, `f` here denotes the Functor.
-- coe := Functor.onMorphisms }
@[reducible] definition IdentityFunctor ( C: Category ) : Functor C C :=
{
onObjects := id,
onMorphisms := λ _ _ f, f,
identities := ♮,
functoriality := ♮
}
@[reducible] definition FunctorComposition { C D E : Category } ( F : Functor C D ) ( G : Functor D E ) : Functor C E :=
{
onObjects := λ X, G (F X),
onMorphisms := λ _ _ f, G^.onMorphisms (F^.onMorphisms f),
identities := ♮,
functoriality := ♮
}
-- We'll want to be able to prove that two functors are equal if they are equal on objects and on morphisms.
-- Implementation warning:
-- When using `apply Functors_pointwise_equal`, you might expect that Lean will create two goals,
-- one for `objectWitness`, and one for `morphismWitness`.
-- However, because `morphismWitness` depends on `objectWitness`, it will actually only create the goal
-- for `morphismWitness`, leaving the `objectWitness` goal somehow "implicit" and likely unprovable.
-- See https://groups.google.com/d/msg/lean-user/bhStu87PjiI/vqsyr9ZABAAJ for details.
-- If you run into this problem, use `fapply Functors_pointwise_equal` instead.
@[pointwise] lemma Functors_pointwise_equal
{ C D : Category }
{ F G : Functor C D }
( objectWitness : ∀ X : C^.Obj, F^.onObjects X = G^.onObjects X )
( morphismWitness : ∀ X Y : C^.Obj, ∀ f : C^.Hom X Y, ⟦ F^.onMorphisms f ⟧ = G^.onMorphisms f ) : F = G :=
begin
induction F with F_onObjects F_onMorphisms,
induction G with G_onObjects G_onMorphisms,
assert h_objects : F_onObjects = G_onObjects, exact funext objectWitness,
subst h_objects,
assert h_morphisms : @F_onMorphisms = @G_onMorphisms,
apply funext, intro X, apply funext, intro Y, apply funext, intro f,
exact morphismWitness X Y f,
subst h_morphisms
end
lemma FunctorComposition_left_identity { C D : Category } ( F : Functor C D ) :
FunctorComposition (IdentityFunctor C) F = F := ♮
lemma FunctorComposition_right_identity { C D : Category } ( F : Functor C D ) :
FunctorComposition F (IdentityFunctor D) = F := ♮
lemma FunctorComposition_associative { B C D E : Category } ( F : Functor B C ) ( G : Functor C D ) ( H : Functor D E ) :
FunctorComposition (FunctorComposition F G) H = FunctorComposition F (FunctorComposition G H) := ♮
end tqft.categories.functor
|
546eb323962abcfd73f8433f92faaee1a0329ae2 | b815abf92ce063fe0d1fabf5b42da483552aa3e8 | /library/init/meta/vm.lean | a334321ef3597f0ef4e4d358a4f6c2d0e53aa4b1 | [
"Apache-2.0"
] | permissive | yodalee/lean | a368d842df12c63e9f79414ed7bbee805b9001ef | 317989bf9ef6ae1dec7488c2363dbfcdc16e0756 | refs/heads/master | 1,610,551,176,860 | 1,481,430,138,000 | 1,481,646,441,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,383 | 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.tactic init.data.option.basic
meta constant vm_obj : Type
inductive vm_obj_kind
| simple | constructor | closure | mpz
| name | level | expr | declaration
| environment | tactic_state | format
| options | other
namespace vm_obj
meta constant kind : vm_obj → vm_obj_kind
/- For simple and constructor vm_obj's, it returns the constructor tag/index.
Return 0 otherwise. -/
meta constant cidx : vm_obj → nat
/- For closure vm_obj's, it returns the internal function index. -/
meta constant fn_idx : vm_obj → nat
/- For constructor vm_obj's, it returns the data stored in the object.
For closure vm_obj's, it returns the local arguments captured by the closure. -/
meta constant fields : vm_obj → list vm_obj
/- For simple and mpz vm_obj's -/
meta constant to_nat : vm_obj → nat
/- For name vm_obj's, it returns the name wrapped by the vm_obj. -/
meta constant to_name : vm_obj → name
/- For level vm_obj's, it returns the universe level wrapped by the vm_obj. -/
meta constant to_level : vm_obj → level
/- For expr vm_obj's, it returns the expression wrapped by the vm_obj. -/
meta constant to_expr : vm_obj → expr
/- For declaration vm_obj's, it returns the declaration wrapped by the vm_obj. -/
meta constant to_declaration : vm_obj → declaration
/- For environment vm_obj's, it returns the environment wrapped by the vm_obj. -/
meta constant to_environment : vm_obj → environment
/- For tactic_state vm_obj's, it returns the tactic_state object wrapped by the vm_obj. -/
meta constant to_tactic_state : vm_obj → tactic_state
/- For format vm_obj's, it returns the format object wrapped by the vm_obj. -/
meta constant to_format : vm_obj → format
end vm_obj
meta constant vm_decl : Type
inductive vm_decl_kind
| bytecode | builtin | cfun
/- Information for local variables and arguments on the VM stack.
Remark: type is only available if it is a closed term at compilation time. -/
meta structure vm_local_info :=
(id : name) (type : option expr)
namespace vm_decl
meta constant kind : vm_decl → vm_decl_kind
meta constant to_name : vm_decl → name
/- Internal function index associated with the given VM declaration. -/
meta constant idx : vm_decl → nat
/- Number of arguments needed to execute the given VM declaration. -/
meta constant arity : vm_decl → nat
/- Return (line, column) if available -/
meta constant pos : vm_decl → option (nat × nat)
/- Return .olean file where the given VM declaration was imported from. -/
meta constant olean : vm_decl → option string
/- Return names .olean file where the given VM declaration was imported from. -/
meta constant args_info : vm_decl → list vm_local_info
end vm_decl
meta constant vm_core : Type → Type
meta constant vm_core.map {α β : Type} : (α → β) → vm_core α → vm_core β
meta constant vm_core.ret {α : Type} : α → vm_core α
meta constant vm_core.bind {α β : Type} : vm_core α → (α → vm_core β) → vm_core β
meta instance : monad vm_core :=
{map := @vm_core.map, ret := @vm_core.ret, bind := @vm_core.bind}
@[reducible] meta def vm (α : Type) : Type := option_t.{1 1} vm_core α
namespace vm
meta constant get_env : vm environment
meta constant get_decl : name → vm vm_decl
meta constant get_options : vm options
meta constant stack_size : vm nat
/- Return the vm_obj stored at the given position on the execution stack.
It fails if position >= vm.stack_size -/
meta constant stack_obj : nat → vm vm_obj
/- Return (name, type) for the object at the given position on the execution stack.
It fails if position >= vm.stack_size.
The name is anonymous if vm_obj is a transient value created by the compiler.
Type information is only recorded if the type is a closed term at compilation time. -/
meta constant stack_obj_info : nat → vm (name × option expr)
/- Pretty print the vm_obj at the given position on the execution stack. -/
meta constant pp_stack_obj : nat → vm format
/- Pretty print the given expression. -/
meta constant pp_expr : expr → vm format
/- Number of frames on the call stack. -/
meta constant call_stack_size : vm nat
/- Return the function name at the given stack frame.
Action fails if position >= vm.call_stack_size. -/
meta constant call_stack_fn : nat → vm name
/- Return the range [start, end) for the given stack frame.
Action fails if position >= vm.call_stack_size.
The values start and end correspond to positions at the execution stack.
We have that 0 <= start < end <= vm.stack_size -/
meta constant call_stack_var_range : nat → vm (nat × nat)
/- Return the name of the function on top of the call stack. -/
meta constant curr_fn : vm name
/- Return the base stack pointer for the frame on top of the call stack. -/
meta constant bp : vm nat
/- Return the program counter. -/
meta constant pc : vm nat
/- Convert the given vm_obj into a string -/
meta constant obj_to_string : vm_obj → vm string
meta constant put_str : string → vm unit
meta constant get_line : vm string
/- Return tt if end of the input stream has been reached.
For example, this can happen if the user presses Ctrl-D -/
meta constant eof : vm bool
/- Return the list of declarations tagged with the given attribute. -/
meta constant get_attribute : name → vm (list name)
meta def trace {α : Type} [has_to_format α] (a : α) : vm unit :=
do fmt ← return $ to_fmt a,
return $ _root_.trace_fmt fmt (λ u, ())
end vm
meta structure vm_monitor (s : Type) :=
(init : s) (step : s → vm s)
/- Registers a new virtual machine monitor. The argument must be the name of a definition of type
`vm_monitor S`. The command will override the last monitor.
If option 'debugger' is true, then the VM will initialize the vm_monitor state using the
'init' field, and will invoke the function 'step' before each instruction is invoked. -/
meta constant vm_monitor.register : name → command
|
fb67d35687533cd49071c4d41e42519fc7970480 | e030b0259b777fedcdf73dd966f3f1556d392178 | /tests/lean/run/offset1.lean | 7e068bdda511b418fa5f8a370e0429e519e8a2b6 | [
"Apache-2.0"
] | permissive | fgdorais/lean | 17b46a095b70b21fa0790ce74876658dc5faca06 | c3b7c54d7cca7aaa25328f0a5660b6b75fe26055 | refs/heads/master | 1,611,523,590,686 | 1,484,412,902,000 | 1,484,412,902,000 | 38,489,734 | 0 | 0 | null | 1,435,923,380,000 | 1,435,923,379,000 | null | UTF-8 | Lean | false | false | 470 | lean | open nat
inductive vec (α : Type*) : ℕ → Type*
| nil {} : vec 0
| cons : α → Π {n : nat}, vec n → vec (n+1)
namespace vec
def head {α : Type*} : Π {n : ℕ}, vec α (n+1) → α
| n (cons x xs) := x
end vec
constants (dret : Π {n : ℕ}, vec nat n → (vec nat n → nat) → nat)
axiom dret_spec : Π {n : ℕ} (xs : vec nat n) (f : vec nat n → nat), dret xs f = f xs
example (v : vec nat (id 1)) : dret v vec.head = vec.head v :=
by rw dret_spec
|
c3c32d150d3beb1413424e8a7693452ce68484c7 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/abelian/subobject.lean | 02997c657fea5bd9eacbe68a4668549aab67bb3d | [
"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,049 | lean | /-
Copyright (c) 2022 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import category_theory.subobject.limits
import category_theory.abelian.basic
/-!
# Equivalence between subobjects and quotients in an abelian category
-/
open category_theory category_theory.limits opposite
universes v u
noncomputable theory
namespace category_theory.abelian
variables {C : Type u} [category.{v} C]
/-- In an abelian category, the subobjects and quotient objects of an object `X` are
order-isomorphic via taking kernels and cokernels.
Implemented here using subobjects in the opposite category,
since mathlib does not have a notion of quotient objects at the time of writing. -/
@[simps]
def subobject_iso_subobject_op [abelian C] (X : C) : subobject X ≃o (subobject (op X))ᵒᵈ :=
begin
refine order_iso.of_hom_inv (cokernel_order_hom X) (kernel_order_hom X) _ _,
{ change (cokernel_order_hom X).comp (kernel_order_hom X) = _,
refine order_hom.ext _ _ (funext (subobject.ind _ _)),
introsI A f hf,
dsimp only [order_hom.comp_coe, function.comp_app, kernel_order_hom_coe, subobject.lift_mk,
cokernel_order_hom_coe, order_hom.id_coe, id.def],
refine subobject.mk_eq_mk_of_comm _ _ ⟨_, _, quiver.hom.unop_inj _, quiver.hom.unop_inj _⟩ _,
{ exact (abelian.epi_desc f.unop _ (cokernel.condition (kernel.ι f.unop))).op },
{ exact (cokernel.desc _ _ (kernel.condition f.unop)).op },
{ simp only [← cancel_epi (cokernel.π (kernel.ι f.unop)), unop_comp, quiver.hom.unop_op,
unop_id_op, cokernel.π_desc_assoc, comp_epi_desc, category.comp_id] },
{ simp only [← cancel_epi f.unop, unop_comp, quiver.hom.unop_op, unop_id, comp_epi_desc_assoc,
cokernel.π_desc, category.comp_id] },
{ exact quiver.hom.unop_inj (by simp only [unop_comp, quiver.hom.unop_op, comp_epi_desc]) } },
{ change (kernel_order_hom X).comp (cokernel_order_hom X) = _,
refine order_hom.ext _ _ (funext (subobject.ind _ _)),
introsI A f hf,
dsimp only [order_hom.comp_coe, function.comp_app, cokernel_order_hom_coe, subobject.lift_mk,
kernel_order_hom_coe, order_hom.id_coe, id.def, unop_op, quiver.hom.unop_op],
refine subobject.mk_eq_mk_of_comm _ _ ⟨_, _, _, _⟩ _,
{ exact abelian.mono_lift f _ (kernel.condition (cokernel.π f)) },
{ exact kernel.lift _ _ (cokernel.condition f) },
{ simp only [← cancel_mono (kernel.ι (cokernel.π f)), category.assoc, image.fac, mono_lift_comp,
category.id_comp, auto_param_eq] },
{ simp only [← cancel_mono f, category.assoc, mono_lift_comp, image.fac, category.id_comp,
auto_param_eq] },
{ simp only [mono_lift_comp] } }
end
/-- A well-powered abelian category is also well-copowered. -/
instance well_powered_opposite [abelian C] [well_powered C] : well_powered Cᵒᵖ :=
{ subobject_small := λ X,
(small_congr (subobject_iso_subobject_op (unop X)).to_equiv).1 infer_instance }
end category_theory.abelian
|
93e465fe1583440d742f12f233e1444e9f29acb8 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /counterexamples/canonically_ordered_comm_semiring_two_mul.lean | 92eb998214db3646633e396cfa258cbf3bf152f1 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 8,914 | lean | /-
Copyright (c) 2021 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import data.zmod.basic
import ring_theory.subsemiring.basic
import algebra.order.monoid
/-!
A `canonically_ordered_comm_semiring` with two different elements `a` and `b` such that
`a ≠ b` and `2 * a = 2 * b`. Thus, multiplication by a fixed non-zero element of a canonically
ordered semiring need not be injective. In particular, multiplying by a strictly positive element
need not be strictly monotone.
Recall that a `canonically_ordered_comm_semiring` is a commutative semiring with a partial ordering
that is "canonical" in the sense that the inequality `a ≤ b` holds if and only if there is a `c`
such that `a + c = b`. There are several compatibility conditions among addition/multiplication
and the order relation. The point of the counterexample is to show that monotonicity of
multiplication cannot be strengthened to **strict** monotonicity.
Reference:
https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/canonically_ordered.20pathology
-/
namespace from_Bhavik
/-- Bhavik Mehta's example. There are only the initial definitions, but no proofs. The Type
`K` is a canonically ordered commutative semiring with the property that `2 * (1/2) ≤ 2 * 1`, even
though it is not true that `1/2 ≤ 1`, since `1/2` and `1` are not comparable. -/
@[derive [comm_semiring]]
def K : Type := subsemiring.closure ({1.5} : set ℚ)
instance : has_coe K ℚ := ⟨λ x, x.1⟩
instance inhabited_K : inhabited K := ⟨0⟩
instance : preorder K :=
{ le := λ x y, x = y ∨ (x : ℚ) + 1 ≤ (y : ℚ),
le_refl := λ x, or.inl rfl,
le_trans := λ x y z xy yz,
begin
rcases xy with (rfl | _), { apply yz },
rcases yz with (rfl | _), { right, apply xy },
right,
exact xy.trans (le_trans ((le_add_iff_nonneg_right _).mpr zero_le_one) yz)
end }
end from_Bhavik
lemma mem_zmod_2 (a : zmod 2) : a = 0 ∨ a = 1 :=
begin
rcases a with ⟨_ | _ | _ | _ | a_val, _ | ⟨_, _ | ⟨_, ⟨⟩⟩⟩⟩,
{ exact or.inl rfl },
{ exact or.inr rfl },
end
lemma add_self_zmod_2 (a : zmod 2) : a + a = 0 :=
begin
rcases mem_zmod_2 a with rfl | rfl;
refl,
end
namespace Nxzmod_2
variables {a b : ℕ × zmod 2}
/-- The preorder relation on `ℕ × ℤ/2ℤ` where we only compare the first coordinate,
except that we leave incomparable each pair of elements with the same first component.
For instance, `∀ α, β ∈ ℤ/2ℤ`, the inequality `(1,α) ≤ (2,β)` holds,
whereas, `∀ n ∈ ℤ`, the elements `(n,0)` and `(n,1)` are incomparable. -/
instance preN2 : partial_order (ℕ × zmod 2) :=
{ le := λ x y, x = y ∨ x.1 < y.1,
le_refl := λ a, or.inl rfl,
le_trans := λ x y z xy yz,
begin
rcases xy with (rfl | _),
{ exact yz },
{ rcases yz with (rfl | _),
{ exact or.inr xy},
{ exact or.inr (xy.trans yz) } }
end,
le_antisymm := begin
intros a b ab ba,
cases ab with ab ab,
{ exact ab },
{ cases ba with ba ba,
{ exact ba.symm },
{ exact (nat.lt_asymm ab ba).elim } }
end }
instance csrN2 : comm_semiring (ℕ × zmod 2) := by apply_instance
instance csrN2_1 : add_cancel_comm_monoid (ℕ × zmod 2) :=
{ add_left_cancel := λ a b c h, (add_right_inj a).mp h,
..Nxzmod_2.csrN2 }
/-- A strict inequality forces the first components to be different. -/
@[simp] lemma lt_def : a < b ↔ a.1 < b.1 :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ rcases h with ⟨(rfl | a1), h1⟩,
{ exact ((not_or_distrib.mp h1).1).elim rfl },
{ exact a1 } },
refine ⟨or.inr h, not_or_distrib.mpr ⟨λ k, _, not_lt.mpr h.le⟩⟩,
rw k at h,
exact nat.lt_asymm h h
end
lemma add_left_cancel : ∀ (a b c : ℕ × zmod 2), a + b = a + c → b = c :=
λ a b c h, (add_right_inj a).mp h
lemma add_le_add_left : ∀ (a b : ℕ × zmod 2), a ≤ b → ∀ (c : ℕ × zmod 2), c + a ≤ c + b :=
begin
rintros a b (rfl | ab) c,
{ refl },
{ exact or.inr (by simpa) }
end
lemma le_of_add_le_add_left : ∀ (a b c : ℕ × zmod 2), a + b ≤ a + c → b ≤ c :=
begin
rintros a b c (bc | bc),
{ exact le_of_eq ((add_right_inj a).mp bc) },
{ exact or.inr (by simpa using bc) }
end
instance : zero_le_one_class (ℕ × zmod 2) := ⟨dec_trivial⟩
lemma mul_lt_mul_of_pos_left : ∀ (a b c : ℕ × zmod 2), a < b → 0 < c → c * a < c * b :=
λ a b c ab c0, lt_def.mpr ((mul_lt_mul_left (lt_def.mp c0)).mpr (lt_def.mp ab))
lemma mul_lt_mul_of_pos_right : ∀ (a b c : ℕ × zmod 2), a < b → 0 < c → a * c < b * c :=
λ a b c ab c0, lt_def.mpr ((mul_lt_mul_right (lt_def.mp c0)).mpr (lt_def.mp ab))
instance ocsN2 : ordered_comm_semiring (ℕ × zmod 2) :=
{ add_le_add_left := add_le_add_left,
le_of_add_le_add_left := le_of_add_le_add_left,
zero_le_one := zero_le_one,
mul_lt_mul_of_pos_left := mul_lt_mul_of_pos_left,
mul_lt_mul_of_pos_right := mul_lt_mul_of_pos_right,
..Nxzmod_2.csrN2_1,
..(infer_instance : partial_order (ℕ × zmod 2)),
..(infer_instance : comm_semiring (ℕ × zmod 2)) }
end Nxzmod_2
namespace ex_L
open Nxzmod_2 subtype
/-- Initially, `L` was defined as the subsemiring closure of `(1,0)`. -/
def L : Type := { l : (ℕ × zmod 2) // l ≠ (0, 1) }
lemma add_L {a b : ℕ × zmod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) :
a + b ≠ (0, 1) :=
begin
rcases a with ⟨a, a2⟩,
rcases b with ⟨b, b2⟩,
cases b,
{ rcases mem_zmod_2 b2 with rfl | rfl,
{ simp [ha] },
{ simpa only } },
{ simp [(a + b).succ_ne_zero] }
end
lemma mul_L {a b : ℕ × zmod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) :
a * b ≠ (0, 1) :=
begin
rcases a with ⟨a, a2⟩,
rcases b with ⟨b, b2⟩,
cases b,
{ rcases mem_zmod_2 b2 with rfl | rfl;
rcases mem_zmod_2 a2 with rfl | rfl;
-- while this looks like a non-terminal `simp`, it (almost) isn't: there is only one goal where
-- it does not finish the proof and on that goal it asks to prove `false`
simp,
exact hb rfl },
cases a,
{ rcases mem_zmod_2 b2 with rfl | rfl;
rcases mem_zmod_2 a2 with rfl | rfl;
-- while this looks like a non-terminal `simp`, it (almost) isn't: there is only one goal where
-- it does not finish the proof and on that goal it asks to prove `false`
simp,
exact ha rfl },
{ simp [mul_ne_zero _ _, nat.succ_ne_zero _] }
end
/-- The subsemiring corresponding to the elements of `L`, used to transfer instances. -/
def L_subsemiring : subsemiring (ℕ × zmod 2) :=
{ carrier := { l | l ≠ (0, 1) },
zero_mem' := dec_trivial,
one_mem' := dec_trivial,
add_mem' := λ _ _, add_L,
mul_mem' := λ _ _, mul_L }
instance : ordered_comm_semiring L :=
L_subsemiring.to_ordered_comm_semiring
instance inhabited : inhabited L := ⟨1⟩
lemma bot_le : ∀ (a : L), 0 ≤ a :=
begin
rintros ⟨⟨an, a2⟩, ha⟩,
cases an,
{ rcases mem_zmod_2 a2 with (rfl | rfl),
{ refl, },
{ exact (ha rfl).elim } },
{ refine or.inr _,
exact nat.succ_pos _ }
end
instance order_bot : order_bot L := ⟨0, bot_le⟩
lemma exists_add_of_le : ∀ a b : L, a ≤ b → ∃ c, b = a + c :=
begin
rintro a ⟨b, _⟩ (⟨rfl, rfl⟩ | h),
{ exact ⟨0, (add_zero _).symm⟩ },
{ exact ⟨⟨b - a.1, λ H, (tsub_pos_of_lt h).ne' (prod.mk.inj_iff.1 H).1⟩,
subtype.ext $ prod.ext (add_tsub_cancel_of_le h.le).symm (add_sub_cancel'_right _ _).symm⟩ }
end
lemma le_self_add : ∀ a b : L, a ≤ a + b :=
begin
rintro a ⟨⟨bn, b2⟩, hb⟩,
obtain rfl | h := nat.eq_zero_or_pos bn,
{ obtain rfl | rfl := mem_zmod_2 b2,
{ exact or.inl (prod.ext (add_zero _).symm (add_zero _).symm) },
{ exact (hb rfl).elim } },
{ exact or.inr ((lt_add_iff_pos_right _).mpr h) }
end
lemma eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : L), a * b = 0 → a = 0 ∨ b = 0 :=
begin
rintros ⟨⟨a, a2⟩, ha⟩ ⟨⟨b, b2⟩, hb⟩ ab1,
injection ab1 with ab,
injection ab with abn ab2,
rw mul_eq_zero at abn,
rcases abn with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩,
{ refine or.inl _,
rcases mem_zmod_2 a2 with rfl | rfl,
{ refl },
{ exact (ha rfl).elim } },
{ refine or.inr _,
rcases mem_zmod_2 b2 with rfl | rfl,
{ refl },
{ exact (hb rfl).elim } }
end
instance can : canonically_ordered_comm_semiring L :=
{ exists_add_of_le := exists_add_of_le,
le_self_add := le_self_add,
eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero,
..(infer_instance : order_bot L),
..(infer_instance : ordered_comm_semiring L) }
/--
The elements `(1,0)` and `(1,1)` of `L` are different, but their doubles coincide.
-/
example : ∃ a b : L, a ≠ b ∧ 2 * a = 2 * b :=
begin
refine ⟨⟨(1,0), by simp⟩, 1, λ (h : (⟨(1, 0), _⟩ : L) = ⟨⟨1, 1⟩, _⟩), _, rfl⟩,
obtain (F : (0 : zmod 2) = 1) := congr_arg (λ j : L, j.1.2) h,
cases F,
end
end ex_L
|
b43c67760a216727551086eedc12e74ef1fe097f | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/measure_theory/group.lean | d52c92d10b704634572939ac109f57c8e4159132 | [
"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 | 9,431 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import measure_theory.integration
/-!
# Measures on Groups
We develop some properties of measures on (topological) groups
* We define properties on measures: left and right invariant measures.
* We define the measure `μ.inv : A ↦ μ(A⁻¹)` and show that it is right invariant iff
`μ` is left invariant.
-/
noncomputable theory
open_locale ennreal
open has_inv set function measure_theory.measure
namespace measure_theory
variables {G : Type*}
section
variables [measurable_space G] [has_mul G]
/-- A measure `μ` on a topological group is left invariant
if the measure of left translations of a set are equal to the measure of the set itself.
To left translate sets we use preimage under left multiplication,
since preimages are nicer to work with than images. -/
@[to_additive "A measure on a topological group is left invariant
if the measure of left translations of a set are equal to the measure of the set itself.
To left translate sets we use preimage under left addition,
since preimages are nicer to work with than images."]
def is_mul_left_invariant (μ : set G → ℝ≥0∞) : Prop :=
∀ (g : G) {A : set G} (h : measurable_set A), μ ((λ h, g * h) ⁻¹' A) = μ A
/-- A measure `μ` on a topological group is right invariant
if the measure of right translations of a set are equal to the measure of the set itself.
To right translate sets we use preimage under right multiplication,
since preimages are nicer to work with than images. -/
@[to_additive "A measure on a topological group is right invariant
if the measure of right translations of a set are equal to the measure of the set itself.
To right translate sets we use preimage under right addition,
since preimages are nicer to work with than images."]
def is_mul_right_invariant (μ : set G → ℝ≥0∞) : Prop :=
∀ (g : G) {A : set G} (h : measurable_set A), μ ((λ h, h * g) ⁻¹' A) = μ A
end
namespace measure
variables [measurable_space G]
@[to_additive]
lemma map_mul_left_eq_self [topological_space G] [has_mul G] [has_continuous_mul G] [borel_space G]
{μ : measure G} : (∀ g, measure.map ((*) g) μ = μ) ↔ is_mul_left_invariant μ :=
begin
apply forall_congr, intro g, rw [measure.ext_iff], apply forall_congr, intro A,
apply forall_congr, intro hA, rw [map_apply (measurable_const_mul g) hA]
end
@[to_additive]
lemma map_mul_right_eq_self [topological_space G] [has_mul G] [has_continuous_mul G] [borel_space G]
{μ : measure G} : (∀ g, measure.map (λ h, h * g) μ = μ) ↔ is_mul_right_invariant μ :=
begin
apply forall_congr, intro g, rw [measure.ext_iff], apply forall_congr, intro A,
apply forall_congr, intro hA, rw [map_apply (measurable_mul_const g) hA]
end
/-- The measure `A ↦ μ (A⁻¹)`, where `A⁻¹` is the pointwise inverse of `A`. -/
@[to_additive "The measure `A ↦ μ (- A)`, where `- A` is the pointwise negation of `A`."]
protected def inv [has_inv G] (μ : measure G) : measure G :=
measure.map inv μ
variables [group G] [topological_space G] [topological_group G] [borel_space G]
@[to_additive]
lemma inv_apply (μ : measure G) {s : set G} (hs : measurable_set s) :
μ.inv s = μ s⁻¹ :=
measure.map_apply measurable_inv hs
@[simp, to_additive] protected lemma inv_inv (μ : measure G) : μ.inv.inv = μ :=
begin
ext1 s hs, rw [μ.inv.inv_apply hs, μ.inv_apply, set.inv_inv],
exact measurable_inv hs
end
variables {μ : measure G}
@[to_additive]
lemma regular.inv [t2_space G] (hμ : μ.regular) : μ.inv.regular :=
hμ.map (homeomorph.inv G)
end measure
section inv
variables [measurable_space G] [group G] [topological_space G] [topological_group G] [borel_space G]
{μ : measure G}
@[simp, to_additive] lemma regular_inv_iff [t2_space G] : μ.inv.regular ↔ μ.regular :=
by { refine ⟨λ h, _, measure.regular.inv⟩, rw ←μ.inv_inv, exact measure.regular.inv h }
@[to_additive]
lemma is_mul_left_invariant.inv (h : is_mul_left_invariant μ) :
is_mul_right_invariant μ.inv :=
begin
intros g A hA,
rw [μ.inv_apply (measurable_mul_const g hA), μ.inv_apply hA],
convert h g⁻¹ (measurable_inv hA) using 2,
simp only [←preimage_comp, ← inv_preimage],
apply preimage_congr,
intro h,
simp only [mul_inv_rev, comp_app, inv_inv]
end
@[to_additive]
lemma is_mul_right_invariant.inv (h : is_mul_right_invariant μ) : is_mul_left_invariant μ.inv :=
begin
intros g A hA,
rw [μ.inv_apply (measurable_const_mul g hA), μ.inv_apply hA],
convert h g⁻¹ (measurable_inv hA) using 2,
simp only [←preimage_comp, ← inv_preimage],
apply preimage_congr,
intro h,
simp only [mul_inv_rev, comp_app, inv_inv]
end
@[simp, to_additive]
lemma is_mul_right_invariant_inv : is_mul_right_invariant μ.inv ↔ is_mul_left_invariant μ :=
⟨λ h, by { rw ← μ.inv_inv, exact h.inv }, λ h, h.inv⟩
@[simp, to_additive]
lemma is_mul_left_invariant_inv : is_mul_left_invariant μ.inv ↔ is_mul_right_invariant μ :=
⟨λ h, by { rw ← μ.inv_inv, exact h.inv }, λ h, h.inv⟩
end inv
variables [measurable_space G] [topological_space G] [borel_space G] {μ : measure G}
section group
variables [group G] [topological_group G]
/-! Properties of regular left invariant measures -/
@[to_additive measure_theory.measure.is_add_left_invariant.null_iff_empty]
lemma is_mul_left_invariant.null_iff_empty (hμ : μ.regular) (h2μ : is_mul_left_invariant μ)
(h3μ : μ ≠ 0) {s : set G} (hs : is_open s) : μ s = 0 ↔ s = ∅ :=
begin
obtain ⟨K, hK, h2K⟩ := hμ.exists_compact_not_null.mpr h3μ,
refine ⟨λ h, _, λ h, by simp [h]⟩,
apply classical.by_contradiction, -- `by_contradiction` is very slow
refine mt (λ h2s, _) h2K,
rw [← ne.def, ne_empty_iff_nonempty] at h2s, cases h2s with y hy,
obtain ⟨t, -, h1t, h2t⟩ := hK.elim_finite_subcover_image
(show ∀ x ∈ @univ G, is_open ((λ y, x * y) ⁻¹' s),
from λ x _, (continuous_mul_left x).is_open_preimage _ hs) _,
{ rw [← nonpos_iff_eq_zero],
refine (measure_mono h2t).trans _,
refine (measure_bUnion_le h1t.countable _).trans_eq _,
simp_rw [h2μ _ hs.measurable_set], rw [h, tsum_zero] },
{ intros x _,
simp_rw [mem_Union, mem_preimage],
use [y * x⁻¹, mem_univ _],
rwa [inv_mul_cancel_right] }
end
@[to_additive measure_theory.measure.is_add_left_invariant.null_iff]
lemma is_mul_left_invariant.null_iff (hμ : regular μ) (h2μ : is_mul_left_invariant μ)
{s : set G} (hs : is_open s) : μ s = 0 ↔ s = ∅ ∨ μ = 0 :=
begin
by_cases h3μ : μ = 0, { simp [h3μ] },
simp only [h3μ, or_false],
exact h2μ.null_iff_empty hμ h3μ hs,
end
@[to_additive measure_theory.measure.is_add_left_invariant.measure_ne_zero_iff_nonempty]
lemma is_mul_left_invariant.measure_ne_zero_iff_nonempty (hμ : regular μ)
(h2μ : is_mul_left_invariant μ) (h3μ : μ ≠ 0) {s : set G} (hs : is_open s) :
μ s ≠ 0 ↔ s.nonempty :=
by simp_rw [← ne_empty_iff_nonempty, ne.def, h2μ.null_iff_empty hμ h3μ hs]
/-- For nonzero regular left invariant measures, the integral of a continuous nonnegative function
`f` is 0 iff `f` is 0. -/
-- @[to_additive] (fails for now)
lemma lintegral_eq_zero_of_is_mul_left_invariant (hμ : regular μ)
(h2μ : is_mul_left_invariant μ) (h3μ : μ ≠ 0) {f : G → ℝ≥0∞} (hf : continuous f) :
∫⁻ x, f x ∂μ = 0 ↔ f = 0 :=
begin
split, swap, { rintro rfl, simp_rw [pi.zero_apply, lintegral_zero] },
intro h, contrapose h,
simp_rw [funext_iff, not_forall, pi.zero_apply] at h, cases h with x hx,
obtain ⟨r, h1r, h2r⟩ : ∃ r : ℝ≥0∞, 0 < r ∧ r < f x :=
exists_between (pos_iff_ne_zero.mpr hx),
have h3r := hf.is_open_preimage (Ioi r) is_open_Ioi,
let s := Ioi r,
rw [← ne.def, ← pos_iff_ne_zero],
have : 0 < r * μ (f ⁻¹' Ioi r),
{ rw ennreal.mul_pos,
refine ⟨h1r, _⟩,
rw [pos_iff_ne_zero, h2μ.measure_ne_zero_iff_nonempty hμ h3μ h3r],
exact ⟨x, h2r⟩ },
refine this.trans_le _,
rw [← set_lintegral_const, ← lintegral_indicator _ h3r.measurable_set],
apply lintegral_mono,
refine indicator_le (λ y, le_of_lt),
end
end group
section integration
variables [group G] [has_continuous_mul G]
open measure
/-- Translating a function by left-multiplication does not change its `lintegral` with respect to
a left-invariant measure. -/
@[to_additive]
lemma lintegral_mul_left_eq_self (hμ : is_mul_left_invariant μ) (f : G → ℝ≥0∞) (g : G) :
∫⁻ x, f (g * x) ∂μ = ∫⁻ x, f x ∂μ :=
begin
have : measure.map (has_mul.mul g) μ = μ,
{ rw ← map_mul_left_eq_self at hμ,
exact hμ g },
convert (lintegral_map_equiv f (homeomorph.mul_left g).to_measurable_equiv).symm,
simp [this]
end
/-- Translating a function by right-multiplication does not change its `lintegral` with respect to
a right-invariant measure. -/
@[to_additive]
lemma lintegral_mul_right_eq_self (hμ : is_mul_right_invariant μ) (f : G → ℝ≥0∞) (g : G) :
∫⁻ x, f (x * g) ∂μ = ∫⁻ x, f x ∂μ :=
begin
have : measure.map (homeomorph.mul_right g) μ = μ,
{ rw ← map_mul_right_eq_self at hμ,
exact hμ g },
convert (lintegral_map_equiv f (homeomorph.mul_right g).to_measurable_equiv).symm,
simp [this]
end
end integration
end measure_theory
|
c58e8c3cbf13df73cabd60bbdd168f4ec369d57d | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/group_theory/free_abelian_group_auto.lean | eb24deacf5f2e26661c95b890c3593cd214dc2db | [] | 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 | 11,505 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Free abelian groups as abelianization of free groups.
-- TODO: rewrite in terms of finsupp
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.group.pi
import Mathlib.group_theory.free_group
import Mathlib.group_theory.abelianization
import Mathlib.PostPort
universes u v u_1 u_2 u_3
namespace Mathlib
def free_abelian_group (α : Type u) := additive (abelianization (free_group α))
protected instance free_abelian_group.add_comm_group (α : Type u) :
add_comm_group (free_abelian_group α) :=
additive.add_comm_group
protected instance free_abelian_group.inhabited (α : Type u) : Inhabited (free_abelian_group α) :=
{ default := 0 }
namespace free_abelian_group
def of {α : Type u} (x : α) : free_abelian_group α := coe_fn abelianization.of (free_group.of x)
def lift {α : Type u} {β : Type v} [add_comm_group β] (f : α → β) : free_abelian_group α →+ β :=
coe_fn monoid_hom.to_additive (abelianization.lift (monoid_hom.of ⇑(free_group.to_group f)))
namespace lift
@[simp] protected theorem add {α : Type u} {β : Type v} [add_comm_group β] (f : α → β)
(x : free_abelian_group α) (y : free_abelian_group α) :
coe_fn (lift f) (x + y) = coe_fn (lift f) x + coe_fn (lift f) y :=
is_add_hom.map_add (⇑(lift f)) x y
@[simp] protected theorem neg {α : Type u} {β : Type v} [add_comm_group β] (f : α → β)
(x : free_abelian_group α) : coe_fn (lift f) (-x) = -coe_fn (lift f) x :=
is_add_group_hom.map_neg (⇑(lift f)) x
@[simp] protected theorem sub {α : Type u} {β : Type v} [add_comm_group β] (f : α → β)
(x : free_abelian_group α) (y : free_abelian_group α) :
coe_fn (lift f) (x - y) = coe_fn (lift f) x - coe_fn (lift f) y :=
sorry
@[simp] protected theorem zero {α : Type u} {β : Type v} [add_comm_group β] (f : α → β) :
coe_fn (lift f) 0 = 0 :=
is_add_group_hom.map_zero ⇑(lift f)
@[simp] protected theorem of {α : Type u} {β : Type v} [add_comm_group β] (f : α → β) (x : α) :
coe_fn (lift f) (of x) = f x :=
sorry
protected theorem unique {α : Type u} {β : Type v} [add_comm_group β] (f : α → β)
(g : free_abelian_group α →+ β) (hg : ∀ (x : α), coe_fn g (of x) = f x)
{x : free_abelian_group α} : coe_fn g x = coe_fn (lift f) x :=
abelianization.lift.unique (monoid_hom.of ⇑(free_group.to_group f))
(coe_fn add_monoid_hom.to_multiplicative g)
fun (x : free_group α) =>
free_group.to_group.unique
(monoid_hom.comp (coe_fn add_monoid_hom.to_multiplicative' g) abelianization.of) hg
/-- See note [partially-applied ext lemmas]. -/
protected theorem ext {α : Type u} {β : Type v} [add_comm_group β] (g : free_abelian_group α →+ β)
(h : free_abelian_group α →+ β) (H : ∀ (x : α), coe_fn g (of x) = coe_fn h (of x)) : g = h :=
sorry
theorem map_hom {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group β] [add_comm_group γ]
(a : free_abelian_group α) (f : α → β) (g : β →+ γ) :
coe_fn g (coe_fn (lift f) a) = coe_fn (lift (⇑g ∘ f)) a :=
sorry
end lift
theorem of_injective {α : Type u} : function.injective of := sorry
/-- The bijection underlying the free-forgetful adjunction for abelian groups.-/
def hom_equiv (X : Type u_1) (G : Type u_2) [add_comm_group G] :
(free_abelian_group X →+ G) ≃ (X → G) :=
equiv.mk (fun (f : free_abelian_group X →+ G) => add_monoid_hom.to_fun f ∘ of)
(fun (f : X → G) => add_monoid_hom.of ⇑(lift f)) sorry sorry
@[simp] theorem hom_equiv_apply (X : Type u_1) (G : Type u_2) [add_comm_group G]
(f : free_abelian_group X →+ G) (x : X) : coe_fn (hom_equiv X G) f x = coe_fn f (of x) :=
rfl
@[simp] theorem hom_equiv_symm_apply (X : Type u_1) (G : Type u_2) [add_comm_group G] (f : X → G)
(x : free_abelian_group X) :
coe_fn (coe_fn (equiv.symm (hom_equiv X G)) f) x = coe_fn (lift f) x :=
rfl
protected theorem induction_on {α : Type u} {C : free_abelian_group α → Prop}
(z : free_abelian_group α) (C0 : C 0) (C1 : ∀ (x : α), C (of x))
(Cn : ∀ (x : α), C (of x) → C (-of x))
(Cp : ∀ (x y : free_abelian_group α), C x → C y → C (x + y)) : C z :=
sorry
theorem lift.add' {α : Type u_1} {β : Type u_2} [add_comm_group β] (a : free_abelian_group α)
(f : α → β) (g : α → β) : coe_fn (lift (f + g)) a = coe_fn (lift f) a + coe_fn (lift g) a :=
sorry
protected instance is_add_group_hom_lift' {α : Type u_1} (β : Type u_2) [add_comm_group β]
(a : free_abelian_group α) : is_add_group_hom fun (f : α → β) => coe_fn (lift f) a :=
is_add_group_hom.mk
protected instance monad : Monad free_abelian_group := sorry
protected theorem induction_on' {α : Type u} {C : free_abelian_group α → Prop}
(z : free_abelian_group α) (C0 : C 0) (C1 : ∀ (x : α), C (pure x))
(Cn : ∀ (x : α), C (pure x) → C (-pure x))
(Cp : ∀ (x y : free_abelian_group α), C x → C y → C (x + y)) : C z :=
free_abelian_group.induction_on z C0 C1 Cn Cp
@[simp] theorem map_pure {α : Type u} {β : Type u} (f : α → β) (x : α) :
f <$> pure x = pure (f x) :=
lift.of (of ∘ f) x
@[simp] theorem map_zero {α : Type u} {β : Type u} (f : α → β) : f <$> 0 = 0 := lift.zero (of ∘ f)
@[simp] theorem map_add {α : Type u} {β : Type u} (f : α → β) (x : free_abelian_group α)
(y : free_abelian_group α) : f <$> (x + y) = f <$> x + f <$> y :=
lift.add (of ∘ f) x y
@[simp] theorem map_neg {α : Type u} {β : Type u} (f : α → β) (x : free_abelian_group α) :
f <$> (-x) = -f <$> x :=
lift.neg (of ∘ f) x
@[simp] theorem map_sub {α : Type u} {β : Type u} (f : α → β) (x : free_abelian_group α)
(y : free_abelian_group α) : f <$> (x - y) = f <$> x - f <$> y :=
lift.sub (of ∘ f) x y
@[simp] theorem map_of {α : Type u} {β : Type u} (f : α → β) (y : α) : f <$> of y = of (f y) := rfl
/-- The additive group homomorphism `free_abelian_group α →+ free_abelian_group β` induced from a
map `α → β` -/
def map {α : Type u} {β : Type u} (f : α → β) : free_abelian_group α →+ free_abelian_group β :=
add_monoid_hom.mk' (fun (x : free_abelian_group α) => f <$> x) (map_add f)
theorem lift_comp {α : Type u_1} {β : Type u_1} {γ : Type u_2} [add_comm_group γ] (f : α → β)
(g : β → γ) (x : free_abelian_group α) : coe_fn (lift (g ∘ f)) x = coe_fn (lift g) (f <$> x) :=
sorry
@[simp] theorem pure_bind {α : Type u} {β : Type u} (f : α → free_abelian_group β) (x : α) :
pure x >>= f = f x :=
lift.of f x
@[simp] theorem zero_bind {α : Type u} {β : Type u} (f : α → free_abelian_group β) : 0 >>= f = 0 :=
lift.zero f
@[simp] theorem add_bind {α : Type u} {β : Type u} (f : α → free_abelian_group β)
(x : free_abelian_group α) (y : free_abelian_group α) : x + y >>= f = (x >>= f) + (y >>= f) :=
lift.add f x y
@[simp] theorem neg_bind {α : Type u} {β : Type u} (f : α → free_abelian_group β)
(x : free_abelian_group α) : -x >>= f = -(x >>= f) :=
lift.neg f x
@[simp] theorem sub_bind {α : Type u} {β : Type u} (f : α → free_abelian_group β)
(x : free_abelian_group α) (y : free_abelian_group α) : x - y >>= f = (x >>= f) - (y >>= f) :=
lift.sub f x y
@[simp] theorem pure_seq {α : Type u} {β : Type u} (f : α → β) (x : free_abelian_group α) :
pure f <*> x = f <$> x :=
pure_bind
(fun (_x : α → β) =>
(fun (α β : Type u) (f : α → β) (x : free_abelian_group α) => coe_fn (lift (of ∘ f)) x) α β _x
x)
f
@[simp] theorem zero_seq {α : Type u} {β : Type u} (x : free_abelian_group α) : 0 <*> x = 0 :=
zero_bind
fun (_x : α → β) =>
(fun (α β : Type u) (f : α → β) (x : free_abelian_group α) => coe_fn (lift (of ∘ f)) x) α β _x
x
@[simp] theorem add_seq {α : Type u} {β : Type u} (f : free_abelian_group (α → β))
(g : free_abelian_group (α → β)) (x : free_abelian_group α) :
f + g <*> x = (f <*> x) + (g <*> x) :=
add_bind
(fun (_x : α → β) =>
(fun (α β : Type u) (f : α → β) (x : free_abelian_group α) => coe_fn (lift (of ∘ f)) x) α β _x
x)
f g
@[simp] theorem neg_seq {α : Type u} {β : Type u} (f : free_abelian_group (α → β))
(x : free_abelian_group α) : -f <*> x = -(f <*> x) :=
neg_bind
(fun (_x : α → β) =>
(fun (α β : Type u) (f : α → β) (x : free_abelian_group α) => coe_fn (lift (of ∘ f)) x) α β _x
x)
f
@[simp] theorem sub_seq {α : Type u} {β : Type u} (f : free_abelian_group (α → β))
(g : free_abelian_group (α → β)) (x : free_abelian_group α) :
f - g <*> x = (f <*> x) - (g <*> x) :=
sub_bind
(fun (_x : α → β) =>
(fun (α β : Type u) (f : α → β) (x : free_abelian_group α) => coe_fn (lift (of ∘ f)) x) α β _x
x)
f g
protected instance is_add_group_hom_seq {α : Type u} {β : Type u} (f : free_abelian_group (α → β)) :
is_add_group_hom (Seq.seq f) :=
is_add_group_hom.mk
@[simp] theorem seq_zero {α : Type u} {β : Type u} (f : free_abelian_group (α → β)) : f <*> 0 = 0 :=
is_add_group_hom.map_zero (Seq.seq f)
@[simp] theorem seq_add {α : Type u} {β : Type u} (f : free_abelian_group (α → β))
(x : free_abelian_group α) (y : free_abelian_group α) : f <*> x + y = (f <*> x) + (f <*> y) :=
is_add_hom.map_add (Seq.seq f) x y
@[simp] theorem seq_neg {α : Type u} {β : Type u} (f : free_abelian_group (α → β))
(x : free_abelian_group α) : f <*> -x = -(f <*> x) :=
is_add_group_hom.map_neg (Seq.seq f) x
@[simp] theorem seq_sub {α : Type u} {β : Type u} (f : free_abelian_group (α → β))
(x : free_abelian_group α) (y : free_abelian_group α) : f <*> x - y = (f <*> x) - (f <*> y) :=
is_add_group_hom.map_sub (Seq.seq f) x y
protected instance is_lawful_monad : is_lawful_monad free_abelian_group := sorry
protected instance is_comm_applicative : is_comm_applicative free_abelian_group := sorry
protected instance semigroup (α : Type u) [monoid α] : semigroup (free_abelian_group α) :=
semigroup.mk
(fun (x : free_abelian_group α) =>
⇑(lift fun (x₂ : α) => coe_fn (lift fun (x₁ : α) => of (x₁ * x₂)) x))
sorry
theorem mul_def (α : Type u) [monoid α] (x : free_abelian_group α) (y : free_abelian_group α) :
x * y = coe_fn (lift fun (x₂ : α) => coe_fn (lift fun (x₁ : α) => of (x₁ * x₂)) x) y :=
rfl
theorem of_mul_of (α : Type u) [monoid α] (x : α) (y : α) : of x * of y = of (x * y) := rfl
theorem of_mul (α : Type u) [monoid α] (x : α) (y : α) : of (x * y) = of x * of y := rfl
protected instance ring (α : Type u) [monoid α] : ring (free_abelian_group α) :=
ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg
add_comm_group.sub sorry sorry semigroup.mul sorry (of 1) sorry sorry sorry sorry
theorem one_def (α : Type u) [monoid α] : 1 = of 1 := rfl
theorem of_one (α : Type u) [monoid α] : of 1 = 1 := rfl
protected instance comm_ring (α : Type u) [comm_monoid α] : comm_ring (free_abelian_group α) :=
comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry
ring.one sorry sorry sorry sorry sorry
end Mathlib |
81c6aefb42f82573d7fb38d5e0170f39724fe7a2 | f3a5af2927397cf346ec0e24312bfff077f00425 | /src/game/world10/level15.lean | 8bcc9a03b8d6d283bd86a857029e4f8d29881d2d | [
"Apache-2.0"
] | permissive | ImperialCollegeLondon/natural_number_game | 05c39e1586408cfb563d1a12e1085a90726ab655 | f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd | refs/heads/master | 1,688,570,964,990 | 1,636,908,242,000 | 1,636,908,242,000 | 195,403,790 | 277 | 84 | Apache-2.0 | 1,694,547,955,000 | 1,562,328,792,000 | Lean | UTF-8 | Lean | false | false | 927 | lean | --import mynat.lt -- definition of <
import game.world10.level14 -- hide
namespace mynat -- hide
/-
# Inequality world.
## Level 15: introducing `<`
To get the remaining collectibles in this world, we need to
give a definition of `<`. By default, the definition of `a < b`
in Lean, once `≤` is defined, is this:
`a < b := a ≤ b ∧ ¬ (b ≤ a)`
. But a much more usable definition would be this:
`a < b := succ(a) ≤ b`
. Let's prove that these two definitions are the same
-/
/- Lemma :
For all naturals $a$ and $b$,
$$a\le b\land\lnot(b\le a)\implies\operatorname{succ}(a)\le b.$$
-/
lemma lt_aux_one (a b : mynat) : a ≤ b ∧ ¬ (b ≤ a) → succ a ≤ b :=
begin [nat_num_game]
intro h,
cases h with h1 h2,
cases h1 with c hc,
cases c with d,
exfalso,
rw add_zero at hc,
apply h2,
rw hc,
refl,
use d,
rw hc,
rw add_succ,
rw succ_add,
refl,
end
end mynat -- hide
|
bf95572d4f34506325b3c4f0e4ab5f6419e0bc26 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/range.lean | 3d499ab20991d930b2ffbccd5a27344a58b4311a | [
"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 | 413 | lean |
def ex1 : IO Unit := do
IO.println "example 1"
for x in [:100:10] do
IO.println s!"x: {x}"
#eval ex1
def ex2 : IO Unit := do
IO.println "example 2"
for x in [:10] do
IO.println s!"x: {x}"
#eval ex2
def ex3 : IO Unit := do
IO.println "example 3"
for x in [1:10] do
IO.println s!"x: {x}"
#eval ex3
def ex4 : IO Unit := do
IO.println "example 4"
for x in [1:10:3] do
IO.println s!"x: {x}"
#eval ex4
|
d7f601bfb702a771ccaf81a5f9d91f291700a446 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/linear_algebra/special_linear_group.lean | 16f53cc952fd1365dbf54b7f373098e0ffdb1ae3 | [
"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 | 5,726 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Anne Baanen.
The Special Linear group $SL(n, R)$
-/
import linear_algebra.matrix
import linear_algebra.nonsingular_inverse
/-!
# The Special Linear group $SL(n, R)$
This file defines the elements of the Special Linear group `special_linear_group n R`,
also written `SL(n, R)` or `SLₙ(R)`, consisting of all `n` by `n` `R`-matrices with
determinant `1`. In addition, we define the group structure on `special_linear_group n R`
and the embedding into the general linear group `general_linear_group R (n → R)`
(i.e. `GL(n, R)` or `GLₙ(R)`).
## Main definitions
* `matrix.special_linear_group` is the type of matrices with determinant 1
* `matrix.special_linear_group.group` gives the group structure (under multiplication)
* `matrix.special_linear_group.embedding_GL` is the embedding `SLₙ(R) → GLₙ(R)`
## Implementation notes
The inverse operation in the `special_linear_group` is defined to be the adjugate
matrix, so that `special_linear_group n R` has a group structure for all `comm_ring R`.
We define the elements of `special_linear_group` to be matrices, since we need to
compute their determinant. This is in contrast with `general_linear_group R M`,
which consists of invertible `R`-linear maps on `M`.
## References
* https://en.wikipedia.org/wiki/Special_linear_group
## Tags
matrix group, group, matrix inverse
-/
namespace matrix
universes u v
open_locale matrix
open linear_map
section
variables (n : Type u) [decidable_eq n] [fintype n] (R : Type v) [comm_ring R]
/-- `special_linear_group n R` is the group of `n` by `n` `R`-matrices with determinant equal to 1. -/
def special_linear_group := { A : matrix n n R // A.det = 1 }
end
namespace special_linear_group
variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [comm_ring R]
instance coe_matrix : has_coe (special_linear_group n R) (matrix n n R) :=
⟨λ A, A.val⟩
instance coe_fun : has_coe_to_fun (special_linear_group n R) :=
{ F := λ _, n → n → R,
coe := λ A, A.val }
/--
`to_lin' A` is matrix multiplication of vectors by `A`, as a linear map.
After the group structure on `special_linear_group n R` is defined,
we show in `to_linear_equiv` that this gives a linear equivalence.
-/
def to_lin' (A : special_linear_group n R) := matrix.to_lin' A
lemma ext_iff (A B : special_linear_group n R) : A = B ↔ (∀ i j, A i j = B i j) :=
iff.trans subtype.ext_iff_val ⟨(λ h i j, congr_fun (congr_fun h i) j), matrix.ext⟩
@[ext] lemma ext (A B : special_linear_group n R) : (∀ i j, A i j = B i j) → A = B :=
(special_linear_group.ext_iff A B).mpr
instance has_inv : has_inv (special_linear_group n R) :=
⟨λ A, ⟨adjugate A, det_adjugate_eq_one A.2⟩⟩
instance has_mul : has_mul (special_linear_group n R) :=
⟨λ A B, ⟨A.1 ⬝ B.1, by erw [det_mul, A.2, B.2, one_mul]⟩⟩
instance has_one : has_one (special_linear_group n R) :=
⟨⟨1, det_one⟩⟩
instance : inhabited (special_linear_group n R) := ⟨1⟩
section coe_lemmas
variables (A B : special_linear_group n R)
@[simp] lemma inv_val : ↑(A⁻¹) = adjugate A := rfl
@[simp] lemma inv_apply : ⇑(A⁻¹) = adjugate A := rfl
@[simp] lemma mul_val : ↑(A * B) = A ⬝ B := rfl
@[simp] lemma mul_apply : ⇑(A * B) = (A ⬝ B) := rfl
@[simp] lemma one_val : ↑(1 : special_linear_group n R) = (1 : matrix n n R) := rfl
@[simp] lemma one_apply : ⇑(1 : special_linear_group n R) = (1 : matrix n n R) := rfl
@[simp] lemma det_coe_matrix : det A = 1 := A.2
lemma det_coe_fun : det ⇑A = 1 := A.2
@[simp] lemma to_lin'_mul :
to_lin' (A * B) = (to_lin' A).comp (to_lin' B) :=
matrix.to_lin'_mul A B
@[simp] lemma to_lin'_one :
to_lin' (1 : special_linear_group n R) = linear_map.id :=
matrix.to_lin'_one
end coe_lemmas
instance group : group (special_linear_group n R) :=
{ mul_assoc := λ A B C, by { ext, simp [matrix.mul_assoc] },
one_mul := λ A, by { ext, simp },
mul_one := λ A, by { ext, simp },
mul_left_inv := λ A, by { ext, simp [adjugate_mul] },
..special_linear_group.has_mul,
..special_linear_group.has_one,
..special_linear_group.has_inv }
/-- `to_linear_equiv A` is matrix multiplication of vectors by `A`, as a linear equivalence. -/
def to_linear_equiv (A : special_linear_group n R) : (n → R) ≃ₗ[R] (n → R) :=
{ inv_fun := A⁻¹.to_lin',
left_inv := λ x, calc
A⁻¹.to_lin'.comp A.to_lin' x
= (A⁻¹ * A).to_lin' x : by rw [←to_lin'_mul]
... = x : by rw [mul_left_inv, to_lin'_one, id_apply],
right_inv := λ x, calc
A.to_lin'.comp A⁻¹.to_lin' x
= (A * A⁻¹).to_lin' x : by rw [←to_lin'_mul]
... = x : by rw [mul_right_inv, to_lin'_one, id_apply],
..matrix.to_lin' A }
/-- `to_GL` is the map from the special linear group to the general linear group -/
def to_GL (A : special_linear_group n R) : general_linear_group R (n → R) :=
general_linear_group.of_linear_equiv (to_linear_equiv A)
lemma coe_to_GL (A : special_linear_group n R) :
(@coe (units _) _ _ (to_GL A)) = A.to_lin' :=
rfl
@[simp]
lemma to_GL_one : to_GL (1 : special_linear_group n R) = 1 :=
by { ext v i, rw [coe_to_GL, to_lin'_one], refl }
@[simp]
lemma to_GL_mul (A B : special_linear_group n R) :
to_GL (A * B) = to_GL A * to_GL B :=
by { ext v i, rw [coe_to_GL, to_lin'_mul], refl }
/-- `special_linear_group.embedding_GL` is the embedding from `special_linear_group n R`
to `general_linear_group n R`. -/
def embedding_GL : (special_linear_group n R) →* (general_linear_group R (n → R)) :=
⟨λ A, to_GL A, by simp, by simp⟩
end special_linear_group
end matrix
|
5e8519447a18a32af11c0d0724c414703273ff38 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/combinatorics/simple_graph/ends/properties.lean | 009e5a47a1e97e3ddc6c7a0fee59343de3932251 | [
"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 | 851 | lean | /-
Copyright (c) 2022 Anand Rao, Rémi Bottinelli. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anand Rao, Rémi Bottinelli
-/
import combinatorics.simple_graph.ends.defs
/-!
# Properties of the ends of graphs
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file is meant to contain results about the ends of (locally finite connected) graphs.
-/
variables {V : Type} (G : simple_graph V)
namespace simple_graph
instance [finite V] : is_empty G.end :=
⟨ begin
rintro ⟨s, _⟩,
casesI nonempty_fintype V,
obtain ⟨v, h⟩ := (s $ opposite.op finset.univ).nonempty,
exact set.disjoint_iff.mp (s _).disjoint_right
⟨by simp only [opposite.unop_op, finset.coe_univ], h⟩,
end ⟩
end simple_graph
|
9a22cd882e3991cddd70fad210644c92e7e68ad0 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/linear_algebra/direct_sum_module.lean | b3c80ba1bc58d9b4852bda46bea93e96273d4355 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,919 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Direct sum of modules over commutative rings, indexed by a discrete type.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.direct_sum
import Mathlib.linear_algebra.dfinsupp
import Mathlib.PostPort
universes u v w u₁ u_1
namespace Mathlib
/-!
# Direct sum of modules over commutative rings, indexed by a discrete type.
This file provides constructors for finite direct sums of modules.
It provides a construction of the direct sum using the universal property and proves
its uniqueness.
## Implementation notes
All of this file assumes that
* `R` is a commutative ring,
* `ι` is a discrete type,
* `S` is a finite set in `ι`,
* `M` is a family of `R` semimodules indexed over `ι`.
-/
namespace direct_sum
protected instance semimodule {R : Type u} [semiring R] {ι : Type v} {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] : semimodule R (direct_sum ι fun (i : ι) => M i) :=
dfinsupp.semimodule
theorem smul_apply {R : Type u} [semiring R] {ι : Type v} {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (b : R) (v : direct_sum ι fun (i : ι) => M i) (i : ι) : coe_fn (b • v) i = b • coe_fn v i :=
dfinsupp.smul_apply b v i
/-- Create the direct sum given a family `M` of `R` semimodules indexed over `ι`. -/
def lmk (R : Type u) [semiring R] (ι : Type v) [dec_ι : DecidableEq ι] (M : ι → Type w) [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (s : finset ι) : linear_map R ((i : ↥↑s) → M (subtype.val i)) (direct_sum ι fun (i : ι) => M i) :=
dfinsupp.lmk
/-- Inclusion of each component into the direct sum. -/
def lof (R : Type u) [semiring R] (ι : Type v) [dec_ι : DecidableEq ι] (M : ι → Type w) [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) : linear_map R (M i) (direct_sum ι fun (i : ι) => M i) :=
dfinsupp.lsingle
theorem single_eq_lof (R : Type u) [semiring R] {ι : Type v} [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) (b : M i) : dfinsupp.single i b = coe_fn (lof R ι M i) b :=
rfl
/-- Scalar multiplication commutes with direct sums. -/
theorem mk_smul (R : Type u) [semiring R] {ι : Type v} [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (s : finset ι) (c : R) (x : (i : ↥↑s) → M (subtype.val i)) : coe_fn (mk M s) (c • x) = c • coe_fn (mk M s) x :=
linear_map.map_smul (lmk R ι M s) c x
/-- Scalar multiplication commutes with the inclusion of each component into the direct sum. -/
theorem of_smul (R : Type u) [semiring R] {ι : Type v} [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) (c : R) (x : M i) : coe_fn (of M i) (c • x) = c • coe_fn (of M i) x :=
linear_map.map_smul (lof R ι M i) c x
theorem support_smul {R : Type u} [semiring R] {ι : Type v} [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] [(i : ι) → (x : M i) → Decidable (x ≠ 0)] (c : R) (v : direct_sum ι fun (i : ι) => M i) : dfinsupp.support (c • v) ⊆ dfinsupp.support v :=
dfinsupp.support_smul c v
/-- The linear map constructed using the universal property of the coproduct. -/
def to_module (R : Type u) [semiring R] (ι : Type v) [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (N : Type u₁) [add_comm_monoid N] [semimodule R N] (φ : (i : ι) → linear_map R (M i) N) : linear_map R (direct_sum ι fun (i : ι) => M i) N :=
coe_fn dfinsupp.lsum φ
/-- The map constructed using the universal property gives back the original maps when
restricted to each component. -/
@[simp] theorem to_module_lof (R : Type u) [semiring R] {ι : Type v} [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] {N : Type u₁} [add_comm_monoid N] [semimodule R N] {φ : (i : ι) → linear_map R (M i) N} (i : ι) (x : M i) : coe_fn (to_module R ι N φ) (coe_fn (lof R ι M i) x) = coe_fn (φ i) x :=
to_add_monoid_of (fun (i : ι) => linear_map.to_add_monoid_hom (φ i)) i x
/-- Every linear map from a direct sum agrees with the one obtained by applying
the universal property to each of its components. -/
theorem to_module.unique (R : Type u) [semiring R] {ι : Type v} [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] {N : Type u₁} [add_comm_monoid N] [semimodule R N] (ψ : linear_map R (direct_sum ι fun (i : ι) => M i) N) (f : direct_sum ι fun (i : ι) => M i) : coe_fn ψ f = coe_fn (to_module R ι N fun (i : ι) => linear_map.comp ψ (lof R ι M i)) f :=
to_add_monoid.unique (linear_map.to_add_monoid_hom ψ) f
theorem to_module.ext (R : Type u) [semiring R] {ι : Type v} [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] {N : Type u₁} [add_comm_monoid N] [semimodule R N] {ψ : linear_map R (direct_sum ι fun (i : ι) => M i) N} {ψ' : linear_map R (direct_sum ι fun (i : ι) => M i) N} (H : ∀ (i : ι), linear_map.comp ψ (lof R ι M i) = linear_map.comp ψ' (lof R ι M i)) (f : direct_sum ι fun (i : ι) => M i) : coe_fn ψ f = coe_fn ψ' f :=
eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn ψ f = coe_fn ψ' f)) (dfinsupp.lhom_ext' H))) (Eq.refl (coe_fn ψ' f))
/--
The inclusion of a subset of the direct summands
into a larger subset of the direct summands, as a linear map.
-/
def lset_to_set (R : Type u) [semiring R] {ι : Type v} [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (S : set ι) (T : set ι) (H : S ⊆ T) : linear_map R (direct_sum ↥S fun (i : ↥S) => M ↑i) (direct_sum ↥T fun (i : ↥T) => M ↑i) :=
to_module R (↥S) (direct_sum ↥T fun (i : ↥T) => M ↑i)
fun (i : ↥S) => lof R (↥T) (fun (i : Subtype T) => M ↑i) { val := ↑i, property := sorry }
/-- The natural linear equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/
protected def lid (R : Type u) [semiring R] (M : Type v) (ι : optParam (Type u_1) PUnit) [add_comm_monoid M] [semimodule R M] [unique ι] : linear_equiv R (direct_sum ι fun (_x : ι) => M) M :=
linear_equiv.mk (add_equiv.to_fun (direct_sum.id M ι)) sorry sorry (add_equiv.inv_fun (direct_sum.id M ι)) sorry sorry
/-- The projection map onto one component, as a linear map. -/
def component (R : Type u) [semiring R] (ι : Type v) (M : ι → Type w) [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) : linear_map R (direct_sum ι fun (i : ι) => M i) (M i) :=
dfinsupp.lapply i
theorem apply_eq_component (R : Type u) [semiring R] {ι : Type v} {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (f : direct_sum ι fun (i : ι) => M i) (i : ι) : coe_fn f i = coe_fn (component R ι M i) f :=
rfl
theorem ext (R : Type u) [semiring R] {ι : Type v} {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] {f : direct_sum ι fun (i : ι) => M i} {g : direct_sum ι fun (i : ι) => M i} (h : ∀ (i : ι), coe_fn (component R ι M i) f = coe_fn (component R ι M i) g) : f = g :=
dfinsupp.ext h
theorem ext_iff (R : Type u) [semiring R] {ι : Type v} {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] {f : direct_sum ι fun (i : ι) => M i} {g : direct_sum ι fun (i : ι) => M i} : f = g ↔ ∀ (i : ι), coe_fn (component R ι M i) f = coe_fn (component R ι M i) g := sorry
@[simp] theorem lof_apply (R : Type u) [semiring R] {ι : Type v} [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) (b : M i) : coe_fn (coe_fn (lof R ι M i) b) i = b :=
dfinsupp.single_eq_same
@[simp] theorem component.lof_self (R : Type u) [semiring R] {ι : Type v} [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) (b : M i) : coe_fn (component R ι M i) (coe_fn (lof R ι M i) b) = b :=
lof_apply R i b
theorem component.of (R : Type u) [semiring R] {ι : Type v} [dec_ι : DecidableEq ι] {M : ι → Type w} [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) (j : ι) (b : M j) : coe_fn (component R ι M i) (coe_fn (lof R ι M j) b) =
dite (j = i) (fun (h : j = i) => eq.rec_on h b) fun (h : ¬j = i) => 0 :=
dfinsupp.single_apply
|
5d45930dee8121b64cf55fe32285b886bfe4d8d3 | 7a468d7c7c0949ab8b191bb62ff6d4d2af9f3917 | /test/P_implies_Q_fail.lean | c0d5cea96dcf72467dec5bb8fc02c0a89303d079 | [
"Apache-2.0"
] | permissive | seanpm2001/LeanProver_SMT2_Interface | c15b2fba021c406d965655b182eef54a14121b82 | 7ff0ce248b68ea4db2a2d4966a97b5786da05ed7 | refs/heads/master | 1,688,599,220,366 | 1,547,825,187,000 | 1,547,825,187,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 106 | lean | import smt2
import .test_tactics
example (P Q : Prop) : P -> Q :=
begin
intros,
must_fail z3
end
|
4e734c9c91d77f1fbdec7b55e8cefc3a74da799a | 947b78d97130d56365ae2ec264df196ce769371a | /tests/compiler/t4.lean | 1931e935ae37c183d7cc74fe6a39d2e55eed1456 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,394 | lean | /- Benchmark for new code generator -/
inductive Expr
| Val : Int → Expr
| Var : String → Expr
| Add : Expr → Expr → Expr
| Mul : Expr → Expr → Expr
| Pow : Expr → Expr → Expr
| Ln : Expr → Expr
open Expr
def Expr.toString : Expr → String
| Val n => toString n
| Var x => x
| Add f g => "(" ++ Expr.toString f ++ " + " ++ Expr.toString g ++ ")"
| Mul f g => "(" ++ Expr.toString f ++ " * " ++ Expr.toString g ++ ")"
| Pow f g => "(" ++ Expr.toString f ++ " ^ " ++ Expr.toString g ++ ")"
| Ln f => "ln(" ++ Expr.toString f ++ ")"
instance : HasToString Expr :=
⟨Expr.toString⟩
partial def pown : Int → Int → Int
| a, 0 => 1
| a, 1 => a
| a, n =>
let b := pown a (n / 2);
b * b * (if n % 2 = 0 then 1 else a)
partial def addAux : Expr → Expr → Expr
| Val n, Val m => Val (n + m)
| Val 0, f => f
| f, Val 0 => f
| f, Val n => addAux (Val n) f
| Val n, Add (Val m) f => addAux (Val (n+m)) f
| f, Add (Val n) g => addAux (Val n) (addAux f g)
| Add f g, h => addAux f (addAux g h)
| f, g => Add f g
def add (a b : Expr) : Expr :=
-- dbgTrace (">> add (" ++ toString a ++ ", " ++ toString b ++ ")") $ fun _ =>
addAux a b
-- set_option trace.compiler.borrowed_inference true
partial def mulAux : Expr → Expr → Expr
| Val n, Val m => Val (n*m)
| Val 0, _ => Val 0
| _, Val 0 => Val 0
| Val 1, f => f
| f, Val 1 => f
| f, Val n => mulAux (Val n) f
| Val n, Mul (Val m) f => mulAux (Val (n*m)) f
| f, Mul (Val n) g => mulAux (Val n) (mulAux f g)
| Mul f g, h => mulAux f (mulAux g h)
| f, g => Mul f g
def mul (a b : Expr) : Expr :=
-- dbgTrace (">> mul (" ++ toString a ++ ", " ++ toString b ++ ")") $ fun _ =>
mulAux a b
def pow : Expr → Expr → Expr
| Val m, Val n => Val (pown m n)
| _, Val 0 => Val 1
| f, Val 1 => f
| Val 0, _ => Val 0
| f, g => Pow f g
def ln : Expr → Expr
| Val 1 => Val 0
| f => Ln f
def d (x : String) : Expr → Expr
| Val _ => Val 0
| Var y => if x = y then Val 1 else Val 0
| Add f g => add (d f) (d g)
| Mul f g =>
-- dbgTrace (">> d (" ++ toString f ++ ", " ++ toString g ++ ")") $ fun _ =>
add (mul f (d g)) (mul g (d f))
| Pow f g => mul (pow f g) (add (mul (mul g (d f)) (pow f (Val (-1)))) (mul (ln f) (d g)))
| Ln f => mul (d f) (pow f (Val (-1)))
def count : Expr → Nat
| Val _ => 1
| Var _ => 1
| Add f g => count f + count g
| Mul f g => count f + count g
| Pow f g => count f + count g
| Ln f => count f
def nestAux (s : Nat) (f : Nat → Expr → IO Expr) : Nat → Expr → IO Expr
| 0, x => pure x
| m@(n+1), x => f (s - m) x >>= nestAux n
def nest (f : Nat → Expr → IO Expr) (n : Nat) (e : Expr) : IO Expr :=
nestAux n f n e
def deriv (i : Nat) (f : Expr) : IO Expr :=
do
let d := d "x" f;
IO.println (toString (i+1) ++ " count: " ++ (toString $ count d));
IO.println (toString d);
pure d
def main (xs : List String) : IO UInt32 :=
do let x := Var "x";
let f := add x (mul x (mul x (add x x)));
IO.println f;
_ ← nest deriv 3 f;
pure 0
-- setOption profiler True
-- #eval main []
|
4ffc96b914fd151499f4d56de930dd6c2fb71680 | cf39355caa609c0f33405126beee2739aa3cb77e | /library/init/meta/declaration.lean | 79881e2773ece93f0400acb48198cfbd0dce5a08 | [
"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 | 5,282 | 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 = tt`, 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
| abbrev
| regular (height : nat) (self_opt : bool)
/-- Reflect a C++ declaration object. The VM replaces it with the C++ implementation. -/
meta inductive declaration
/- definition-/
| defn (n : name) (univs : list name) (type : expr) (value : expr)
(red : reducibility_hints) (is_trusted : bool)
/- theorem (remark: theorems are always trusted) -/
| thm (n : name) (univs : list name) (type : expr) (value : task expr)
/- constant assumption -/
| cnst (n : name) (univs : list name) (type : expr) (is_trusted : bool)
/- axiom (remark: axioms are always trusted) -/
| ax (n : name) (univs : list name) (type : expr)
open declaration
meta def mk_definition (n : name) (ls : list name) (v : expr) (e : expr) : declaration :=
defn n ls v e (reducibility_hints.regular 1 tt) tt
namespace declaration
meta def to_name : declaration → name
| (defn n _ _ _ _ _) := n
| (thm n _ _ _) := n
| (cnst n _ _ _) := n
| (ax n _ _) := n
meta def univ_params : declaration → list name
| (defn _ ls _ _ _ _) := ls
| (thm _ ls _ _) := ls
| (cnst _ ls _ _) := ls
| (ax _ ls _) := ls
meta def type : declaration → expr
| (defn _ _ t _ _ _) := t
| (thm _ _ t _) := t
| (cnst _ _ t _) := t
| (ax _ _ t) := t
meta def value : declaration → expr
| (defn _ _ _ v _ _) := v
| (thm _ _ _ v) := v.get
| _ := default
meta def value_task : declaration → task expr
| (defn _ _ _ v _ _) := task.pure v
| (thm _ _ _ v) := v
| _ := task.pure default
meta def is_trusted : declaration → bool
| (defn _ _ _ _ _ t) := t
| (cnst _ _ _ t) := t
| _ := tt
meta def update_type : declaration → expr → declaration
| (defn n ls t v h tr) new_t := defn n ls new_t v h tr
| (thm n ls t v) new_t := thm n ls new_t v
| (cnst n ls t tr) new_t := cnst n ls new_t tr
| (ax n ls t) new_t := ax n ls new_t
meta def update_name : declaration → name → declaration
| (defn n ls t v h tr) new_n := defn new_n ls t v h tr
| (thm n ls t v) new_n := thm new_n ls t v
| (cnst n ls t tr) new_n := cnst new_n ls t tr
| (ax n ls t) new_n := ax new_n ls t
meta def update_value : declaration → expr → declaration
| (defn n ls t v h tr) new_v := defn n ls t new_v h tr
| (thm n ls t v) new_v := thm n ls t (task.pure new_v)
| d new_v := d
meta def update_value_task : declaration → task expr → declaration
| (defn n ls t v h tr) new_v := defn n ls t new_v.get h tr
| (thm n ls t v) new_v := thm n ls t new_v
| d new_v := d
meta def map_value : declaration → (expr → expr) → declaration
| (defn n ls t v h tr) f := defn n ls t (f v) h tr
| (thm n ls t v) f := thm n ls t (task.map f v)
| d f := d
meta def to_definition : declaration → declaration
| (cnst n ls t tr) := defn n ls t default reducibility_hints.abbrev tr
| (ax n ls t) := thm n ls t (task.pure default)
| d := d
meta def is_definition : declaration → bool
| (defn _ _ _ _ _ _) := tt
| _ := ff
/-- Instantiate a universe polymorphic declaration type with the given universes. -/
meta constant instantiate_type_univ_params : declaration → list level → option expr
/-- Instantiate a universe polymorphic declaration value with the given universes. -/
meta constant instantiate_value_univ_params : declaration → list level → option expr
end declaration
|
35acec0d60645c65f33e99c6966d7970e79414c1 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/data/sum.lean | 05ced3f728042e40aca9ec3e36b63cf4fae2da40 | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 4,094 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
More theorems about the sum type.
-/
import tactic.lint
universes u v
variables {α : Type u} {β : Type v}
open sum
attribute [derive decidable_eq] sum
@[simp] theorem sum.forall {p : α ⊕ β → Prop} : (∀ x, p x) ↔ (∀ a, p (inl a)) ∧ (∀ b, p (inr b)) :=
⟨λ h, ⟨λ a, h _, λ b, h _⟩, λ ⟨h₁, h₂⟩, sum.rec h₁ h₂⟩
@[simp] theorem sum.exists {p : α ⊕ β → Prop} : (∃ x, p x) ↔ (∃ a, p (inl a)) ∨ ∃ b, p (inr b) :=
⟨λ h, match h with
| ⟨inl a, h⟩ := or.inl ⟨a, h⟩
| ⟨inr b, h⟩ := or.inr ⟨b, h⟩
end, λ h, match h with
| or.inl ⟨a, h⟩ := ⟨inl a, h⟩
| or.inr ⟨b, h⟩ := ⟨inr b, h⟩
end⟩
namespace sum
protected def map {α α' β β'} (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β'
| (sum.inl x) := sum.inl (f x)
| (sum.inr x) := sum.inr (g x)
theorem inl.inj_iff {a b} : (inl a : α ⊕ β) = inl b ↔ a = b :=
⟨inl.inj, congr_arg _⟩
theorem inr.inj_iff {a b} : (inr a : α ⊕ β) = inr b ↔ a = b :=
⟨inr.inj, congr_arg _⟩
theorem inl_ne_inr {a : α} {b : β} : inl a ≠ inr b.
theorem inr_ne_inl {a : α} {b : β} : inr b ≠ inl a.
protected def elim {α β γ : Sort*} (f : α → γ) (g : β → γ) : α ⊕ β → γ := λ x, sum.rec_on x f g
@[simp] lemma elim_inl {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : α) :
sum.elim f g (inl x) = f x := rfl
@[simp] lemma elim_inr {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : β) :
sum.elim f g (inr x) = g x := rfl
lemma elim_injective {α β γ : Sort*} {f : α → γ} {g : β → γ}
(hf : function.injective f) (hg : function.injective g)
(hfg : ∀ a b, f a ≠ g b) : function.injective (sum.elim f g) :=
λ x y, sum.rec_on x
(sum.rec_on y (λ x y hxy, by rw hf hxy) (λ x y hxy, false.elim $ hfg _ _ hxy))
(sum.rec_on y (λ x y hxy, false.elim $ hfg x y hxy.symm) (λ x y hxy, by rw hg hxy))
section
variables (ra : α → α → Prop) (rb : β → β → Prop)
/-- Lexicographic order for sum. Sort all the `inl a` before the `inr b`,
otherwise use the respective order on `α` or `β`. -/
inductive lex : α ⊕ β → α ⊕ β → Prop
| inl {a₁ a₂} (h : ra a₁ a₂) : lex (inl a₁) (inl a₂)
| inr {b₁ b₂} (h : rb b₁ b₂) : lex (inr b₁) (inr b₂)
| sep (a b) : lex (inl a) (inr b)
variables {ra rb}
@[simp] theorem lex_inl_inl {a₁ a₂} : lex ra rb (inl a₁) (inl a₂) ↔ ra a₁ a₂ :=
⟨λ h, by cases h; assumption, lex.inl _⟩
@[simp] theorem lex_inr_inr {b₁ b₂} : lex ra rb (inr b₁) (inr b₂) ↔ rb b₁ b₂ :=
⟨λ h, by cases h; assumption, lex.inr _⟩
@[simp] theorem lex_inr_inl {b a} : ¬ lex ra rb (inr b) (inl a) :=
λ h, by cases h
attribute [simp] lex.sep
theorem lex_acc_inl {a} (aca : acc ra a) : acc (lex ra rb) (inl a) :=
begin
induction aca with a H IH,
constructor, intros y h,
cases h with a' _ h',
exact IH _ h'
end
theorem lex_acc_inr (aca : ∀ a, acc (lex ra rb) (inl a)) {b} (acb : acc rb b) : acc (lex ra rb) (inr b) :=
begin
induction acb with b H IH,
constructor, intros y h,
cases h with _ _ _ b' _ h' a,
{ exact IH _ h' },
{ exact aca _ }
end
theorem lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) :=
have aca : ∀ a, acc (lex ra rb) (inl a), from λ a, lex_acc_inl (ha.apply a),
⟨λ x, sum.rec_on x aca (λ b, lex_acc_inr aca (hb.apply b))⟩
end
/-- Swap the factors of a sum type -/
@[simp] def swap : α ⊕ β → β ⊕ α
| (inl a) := inr a
| (inr b) := inl b
@[simp] lemma swap_swap (x : α ⊕ β) : swap (swap x) = x :=
by cases x; refl
@[simp] lemma swap_swap_eq : swap ∘ swap = @id (α ⊕ β) :=
funext $ swap_swap
@[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap :=
swap_swap
@[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap :=
swap_swap
end sum
|
f73e3e89b18f5f2015fd8b455073218849c682bc | 4727251e0cd73359b15b664c3170e5d754078599 | /src/order/sup_indep.lean | e8c0829f3ea720e1ef11cb8b8409f3d7fba9d7de | [
"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 | 13,588 | lean | /-
Copyright (c) 2021 Aaron Anderson, Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Kevin Buzzard, Yaël Dillies, Eric Wieser
-/
import data.finset.pairwise
import data.set.finite
/-!
# Supremum independence
In this file, we define supremum independence of indexed sets. An indexed family `f : ι → α` is
sup-independent if, for all `a`, `f a` and the supremum of the rest are disjoint.
## Main definitions
* `finset.sup_indep s f`: a family of elements `f` are supremum independent on the finite set `s`.
* `complete_lattice.set_independent s`: a set of elements are supremum independent.
* `complete_lattice.independent f`: a family of elements are supremum independent.
## Main statements
* In a distributive lattice, supremum independence is equivalent to pairwise disjointness:
* `finset.sup_indep_iff_pairwise_disjoint`
* `complete_lattice.set_independent_iff_pairwise_disjoint`
* `complete_lattice.independent_iff_pairwise_disjoint`
* Otherwise, supremum independence is stronger than pairwise disjointness:
* `finset.sup_indep.pairwise_disjoint`
* `complete_lattice.set_independent.pairwise_disjoint`
* `complete_lattice.independent.pairwise_disjoint`
## Implementation notes
For the finite version, we avoid the "obvious" definition
`∀ i ∈ s, disjoint (f i) ((s.erase i).sup f)` because `erase` would require decidable equality on
`ι`.
-/
variables {α β ι ι' : Type*}
/-! ### On lattices with a bottom element, via `finset.sup` -/
namespace finset
section lattice
variables [lattice α] [order_bot α]
/-- Supremum independence of finite sets. We avoid the "obvious" definition using `s.erase i`
because `erase` would require decidable equality on `ι`. -/
def sup_indep (s : finset ι) (f : ι → α) : Prop :=
∀ ⦃t⦄, t ⊆ s → ∀ ⦃i⦄, i ∈ s → i ∉ t → disjoint (f i) (t.sup f)
variables {s t : finset ι} {f : ι → α} {i : ι}
instance [decidable_eq ι] [decidable_eq α] : decidable (sup_indep s f) :=
begin
apply @finset.decidable_forall_of_decidable_subsets _ _ _ _,
intros t ht,
apply @finset.decidable_dforall_finset _ _ _ _,
exact λ i hi, @implies.decidable _ _ _ (decidable_of_iff' (_ = ⊥) disjoint_iff),
end
lemma sup_indep.subset (ht : t.sup_indep f) (h : s ⊆ t) : s.sup_indep f :=
λ u hu i hi, ht (hu.trans h) (h hi)
lemma sup_indep_empty (f : ι → α) : (∅ : finset ι).sup_indep f := λ _ _ a ha, ha.elim
lemma sup_indep_singleton (i : ι) (f : ι → α) : ({i} : finset ι).sup_indep f :=
λ s hs j hji hj, begin
rw [eq_empty_of_ssubset_singleton ⟨hs, λ h, hj (h hji)⟩, sup_empty],
exact disjoint_bot_right,
end
lemma sup_indep.pairwise_disjoint (hs : s.sup_indep f) : (s : set ι).pairwise_disjoint f :=
λ a ha b hb hab, sup_singleton.subst $ hs (singleton_subset_iff.2 hb) ha $ not_mem_singleton.2 hab
/-- The RHS looks like the definition of `complete_lattice.independent`. -/
lemma sup_indep_iff_disjoint_erase [decidable_eq ι] :
s.sup_indep f ↔ ∀ i ∈ s, disjoint (f i) ((s.erase i).sup f) :=
⟨λ hs i hi, hs (erase_subset _ _) hi (not_mem_erase _ _), λ hs t ht i hi hit,
(hs i hi).mono_right (sup_mono $ λ j hj, mem_erase.2 ⟨ne_of_mem_of_not_mem hj hit, ht hj⟩)⟩
@[simp] lemma sup_indep_pair [decidable_eq ι] {i j : ι} (hij : i ≠ j) :
({i, j} : finset ι).sup_indep f ↔ disjoint (f i) (f j) :=
⟨λ h, h.pairwise_disjoint (by simp) (by simp) hij, λ h, begin
rw sup_indep_iff_disjoint_erase,
intros k hk,
rw [finset.mem_insert, finset.mem_singleton] at hk,
obtain rfl | rfl := hk,
{ convert h using 1,
rw [finset.erase_insert, finset.sup_singleton],
simpa using hij },
{ convert h.symm using 1,
have : ({i, k} : finset ι).erase k = {i},
{ ext,
rw [mem_erase, mem_insert, mem_singleton, mem_singleton, and_or_distrib_left,
ne.def, not_and_self, or_false, and_iff_right_of_imp],
rintro rfl,
exact hij },
rw [this, finset.sup_singleton] }
end⟩
lemma sup_indep_univ_bool (f : bool → α) :
(finset.univ : finset bool).sup_indep f ↔ disjoint (f ff) (f tt) :=
begin
have : tt ≠ ff := by simp only [ne.def, not_false_iff],
exact (sup_indep_pair this).trans disjoint.comm,
end
@[simp] lemma sup_indep_univ_fin_two (f : fin 2 → α) :
(finset.univ : finset (fin 2)).sup_indep f ↔ disjoint (f 0) (f 1) :=
begin
have : (0 : fin 2) ≠ 1 := by simp,
exact sup_indep_pair this,
end
lemma sup_indep.attach (hs : s.sup_indep f) : s.attach.sup_indep (f ∘ subtype.val) :=
begin
intros t ht i _ hi,
classical,
rw ←finset.sup_image,
refine hs (image_subset_iff.2 $ λ (j : {x // x ∈ s}) _, j.2) i.2 (λ hi', hi _),
rw mem_image at hi',
obtain ⟨j, hj, hji⟩ := hi',
rwa subtype.ext hji at hj,
end
end lattice
section distrib_lattice
variables [distrib_lattice α] [order_bot α] {s : finset ι} {f : ι → α}
lemma sup_indep_iff_pairwise_disjoint : s.sup_indep f ↔ (s : set ι).pairwise_disjoint f :=
⟨sup_indep.pairwise_disjoint, λ hs t ht i hi hit,
disjoint_sup_right.2 $ λ j hj, hs hi (ht hj) (ne_of_mem_of_not_mem hj hit).symm⟩
alias sup_indep_iff_pairwise_disjoint ↔ finset.sup_indep.pairwise_disjoint
set.pairwise_disjoint.sup_indep
/-- Bind operation for `sup_indep`. -/
lemma sup_indep.sup [decidable_eq ι] {s : finset ι'} {g : ι' → finset ι} {f : ι → α}
(hs : s.sup_indep (λ i, (g i).sup f)) (hg : ∀ i' ∈ s, (g i').sup_indep f) :
(s.sup g).sup_indep f :=
begin
simp_rw sup_indep_iff_pairwise_disjoint at ⊢ hs hg,
rw [sup_eq_bUnion, coe_bUnion],
exact hs.bUnion_finset hg,
end
/-- Bind operation for `sup_indep`. -/
lemma sup_indep.bUnion [decidable_eq ι] {s : finset ι'} {g : ι' → finset ι} {f : ι → α}
(hs : s.sup_indep (λ i, (g i).sup f)) (hg : ∀ i' ∈ s, (g i').sup_indep f) :
(s.bUnion g).sup_indep f :=
by { rw ←sup_eq_bUnion, exact hs.sup hg }
end distrib_lattice
end finset
/-! ### On complete lattices via `has_Sup.Sup` -/
namespace complete_lattice
variables [complete_lattice α]
open set
/-- An independent set of elements in a complete lattice is one in which every element is disjoint
from the `Sup` of the rest. -/
def set_independent (s : set α) : Prop := ∀ ⦃a⦄, a ∈ s → disjoint a (Sup (s \ {a}))
variables {s : set α} (hs : set_independent s)
@[simp]
lemma set_independent_empty : set_independent (∅ : set α) :=
λ x hx, (set.not_mem_empty x hx).elim
theorem set_independent.mono {t : set α} (hst : t ⊆ s) :
set_independent t :=
λ a ha, (hs (hst ha)).mono_right (Sup_le_Sup (diff_subset_diff_left hst))
/-- If the elements of a set are independent, then any pair within that set is disjoint. -/
lemma set_independent.pairwise_disjoint : s.pairwise_disjoint id :=
λ x hx y hy h, disjoint_Sup_right (hs hx) ((mem_diff y).mpr ⟨hy, h.symm⟩)
lemma set_independent_pair {a b : α} (hab : a ≠ b) :
set_independent ({a, b} : set α) ↔ disjoint a b :=
begin
split,
{ intro h,
exact h.pairwise_disjoint (mem_insert _ _) (mem_insert_of_mem _ (mem_singleton _)) hab, },
{ rintros h c ((rfl : c = a) | (rfl : c = b)),
{ convert h using 1,
simp [hab, Sup_singleton] },
{ convert h.symm using 1,
simp [hab, Sup_singleton] }, },
end
include hs
/-- If the elements of a set are independent, then any element is disjoint from the `Sup` of some
subset of the rest. -/
lemma set_independent.disjoint_Sup {x : α} {y : set α} (hx : x ∈ s) (hy : y ⊆ s) (hxy : x ∉ y) :
disjoint x (Sup y) :=
begin
have := (hs.mono $ insert_subset.mpr ⟨hx, hy⟩) (mem_insert x _),
rw [insert_diff_of_mem _ (mem_singleton _), diff_singleton_eq_self hxy] at this,
exact this,
end
omit hs
/-- An independent indexed family of elements in a complete lattice is one in which every element
is disjoint from the `supr` of the rest.
Example: an indexed family of non-zero elements in a
vector space is linearly independent iff the indexed family of subspaces they generate is
independent in this sense.
Example: an indexed family of submodules of a module is independent in this sense if
and only the natural map from the direct sum of the submodules to the module is injective. -/
def independent {ι : Sort*} {α : Type*} [complete_lattice α] (t : ι → α) : Prop :=
∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j)
lemma set_independent_iff {α : Type*} [complete_lattice α] (s : set α) :
set_independent s ↔ independent (coe : s → α) :=
begin
simp_rw [independent, set_independent, set_coe.forall, Sup_eq_supr],
refine forall₂_congr (λ a ha, _),
congr' 2,
convert supr_subtype.symm,
simp [supr_and],
end
variables {t : ι → α} (ht : independent t)
theorem independent_def : independent t ↔ ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) :=
iff.rfl
theorem independent_def' {ι : Type*} {t : ι → α} :
independent t ↔ ∀ i, disjoint (t i) (Sup (t '' {j | j ≠ i})) :=
by {simp_rw Sup_image, refl}
theorem independent_def'' {ι : Type*} {t : ι → α} :
independent t ↔ ∀ i, disjoint (t i) (Sup {a | ∃ j ≠ i, t j = a}) :=
by {rw independent_def', tidy}
@[simp]
lemma independent_empty (t : empty → α) : independent t.
@[simp]
lemma independent_pempty (t : pempty → α) : independent t.
/-- If the elements of a set are independent, then any pair within that set is disjoint. -/
lemma independent.pairwise_disjoint : pairwise (disjoint on t) :=
λ x y h, disjoint_Sup_right (ht x) ⟨y, supr_pos h.symm⟩
lemma independent.mono {ι : Type*} {α : Type*} [complete_lattice α]
{s t : ι → α} (hs : independent s) (hst : t ≤ s) :
independent t :=
λ i, (hs i).mono (hst i) $ supr₂_mono $ λ j _, hst j
/-- Composing an independent indexed family with an injective function on the index results in
another indepedendent indexed family. -/
lemma independent.comp {ι ι' : Sort*} {α : Type*} [complete_lattice α]
{s : ι → α} (hs : independent s) (f : ι' → ι) (hf : function.injective f) :
independent (s ∘ f) :=
λ i, (hs (f i)).mono_right $ begin
refine (supr_mono $ λ i, _).trans (supr_comp_le _ f),
exact supr_const_mono hf.ne,
end
lemma independent_pair {i j : ι} (hij : i ≠ j) (huniv : ∀ k, k = i ∨ k = j):
independent t ↔ disjoint (t i) (t j) :=
begin
split,
{ intro h,
exact h.pairwise_disjoint _ _ hij, },
{ rintros h k,
obtain rfl | rfl := huniv k,
{ refine h.mono_right (supr_le $ λ i, supr_le $ λ hi, eq.le _),
rw (huniv i).resolve_left hi },
{ refine h.symm.mono_right (supr_le $ λ j, supr_le $ λ hj, eq.le _),
rw (huniv j).resolve_right hj } },
end
/-- Composing an indepedent indexed family with an order isomorphism on the elements results in
another indepedendent indexed family. -/
lemma independent.map_order_iso {ι : Sort*} {α β : Type*}
[complete_lattice α] [complete_lattice β] (f : α ≃o β) {a : ι → α} (ha : independent a) :
independent (f ∘ a) :=
λ i, ((ha i).map_order_iso f).mono_right (f.monotone.le_map_supr₂ _)
@[simp] lemma independent_map_order_iso_iff {ι : Sort*} {α β : Type*}
[complete_lattice α] [complete_lattice β] (f : α ≃o β) {a : ι → α} :
independent (f ∘ a) ↔ independent a :=
⟨ λ h, have hf : f.symm ∘ f ∘ a = a := congr_arg (∘ a) f.left_inv.comp_eq_id,
hf ▸ h.map_order_iso f.symm,
λ h, h.map_order_iso f⟩
/-- If the elements of a set are independent, then any element is disjoint from the `supr` of some
subset of the rest. -/
lemma independent.disjoint_bsupr {ι : Type*} {α : Type*} [complete_lattice α]
{t : ι → α} (ht : independent t) {x : ι} {y : set ι} (hx : x ∉ y) :
disjoint (t x) (⨆ i ∈ y, t i) :=
disjoint.mono_right (bsupr_mono $ λ i hi, (ne_of_mem_of_not_mem hi hx : _)) (ht x)
end complete_lattice
lemma complete_lattice.independent_iff_sup_indep [complete_lattice α] {s : finset ι} {f : ι → α} :
complete_lattice.independent (f ∘ (coe : s → ι)) ↔ s.sup_indep f :=
begin
classical,
rw finset.sup_indep_iff_disjoint_erase,
refine subtype.forall.trans (forall₂_congr $ λ a b, _),
rw finset.sup_eq_supr,
congr' 2,
refine supr_subtype.trans _,
congr' 1 with x,
simp [supr_and, @supr_comm _ (x ∈ s)],
end
alias complete_lattice.independent_iff_sup_indep ↔ complete_lattice.independent.sup_indep
finset.sup_indep.independent
/-- A variant of `complete_lattice.independent_iff_sup_indep` for `fintype`s. -/
lemma complete_lattice.independent_iff_sup_indep_univ [complete_lattice α] [fintype ι] {f : ι → α} :
complete_lattice.independent f ↔ finset.univ.sup_indep f :=
begin
classical,
simp [finset.sup_indep_iff_disjoint_erase, complete_lattice.independent, finset.sup_eq_supr],
end
alias complete_lattice.independent_iff_sup_indep_univ ↔ complete_lattice.independent.sup_indep_univ
finset.sup_indep.independent_of_univ
section frame
namespace complete_lattice
variables [order.frame α]
lemma set_independent_iff_pairwise_disjoint {s : set α} :
set_independent s ↔ s.pairwise_disjoint id :=
⟨set_independent.pairwise_disjoint, λ hs i hi, disjoint_Sup_iff.2 $ λ j hj,
hs hi hj.1 $ ne.symm hj.2⟩
alias set_independent_iff_pairwise_disjoint ↔ _ set.pairwise_disjoint.set_independent
lemma independent_iff_pairwise_disjoint {f : ι → α} : independent f ↔ pairwise (disjoint on f) :=
⟨independent.pairwise_disjoint, λ hs i, disjoint_supr_iff.2 $ λ j, disjoint_supr_iff.2 $ λ hij,
hs _ _ hij.symm⟩
end complete_lattice
end frame
|
d950a57e8e16fefa5f873673552a8766cb2de6f7 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/geometry/euclidean/sphere.lean | f7bacb34d643c8b81134a22793ba4b1118eb5468 | [
"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,377 | lean | /-
Copyright (c) 2021 Manuel Candales. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Manuel Candales, Benjamin Davidson
-/
import geometry.euclidean.triangle
/-!
# Spheres
This file proves basic geometrical results about distances and angles
in spheres in real inner product spaces and Euclidean affine spaces.
## Main theorems
* `mul_dist_eq_mul_dist_of_cospherical_of_angle_eq_pi`: Intersecting Chords Theorem (Freek No. 55).
* `mul_dist_eq_mul_dist_of_cospherical_of_angle_eq_zero`: Intersecting Secants Theorem.
* `mul_dist_add_mul_dist_eq_mul_dist_of_cospherical`: Ptolemy’s Theorem (Freek No. 95).
TODO: The current statement of Ptolemy’s theorem works around the lack of a "cyclic polygon" concept
in mathlib, which is what the theorem statement would naturally use (or two such concepts, since
both a strict version, where all vertices must be distinct, and a weak version, where consecutive
vertices may be equal, would be useful; Ptolemy's theorem should then use the weak one).
An API needs to be built around that concept, which would include:
- strict cyclic implies weak cyclic,
- weak cyclic and consecutive points distinct implies strict cyclic,
- weak/strict cyclic implies weak/strict cyclic for any subsequence,
- any three points on a sphere are weakly or strictly cyclic according to whether they are distinct,
- any number of points on a sphere intersected with a two-dimensional affine subspace are cyclic in
some order,
- a list of points is cyclic if and only if its reversal is,
- a list of points is cyclic if and only if any cyclic permutation is, while other permutations
are not when the points are distinct,
- a point P where the diagonals of a cyclic polygon cross exists (and is unique) with weak/strict
betweenness depending on weak/strict cyclicity,
- four points on a sphere with such a point P are cyclic in the appropriate order,
and so on.
-/
open real
open_locale euclidean_geometry real_inner_product_space real
variables {V : Type*} [inner_product_space ℝ V]
namespace inner_product_geometry
/-!
### Geometrical results on spheres in real inner product spaces
This section develops some results on spheres in real inner product spaces,
which are used to deduce corresponding results for Euclidean affine spaces.
-/
lemma mul_norm_eq_abs_sub_sq_norm {x y z : V}
(h₁ : ∃ k : ℝ, k ≠ 1 ∧ x + y = k • (x - y)) (h₂ : ∥z - y∥ = ∥z + y∥) :
∥x - y∥ * ∥x + y∥ = |∥z + y∥ ^ 2 - ∥z - x∥ ^ 2| :=
begin
obtain ⟨k, hk_ne_one, hk⟩ := h₁,
let r := (k - 1)⁻¹ * (k + 1),
have hxy : x = r • y,
{ rw [← smul_smul, eq_inv_smul_iff₀ (sub_ne_zero.mpr hk_ne_one), ← sub_eq_zero],
calc (k - 1) • x - (k + 1) • y
= (k • x - x) - (k • y + y) : by simp_rw [sub_smul, add_smul, one_smul]
... = (k • x - k • y) - (x + y) : by simp_rw [← sub_sub, sub_right_comm]
... = k • (x - y) - (x + y) : by rw ← smul_sub k x y
... = 0 : sub_eq_zero.mpr hk.symm },
have hzy : ⟪z, y⟫ = 0,
by rwa [inner_eq_zero_iff_angle_eq_pi_div_two, ← norm_add_eq_norm_sub_iff_angle_eq_pi_div_two,
eq_comm],
have hzx : ⟪z, x⟫ = 0 := by rw [hxy, inner_smul_right, hzy, mul_zero],
calc ∥x - y∥ * ∥x + y∥
= ∥(r - 1) • y∥ * ∥(r + 1) • y∥ : by simp [sub_smul, add_smul, hxy]
... = ∥r - 1∥ * ∥y∥ * (∥r + 1∥ * ∥y∥) : by simp_rw [norm_smul]
... = ∥r - 1∥ * ∥r + 1∥ * ∥y∥ ^ 2 : by ring
... = |(r - 1) * (r + 1) * ∥y∥ ^ 2| : by simp [abs_mul, norm_eq_abs]
... = |r ^ 2 * ∥y∥ ^ 2 - ∥y∥ ^ 2| : by ring_nf
... = |∥x∥ ^ 2 - ∥y∥ ^ 2| : by simp [hxy, norm_smul, mul_pow, norm_eq_abs, sq_abs]
... = |∥z + y∥ ^ 2 - ∥z - x∥ ^ 2| : by simp [norm_add_sq_real, norm_sub_sq_real,
hzy, hzx, abs_sub_comm],
end
end inner_product_geometry
namespace euclidean_geometry
/-!
### Geometrical results on spheres in Euclidean affine spaces
This section develops some results on spheres in Euclidean affine spaces.
-/
open inner_product_geometry
variables {P : Type*} [metric_space P] [normed_add_torsor V P]
include V
/-- If `P` is a point on the line `AB` and `Q` is equidistant from `A` and `B`, then
`AP * BP = abs (BQ ^ 2 - PQ ^ 2)`. -/
lemma mul_dist_eq_abs_sub_sq_dist {a b p q : P}
(hp : ∃ k : ℝ, k ≠ 1 ∧ b -ᵥ p = k • (a -ᵥ p)) (hq : dist a q = dist b q) :
dist a p * dist b p = |dist b q ^ 2 - dist p q ^ 2| :=
begin
let m : P := midpoint ℝ a b,
obtain ⟨v, h1, h2, h3⟩ := ⟨vsub_sub_vsub_cancel_left, v a p m, v p q m, v a q m⟩,
have h : ∀ r, b -ᵥ r = (m -ᵥ r) + (m -ᵥ a) :=
λ r, by rw [midpoint_vsub_left, ← right_vsub_midpoint, add_comm, vsub_add_vsub_cancel],
iterate 4 { rw dist_eq_norm_vsub V },
rw [← h1, ← h2, h, h],
rw [← h1, h] at hp,
rw [dist_eq_norm_vsub V a q, dist_eq_norm_vsub V b q, ← h3, h] at hq,
exact mul_norm_eq_abs_sub_sq_norm hp hq,
end
/-- If `A`, `B`, `C`, `D` are cospherical and `P` is on both lines `AB` and `CD`, then
`AP * BP = CP * DP`. -/
lemma mul_dist_eq_mul_dist_of_cospherical {a b c d p : P}
(h : cospherical ({a, b, c, d} : set P))
(hapb : ∃ k₁ : ℝ, k₁ ≠ 1 ∧ b -ᵥ p = k₁ • (a -ᵥ p))
(hcpd : ∃ k₂ : ℝ, k₂ ≠ 1 ∧ d -ᵥ p = k₂ • (c -ᵥ p)) :
dist a p * dist b p = dist c p * dist d p :=
begin
obtain ⟨q, r, h'⟩ := (cospherical_def {a, b, c, d}).mp h,
obtain ⟨ha, hb, hc, hd⟩ := ⟨h' a _, h' b _, h' c _, h' d _⟩,
{ rw ← hd at hc,
rw ← hb at ha,
rw [mul_dist_eq_abs_sub_sq_dist hapb ha, hb, mul_dist_eq_abs_sub_sq_dist hcpd hc, hd] },
all_goals { simp },
end
/-- **Intersecting Chords Theorem**. -/
theorem mul_dist_eq_mul_dist_of_cospherical_of_angle_eq_pi {a b c d p : P}
(h : cospherical ({a, b, c, d} : set P))
(hapb : ∠ a p b = π) (hcpd : ∠ c p d = π) :
dist a p * dist b p = dist c p * dist d p :=
begin
obtain ⟨-, k₁, _, hab⟩ := angle_eq_pi_iff.mp hapb,
obtain ⟨-, k₂, _, hcd⟩ := angle_eq_pi_iff.mp hcpd,
exact mul_dist_eq_mul_dist_of_cospherical h ⟨k₁, (by linarith), hab⟩ ⟨k₂, (by linarith), hcd⟩,
end
/-- **Intersecting Secants Theorem**. -/
theorem mul_dist_eq_mul_dist_of_cospherical_of_angle_eq_zero {a b c d p : P}
(h : cospherical ({a, b, c, d} : set P))
(hab : a ≠ b) (hcd : c ≠ d) (hapb : ∠ a p b = 0) (hcpd : ∠ c p d = 0) :
dist a p * dist b p = dist c p * dist d p :=
begin
obtain ⟨-, k₁, -, hab₁⟩ := angle_eq_zero_iff.mp hapb,
obtain ⟨-, k₂, -, hcd₁⟩ := angle_eq_zero_iff.mp hcpd,
refine mul_dist_eq_mul_dist_of_cospherical h ⟨k₁, _, hab₁⟩ ⟨k₂, _, hcd₁⟩;
by_contra hnot;
simp only [not_not, *, one_smul] at *,
exacts [hab (vsub_left_cancel hab₁).symm, hcd (vsub_left_cancel hcd₁).symm],
end
/-- **Ptolemy’s Theorem**. -/
theorem mul_dist_add_mul_dist_eq_mul_dist_of_cospherical {a b c d p : P}
(h : cospherical ({a, b, c, d} : set P))
(hapc : ∠ a p c = π) (hbpd : ∠ b p d = π) :
dist a b * dist c d + dist b c * dist d a = dist a c * dist b d :=
begin
have h' : cospherical ({a, c, b, d} : set P), { rwa set.insert_comm c b {d} },
have hmul := mul_dist_eq_mul_dist_of_cospherical_of_angle_eq_pi h' hapc hbpd,
have hbp := left_dist_ne_zero_of_angle_eq_pi hbpd,
have h₁ : dist c d = dist c p / dist b p * dist a b,
{ rw [dist_mul_of_eq_angle_of_dist_mul b p a c p d, dist_comm a b],
{ rw [angle_eq_angle_of_angle_eq_pi_of_angle_eq_pi hbpd hapc, angle_comm] },
all_goals { field_simp [mul_comm, hmul] } },
have h₂ : dist d a = dist a p / dist b p * dist b c,
{ rw [dist_mul_of_eq_angle_of_dist_mul c p b d p a, dist_comm c b],
{ rwa [angle_comm, angle_eq_angle_of_angle_eq_pi_of_angle_eq_pi], rwa angle_comm },
all_goals { field_simp [mul_comm, hmul] } },
have h₃ : dist d p = dist a p * dist c p / dist b p, { field_simp [mul_comm, hmul] },
have h₄ : ∀ x y : ℝ, x * (y * x) = x * x * y := λ x y, by rw [mul_left_comm, mul_comm],
field_simp [h₁, h₂, dist_eq_add_dist_of_angle_eq_pi hbpd, h₃, hbp, dist_comm a b,
h₄, ← sq, dist_sq_mul_dist_add_dist_sq_mul_dist b, hapc],
end
end euclidean_geometry
|
ea55b4272f9d2153a2be12ff6850632360c681e6 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/analysis/convex/extrema.lean | 7259dcec73899f7df146605bb871f1625894b34a | [
"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,454 | lean | /-
Copyright (c) 2020 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis
-/
import analysis.calculus.local_extr
import topology.algebra.affine
/-!
# Minima and maxima of convex functions
We show that if a function `f : E → β` is convex, then a local minimum is also
a global minimum, and likewise for concave functions.
-/
variables {E β: Type*} [add_comm_group E] [topological_space E]
[module ℝ E] [topological_add_group E] [topological_vector_space ℝ E]
[decidable_linear_ordered_add_comm_group β] [ordered_semimodule ℝ β]
{s : set E}
open set filter
open_locale classical
/--
Helper lemma for the more general case: `is_min_on.of_is_local_min_on_of_convex_on`.
-/
lemma is_min_on.of_is_local_min_on_of_convex_on_Icc {f : ℝ → β} {a b : ℝ}
(a_lt_b : a < b) (h_local_min : is_local_min_on f (Icc a b) a) (h_conv : convex_on (Icc a b) f) :
∀ x ∈ Icc a b, f a ≤ f x :=
begin
by_contradiction H_cont,
push_neg at H_cont,
rcases H_cont with ⟨x, ⟨h_ax, h_xb⟩, fx_lt_fa⟩,
obtain ⟨z, hz, ge_on_nhd⟩ : ∃ z > a, ∀ y ∈ (Icc a z), f y ≥ f a,
{ rcases eventually_iff_exists_mem.mp h_local_min with ⟨U, U_in_nhds_within, fy_ge_fa⟩,
rw [nhds_within_Icc_eq_nhds_within_Ici a_lt_b, mem_nhds_within_Ici_iff_exists_Icc_subset]
at U_in_nhds_within,
rcases U_in_nhds_within with ⟨ε, ε_in_Ioi, Ioc_in_U⟩,
exact ⟨ε, mem_Ioi.mp ε_in_Ioi, λ y y_in_Ioc, fy_ge_fa y $ Ioc_in_U y_in_Ioc⟩ },
have a_lt_x : a < x := lt_of_le_of_ne h_ax (λ H, by subst H; exact lt_irrefl (f a) fx_lt_fa),
have lt_on_nhd : ∀ y ∈ Ioc a x, f y < f a,
{ intros y y_in_Ioc,
rcases (convex.mem_Ioc a_lt_x).mp y_in_Ioc with ⟨ya, yx, ya_pos, yx_pos, yax, y_combo⟩,
calc
f y = f (ya * a + yx * x) : by rw [y_combo]
... ≤ ya • f a + yx • f x
: h_conv.2 (left_mem_Icc.mpr (le_of_lt a_lt_b)) ⟨h_ax, h_xb⟩ (ya_pos)
(le_of_lt yx_pos) yax
... < ya • f a + yx • f a : add_lt_add_left (smul_lt_smul_of_pos fx_lt_fa yx_pos) (ya • f a)
... = f a : by rw [←add_smul, yax, one_smul] },
by_cases h_xz : x ≤ z,
{ exact not_lt_of_ge (ge_on_nhd x (show x ∈ Icc a z, by exact ⟨h_ax, h_xz⟩)) fx_lt_fa, },
{ have h₁ : z ∈ Ioc a x := ⟨hz, le_of_not_ge h_xz⟩,
have h₂ : z ∈ Icc a z := ⟨le_of_lt hz, le_refl z⟩,
exact not_lt_of_ge (ge_on_nhd z h₂) (lt_on_nhd z h₁) }
end
/--
A local minimum of a convex function is a global minimum, restricted to a set `s`.
-/
lemma is_min_on.of_is_local_min_on_of_convex_on {f : E → β} {a : E}
(a_in_s : a ∈ s) (h_localmin: is_local_min_on f s a) (h_conv : convex_on s f) :
∀ x ∈ s, f a ≤ f x :=
begin
by_contradiction H_cont,
push_neg at H_cont,
rcases H_cont with ⟨x, ⟨x_in_s, fx_lt_fa⟩⟩,
let g : affine_map ℝ ℝ E := affine_map.line_map a (x - a),
have hg0 : g 0 = a := affine_map.line_map_apply_zero a (x - a),
have hg1 : g 1 = x := by simp [affine_map.line_map_apply, one_smul],
have fg_local_min_on : is_local_min_on (f ∘ g) (g ⁻¹' s) 0,
{ rw ←hg0 at h_localmin,
refine is_local_min_on.comp_continuous_on h_localmin subset.rfl
(continuous.continuous_on (affine_map.line_map_continuous)) _,
simp [mem_preimage, hg0, a_in_s] },
have fg_min_on : ∀ x ∈ (Icc 0 1 : set ℝ), (f ∘ g) 0 ≤ (f ∘ g) x,
{ have Icc_in_s' : Icc 0 1 ⊆ (g ⁻¹' s),
{ have h0 : (0 : ℝ) ∈ (g ⁻¹' s) := by simp [mem_preimage, a_in_s],
have h1 : (1 : ℝ) ∈ (g ⁻¹' s) := by simp [mem_preimage, hg1, x_in_s],
rw ←segment_eq_Icc (show (0 : ℝ) ≤ 1, by linarith),
exact (convex.affine_preimage g h_conv.1).segment_subset
(by simp [mem_preimage, hg0, a_in_s]) (by simp [mem_preimage, hg1, x_in_s]) },
have fg_local_min_on' : is_local_min_on (f ∘ g) (Icc 0 1) 0 :=
is_local_min_on.on_subset fg_local_min_on Icc_in_s',
refine is_min_on.of_is_local_min_on_of_convex_on_Icc (by linarith) fg_local_min_on' _,
exact (convex_on.comp_affine_map g h_conv).subset Icc_in_s' (convex_Icc 0 1) },
have gx_lt_ga : (f ∘ g) 1 < (f ∘ g) 0 := by simp [hg1, fx_lt_fa, hg0],
exact not_lt_of_ge (fg_min_on 1 (mem_Icc.mpr ⟨zero_le_one, le_refl 1⟩)) gx_lt_ga,
end
/-- A local maximum of a concave function is a global maximum, restricted to a set `s`. -/
lemma is_max_on.of_is_local_max_on_of_concave_on {f : E → β} {a : E}
(a_in_s : a ∈ s) (h_localmax: is_local_max_on f s a) (h_conc : concave_on s f) :
∀ x ∈ s, f x ≤ f a :=
@is_min_on.of_is_local_min_on_of_convex_on _ (order_dual β) _ _ _ _ _ _ _ s f a a_in_s h_localmax h_conc
/-- A local minimum of a convex function is a global minimum. -/
lemma is_min_on.of_is_local_min_of_convex_univ {f : E → β} {a : E}
(h_local_min : is_local_min f a) (h_conv : convex_on univ f) : ∀ x, f a ≤ f x :=
λ x, (is_min_on.of_is_local_min_on_of_convex_on (mem_univ a)
(is_local_min.on h_local_min univ) h_conv) x (mem_univ x)
/-- A local maximum of a concave function is a global maximum. -/
lemma is_max_on.of_is_local_max_of_convex_univ {f : E → β} {a : E}
(h_local_max : is_local_max f a) (h_conc : concave_on univ f) : ∀ x, f x ≤ f a :=
@is_min_on.of_is_local_min_of_convex_univ _ (order_dual β) _ _ _ _ _ _ _ f a h_local_max h_conc
|
8f1a711966f639aed3def429ef813ef344771367 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/AuxDef.lean | bb8984e5233205eb700149775c09ba4218736a34 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,394 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Lean.Elab.Command
namespace Lean.Elab.Command
open Lean.Parser.Command
open Lean.Parser.Term
/--
Declares an auxiliary definition with an automatically generated name.
For example, `aux_def foo : Nat := 42` creates a definition
with an internal, unused name based on the suggestion `foo`.
-/
scoped syntax (name := aux_def) docComment ? attributes ? "aux_def" ident+ ":" term ":=" term : command
@[builtin_command_elab «aux_def»]
def elabAuxDef : CommandElab
| `($[$doc?:docComment]? $[$attrs?:attributes]? aux_def $suggestion* : $ty := $body) => do
let id := suggestion.map (·.getId.eraseMacroScopes) |>.foldl (· ++ ·) Name.anonymous
let id := `_aux ++ (← getMainModule) ++ `_ ++ id
let id := String.intercalate "_" <| id.components.map (·.toString (escape := false))
let ns ← getCurrNamespace
-- make sure we only add a single component so that scoped workes
let id ← mkAuxName (ns.mkStr id) 1
let id := id.replacePrefix ns Name.anonymous -- TODO: replace with def _root_.id
elabCommand <|
← `($[$doc?:docComment]? $[$attrs?:attributes]?
def $(mkIdentFrom (mkNullNode suggestion) id (canonical := true)):ident : $ty := $body)
| _ => throwUnsupportedSyntax
|
a35168f6ae843e7be07da3c36a211fc98171a6de | 1437b3495ef9020d5413178aa33c0a625f15f15f | /data/list/basic.lean | ca15f774c4a2891eb210e7fdfd371b25d4077a05 | [
"Apache-2.0"
] | permissive | jean002/mathlib | c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30 | dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd | refs/heads/master | 1,587,027,806,375 | 1,547,306,358,000 | 1,547,306,358,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 183,846 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
Basic properties of lists.
-/
import
tactic.interactive tactic.mk_iff_of_inductive_prop tactic.split_ifs
logic.basic logic.function logic.relation
algebra.group order.basic
data.list.defs data.nat.basic data.option.basic
data.bool data.prod data.sigma data.fin
open function nat
namespace list
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
instance : is_left_id (list α) has_append.append [] :=
⟨ nil_append ⟩
instance : is_right_id (list α) has_append.append [] :=
⟨ append_nil ⟩
instance : is_associative (list α) has_append.append :=
⟨ append_assoc ⟩
@[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ [].
theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → h₁ = h₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq)
theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → t₁ = t₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq)
theorem cons_inj {a : α} : injective (cons a) :=
assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe
@[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' :=
⟨λ e, cons_inj e, congr_arg _⟩
/- mem -/
theorem eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil
| [] := assume h, rfl
| (b :: l') := assume h, absurd (mem_cons_self b l') (h b)
theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _
theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b :=
assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, this)
(assume : a ∈ [], absurd this (not_mem_nil a))
@[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b :=
⟨eq_of_mem_singleton, or.inl⟩
theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(assume : a = b, begin subst a, exact binl end)
(assume : a ∈ l, this)
theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) :=
classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩
theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t :=
mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩
theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] :=
by intro e; rw e at h; cases h
theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] :=
⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩
theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l
| (b::l) _ := zero_lt_succ _
theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l
| (b::l) _ := ⟨b, mem_cons_self _ _⟩
theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l :=
⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩
theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] :=
⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩
theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t :=
begin
induction l with b l ih, {cases h}, rcases h with rfl | h,
{ exact ⟨[], l, rfl⟩ },
{ rcases ih h with ⟨s, t, rfl⟩,
exact ⟨b::s, t, rfl⟩ }
end
theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r)
theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l :=
assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2))
theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l :=
assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p)
theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l :=
begin
induction l with b l' ih,
{cases h},
{rcases h with rfl | h,
{exact or.inl rfl},
{exact or.inr (ih h)}}
end
theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b :=
begin
induction l with c l' ih,
{cases h},
{cases (eq_or_mem_of_mem_cons h) with h h,
{exact ⟨c, mem_cons_self _ _, h.symm⟩},
{rcases ih h with ⟨a, ha₁, ha₂⟩,
exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }}
end
@[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b :=
⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩
@[simp] theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} :
f a ∈ map f l ↔ a ∈ l :=
⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩
@[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l
| [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩
| (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left]
theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l :=
mem_join.1
theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L :=
mem_join.2 ⟨l, lL, al⟩
@[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a :=
iff.trans mem_join
⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩,
λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩
theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a :=
mem_bind.1
theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f :=
mem_bind.2 ⟨a, al, h⟩
lemma bind_map {g : α → list β} {f : β → γ} :
∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f)
| [] := rfl
| (a::l) := by simp only [cons_bind, map_append, bind_map l]
/- bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x.
@[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} :
(∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp only [or_imp_distrib, forall_and_distrib, forall_eq]
theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} :
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp only [mem_cons_iff, forall_mem_cons']
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α}
(h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x :=
(forall_mem_cons.1 h).2
theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a :=
by simp only [mem_singleton, forall_eq]
theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_append, or_imp_distrib, forall_and_distrib]
theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x.
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) :
∃ x ∈ a :: l, p x :=
bex.intro a (mem_cons_self _ _) h
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) :
∃ x ∈ a :: l, p x :=
bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px)
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) :
p a ∨ ∃ x ∈ l, p x :=
bex.elim h (λ x xal px,
or.elim (eq_or_mem_of_mem_cons xal)
(assume : x = a, begin rw ←this, left, exact px end)
(assume : x ∈ l, or.inr (bex.intro x this px)))
@[simp] theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
iff.intro or_exists_of_exists_mem_cons
(assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists)
/- list subset -/
theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl
theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_left _ _
theorem subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_right _ _
@[simp] theorem cons_subset {a : α} {l m : list α} :
a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m :=
by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq]
theorem cons_subset_of_subset_of_mem {a : α} {l m : list α}
(ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m :=
cons_subset.2 ⟨ainm, lsubm⟩
theorem app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _)
theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = []
| [] s := rfl
| (a::l) s := false.elim $ s $ mem_cons_self a l
theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l :=
show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩
theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ :=
λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩
/- append -/
lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl
theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t :=
by {induction s with b s H generalizing a, refl, simp only [foldl, cons_append], rw H _}
theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s :=
by {induction s with b s H generalizing a, refl, simp only [foldr, cons_append], rw H _}
@[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] :=
by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and]
@[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] :=
by rw [eq_comm, append_eq_nil]
lemma append_eq_cons_iff {a b c : list α} {x : α} :
a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true,
true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left']
lemma cons_eq_append_iff {a b c : list α} {x : α} :
(x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by rw [eq_comm, append_eq_cons_iff]
lemma append_eq_append_iff {a b c d : list α} :
a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) :=
begin
induction a generalizing c,
case nil { rw nil_append, split,
{ rintro rfl, left, exact ⟨_, rfl, rfl⟩ },
{ rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } },
case cons : a as ih {
cases c,
{ simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm },
{ simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } }
end
@[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l)
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop]
@[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs
-- TODO(Leo): cleanup proof after arith dec proc
theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂
| [] [] t₁ t₂ h hl := ⟨rfl, h⟩
| (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl
| [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm
| (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap,
let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in
by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩
theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ :=
(append_inj h hl).right
theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ :=
(append_inj h hl).left
theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ :=
append_inj h $ @nat.add_right_cancel _ (length t₁) _ $
let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap
theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ :=
(append_inj' h hl).right
theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ :=
(append_inj' h hl).left
theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ :=
append_inj_left h rfl
theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_right' h rfl
theorem append_left_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ :=
⟨append_left_cancel, congr_arg _⟩
theorem append_right_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ :=
⟨append_right_cancel, congr_arg _⟩
theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β}
(h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ :=
begin
have := h, rw [← take_append_drop (length s₁) l] at this ⊢,
rw map_append at this,
refine ⟨_, _, rfl, append_inj this _⟩,
rw [length_map, length_take, min_eq_left],
rw [← length_map f l, h, length_append],
apply nat.le_add_right
end
/- join -/
attribute [simp] join
theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = []
| [] := iff_of_true rfl (forall_mem_nil _)
| (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons]
@[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ :=
by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]]
/- repeat -/
@[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl
theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a
| (n+1) h := or.elim h id $ @eq_of_mem_repeat _
theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length
| [] H := rfl
| (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂;
unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂]
theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩
theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n :=
by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl
theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] :=
λ b h, mem_singleton.2 (eq_of_mem_repeat h)
@[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
by rw map_const at h; exact eq_of_mem_repeat h
@[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n :=
by induction n; [refl, simp only [*, repeat, map]]; split; refl
@[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred :=
by cases n; refl
@[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α :=
by induction n; [refl, simp only [*, repeat, join, append_nil]]
/- bind -/
@[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) :
l >>= f = l.bind f := rfl
@[simp] theorem bind_append {α β} (f : α → list β) (l₁ l₂ : list α) :
(l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f :=
append_bind _ _ _
/- concat -/
@[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl
@[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl
@[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] :=
by induction l; intro h; contradiction
@[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ :=
by induction l₁; simp only [*, cons_append, concat]; split; refl
@[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] :=
by induction l; simp only [*, concat]; split; refl
@[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) :=
by simp only [concat_eq_append, length_append, length]
theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a :=
by induction l₂ with b l₂ ih; simp only [concat_eq_append, nil_append, cons_append, append_assoc]
/- reverse -/
@[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl
local attribute [simp] reverse_core
@[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] :=
have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]),
by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]],
(aux l nil).symm
theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ :=
by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl
theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a :=
by simp only [reverse_cons, concat_eq_append]
@[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl
@[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) :=
by induction s; [rw [nil_append, reverse_nil, append_nil],
simp only [*, cons_append, reverse_cons, append_assoc]]
@[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l :=
by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl
theorem reverse_injective : injective (@reverse α) :=
injective_of_left_inverse reverse_reverse
@[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ :=
reverse_injective.eq_iff
@[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] :=
@reverse_inj _ l []
theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) :=
by simp only [concat_eq_append, reverse_cons, reverse_reverse]
@[simp] theorem length_reverse (l : list α) : length (reverse l) = length l :=
by induction l; [refl, simp only [*, reverse_cons, length_append, length]]
@[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) :=
by induction l; [refl, simp only [*, map, reverse_cons, map_append]]
theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) :
map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) :=
by simp only [reverse_core_eq, map_append, map_reverse]
@[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l :=
by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]]
@[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n :=
eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩
@[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*}
(l : list α) (H0 : C [])
(H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l :=
begin
rw ← reverse_reverse l,
induction reverse l,
{ exact H0 },
{ rw reverse_cons, exact H1 _ _ ih }
end
/- last -/
@[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ :=
by {induction l; intros, contradiction, reflexivity}
@[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a :=
by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]]
theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a :=
by simp only [concat_eq_append, last_append]
@[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl
@[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) :
last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl
theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
last l₁ h₁ = last l₂ h₂ :=
by subst l₁
/- head(') and tail -/
theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget :=
by cases l; refl
@[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl
@[simp] theorem tail_nil : tail (@nil α) = [] := rfl
@[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl
@[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s :=
by {induction s, contradiction, refl}
theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l :=
by {induction l, contradiction, refl}
/- map -/
lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l
| [] _ := rfl
| (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in
by rw [map, map, h₁, map_congr h₂]
theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) :=
by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl
theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l :=
by induction l; [refl, simp only [*, map]]; split; refl
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldl]]
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldr]]
theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α)
(h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l :=
by revert a; induction l; intros; [refl, simp only [*, foldl]]
theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α)
(h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l :=
by revert a; induction l; intros; [refl, simp only [*, foldr]]
theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil :=
eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl
@[simp] theorem map_join (f : α → β) (L : list (list α)) :
map f (join L) = join (map (map f) L) :=
by induction L; [refl, simp only [*, join, map, map_append]]
theorem bind_ret_eq_map {α β} (f : α → β) (l : list α) :
l.bind (list.ret ∘ f) = map f l :=
by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl
@[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) :
f <$> l = map f l := rfl
@[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) :=
by cases l; refl
/- map₂ -/
theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] :=
by cases l; refl
theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] :=
by cases l; refl
/- sublists -/
@[simp] theorem nil_sublist : Π (l : list α), [] <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons _ _ a (nil_sublist l)
@[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons2 _ _ a (sublist.refl l)
@[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ :=
sublist.rec_on h₂ (λ_ s, s)
(λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁))
(λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁
(λ_, nil_sublist _)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl)
l₁ h₁
@[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l :=
sublist.cons _ _ _ (sublist.refl l)
theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ :=
sublist.trans (sublist_cons a l₁)
theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ :=
sublist.cons2 _ _ _ s
@[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂
| [] l₂ := nil_sublist _
| (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂)
@[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂
| [] l₂ := sublist.refl _
| (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂)
theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ :=
sublist.cons _ _ _
theorem sublist_app_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ :=
s.trans $ sublist_append_left _ _
theorem sublist_app_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ :=
s.trans $ sublist_append_right _ _
theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂
| ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s
| ._ (sublist.cons2 ._ ._ a s) := s
theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ :=
⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩
@[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂
| [] := iff.rfl
| (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l)
theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l :=
begin
induction h with _ _ a _ ih _ _ a _ ih,
{ refl },
{ apply sublist_cons_of_sublist a ih },
{ apply cons_sublist_cons a ih }
end
theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l :=
begin
induction l₁ with b l₁ IH generalizing l,
{ cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } },
{ cases h with _ _ _ h _ _ _ h,
{ exact or.imp_left (sublist_cons_of_sublist _) (IH h) },
{ exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } }
end
theorem reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse :=
begin
induction h with _ _ _ _ ih _ _ a _ ih, {refl},
{ rw reverse_cons, exact sublist_app_of_sublist_left ih },
{ rw [reverse_cons, reverse_cons], exact append_sublist_append_of_sublist_right ih [a] }
end
@[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp only [reverse_reverse] at this; assumption, reverse_sublist⟩
@[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp only [reverse_append, append_sublist_append_left, reverse_sublist_iff] at this; assumption,
λ h, append_sublist_append_of_sublist_right h l⟩
theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂
| ._ ._ sublist.slnil b h := h
| ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h)
| ._ ._ (sublist.cons2 l₁ l₂ a s) b h :=
match eq_or_mem_of_mem_cons h with
| or.inl h := h ▸ mem_cons_self _ _
| or.inr h := mem_cons_of_mem _ (subset_of_sublist s h)
end
theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l :=
⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h,
let ⟨s, t, e⟩ := mem_split h in e.symm ▸
(cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩
theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil $ subset_of_sublist s
theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n :=
⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h,
λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩
theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂
| ._ ._ sublist.slnil h := rfl
| ._ ._ (sublist.cons l₁ l₂ a s) h :=
absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self
| ._ ._ (sublist.cons2 l₁ l₂ a s) h :=
by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h
theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h)
theorem sublist_antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂)
instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂)
| [] l₂ := is_true $ nil_sublist _
| (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h
| (a::l₁) (b::l₂) :=
if h : a = b then
decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $
by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩
else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂)
⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with
| a, l₁, sublist.cons ._ ._ ._ s', h := s'
| ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h
end⟩
/- index_of -/
section index_of
variable [decidable_eq α]
@[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl
theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl
theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 :=
assume e, if_pos e
@[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 :=
index_of_cons_eq _ rfl
@[simp] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) :=
assume n, if_neg n
theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l :=
begin
induction l with b l ih,
{ exact iff_of_true rfl (not_mem_nil _) },
simp only [length, mem_cons_iff, index_of_cons], split_ifs,
{ exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) },
{ simp only [h, false_or], rw ← ih, exact succ_inj' }
end
@[simp] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l :=
index_of_eq_length.2
theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l :=
begin
induction l with b l ih, {refl},
simp only [length, index_of_cons],
by_cases h : a = b, {rw if_pos h, exact nat.zero_le _},
rw if_neg h, exact succ_le_succ ih
end
theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l :=
⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al,
λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩
end index_of
/- nth element -/
theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a
| a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩
| a (b :: l) (or.inr m) :=
let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩
theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h)
| (a :: l) 0 h := rfl
| (a :: l) (n+1) h := @nth_le_nth l n _
theorem nth_ge_len : ∀ {l : list α} {n}, n ≥ length l → nth l n = none
| [] n h := rfl
| (a :: l) (n+1) h := nth_ge_len (le_of_succ_le_succ h)
theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a :=
⟨λ e,
have h : n < length l, from lt_of_not_ge $ λ hn,
by rw nth_ge_len hn at e; contradiction,
⟨h, by rw nth_le_nth h at e;
injection e with e; apply nth_le_mem⟩,
λ ⟨h, e⟩, e ▸ nth_le_nth _⟩
theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a :=
let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩
theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l
| (a :: l) 0 h := mem_cons_self _ _
| (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _)
theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l :=
let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _
theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a :=
⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩
theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a :=
mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm
@[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f
| [] n := rfl
| (a :: l) 0 := rfl
| (a :: l) (n+1) := nth_map l n
theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) :=
option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl
@[simp] theorem nth_le_map' (f : α → β) {l n} (H) :
nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) :=
nth_le_map f _ _
@[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) :
nth_le [a] n hn = a :=
have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn),
by subst hn0; refl
lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂),
(l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂
| [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim
| (a::l) _ 0 hn₁ hn₂ := rfl
| (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append];
exact nth_le_append _ _
@[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < n) :
(list.repeat a n).nth_le m (by rwa list.length_repeat) = a :=
eq_of_mem_repeat (nth_le_mem _ _ _)
lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) :
(l₁ ++ l₂).nth n = l₁.nth n :=
have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn
(by rw length_append; exact le_add_right _ _),
by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append]
@[simp] lemma nth_concat_length: ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = a
| [] a := rfl
| (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length]
@[extensionality]
theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂
| [] [] h := rfl
| (a::l₁) [] h := by have h0 := h 0; contradiction
| [] (a'::l₂) h := by have h0 := h 0; contradiction
| (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa;
simp only [aa, ext (λn, h (n+1))]; split; refl
theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ :=
ext $ λn, if h₁ : n < length l₁
then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])]
else let h₁ := le_of_not_gt h₁ in by rw [nth_ge_len h₁, nth_ge_len (by rwa [← hl])]
@[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a
| (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l]
@[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a :=
by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)]
theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2
| [] r i := λh1 h2, rfl
| (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact
λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2)
theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2),
nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2
| [] r i h1 h2 := absurd h2 (not_lt_zero _)
| (a :: l) r 0 h1 h2 := begin
have aux := nth_le_reverse_aux1 l (a :: r) 0,
rw zero_add at aux,
exact aux _ (zero_lt_succ _)
end
| (a :: l) r (i+1) h1 h2 := begin
have aux := nth_le_reverse_aux2 l (a :: r) i,
have heq := calc length (a :: l) - 1 - (i + 1)
= length l - (1 + i) : by rw add_comm; refl
... = length l - 1 - i : by rw nat.sub_sub,
rw [← heq] at aux,
apply aux
end
@[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) :
nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 :=
nth_le_reverse_aux2 _ _ _ _ _
lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) :
∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) =
l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l)
lemma modify_nth_tail_modify_nth_tail_le
{f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) :
(l.modify_nth_tail f n).modify_nth_tail g m =
l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n :=
begin
rcases le_iff_exists_add.1 h with ⟨m, rfl⟩,
rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail]
end
lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) :
(l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n :=
by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl
lemma modify_nth_tail_id :
∀n (l:list α), l.modify_nth_tail id n = l
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l)
theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _)
theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α),
update_nth l n a = modify_nth (λ _, a) n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _)
theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α),
modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := (congr_arg (cons b)
(modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl
theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m,
nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m
| n l 0 := by cases l; cases n; refl
| n [] (m+1) := by cases n; refl
| 0 (a::l) (m+1) := by cases nth l m; refl
| (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $
by cases nth l m with b; by_cases n = m;
simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ_inj, not_false_iff]
theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) :
∀ n l, length (modify_nth_tail f n l) = length l
| 0 l := H _
| (n+1) [] := rfl
| (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _)
@[simp] theorem modify_nth_length (f : α → α) :
∀ n l, length (modify_nth f n l) = length l :=
modify_nth_tail_length _ (λ l, by cases l; refl)
@[simp] theorem update_nth_length (l : list α) (n) (a : α) :
length (update_nth l n a) = length l :=
by simp only [update_nth_eq_modify_nth, modify_nth_length]
@[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) :
nth (modify_nth f n l) n = f <$> nth l n :=
by simp only [nth_modify_nth, if_pos]
@[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) :
nth (modify_nth f m l) n = nth l n :=
by simp only [nth_modify_nth, if_neg h, id_map']
theorem nth_update_nth_eq (a : α) (n) (l : list α) :
nth (update_nth l n a) n = (λ _, a) <$> nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq]
theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) :
nth (update_nth l n a) n = some a :=
by rw [nth_update_nth_eq, nth_le_nth h]; refl
theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) :
nth (update_nth l m a) n = nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h]
section insert_nth
variable {a : α}
@[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl
lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1
| 0 as h := rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h)
lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l :=
by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same];
from modify_nth_tail_id _ _
lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → m ≥ n →
insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n
| 0 0 [] has _ := (lt_irrefl _ has).elim
| 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth]
| 0 (m+1) (a::as) has hmn := rfl
| (n+1) (m+1) (a::as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n →
insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1)
| n 0 (a :: as) has hmn := rfl
| (n + 1) (m + 1) (a :: as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_comm (a b : α) :
∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l),
(l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a
| 0 j l := by simp [insert_nth]
| (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim
| (i + 1) (j+1) [] := by simp
| (i + 1) (j+1) (c::l) :=
assume h₀ h₁,
by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁)
end insert_nth
/- take, drop -/
@[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl
@[simp] theorem take_nil : ∀ n, take n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl
@[simp] theorem take_all : ∀ (l : list α), take (length l) l = l
| [] := rfl
| (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end
theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _))
| (n+1) [] h := rfl
| (n+1) (a::l) h :=
begin
change a :: take n l = a :: l,
rw [take_all_of_ge (le_of_succ_le_succ h)]
end
@[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁
| [] l₂ := rfl
| (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂)
theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take_left
theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l
| n 0 l := by rw [min_zero, take_zero, take_nil]
| 0 m l := by rw [zero_min, take_zero, take_zero]
| (succ n) (succ m) nil := by simp only [take_nil]
| (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl
@[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
@[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l
| [] := rfl
| (a :: l) := rfl
theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l)
| m 0 l := rfl
| m (n+1) [] := (drop_nil _).symm
| m (n+1) (a::l) := drop_add m n _
@[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂
| [] l₂ := rfl
| (a::l₁) l₂ := drop_left l₁ l₂
theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
drop n (l₁ ++ l₂) = l₂ :=
by rw ← h; apply drop_left
theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h,
drop n l = nth_le l n h :: drop (n+1) l
| 0 (a::l) h := rfl
| (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _
@[simp] lemma drop_all (l : list α) : l.drop l.length = [] :=
calc l.drop l.length = (l ++ []).drop l.length : by simp
... = [] : drop_left _ _
lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length →
(l₁ ++ l₂).drop n = l₁.drop n ++ l₂
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)]
lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ},
n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)]
@[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l
| m [] := by simp
| 0 l := by simp
| (m+1) (a::l) :=
calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl
... = drop (n + m) l : drop_drop m l
... = drop (n + (m + 1)) (a :: l) : rfl
theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α),
drop m (take (m + n) l) = take n (drop m l)
| 0 n _ := by simp
| (m+1) n nil := by simp
| (m+1) n (_::l) :=
have h: m + 1 + n = (m+n) + 1, by simp,
by simpa [take_cons, h] using drop_take m n l
theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) :
∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l)
| 0 l := rfl
| (n+1) [] := H.symm
| (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l)
theorem modify_nth_eq_take_drop (f : α → α) :
∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) :=
modify_nth_tail_eq_take_drop _ rfl
theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) :
modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l :=
by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl
theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) :
update_nth l n a = take n l ++ a :: drop (n+1) l :=
by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h]
@[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] :=
by cases l; cases n; simp only [update_nth]
section take'
variable [inhabited α]
@[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n
| 0 l := rfl
| (n+1) l := congr_arg succ (take'_length _ _)
@[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n
| 0 := rfl
| (n+1) := congr_arg (cons _) (take'_nil _)
theorem take'_eq_take : ∀ {n} {l : list α},
n ≤ length l → take' n l = take n l
| 0 l h := rfl
| (n+1) (a::l) h := congr_arg (cons _) $
take'_eq_take $ le_of_succ_le_succ h
@[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ :=
(take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _)
theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take' n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take'_left
end take'
/- foldl, foldr -/
lemma foldl_ext (f g : α → β → α) (a : α)
{l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) :
foldl f a l = foldl g a l :=
begin
induction l with hd tl ih generalizing a, {refl},
unfold foldl,
rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)]
end
lemma foldr_ext (f g : α → β → β) (b : β)
{l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) :
foldr f b l = foldr g b l :=
begin
induction l with hd tl ih, {refl},
simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H,
simp only [foldr, ih H.2, H.1]
end
@[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl
@[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) :
foldl f a (b::l) = foldl f (f a b) l := rfl
@[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
foldr f b (a::l) = f a (foldr f b l) := rfl
@[simp] theorem foldl_append (f : α → β → α) :
∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂
| a [] l₂ := rfl
| a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂]
@[simp] theorem foldr_append (f : α → β → β) :
∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁
| b [] l₂ := rfl
| b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂]
@[simp] theorem foldl_join (f : α → β → α) :
∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L
| a [] := rfl
| a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L]
@[simp] theorem foldr_join (f : α → β → β) :
∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L
| a [] := rfl
| a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons]
theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l :=
by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]]
theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l :=
let t := foldl_reverse (λx y, f y x) a (reverse l) in
by rw reverse_reverse l at t; rwa t
@[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l
| [] := rfl
| (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl
@[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l :=
by rw ←foldr_reverse; simp
/- scanr -/
@[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl
@[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α),
scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l)
| a [] := rfl
| a (x::l) := let t := scanr_aux_cons x l in
by simp only [scanr, scanr_aux, t, foldr_cons]
@[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
scanr f b (a::l) = foldr f b (a::l) :: scanr f b l :=
by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f)
include hassoc
theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l)
| a b nil := rfl
| a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc
include hcomm
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := hcomm a b
| a b (c::l) := by simp only [foldl_cons];
rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l)
end foldl_eq_foldr
section
variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
include ha
lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂)
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ :=
calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc]
... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons]
lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc]
include hc
lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) :=
by rw [foldl_cons, hc.comm, foldl_assoc]
end
/- mfoldl, mfoldr -/
section mfoldl_mfoldr
variables {m : Type v → Type w} [monad m]
@[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl
@[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl
@[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} :
mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl
@[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} :
mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl
variables [is_lawful_monad m]
@[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂},
mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂
| _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind]
| _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc]
@[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂},
mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁
| _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure]
| _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc]
end mfoldl_mfoldr
/- sum -/
attribute [to_additive list.sum] list.prod
attribute [to_additive list.sum.equations._eqn_1] list.prod.equations._eqn_1
section monoid
variables [monoid α] {l l₁ l₂ : list α} {a : α}
@[simp, to_additive list.sum_nil]
theorem prod_nil : ([] : list α).prod = 1 := rfl
@[simp, to_additive list.sum_cons]
theorem prod_cons : (a::l).prod = a * l.prod :=
calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one]
... = _ : foldl_assoc
@[simp, to_additive list.sum_append]
theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod :=
calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod]
... = l₁.prod * l₂.prod : foldl_assoc
@[simp, to_additive list.sum_join]
theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod :=
by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]]
end monoid
@[simp, to_additive list.sum_erase]
theorem prod_erase [decidable_eq α] [comm_monoid α] {a} :
Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod
| (b::l) h :=
begin
rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩,
{ simp only [list.erase, if_pos, prod_cons] },
{ simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] }
end
lemma dvd_prod [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod :=
let ⟨s, t, h⟩ := mem_split ha in
by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _
@[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n :=
by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]]
@[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) :=
by induction L; [refl, simp only [*, join, map, sum_cons, length_append]]
@[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) :=
by rw [list.bind, length_join, map_map]
/- lexicographic ordering -/
inductive lex (r : α → α → Prop) : list α → list α → Prop
| nil {} {a l} : lex [] (a :: l)
| cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂)
| rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂)
namespace lex
theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} :
lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ :=
⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h;
[exact h, exact (irrefl_of r a h).elim], lex.cons⟩
instance is_order_connected (r : α → α → Prop)
[is_order_connected α r] [is_trichotomous α r] :
is_order_connected (list α) (lex r) :=
⟨λ l₁, match l₁ with
| _, [], c::l₃, nil := or.inr nil
| _, [], c::l₃, rel _ := or.inr nil
| _, [], c::l₃, cons _ := or.inr nil
| _, b::l₂, c::l₃, nil := or.inl nil
| a::l₁, b::l₂, c::l₃, rel h :=
(is_order_connected.conn _ b _ h).imp rel rel
| a::l₁, b::l₂, _::l₃, cons h := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match _ l₂ _ h).imp cons cons },
{ exact or.inr (rel ab) }
end
end⟩
instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] :
is_trichotomous (list α) (lex r) :=
⟨λ l₁, match l₁ with
| [], [] := or.inr (or.inl rfl)
| [], b::l₂ := or.inl nil
| a::l₁, [] := or.inr (or.inr nil)
| a::l₁, b::l₂ := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match l₁ l₂).imp cons
(or.imp (congr_arg _) cons) },
{ exact or.inr (or.inr (rel ab)) }
end
end⟩
instance is_asymm (r : α → α → Prop)
[is_asymm α r] : is_asymm (list α) (lex r) :=
⟨λ l₁, match l₁ with
| a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂
| a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁
| a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂
| a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ :=
by exact _match _ _ h₁ h₂
end⟩
instance is_strict_total_order (r : α → α → Prop)
[is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) :=
{..is_strict_weak_order_of_is_order_connected}
instance decidable_rel [decidable_eq α] (r : α → α → Prop)
[decidable_rel r] : decidable_rel (lex r)
| l₁ [] := is_false $ λ h, by cases h
| [] (b::l₂) := is_true lex.nil
| (a::l₁) (b::l₂) := begin
haveI := decidable_rel l₁ l₂,
refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩,
{ rcases h with h | ⟨rfl, h⟩,
{ exact lex.rel h },
{ exact lex.cons h } },
{ rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩,
{ exact or.inr ⟨rfl, h⟩ },
{ exact or.inl h } }
end
theorem append_right (r : α → α → Prop) :
∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t)
| _ _ t nil := nil
| _ _ t (cons h) := cons (append_right _ h)
| _ _ t (rel r) := rel r
theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) :
∀ s, lex R (s ++ t₁) (s ++ t₂)
| [] := h
| (a::l) := cons (append_left l)
theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) :
∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂
| _ _ nil := nil
| _ _ (cons h) := cons (imp _ _ h)
| _ _ (rel r) := rel (H _ _ r)
theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂
| _ _ (cons h) e := to_ne h (list.cons.inj e).2
| _ _ (rel r) e := r (list.cons.inj e).1
theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) :
lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ :=
⟨to_ne, λ h, begin
induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂,
{ contradiction },
{ apply nil },
{ exact (not_lt_of_ge H).elim (succ_pos _) },
{ cases classical.em (a = b) with ab ab,
{ subst b, apply cons,
exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) },
{ exact rel ab } }
end⟩
end lex
--Note: this overrides an instance in core lean
instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩
theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l :=
lex.nil
instance [linear_order α] : linear_order (list α) :=
linear_order_of_STO' (lex (<))
--Note: this overrides an instance in core lean
instance has_le' [linear_order α] : has_le (list α) :=
preorder.to_has_le _
instance [decidable_linear_order α] : decidable_linear_order (list α) :=
decidable_linear_order_of_STO' (lex (<))
/- all & any -/
@[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl
@[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl
theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
simp only [all_cons, band_coe_iff, ih, forall_mem_cons]
end
theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p]
{l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a :=
by simp only [all_iff_forall, bool.of_to_bool_iff]
@[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl
@[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl
theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_false bool.not_ff (not_exists_mem_nil _) },
simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff]
end
theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p]
{l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a :=
by simp [any_iff_exists]
theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p :=
any_iff_exists.2 ⟨_, h₁, h₂⟩
@[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∀ x ∈ l, p x) :=
decidable_of_iff _ all_iff_forall_prop
instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∃ x ∈ l, p x) :=
decidable_of_iff _ any_iff_exists_prop
/- map for partial functions -/
/-- Partial map. If `f : Π a, p a → β` is a partial function defined on
`a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β
| [] H := []
| (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new list
with the same elements but in the type `{x // x ∈ l}`. -/
def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id)
theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) :
@pmap _ _ p (λ a _, f a) l H = map f l :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f l H₁ = pmap g l H₂ :=
by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]]
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) :=
by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl)
theorem attach_map_val (l : list α) : l.attach.map subtype.val = l :=
by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l)
@[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ :=
by have := mem_map.1 (by rw [attach_map_val]; exact h);
{ rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m }
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b :=
by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists]
@[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β}
{l H} : length (pmap f l H) = length l :=
by induction l; [refl, simp only [*, pmap, length]]
@[simp] lemma length_attach {α} (L : list α) : L.attach.length = L.length := length_pmap
/- find -/
section find
variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α}
@[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none :=
rfl
@[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a :=
if_pos h
@[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l :=
if_neg h
@[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x :=
begin
induction l with a l IH,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases h : p a,
{ simp only [find_cons_of_pos _ h, h, not_true, false_and] },
{ rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] }
end
@[simp] theorem find_some (H : find p l = some a) : p a :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, exact h },
{ rw find_cons_of_neg _ h at H, exact IH H }
end
@[simp] theorem find_mem (H : find p l = some a) : a ∈ l :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self },
{ rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) }
end
end find
/- lookmap -/
section lookmap
variables (f : α → option α)
@[simp] theorem lookmap_nil : [].lookmap f = [] := rfl
@[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) :
(a :: l).lookmap f = a :: l.lookmap f :=
by simp [lookmap, h]
@[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) :
(a :: l).lookmap f = b :: l :=
by simp [lookmap, h]
theorem lookmap_some : ∀ l : list α, l.lookmap some = l
| [] := rfl
| (a::l) := rfl
theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l
| [] := rfl
| (a::l) := congr_arg (cons a) (lookmap_none l)
theorem lookmap_congr {f g : α → option α} :
∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g
| [] H := rfl
| (a::l) H := begin
cases forall_mem_cons.1 H with H₁ H₂,
cases h : g a with b,
{ simp [h, H₁.trans h, lookmap_congr H₂] },
{ simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] }
end
theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l :=
(lookmap_congr H).trans (lookmap_none l)
theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) :
∀ l : list α, map g (l.lookmap f) = map g l
| [] := rfl
| (a::l) := begin
cases h' : f a with b,
{ simp [h', lookmap_map_eq] },
{ simp [lookmap_cons_some _ _ h', h _ _ h'] }
end
theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l :=
by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h
theorem length_lookmap (l : list α) : length (l.lookmap f) = length l :=
by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp
end lookmap
/- filter_map -/
@[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) :
filter_map f (a :: l) = filter_map f l :=
by simp only [filter_map, h]
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (l : list α) {b : β} (h : f a = some b) :
filter_map f (a :: l) = b :: filter_map f l :=
by simp only [filter_map, h]; split; refl
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
begin
funext l,
induction l with a l IH, {refl},
simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl
end
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
begin
funext l,
induction l with a l IH, {refl},
by_cases pa : p a,
{ simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl },
{ simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] }
end
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) :
filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l :=
begin
induction l with a l IH, {refl},
cases h : f a with b,
{ rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH],
simp only [h, option.none_bind'] },
rw filter_map_cons_some _ _ _ h,
cases h' : g b with c;
[ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH],
rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ];
simp only [h, h', option.some_bind']
end
theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) :
map g (filter_map f l) = filter_map (λ x, (f x).map g) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) :
filter_map g (map f l) = filter_map (g ∘ f) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) :
filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l :=
by rw [← filter_map_eq_filter, filter_map_filter_map]; refl
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) :
filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l :=
begin
rw [← filter_map_eq_filter, filter_map_filter_map], congr,
funext x,
show (option.guard p x).bind f = ite (p x) (f x) none,
by_cases h : p x,
{ simp only [option.guard, if_pos h, option.some_bind'] },
{ simp only [option.guard, if_neg h, option.none_bind'] }
end
@[simp] theorem filter_map_some (l : list α) : filter_map some l = l :=
by rw filter_map_eq_map; apply map_id
@[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} :
b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b :=
begin
induction l with a l IH,
{ split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } },
cases h : f a with b',
{ have : f a ≠ some b, {rw h, intro, contradiction},
simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] },
{ have : f a = some b ↔ b = b',
{ split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} },
simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, this, exists_eq_left] }
end
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (l : list α) :
map g (filter_map f l) = l :=
by simp only [map_filter_map, H, filter_map_some]
theorem filter_map_sublist_filter_map (f : α → option β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ :=
by induction s with l₁ l₂ a s IH l₁ l₂ a s IH;
simp only [filter_map]; cases f a with b;
simp only [filter_map, IH, sublist.cons, sublist.cons2]
theorem map_sublist_map (f : α → β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : map f l₁ <+ map f l₂ :=
by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s
/- filter -/
section filter
variables {p : α → Prop} [decidable_pred p]
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
: ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l
| [] _ := rfl
| (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a;
[simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2],
simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl
@[simp] theorem filter_subset (l : list α) : filter p l ⊆ l :=
subset_of_sublist $ filter_sublist l
theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a
| (b::l) ain :=
if pb : p b then
have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, begin rw [← this] at pb, exact pb end)
(assume : a ∈ filter p l, of_mem_filter this)
else
begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end
theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l :=
filter_subset l h
theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l
| (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self
| (b::l) (or.inr ain) pa := if pb : p b
then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa
else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa
@[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a :=
⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩
theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases p a,
{ rw [filter_cons_of_pos _ h, cons_inj', ih, and_iff_right h] },
{ rw [filter_cons_of_neg _ h],
refine iff_of_false _ (mt and.left h), intro e,
have := filter_sublist l, rw e at this,
exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) }
end
theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a :=
by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and]
theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s
theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) :=
by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl
@[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l,
filter p (filter q l) = filter (λ a, p a ∧ q a) l
| [] := rfl
| (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false,
true_and, false_and, filter_filter l, eq_self_iff_true]
@[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l)
| [] := rfl
| (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while]
else by simp only [span, take_while, drop_while, if_neg pa]
@[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l
| [] := rfl
| (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l]
else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append]
@[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 :=
if_pos pa
@[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l :=
if_neg pa
theorem countp_eq_length_filter (l) : countp p l = length (filter p l) :=
by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h],
simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl
local attribute [simp] countp_eq_length_filter
@[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ :=
by simp only [countp_eq_length_filter, filter_append, length_append]
theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a :=
by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop]
theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ :=
by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s)
@[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) :
countp p (filter q l) = countp (λ a, p a ∧ q a) l :=
by simp only [countp_eq_length_filter, filter_filter]
end filter
/- count -/
section count
variable [decidable_eq α]
@[simp] theorem count_nil (a : α) : count a [] = 0 := rfl
theorem count_cons (a b : α) (l : list α) :
count a (b :: l) = if a = b then succ (count a l) else count a l := rfl
theorem count_cons' (a b : α) (l : list α) :
count a (b :: l) = count a l + (if a = b then 1 else 0) :=
begin rw count_cons, split_ifs; refl end
@[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) :=
if_pos rfl
@[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l :=
if_neg h
theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ :=
countp_le_of_sublist
theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) :=
count_le_of_sublist _ (sublist_cons _ _)
theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl
@[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ :=
countp_append
@[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) :=
by rw [concat_eq_append, count_append, count_singleton]
theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l :=
by simp only [count, countp_pos, exists_prop, exists_eq_right']
@[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l :=
λ h', ne_of_gt (count_pos.2 h') h
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat];
exact λ b m, (eq_of_mem_repeat m).symm
theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l :=
⟨λ h, ((repeat_sublist_repeat a).2 h).trans $
have filter (eq a) l = repeat a (count a l), from eq_repeat.2
⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩,
by rw ← this; apply filter_sublist,
λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {l : list α} (h : p a) : count a (filter p l) = count a l :=
by simp only [count, countp_filter]; congr; exact
set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h))
end count
/- prefix, suffix, infix -/
@[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩
@[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩
@[simp] theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩
theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩
theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩
@[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩
@[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩
@[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a]
@[simp] theorem prefix_concat (a : α) (l) : l <+: concat l a :=
by simp only [concat_eq_append, prefix_append]
theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨[], t, h⟩
theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩
@[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l
theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l
theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ :=
λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩
@[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃
| l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩
@[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃
| l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩
@[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃
| l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩
theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ :=
λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _)
theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_prefix
theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_suffix
theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ :=
⟨λ ⟨r, e⟩, ⟨reverse r,
by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩,
λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩
theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ :=
by rw ← reverse_suffix; simp only [reverse_reverse]
theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ :=
length_le_of_sublist $ sublist_of_infix s
theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] :=
eq_nil_of_sublist_nil $ sublist_of_infix s
theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_prefix s
theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_suffix s
theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=
⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,
λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩
theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_infix s
theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_prefix s
theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_suffix s
theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α},
l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂
| [] l₂ l₃ h₁ h₂ _ := nil_prefix _
| (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin
injection e with _ e', subst b,
rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩
(le_of_succ_le_succ ll) with ⟨r₃, rfl⟩,
exact ⟨r₃, rfl⟩
end
theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=
(le_total (length l₁) (length l₂)).imp
(prefix_of_prefix_length_le h₁ h₂)
(prefix_of_prefix_length_le h₂ h₁)
theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ :=
reverse_prefix.1 $ prefix_of_prefix_length_le
(reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll])
theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=
(prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp
reverse_prefix.1 reverse_prefix.1
theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L
| (_ :: L) l (or.inl rfl) := infix_append [] _ _
| (l' :: L) l (or.inr h) :=
is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _
theorem prefix_append_left_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=
exists_congr $ λ r, by rw [append_assoc, append_left_inj]
theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=
prefix_append_left_inj [a]
theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩
theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩
theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=
⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩
theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=
⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩
theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=
⟨λ h, append_right_cancel $
(prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ take_prefix _ _⟩
theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=
⟨λ h, append_left_cancel $
(suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ drop_suffix _ _⟩
instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂)
| [] l₂ := is_true ⟨l₂, rfl⟩
| (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te
| (a::l₁) (b::l₂) :=
if h : a = b then
@decidable_of_iff _ _ (by rw [← h, prefix_cons_inj])
(decidable_prefix l₁ l₂)
else
is_false $ λ ⟨t, te⟩, h $ by injection te
-- Alternatively, use mem_tails
instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂)
| [] l₂ := is_true ⟨l₂, append_nil _⟩
| (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial
| l₁ l₂ := let len1 := length l₁, len2 := length l₂ in
if hl : len1 ≤ len2 then
decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop
else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h
@[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t
| s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton],
⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩
| s (a::t) :=
suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa,
⟨λo, match s, o with
| ._, or.inl rfl := ⟨_, rfl⟩
| s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in
by rw [← hs, ← ht]; exact ⟨s, rfl⟩
end, λmi, match s, mi with
| [], ⟨._, rfl⟩ := or.inl rfl
| (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $
by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩
end⟩
@[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t
| s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩
| s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from
⟨λo, match s, t, o with
| ._, t, or.inl rfl := suffix_refl _
| s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩
end, λe, match s, t, e with
| ._, t, ⟨[], rfl⟩ := or.inl rfl
| s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩)
end⟩
instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂)
| [] l₂ := is_true ⟨[], l₂, rfl⟩
| (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $
append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h
| l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $
by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm;
exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩
/- sublists -/
@[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl
@[simp] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl
theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) :
map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) :
sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_eq_sublists' (l f r) :
@sublists'_aux α β l f r = map f (sublists' l) ++ r :=
by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl
@[simp] theorem sublists'_cons (a : α) (l : list α) :
sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) :=
by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl
@[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t :=
begin
induction t with a t IH generalizing s,
{ simp only [sublists'_nil, mem_singleton],
exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ },
simp only [sublists'_cons, mem_append, IH, mem_map],
split; intro h, rcases h with h | ⟨s, h, rfl⟩,
{ exact sublist_cons_of_sublist _ h },
{ exact cons_sublist_cons _ h },
{ cases h with _ _ _ h s _ _ h,
{ exact or.inl h },
{ exact or.inr ⟨s, h, rfl⟩ } }
end
@[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l
| [] := rfl
| (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map,
length, pow_succ, mul_succ, mul_zero, zero_add]
@[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl
@[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl
theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β),
sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r)
| [] f := rfl
| (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc]
theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) :
sublists_aux l cons = sublists_aux₁ l (λ x, [x]) :=
by rw [sublists_aux₁_eq_sublists_aux]; refl
theorem sublists_aux_eq_foldr.aux {a : α} {l : list α}
(IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons))
(IH₂ : ∀ (f : list α → list (list α) → list (list α)),
sublists_aux l f = foldr f [] (sublists_aux l cons))
(f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) :=
begin
simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1,
induction sublists_aux l cons with _ _ ih, {refl},
simp only [ih, foldr_cons]
end
theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β),
sublists_aux l f = foldr f [] (sublists_aux l cons) :=
suffices _ ∧ ∀ f : list α → list (list α) → list (list α),
sublists_aux l f = foldr f [] (sublists_aux l cons),
from this.1,
begin
induction l with a l IH, {split; intro; refl},
exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2,
sublists_aux_eq_foldr.aux IH.2 IH.2⟩
end
theorem sublists_aux_cons_cons (l : list α) (a : α) :
sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) :=
by rw [← sublists_aux_eq_foldr]; refl
theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β),
sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++
sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x)))
| [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil]
| (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl
theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) :
sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++
f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) :=
by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil]
theorem sublists_aux₁_bind : ∀ (l : list α)
(f : list α → list β) (g : β → list γ),
(sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g)
| [] f g := rfl
| (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l]
theorem sublists_aux_cons_append (l₁ l₂ : list α) :
sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++
(do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) :=
begin
simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind],
congr, funext x, apply congr_arg _,
rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm
end
theorem sublists_append (l₁ l₂ : list α) :
sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) :=
by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind,
cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl
@[simp] theorem sublists_concat (l : list α) (a : α) :
sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) :=
by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind,
map_eq_map, map_eq_map, map_id' (append_nil), append_nil]
theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) :=
by induction l with hd tl ih; [refl,
simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton,
map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]]
theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) :=
by rw [← sublists_reverse, reverse_reverse]
theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) :=
by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)]
theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) :=
by rw [← sublists'_reverse, reverse_reverse]
theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons
| [] := id
| (a::l) := begin
rw [sublists_aux_cons_cons],
refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _,
have := sublists_aux_ne_nil l, revert this,
induction sublists_aux l cons; intro, {rwa foldr},
simp only [foldr, mem_cons_iff, false_or, not_or_distrib],
exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩
end
@[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t :=
by rw [← reverse_sublist_iff, ← mem_sublists',
sublists'_reverse, mem_map_of_inj reverse_injective]
@[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l :=
by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse]
theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l :=
reverse_rec_on l (nil_sublist _) $
λ l a IH, by simp only [map, map_append, sublists_concat]; exact
((append_sublist_append_left _).2 $ singleton_sublist.2 $
mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans
((append_sublist_append_right _).2 IH)
/- forall₂ -/
section forall₂
variables {r : α → β → Prop} {p : γ → δ → Prop}
open relator relation
run_cmd tactic.mk_iff_of_inductive_prop `list.forall₂ `list.forall₂_iff
@[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} :
forall₂ R (a::l₁) (b::l₂) ↔ R a b ∧ forall₂ R l₁ l₂ :=
⟨λ h, by cases h with h₁ h₂; split; assumption, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩
theorem forall₂.imp {R S : α → β → Prop}
(H : ∀ a b, R a b → S a b) {l₁ l₂}
(h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ :=
by induction h; constructor; solve_by_elim
lemma forall₂.mp {r q s : α → β → Prop} (h : ∀a b, r a b → q a b → s a b) :
∀{l₁ l₂}, forall₂ r l₁ l₂ → forall₂ q l₁ l₂ → forall₂ s l₁ l₂
| [] [] forall₂.nil forall₂.nil := forall₂.nil
| (a::l₁) (b::l₂) (forall₂.cons hr hrs) (forall₂.cons hq hqs) :=
forall₂.cons (h a b hr hq) (forall₂.mp hrs hqs)
lemma forall₂.flip : ∀{a b}, forall₂ (flip r) b a → forall₂ r a b
| _ _ forall₂.nil := forall₂.nil
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ h₂.flip
lemma forall₂_same {r : α → α → Prop} : ∀{l}, (∀x∈l, r x x) → forall₂ r l l
| [] _ := forall₂.nil
| (a::as) h := forall₂.cons
(h _ (mem_cons_self _ _))
(forall₂_same $ assume a ha, h a $ mem_cons_of_mem _ ha)
lemma forall₂_refl {r} [is_refl α r] (l : list α) : forall₂ r l l :=
forall₂_same $ assume a h, is_refl.refl _ _
lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) :=
begin
funext a b, apply propext,
split,
{ assume h, induction h, {refl}, simp only [*]; split; refl },
{ assume h, subst h, exact forall₂_refl _ }
end
@[simp] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil :=
⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩
@[simp] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil :=
⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩
lemma forall₂_cons_left_iff {a l u} : forall₂ r (a::l) u ↔ (∃b u', r a b ∧ forall₂ r l u' ∧ u = b :: u') :=
iff.intro
(assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end)
(assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end)
lemma forall₂_cons_right_iff {b l u} :
forall₂ r u (b::l) ↔ (∃a u', r a b ∧ forall₂ r u' l ∧ u = a :: u') :=
iff.intro
(assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end)
(assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end)
lemma forall₂_and_left {r : α → β → Prop} {p : α → Prop} :
∀l u, forall₂ (λa b, p a ∧ r a b) l u ↔ (∀a∈l, p a) ∧ forall₂ r l u
| [] u := by simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _), imp_true_iff, true_and]
| (a::l) u := by simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons,
and_assoc, and_comm, and.left_comm, exists_and_distrib_left.symm]
@[simp] lemma forall₂_map_left_iff {f : γ → α} :
∀{l u}, forall₂ r (map f l) u ↔ forall₂ (λc b, r (f c) b) l u
| [] _ := by simp only [map, forall₂_nil_left_iff]
| (a::l) _ := by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff]
@[simp] lemma forall₂_map_right_iff {f : γ → β} :
∀{l u}, forall₂ r l (map f u) ↔ forall₂ (λa c, r a (f c)) l u
| _ [] := by simp only [map, forall₂_nil_right_iff]
| _ (b::u) := by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff]
lemma left_unique_forall₂ (hr : left_unique r) : left_unique (forall₂ r)
| a₀ nil a₁ forall₂.nil forall₂.nil := rfl
| (a₀::l₀) (b::l) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) :=
hr ha₀ ha₁ ▸ left_unique_forall₂ h₀ h₁ ▸ rfl
lemma right_unique_forall₂ (hr : right_unique r) : right_unique (forall₂ r)
| nil a₀ a₁ forall₂.nil forall₂.nil := rfl
| (b::l) (a₀::l₀) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) :=
hr ha₀ ha₁ ▸ right_unique_forall₂ h₀ h₁ ▸ rfl
lemma bi_unique_forall₂ (hr : bi_unique r) : bi_unique (forall₂ r) :=
⟨assume a b c, left_unique_forall₂ hr.1, assume a b c, right_unique_forall₂ hr.2⟩
theorem forall₂_length_eq {R : α → β → Prop} :
∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂
| _ _ forall₂.nil := rfl
| _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂_length_eq h₂)
theorem forall₂_zip {R : α → β → Prop} :
∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b
| _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁
| _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃
theorem forall₂_iff_zip {R : α → β → Prop} {l₁ l₂} : forall₂ R l₁ l₂ ↔
length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b :=
⟨λ h, ⟨forall₂_length_eq h, @forall₂_zip _ _ _ _ _ h⟩,
λ h, begin
cases h with h₁ h₂,
induction l₁ with a l₁ IH generalizing l₂,
{ cases length_eq_zero.1 h₁.symm, constructor },
{ cases l₂ with b l₂; injection h₁ with h₁,
exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) }
end⟩
theorem forall₂_take {R : α → β → Prop} :
∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂)
| 0 _ _ _ := by simp only [forall₂.nil, take]
| (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, take]
| (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_take n]
theorem forall₂_drop {R : α → β → Prop} :
∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂)
| 0 _ _ h := by simp only [drop, h]
| (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, drop]
| (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_drop n]
theorem forall₂_take_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β)
(h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.take (length l₁) l) l₁ :=
have h': forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)), from forall₂_take (length l₁) h,
by rwa [take_left] at h'
theorem forall₂_drop_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β)
(h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.drop (length l₁) l) l₂ :=
have h': forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)), from forall₂_drop (length l₁) h,
by rwa [drop_left] at h'
lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈)
| a b h [] [] forall₂.nil := by simp only [not_mem_nil]
| a b h (a'::as) (b'::bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂)
lemma rel_map : ((r ⇒ p) ⇒ forall₂ r ⇒ forall₂ p) map map
| f g h [] [] forall₂.nil := forall₂.nil
| f g h (a::as) (b::bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂)
lemma rel_append : (forall₂ r ⇒ forall₂ r ⇒ forall₂ r) append append
| [] [] h l₁ l₂ hl := hl
| (a::as) (b::bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl)
lemma rel_join : (forall₂ (forall₂ r) ⇒ forall₂ r) join join
| [] [] forall₂.nil := forall₂.nil
| (a::as) (b::bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂)
lemma rel_bind : (forall₂ r ⇒ (r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind :=
assume a b h₁ f g h₂, rel_join (rel_map @h₂ h₁)
lemma rel_foldl : ((p ⇒ r ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldl foldl
| f g hfg _ _ h _ _ forall₂.nil := h
| f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs
lemma rel_foldr : ((r ⇒ p ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldr foldr
| f g hfg _ _ h _ _ forall₂.nil := h
| f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs)
lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q]
(hpq : (r ⇒ (↔)) p q) :
(forall₂ r ⇒ forall₂ r) (filter p) (filter q)
| _ _ forall₂.nil := forall₂.nil
| (a::as) (b::bs) (forall₂.cons h₁ h₂) :=
begin
by_cases p a,
{ have : q b, { rwa [← hpq h₁] },
simp only [filter_cons_of_pos _ h, filter_cons_of_pos _ this, forall₂_cons, h₁, rel_filter h₂, and_true], },
{ have : ¬ q b, { rwa [← hpq h₁] },
simp only [filter_cons_of_neg _ h, filter_cons_of_neg _ this, rel_filter h₂], },
end
theorem filter_map_cons (f : α → option β) (a : α) (l : list α) :
filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) :=
begin
generalize eq : f a = b,
cases b,
{ rw filter_map_cons_none _ _ eq },
{ rw filter_map_cons_some _ _ _ eq },
end
lemma rel_filter_map {f : α → option γ} {q : β → option δ} :
((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map
| f g hfg _ _ forall₂.nil := forall₂.nil
| f g hfg (a::as) (b::bs) (forall₂.cons h₁ h₂) :=
by rw [filter_map_cons, filter_map_cons];
from match f a, g b, hfg h₁ with
| _, _, option.rel.none := rel_filter_map @hfg h₂
| _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂)
end
@[to_additive list.rel_sum]
lemma rel_prod [monoid α] [monoid β]
(h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod :=
assume a b, rel_foldl (assume a b, hf) h
end forall₂
/- sections -/
theorem mem_sections {L : list (list α)} {f} : f ∈ sections L ↔ forall₂ (∈) f L :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ induction L generalizing f, {cases mem_singleton.1 h, exact forall₂.nil},
simp only [sections, bind_eq_bind, mem_bind, mem_map] at h,
rcases h with ⟨_, _, _, _, rfl⟩,
simp only [*, forall₂_cons, true_and] },
{ induction h with a l f L al fL fs, {exact or.inl rfl},
simp only [sections, bind_eq_bind, mem_bind, mem_map],
exact ⟨_, fs, _, al, rfl, rfl⟩ }
end
theorem mem_sections_length {L : list (list α)} {f} (h : f ∈ sections L) : length f = length L :=
forall₂_length_eq (mem_sections.1 h)
lemma rel_sections {r : α → β → Prop} : (forall₂ (forall₂ r) ⇒ forall₂ (forall₂ r)) sections sections
| _ _ forall₂.nil := forall₂.cons forall₂.nil forall₂.nil
| _ _ (forall₂.cons h₀ h₁) :=
rel_bind (rel_sections h₁) (assume _ _ hl, rel_map (assume _ _ ha, forall₂.cons ha hl) h₀)
/- permutations -/
section permutations
@[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] :=
by rw [permutations_aux, permutations_aux.rec]
@[simp] theorem permutations_aux_cons (t : α) (ts is : list α) :
permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2)
(permutations_aux ts (t::is)) (permutations is) :=
by rw [permutations_aux, permutations_aux.rec]; refl
end permutations
/- insert -/
section insert
variable [decidable_eq α]
@[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl
theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl
@[simp] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l :=
by simp only [insert.def, if_pos h]
@[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l :=
by simp only [insert.def, if_neg h]; split; refl
@[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l :=
begin
by_cases h' : b ∈ l,
{ simp only [insert_of_mem h'],
apply (or_iff_right_of_imp _).symm,
exact λ e, e.symm ▸ h' },
simp only [insert_of_not_mem h', mem_cons_iff]
end
@[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l :=
by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]]
@[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l :=
mem_insert_iff.2 (or.inl rfl)
@[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l :=
mem_insert_iff.2 (or.inr h)
theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
mem_insert_iff.1 h
@[simp] theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) :
length (insert a l) = length l :=
by rw insert_of_mem h
@[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) :
length (insert a l) = length l + 1 :=
by rw insert_of_not_mem h; refl
end insert
/- erasep -/
section erasep
variables {p : α → Prop} [decidable_pred p]
@[simp] theorem erasep_nil : [].erasep p = [] := rfl
theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl
@[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l :=
by simp [erasep_cons, h]
@[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p :=
by simp [erasep_cons, h]
theorem erasep_of_forall_not {l : list α}
(h : ∀ a ∈ l, ¬ p a) : l.erasep p = l :=
by induction l with _ _ ih; [refl,
simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]]
theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) :
∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
induction l with b l IH, {cases al},
by_cases pb : p b,
{ exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ },
{ rcases al with rfl | al, {exact pb.elim pa},
rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩,
h₂, by rw h₃; refl, by simp [pb, h₄]⟩ }
end
theorem exists_or_eq_self_of_erasep (l : list α) :
l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
by_cases h : ∃ a ∈ l, p a,
{ rcases h with ⟨a, ha, pa⟩,
exact or.inr (exists_of_erasep ha pa) },
{ simp at h, exact or.inl (erasep_of_forall_not h) }
end
@[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) :
length (l.erasep p) = pred (length l) :=
by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩;
rw e₂; simp [-add_comm, e₁]; refl
theorem erasep_append_left {a : α} (pa : p a) :
∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂
| (x::xs) l₂ h := begin
by_cases h' : p x; simp [h'],
rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h),
rintro rfl, exact pa
end
theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p
| [] l₂ h := rfl
| (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1,
erasep_append_right _ (forall_mem_cons.1 h).2]
theorem erasep_sublist (l : list α) : l.erasep p <+ l :=
by rcases exists_or_eq_self_of_erasep l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩;
[rw h, {rw [h₄, h₃], simp}]
theorem erasep_subset (l : list α) : l.erasep p ⊆ l :=
subset_of_sublist (erasep_sublist l)
theorem erasep_sublist_erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p :=
begin
induction s,
case list.sublist.slnil { refl },
case list.sublist.cons : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] },
case list.sublist.cons2 : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [s, IH.cons2 _ _ _] }
end
theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l :=
@erasep_subset _ _ _ _ _
@[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l :=
⟨mem_of_mem_erasep, λ al, begin
rcases exists_or_eq_self_of_erasep l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
{ rwa h },
{ rw h₄, rw h₃ at al,
have : a ≠ c, {rintro rfl, exact pa.elim h₂},
simpa [this] using al }
end⟩
theorem erasep_map (f : β → α) :
∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f))
| [] := rfl
| (b::l) := by by_cases p (f b); simp [h, erasep_map l]
@[simp] theorem extractp_eq_find_erasep :
∀ l : list α, extractp p l = (find p l, erasep p l)
| [] := rfl
| (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l]
end erasep
/- erase -/
section erase
variable [decidable_eq α]
@[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl
theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl
@[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l :=
by simp only [erase_cons, if_pos rfl]
@[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a :=
by simp only [erase_cons, if_neg h]; split; refl
theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) :=
by { induction l with b l, {refl},
by_cases a = b; [simp [h], simp [h, ne.symm h, *]] }
@[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l :=
by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h'
theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) :
∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ :=
by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩;
rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩
@[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) :=
by rw erase_eq_erasep; exact length_erasep_of_mem h rfl
theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) :
(l₁++l₂).erase a = l₁.erase a ++ l₂ :=
by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h
theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) :
(l₁++l₂).erase a = l₁ ++ l₂.erase a :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right];
rintro b h' rfl; exact h h'
theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l :=
by rw erase_eq_erasep; apply erasep_sublist
theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l :=
subset_of_sublist (erase_sublist a l)
theorem erase_sublist_erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a :=
by simp [erase_eq_erasep]; exact erasep_sublist_erasep h
theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l :=
@erase_subset _ _ _ _ _
@[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l :=
by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm
theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a :=
if ab : a = b then by rw ab else
if ha : a ∈ l then
if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with
| ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb :=
if h₁ : b ∈ l₁ then
by rw [erase_append_left _ h₁, erase_append_left _ h₁,
erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head]
else
by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha',
erase_cons_tail _ ab, erase_cons_head]
end
else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)]
else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)]
theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α}
(l : list α) : map f (l.erase a) = (map f l).erase (f a) :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr;
ext b; simp [finj.eq_iff]
theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ :=
by induction l₂ generalizing l₁; [refl,
simp only [foldl_cons, map_erase finj, *]]
end erase
/- diff -/
section diff
variable [decidable_eq α]
@[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl
@[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ :=
if h : a ∈ l₁ then by simp only [list.diff, if_pos h]
else by simp only [list.diff, if_neg h, erase_of_not_mem h]
@[simp] theorem nil_diff (l : list α) : [].diff l = [] :=
by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]]
theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂
| l₁ [] := rfl
| l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _)
@[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ :=
by simp only [diff_eq_foldl, foldl_append]
@[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) :=
by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj]
theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁
| l₁ [] := sublist.refl _
| l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _
... <+ l₁.erase a : diff_sublist _ _
... <+ l₁ : list.erase_sublist _ _
theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ :=
subset_of_sublist $ diff_sublist _ _
theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂
| l₁ [] h₁ h₂ := h₁
| l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact
mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂)
theorem diff_sublist_of_sublist : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃
| l₁ l₂ [] h := h
| l₁ l₂ (a::l₃) h := by simp only
[diff_cons, diff_sublist_of_sublist (erase_sublist_erase _ h)]
theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α},
l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁
| [] l₂ h := erase_sublist _ _
| (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons]
else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂]
using erase_diff_erase_sublist_of_sublist (erase_sublist_erase b h)
end diff
/- zip & unzip -/
@[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) :
zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl
@[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl
@[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] :=
by cases l; refl
@[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β),
(zip l₁ l₂).map prod.swap = zip l₂ l₁
| [] l₂ := (zip_nil_right _).symm
| l₁ [] := by rw zip_nil_right; refl
| (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk]; split; refl
@[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β),
length (zip l₁ l₂) = min (length l₁) (length l₂)
| [] l₂ := rfl
| l₁ [] := by simp only [length, zip_nil_right, min_zero]
| (a::l₁) (b::l₂) := by by simp only [length, zip_cons_cons, length_zip l₁ l₂, min_add_add_right]
theorem zip_append : ∀ {l₁ l₂ r₁ r₂ : list α} (h : length l₁ = length l₂),
zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂
| [] l₂ r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl
| l₁ [] r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl
| (a::l₁) (b::l₂) r₁ r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ_inj h)]; split; refl
theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β),
zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g)
| [] l₂ := rfl
| l₁ [] := by simp only [map, zip_nil_right]
| (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl
theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) :
zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) :=
by rw [← zip_map, map_id]
theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) :
zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) :=
by rw [← zip_map, map_id]
theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α),
zip (l.map f) (l.map g) = l.map (λ a, (f a, g a))
| [] := rfl
| (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl
theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β},
(a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂
| (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩
| (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h]
@[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl
@[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) :
unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) :=
by rw unzip; cases unzip l; refl
theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd)
| [] := rfl
| ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l]
theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst :=
by simp only [unzip_eq_map]
theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd :=
by simp only [unzip_eq_map]
theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap :=
by simp only [unzip_eq_map, map_map]; split; refl
theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l
| [] := rfl
| ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl
theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ →
(unzip (zip l₁ l₂)).1 = l₁
| [] l₂ h := rfl
| l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl
| (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)]; split; refl
theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) :
(unzip (zip l₁ l₂)).2 = l₂ :=
by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h
theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) :
unzip (zip l₁ l₂) = (l₁, l₂) :=
by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)),
unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)]
@[simp] theorem length_revzip (l : list α) : length (revzip l) = length l :=
by simp only [revzip, length_zip, length_reverse, min_self]
@[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) :=
unzip_zip (length_reverse l).symm
@[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l :=
by rw [← unzip_left, unzip_revzip]
@[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse :=
by rw [← unzip_right, unzip_revzip]
theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse :=
by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip]
theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse :=
by simp [revzip]
/- enum -/
theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l
| n [] := rfl
| n (a::l) := congr_arg nat.succ (length_enum_from _ _)
theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _
@[simp] theorem enum_from_nth : ∀ n (l : list α) m,
nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m
| n [] m := rfl
| n (a :: l) 0 := rfl
| n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $
by rw [add_right_comm]; refl
@[simp] theorem enum_nth : ∀ (l : list α) n,
nth (enum l) n = (λ a, (n, a)) <$> nth l n :=
by simp only [enum, enum_from_nth, zero_add]; intros; refl
@[simp] theorem enum_from_map_snd : ∀ n (l : list α),
map prod.snd (enum_from n l) = l
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _)
@[simp] theorem enum_map_snd : ∀ (l : list α),
map prod.snd (enum l) = l := enum_from_map_snd _
/- product -/
@[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl
@[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl
@[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = []
| [] := rfl
| (a::l) := by rw [product_cons, product_nil]; refl
@[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} :
(a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ :=
by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop,
and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right]
theorem length_product (l₁ : list α) (l₂ : list β) :
length (product l₁ l₂) = length l₁ * length l₂ :=
by induction l₁ with x l₁ IH; [exact (zero_mul _).symm,
simp only [length, product_cons, length_append, IH,
right_distrib, one_mul, length_map, add_comm]]
/- sigma -/
section
variable {σ : α → Type*}
@[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl
@[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a))
: (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl
@[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = []
| [] := rfl
| (a::l) := by rw [sigma_cons, sigma_nil]; refl
@[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} :
sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a :=
by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left,
and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right]
theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum :=
by induction l₁ with x l₁ IH; [refl,
simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]]
end
/- of_fn -/
theorem length_of_fn_aux {n} (f : fin n → α) :
∀ m h l, length (of_fn_aux f m h l) = length l + m
| 0 h l := rfl
| (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _)
@[simp] theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n :=
(length_of_fn_aux f _ _ _).trans (zero_add _)
theorem nth_of_fn_aux {n} (f : fin n → α) (i) :
∀ m h l,
(∀ i, nth l i = of_fn_nth_val f (i + m)) →
nth (of_fn_aux f m h l) i = of_fn_nth_val f i
| 0 h l H := H i
| (succ m) h l H := nth_of_fn_aux m _ _ begin
intro j, cases j with j,
{ simp only [nth, of_fn_nth_val, zero_add, dif_pos (show m < n, from h)] },
{ simp only [nth, H, succ_add] }
end
@[simp] theorem nth_of_fn {n} (f : fin n → α) (i) :
nth (of_fn f) i = of_fn_nth_val f i :=
nth_of_fn_aux f _ _ _ _ $ λ i,
by simp only [of_fn_nth_val, dif_neg (not_lt.2 (le_add_left n i))]; refl
@[simp] theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) :
nth_le (of_fn f) i.1 ((length_of_fn f).symm ▸ i.2) = f i :=
option.some.inj $ by rw [← nth_le_nth];
simp only [list.nth_of_fn, of_fn_nth_val, fin.eta, dif_pos i.2]
theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read :=
suffices ∀ {m h l}, d_array.rev_iterate_aux a
(λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this,
begin
intros, induction m with m IH generalizing l, {refl},
simp only [d_array.rev_iterate_aux, of_fn_aux, IH]
end
theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl
theorem of_fn_succ {n} (f : fin (succ n) → α) :
of_fn f = f 0 :: of_fn (λ i, f i.succ) :=
suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l =
f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this,
begin
intros, induction m with m IH generalizing l, {refl},
rw [of_fn_aux, IH], refl
end
theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i.1 i.2) = l
| [] := rfl
| (a::l) := by rw of_fn_succ; congr; simp only [fin.succ_val]; exact of_fn_nth_le l
/- disjoint -/
section disjoint
theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁
| a i₂ i₁ := d i₁ i₂
@[simp] theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl
theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
disjoint_comm
theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂
| x m₁ := d (ss m₁)
theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂
| x m m₁ := d m (ss m₁)
theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
@[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l
| a := (not_mem_nil a).elim
@[simp] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l :=
by simp only [disjoint, mem_singleton, forall_eq]; refl
@[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l :=
by rw disjoint_comm; simp only [singleton_disjoint]
@[simp] theorem disjoint_append_left {l₁ l₂ l : list α} :
disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l :=
by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_append_right {l₁ l₂ l : list α} :
disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} :
disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ :=
(@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint]
@[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} :
disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left]
theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l :=
(disjoint_append_left.1 d).1
theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l :=
(disjoint_append_left.1 d).2
theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ :=
(disjoint_append_right.1 d).1
theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ :=
(disjoint_append_right.1 d).2
end disjoint
/- union -/
section union
variable [decidable_eq α]
@[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl
@[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl
@[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ :=
by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *]
theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inl h)
theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inr h)
theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂
| [] l₂ := ⟨[], by refl, rfl⟩
| (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
if h : a ∈ l₁ ∪ l₂
then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩
else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩
theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ :=
(sublist_suffix_of_union l₁ l₂).imp (λ a, and.right)
theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ :=
let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
e ▸ (append_sublist_append_right _).2 s
theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_union, or_imp_distrib, forall_and_distrib]
theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x :=
(forall_mem_union.1 h).1
theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x :=
(forall_mem_union.1 h).2
end union
/- inter -/
section inter
variable [decidable_eq α]
@[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl
@[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) :
(a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) :=
if_pos h
@[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) :
(a::l₁) ∩ l₂ = l₁ ∩ l₂ :=
if_neg h
theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ :=
mem_of_mem_filter
theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ :=
of_mem_filter
theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ :=
mem_filter_of_mem
@[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ :=
mem_filter
theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ :=
filter_subset _
theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ :=
λ a, mem_of_mem_inter_right
theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ :=
λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩
theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ :=
by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl
theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x)
(l₂ : list α) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_left) h
theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α}
(h : ∀ x ∈ l₂, p x) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_right) h
end inter
/- bag_inter -/
section bag_inter
variable [decidable_eq α]
@[simp] theorem nil_bag_inter (l : list α) : [].bag_inter l = [] :=
by cases l; refl
@[simp] theorem bag_inter_nil (l : list α) : l.bag_inter [] = [] :=
by cases l; refl
@[simp] theorem cons_bag_inter_of_pos {a} (l₁ : list α) {l₂} (h : a ∈ l₂) :
(a :: l₁).bag_inter l₂ = a :: l₁.bag_inter (l₂.erase a) :=
by cases l₂; exact if_pos h
@[simp] theorem cons_bag_inter_of_neg {a} (l₁ : list α) {l₂} (h : a ∉ l₂) :
(a :: l₁).bag_inter l₂ = l₁.bag_inter l₂ :=
begin
cases l₂, {simp only [bag_inter_nil]},
simp only [erase_of_not_mem h, list.bag_inter, if_neg h]
end
theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂
| [] l₂ := by simp only [nil_bag_inter, not_mem_nil, false_and]
| (b::l₁) l₂ := begin
by_cases b ∈ l₂,
{ rw [cons_bag_inter_of_pos _ h, mem_cons_iff, mem_cons_iff, mem_bag_inter],
by_cases ba : a = b,
{ simp only [ba, h, eq_self_iff_true, true_or, true_and] },
{ simp only [mem_erase_of_ne ba, ba, false_or] } },
{ rw [cons_bag_inter_of_neg _ h, mem_bag_inter, mem_cons_iff, or_and_distrib_right],
symmetry, apply or_iff_right_of_imp,
rintro ⟨rfl, h'⟩, exact h.elim h' }
end
theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁
| [] l₂ := by simp [nil_sublist]
| (b::l₁) l₂ := begin
by_cases b ∈ l₂; simp [h],
{ apply cons_sublist_cons, apply bag_inter_sublist_left },
{ apply sublist_cons_of_sublist, apply bag_inter_sublist_left }
end
end bag_inter
/- pairwise relation (generalized no duplicate) -/
section pairwise
run_cmd tactic.mk_iff_of_inductive_prop `list.pairwise `list.pairwise_iff
variable {R : α → α → Prop}
theorem rel_of_pairwise_cons {a : α} {l : list α}
(p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' :=
(pairwise_cons.1 p).1
theorem pairwise_of_pairwise_cons {a : α} {l : list α}
(p : pairwise R (a::l)) : pairwise R l :=
(pairwise_cons.1 p).2
theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α}
(H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l :=
begin
induction p with a l r p IH generalizing H; constructor,
{ exact ball.imp_right
(λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r },
{ exact IH (λ a b m m', H
(mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) }
end
theorem pairwise.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l :=
pairwise.imp_of_mem (λ a b _ _, H a b)
theorem pairwise.and {S : α → α → Prop} {l : list α} :
pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l :=
⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩,
λ ⟨hR, hS⟩, begin
clear_, induction hR with a l R1 R2 IH;
simp only [pairwise.nil, pairwise_cons] at *,
exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩
end⟩
theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop}
(H : ∀ a b, R a b → S a b → T a b) {l : list α}
(hR : pairwise R l) (hS : pairwise S l) : pairwise T l :=
(pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b)
theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α}
(H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l :=
⟨pairwise.imp_of_mem (λ a b m m', (H m m').1),
pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩
theorem pairwise.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l :=
pairwise.iff_of_mem (λ a b _ _, H a b)
theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l :=
by induction l; [exact pairwise.nil,
simp only [*, pairwise_cons, forall_2_true_iff, and_true]]
theorem pairwise.and_mem {l : list α} :
pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l :=
pairwise.iff_of_mem (by simp only [true_and, iff_self, forall_2_true_iff] {contextual := tt})
theorem pairwise.imp_mem {l : list α} :
pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l :=
pairwise.iff_of_mem (by simp only [forall_prop_of_true, iff_self, forall_2_true_iff] {contextual := tt})
theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁
| ._ ._ sublist.slnil h := h
| ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n
| ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) :=
(pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i)
theorem forall_of_forall_of_pairwise (H : symmetric R)
{l : list α} (H₁ : ∀ x ∈ l, R x x) (H₂ : pairwise R l) :
∀ (x ∈ l) (y ∈ l), R x y :=
begin
induction l with a l IH, { exact forall_mem_nil _ },
cases forall_mem_cons.1 H₁ with H₁₁ H₁₂,
cases pairwise_cons.1 H₂ with H₂₁ H₂₂,
rintro x (rfl | hx) y (rfl | hy),
exacts [H₁₁, H₂₁ _ hy, H (H₂₁ _ hx), IH H₁₂ H₂₂ _ hx _ hy]
end
lemma forall_of_pairwise (H : symmetric R) {l : list α}
(hl : pairwise R l) : (∀a∈l, ∀b∈l, a ≠ b → R a b) :=
forall_of_forall_of_pairwise
(λ a b h hne, H (h hne.symm))
(λ _ _ h, (h rfl).elim)
(pairwise.imp (λ _ _ h _, h) hl)
theorem pairwise_singleton (R) (a : α) : pairwise R [a] :=
by simp only [pairwise_cons, mem_singleton, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true]
theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b :=
by simp only [pairwise_cons, mem_singleton, forall_eq, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true]
theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔
pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y :=
by induction l₁ with x l₁ IH; [simp only [list.pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_true_iff, and_true, true_and, nil_append],
simp only [cons_append, pairwise_cons, forall_mem_append, IH, forall_mem_cons, forall_and_distrib, and_assoc, and.left_comm]]
theorem pairwise_app_comm (s : symmetric R) {l₁ l₂ : list α} :
pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) :=
have ∀ l₁ l₂ : list α,
(∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) →
(∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y),
from λ l₁ l₂ a x xm y ym, s (a y ym x xm),
by simp only [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁)
theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} :
pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) :=
show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂),
by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_app_comm s];
simp only [mem_append, or_comm]
theorem pairwise_map (f : β → α) :
∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l
| [] := by simp only [map, pairwise.nil]
| (b::l) :=
have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from
forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp only [forall_eq'],
by simp only [map, pairwise_cons, mem_map, exists_imp_distrib, and_imp, this, pairwise_map]
theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α}
(p : pairwise S (map f l)) : pairwise R l :=
((pairwise_map f).1 p).imp H
theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α}
(p : pairwise R l) : pairwise S (map f l) :=
(pairwise_map f).2 $ p.imp H
theorem pairwise_filter_map (f : β → option α) {l : list β} :
pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l :=
let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in
begin
simp only [option.mem_def], induction l with a l IH,
{ simp only [filter_map, pairwise.nil] },
cases e : f a with b,
{ rw [filter_map_cons_none _ _ e, IH, pairwise_cons],
simp only [e, forall_prop_of_false not_false, forall_3_true_iff, true_and] },
rw [filter_map_cons_some _ _ _ e],
simp only [pairwise_cons, mem_filter_map, exists_imp_distrib, and_imp, IH, e, forall_eq'],
show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔
(∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l,
from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl
end
theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β)
(H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α}
(p : pairwise R l) : pairwise S (filter_map f l) :=
(pairwise_filter_map _).2 $ p.imp H
theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} :
pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l :=
begin
rw [← filter_map_eq_filter, pairwise_filter_map],
apply pairwise.iff, intros, simp only [option.mem_def, option.guard_eq_some, and_imp, forall_eq'],
end
theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α}
: pairwise R l → pairwise R (filter p l) :=
pairwise_of_sublist (filter_sublist _)
theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔
(∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L :=
begin
induction L with l L IH, {simp only [join, pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_const, and_self]},
have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔
∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y :=
⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩,
simp only [join, pairwise_append, IH, mem_join, exists_imp_distrib, and_imp, this, forall_mem_cons, pairwise_cons],
simp only [and_assoc, and_comm, and.left_comm],
end
@[simp] theorem pairwise_reverse : ∀ {R} {l : list α},
pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l :=
suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l),
from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩,
λ R l p, by induction p with a l h p IH;
[apply pairwise.nil, simpa only [reverse_cons, pairwise_append, IH,
pairwise_cons, forall_prop_of_false (not_mem_nil _), forall_true_iff,
pairwise.nil, mem_reverse, mem_singleton, forall_eq, true_and] using h]
theorem pairwise_iff_nth_le {R} : ∀ {l : list α},
pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁)
| [] := by simp only [pairwise.nil, true_iff]; exact λ i j h, (not_lt_zero j).elim h
| (a::l) := begin
rw [pairwise_cons, pairwise_iff_nth_le],
refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _,
λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩,
{ cases j with j, {exact (not_lt_zero _).elim h₂},
cases i with i,
{ exact H.1 _ (nth_le_mem l _ _) },
{ exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } },
{ rcases nth_le_of_mem m with ⟨n, h, rfl⟩,
exact H _ _ (succ_lt_succ h) (succ_pos _) }
end
theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l →
pairwise (lex (swap R)) (sublists' l)
| _ pairwise.nil := pairwise_singleton _ _
| _ (@pairwise.cons _ _ a l H₁ H₂) :=
begin
simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp_distrib, and_imp],
have IH := pairwise_sublists' H₂,
refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩,
intros l₁ sl₁ x l₂ sl₂ e, subst e,
cases l₁ with b l₁, {constructor},
exact lex.rel (H₁ _ $ subset_of_sublist sl₁ $ mem_cons_self _ _)
end
theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) :
pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) :=
by have := pairwise_sublists' (pairwise_reverse.2 H);
rwa [sublists'_reverse, pairwise_map] at this
/- pairwise reduct -/
variable [decidable_rel R]
@[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl
@[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) :
pw_filter R (a::l) = a :: pw_filter R l := if_pos h
@[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) :
pw_filter R (a::l) = pw_filter R l := if_neg h
theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l
| [] := nil_sublist _
| (x::l) := begin
by_cases (∀ y ∈ pw_filter R l, R x y),
{ rw [pw_filter_cons_of_pos h],
exact cons_sublist_cons _ (pw_filter_sublist l) },
{ rw [pw_filter_cons_of_neg h],
exact sublist_cons_of_sublist _ (pw_filter_sublist l) },
end
theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l :=
subset_of_sublist (pw_filter_sublist _)
theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l)
| [] := pairwise.nil
| (x::l) := begin
by_cases (∀ y ∈ pw_filter R l, R x y),
{ rw [pw_filter_cons_of_pos h],
exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ },
{ rw [pw_filter_cons_of_neg h],
exact pairwise_pw_filter l },
end
theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l :=
⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin
induction l with x l IH, {refl},
cases pairwise_cons.1 p with al p,
rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p],
end⟩
@[simp] theorem pw_filter_idempotent {l : list α} :
pw_filter R (pw_filter R l) = pw_filter R l :=
pw_filter_eq_self.mpr (pairwise_pw_filter l)
theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z)
(a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) :=
⟨begin
induction l with x l IH, { exact λ _ _, false.elim },
simp only [forall_mem_cons],
by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h,
{ simp only [pw_filter_cons_of_pos h, forall_mem_cons, and_imp],
exact λ r H, ⟨r, IH H⟩ },
{ rw [pw_filter_cons_of_neg h],
refine λ H, ⟨_, IH H⟩,
cases e : find (λ y, ¬ R x y) (pw_filter R l) with k,
{ refine h.elim (ball.imp_right _ (find_eq_none.1 e)),
exact λ y _, not_not.1 },
{ have := find_some e,
exact (neg_trans (H k (find_mem e))).resolve_right this } }
end, ball.imp_left (pw_filter_subset l)⟩
end pairwise
/- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/
section chain
run_cmd tactic.mk_iff_of_inductive_prop `list.chain `list.chain_iff
variable {R : α → α → Prop}
theorem rel_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b::l)) : R a b :=
(chain_cons.1 p).1
theorem chain_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b::l)) : chain R b l :=
(chain_cons.1 p).2
theorem chain.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l :=
by induction p with _ a b l r p IH; constructor;
[exact H _ _ r, exact IH]
theorem chain.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l :=
⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩
theorem chain.iff_mem {a : α} {l : list α} :
chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l :=
⟨λ p, by induction p with _ a b l r p IH; constructor;
[exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩,
exact IH.imp (λ a b ⟨am, bm, h⟩,
⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)],
chain.imp (λ a b h, h.2.2)⟩
theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b :=
by simp only [chain_cons, chain.nil, and_true]
theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔
chain R a (l₁++[b]) ∧ chain R b l₂ :=
by induction l₁ with x l₁ IH generalizing a;
simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc]
theorem chain_map (f : β → α) {b : β} {l : list β} :
chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l :=
by induction l generalizing b; simp only [map, chain.nil, chain_cons, *]
theorem chain_of_chain_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α}
(p : chain S (f a) (map f l)) : chain R a l :=
((chain_map f).1 p).imp H
theorem chain_map_of_chain {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α}
(p : chain R a l) : chain S (f a) (map f l) :=
(chain_map f).2 $ p.imp H
theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l :=
begin
cases pairwise_cons.1 p with r p', clear p,
induction p' with b l r' p IH generalizing a, {exact chain.nil},
simp only [chain_cons, forall_mem_cons] at r,
exact chain_cons.2 ⟨r.1, IH r'⟩
end
theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} :
chain R a l ↔ pairwise R (a::l) :=
⟨λ c, begin
induction c with b b c l r p IH, {exact pairwise_singleton _ _},
apply IH.cons _, simp only [mem_cons_iff, forall_mem_cons', r, true_and],
show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)),
end, chain_of_pairwise⟩
theorem chain'.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l :=
by cases l; [trivial, exact p.imp H]
theorem chain'.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l :=
⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩
theorem chain'.iff_mem {S : α → α → Prop} : ∀ {l : list α},
chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l
| [] := iff.rfl
| (x::l) :=
⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩,
chain'.imp $ λ a b h, h.2.2⟩
theorem chain'_singleton (a : α) : chain' R [a] := chain.nil
theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁++a::l₂) ↔
chain' R (l₁++[a]) ∧ chain' R (a::l₂)
| [] l₂ := (and_iff_right (chain'_singleton a)).symm
| (b::l₁) l₂ := chain_split
theorem chain'_map (f : β → α) {l : list β} :
chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l :=
by cases l; [refl, exact chain_map _]
theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α}
(p : chain' S (map f l)) : chain' R l :=
((chain'_map f).1 p).imp H
theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α}
(p : chain' R l) : chain' S (map f l) :=
(chain'_map f).2 $ p.imp H
theorem chain'_of_pairwise : ∀ {l : list α}, pairwise R l → chain' R l
| [] _ := trivial
| (a::l) h := chain_of_pairwise h
theorem chain'_iff_pairwise (tr : transitive R) : ∀ {l : list α},
chain' R l ↔ pairwise R l
| [] := (iff_true_intro pairwise.nil).symm
| (a::l) := chain_iff_pairwise tr
end chain
/- no duplicates predicate -/
section nodup
@[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l :=
⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩
@[simp] theorem nodup_nil : @nodup α [] := pairwise.nil
@[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l :=
by simp only [nodup, pairwise_cons, forall_mem_ne]
lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup
| _ _ forall₂.nil := by simp only [nodup_nil]
| _ _ (forall₂.cons hab h) :=
by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h)
theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton (a : α) : nodup [a] :=
nodup_cons_of_nodup (not_mem_nil a) nodup_nil
theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l :=
(nodup_cons.1 h).1
theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) :=
imp_not_comm.1 not_mem_of_nodup_cons
theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ :=
pairwise_of_sublist
theorem not_nodup_pair (a : α) : ¬ nodup [a, a] :=
not_nodup_cons_of_mem $ mem_singleton_self _
theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l :=
⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin
induction l with a l IH; intro h, {exact nodup_nil},
exact nodup_cons_of_nodup
(λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al)
(IH $ λ a s, h a $ sublist_cons_of_sublist _ s)
end⟩
theorem nodup_iff_nth_le_inj {l : list α} :
nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j :=
pairwise_iff_nth_le.trans
⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _)
.resolve_left (λ h', H _ _ h₂ h' h))
.resolve_right (λ h', H _ _ h₁ h' h.symm),
λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩
@[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n :=
nodup_iff_nth_le_inj.1 H _ _ _ h $
index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _
theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 :=
nodup_iff_sublist.trans $ forall_congr $ λ a,
have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm,
(not_congr this).trans not_lt
theorem nodup_repeat (a : α) : ∀ {n : ℕ}, nodup (repeat a n) ↔ n ≤ 1
| 0 := by simp [nat.zero_le]
| 1 := by simp
| (n+2) := iff_of_false
(λ H, nodup_iff_sublist.1 H a ((repeat_sublist_repeat _).2 (le_add_left 2 n)))
(not_le_of_lt $ le_add_left 2 n)
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α}
(d : nodup l) (h : a ∈ l) : count a l = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ :=
nodup_of_sublist (sublist_append_left l₁ l₂)
theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ :=
nodup_of_sublist (sublist_append_right l₁ l₂)
theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ :=
by simp only [nodup, pairwise_append, disjoint_iff_ne]
theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ :=
(nodup_append.1 d).2.2
theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) :=
nodup_append.2 ⟨d₁, d₂, dj⟩
theorem nodup_app_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) :=
by simp only [nodup_append, and.left_comm, disjoint_comm]
theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) :=
by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right]
theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l :=
pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f
theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y)
(d : nodup l) : nodup (map f l) :=
pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d)
theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) :=
nodup_map_on (assume x _ y _ h, hf h)
theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l :=
⟨nodup_of_nodup_map _, nodup_map hf⟩
@[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l :=
⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h,
λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩
theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) :=
by rw [pmap_eq_map_attach]; exact nodup_map
(λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h)
(nodup_attach.2 h)
theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) :=
pairwise_filter_of_pairwise p
@[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l :=
pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm]
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l :=
begin
induction d with b l m d IH, {refl},
by_cases b = a,
{ subst h, rw [erase_cons_head, filter_cons_of_neg],
symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl },
{ rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h }
end
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_sublist (erase_sublist _ _)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp only [mem_filter, and_comm]
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
λ H, ((mem_erase_iff_of_nodup h).1 H).1 rfl
theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L :=
by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne]
theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔
(∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ :=
by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map, exists_imp_distrib, and_imp];
rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔
(∀ (x : α), x ∈ l₁ → nodup (f x)),
from forall_swap.trans $ forall_congr $ λ_, forall_eq']
theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) :
nodup (product l₁ l₂) :=
nodup_bind.2
⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂,
d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin
rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩,
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩,
exact n rfl
end⟩
theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)}
(d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) :=
nodup_bind.2
⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a),
d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin
rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩,
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩,
exact n rfl
end⟩
theorem nodup_filter_map {f : α → option β} {l : list α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup l → nodup (filter_map f l) :=
pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm'
theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) :=
by rw concat_eq_append; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h)
theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) :=
if h' : a ∈ l then by rw [insert_of_mem h']; exact h
else by rw [insert_of_not_mem h', nodup_cons]; split; assumption
theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) :
nodup (l₁ ∪ l₂) :=
begin
induction l₁ with a l₁ ih generalizing l₂,
{ exact h },
apply nodup_insert,
exact ih h
end
theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) :=
nodup_filter _
@[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l :=
⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h),
λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩
@[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l :=
by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective,
nodup_sublists, nodup_reverse]
end nodup
/- erase duplicates function -/
section erase_dup
variable [decidable_eq α]
@[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl
theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) :
erase_dup (a::l) = erase_dup l :=
pw_filter_cons_of_neg $ by simpa only [forall_mem_ne] using h
theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) :
erase_dup (a::l) = a :: erase_dup l :=
pw_filter_cons_of_pos $ by simpa only [forall_mem_ne] using h
@[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l :=
by simpa only [erase_dup, forall_mem_ne, not_not] using not_congr (@forall_mem_pw_filter α (≠) _
(λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l)
@[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) :
erase_dup (a::l) = erase_dup l :=
erase_dup_cons_of_mem' $ mem_erase_dup.2 h
@[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) :
erase_dup (a::l) = a :: erase_dup l :=
erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h
theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist
theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset
theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l :=
λ a, mem_erase_dup.2
theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter
theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self
@[simp] theorem erase_dup_idempotent {l : list α} : erase_dup (erase_dup l) = erase_dup l :=
pw_filter_idempotent
theorem erase_dup_append (l₁ l₂ : list α) : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ :=
begin
induction l₁ with a l₁ IH, {refl}, rw [cons_union, ← IH],
show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)),
by_cases a ∈ erase_dup (l₁ ++ l₂);
[ rw [erase_dup_cons_of_mem' h, insert_of_mem h],
rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]]
end
end erase_dup
/- iota and range(') -/
@[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n
| s 0 := rfl
| s (n+1) := congr_arg succ (length_range' _ _)
@[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n
| s 0 := (false_iff _).2 $ λ ⟨H1, H2⟩, not_le_of_lt H2 H1
| s (succ n) :=
have m = s → m < s + n + 1,
from λ e, e ▸ lt_succ_of_le (le_add_right _ _),
have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m,
by simpa only [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm,
(mem_cons_iff _ _ _).trans $ by simp only [mem_range',
or_and_distrib_left, or_iff_right_of_imp this, l, add_right_comm]; refl
theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n
| s 0 := rfl
| s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n)
theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n)
| s 0 := chain.nil
| s (n+1) := (chain_succ_range' (s+1) n).cons rfl
theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) :=
(chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _)
theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n)
| s 0 := pairwise.nil
| s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n)
theorem nodup_range' (s n : ℕ) : nodup (range' s n) :=
(pairwise_lt_range' s n).imp (λ a b, ne_of_lt)
theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m)
| s 0 n := rfl
| s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m),
by rw [add_right_comm, range'_append]
theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n :=
⟨λ h, by simpa only [length_range'] using length_le_of_sublist h,
λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩
theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n :=
⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $
(mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2,
λ h, subset_of_sublist (range'_sublist_right.2 h)⟩
theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m)
| s 0 (n+1) _ := rfl
| s (m+1) (n+1) h := (nth_range' (s+1) (lt_of_add_lt_add_right h)).trans $ by rw add_right_comm; refl
theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] :=
by rw add_comm n 1; exact (range'_append s n 1).symm
theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s)
| 0 n := rfl
| (s+1) n := by rw [show n+(s+1) = n+1+s, from add_right_comm n s 1]; exact range_core_range' s (n+1)
theorem range_eq_range' (n : ℕ) : range n = range' 0 n :=
(range_core_range' n 0).trans $ by rw zero_add
theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) :=
by rw [range_eq_range', range_eq_range', range',
add_comm, ← map_add_range'];
congr; exact funext one_add
theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) :=
by rw [range_eq_range', map_add_range']; refl
@[simp] theorem length_range (n : ℕ) : length (range n) = n :=
by simp only [range_eq_range', length_range']
theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) :=
by simp only [range_eq_range', pairwise_lt_range']
theorem nodup_range (n : ℕ) : nodup (range n) :=
by simp only [range_eq_range', nodup_range']
theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n :=
by simp only [range_eq_range', range'_sublist_right]
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n :=
by simp only [range_eq_range', range'_subset_right]
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n :=
by simp only [range_eq_range', mem_range', nat.zero_le, true_and, zero_add]
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n :=
mt mem_range.1 $ lt_irrefl _
theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m :=
by simp only [range_eq_range', nth_range' _ h, zero_add]
theorem range_concat (n : ℕ) : range (n + 1) = range n ++ [n] :=
by simp only [range_eq_range', range'_concat, zero_add]
theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n)
| 0 := rfl
| (n+1) := by simp only [iota, range'_concat, iota_eq_reverse_range' n, reverse_append, add_comm]; refl
@[simp] theorem length_iota (n : ℕ) : length (iota n) = n :=
by simp only [iota_eq_reverse_range', length_reverse, length_range']
theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) :=
by simp only [iota_eq_reverse_range', pairwise_reverse, pairwise_lt_range']
theorem nodup_iota (n : ℕ) : nodup (iota n) :=
by simp only [iota_eq_reverse_range', nodup_reverse, nodup_range']
theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n :=
by simp only [iota_eq_reverse_range', mem_reverse, mem_range', add_comm, lt_succ_iff]
theorem reverse_range' : ∀ s n : ℕ,
reverse (range' s n) = map (λ i, s + n - 1 - i) (range n)
| s 0 := rfl
| s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map];
simpa only [show s + (n + 1) - 1 = s + n, from rfl, (∘),
λ a i, show a - 1 - i = a - succ i, from pred_sub _ _,
reverse_singleton, map_cons, nat.sub_zero, cons_append,
nil_append, eq_self_iff_true, true_and, map_map]
using reverse_range' s n
@[simp] theorem enum_from_map_fst : ∀ n (l : list α),
map prod.fst (enum_from n l) = range' n l.length
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _)
@[simp] theorem enum_map_fst (l : list α) :
map prod.fst (enum l) = range l.length :=
by simp only [enum, enum_from_map_fst, range_eq_range']
theorem last'_mem {α} : ∀ a l, @last' α a l ∈ a :: l
| a [] := or.inl rfl
| a (b::l) := or.inr (last'_mem b l)
@[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)]
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)
section tfae
/- tfae: The Following (propositions) Are Equivalent -/
theorem tfae_nil : tfae [] := forall_mem_nil _
theorem tfae_singleton (p) : tfae [p] := by simp [tfae]
theorem tfae_cons_of_mem {a b} {l : list Prop} (h : b ∈ l) :
tfae (a::l) ↔ (a ↔ b) ∧ tfae l :=
⟨λ H, ⟨H a (by simp) b (or.inr h), λ p hp q hq, H _ (or.inr hp) _ (or.inr hq)⟩,
begin
rintro ⟨ab, H⟩ p (rfl | hp) q (rfl | hq),
{ refl },
{ exact ab.trans (H _ h _ hq) },
{ exact (ab.trans (H _ h _ hp)).symm },
{ exact H _ hp _ hq }
end⟩
theorem tfae_cons_cons {a b} {l : list Prop} : tfae (a::b::l) ↔ (a ↔ b) ∧ tfae (b::l) :=
tfae_cons_of_mem (or.inl rfl)
theorem tfae_of_forall (b : Prop) (l : list Prop) (h : ∀ a ∈ l, a ↔ b) : tfae l :=
λ a₁ h₁ a₂ h₂, (h _ h₁).trans (h _ h₂).symm
theorem tfae_of_cycle {a b} {l : list Prop} :
list.chain (→) a (b::l) → (last' b l → a) → tfae (a::b::l) :=
begin
induction l with c l IH generalizing a b; simp [tfae_cons_cons, tfae_singleton] at *,
{ intros a _ b, exact iff.intro a b },
intros ab bc ch la,
have := IH bc ch (ab ∘ la),
exact ⟨⟨ab, la ∘ (this.2 c (or.inl rfl) _ (last'_mem _ _)).1 ∘ bc⟩, this⟩
end
theorem tfae.out {l} (h : tfae l) (n₁ n₂)
(h₁ : n₁ < list.length l . tactic.exact_dec_trivial)
(h₂ : n₂ < list.length l . tactic.exact_dec_trivial) :
list.nth_le l n₁ h₁ ↔ list.nth_le l n₂ h₂ :=
h _ (list.nth_le_mem _ _ _) _ (list.nth_le_mem _ _ _)
end tfae
lemma rotate_mod (l : list α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n :=
by simp [rotate]
@[simp] lemma rotate_nil (n : ℕ) : ([] : list α).rotate n = [] := by cases n; refl
@[simp] lemma rotate_zero (l : list α) : l.rotate 0 = l := by simp [rotate]
@[simp] lemma rotate'_nil (n : ℕ) : ([] : list α).rotate' n = [] := by cases n; refl
@[simp] lemma rotate'_zero (l : list α) : l.rotate' 0 = l := by cases l; refl
lemma rotate'_cons_succ (l : list α) (a : α) (n : ℕ) :
(a :: l : list α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate']
@[simp] lemma length_rotate' : ∀ (l : list α) (n : ℕ), (l.rotate' n).length = l.length
| [] n := rfl
| (a::l) 0 := rfl
| (a::l) (n+1) := by rw [list.rotate', length_rotate' (l ++ [a]) n]; simp
lemma rotate'_eq_take_append_drop : ∀ {l : list α} {n : ℕ}, n ≤ l.length →
l.rotate' n = l.drop n ++ l.take n
| [] n h := by simp [drop_append_of_le_length h]
| l 0 h := by simp [take_append_of_le_length h]
| (a::l) (n+1) h :=
have hnl : n ≤ l.length, from le_of_succ_le_succ h,
have hnl' : n ≤ (l ++ [a]).length,
by rw [length_append, length_cons, list.length, zero_add];
exact (le_of_succ_le h),
by rw [rotate'_cons_succ, rotate'_eq_take_append_drop hnl', drop, take,
drop_append_of_le_length hnl, take_append_of_le_length hnl];
simp
lemma rotate'_rotate' : ∀ (l : list α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m)
| (a::l) 0 m := by simp
| [] n m := by simp
| (a::l) (n+1) m := by rw [rotate'_cons_succ, rotate'_rotate', add_right_comm, rotate'_cons_succ]
@[simp] lemma rotate'_length (l : list α) : rotate' l l.length = l :=
by rw rotate'_eq_take_append_drop (le_refl _); simp
@[simp] lemma rotate'_length_mul (l : list α) : ∀ n : ℕ, l.rotate' (l.length * n) = l
| 0 := by simp
| (n+1) :=
calc l.rotate' (l.length * (n + 1)) =
(l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length :
by simp [-rotate'_length, nat.mul_succ, rotate'_rotate']
... = l : by rw [rotate'_length, rotate'_length_mul]
lemma rotate'_mod (l : list α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n :=
calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate'
((l.rotate' (n % l.length)).length * (n / l.length)) : by rw rotate'_length_mul
... = l.rotate' n : by rw [rotate'_rotate', length_rotate', nat.mod_add_div]
lemma rotate_eq_rotate' (l : list α) (n : ℕ) : l.rotate n = l.rotate' n :=
if h : l.length = 0 then by simp [length_eq_zero, *] at *
else by
rw [← rotate'_mod, rotate'_eq_take_append_drop (le_of_lt (nat.mod_lt _ (nat.pos_of_ne_zero h)))];
simp [rotate]
lemma rotate_cons_succ (l : list α) (a : α) (n : ℕ) :
(a :: l : list α).rotate n.succ = (l ++ [a]).rotate n :=
by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ]
@[simp] lemma length_rotate (l : list α) (n : ℕ) : (l.rotate n).length = l.length :=
by rw [rotate_eq_rotate', length_rotate']
lemma rotate_eq_take_append_drop {l : list α} {n : ℕ} : n ≤ l.length →
l.rotate n = l.drop n ++ l.take n :=
by rw rotate_eq_rotate'; exact rotate'_eq_take_append_drop
lemma rotate_rotate (l : list α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) :=
by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate']
@[simp] lemma rotate_length (l : list α) : rotate l l.length = l :=
by rw [rotate_eq_rotate', rotate'_length]
@[simp] lemma rotate_length_mul (l : list α) (n : ℕ) : l.rotate (l.length * n) = l :=
by rw [rotate_eq_rotate', rotate'_length_mul]
lemma prod_rotate_eq_one_of_prod_eq_one [group α] : ∀ {l : list α} (hl : l.prod = 1) (n : ℕ),
(l.rotate n).prod = 1
| [] _ _ := by simp
| (a::l) hl n :=
have n % list.length (a :: l) ≤ list.length (a :: l), from le_of_lt (nat.mod_lt _ dec_trivial),
by rw ← list.take_append_drop (n % list.length (a :: l)) (a :: l) at hl;
rw [← rotate_mod, rotate_eq_take_append_drop this, list.prod_append, mul_eq_one_iff_inv_eq,
← one_mul (list.prod _)⁻¹, ← hl, list.prod_append, mul_assoc, mul_inv_self, mul_one]
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
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
end list
theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup
| none := list.nodup_nil
| (some x) := list.nodup_singleton x
|
0ed0971a408d7bc48aef035d61e92194af491383 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/polynomial/hasse_deriv.lean | 1586e250644e6e57367a72f1021ef836cab821df | [
"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,643 | lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.nat.choose.cast
import data.nat.choose.vandermonde
import data.polynomial.derivative
/-!
# Hasse derivative of polynomials
The `k`th Hasse derivative of a polynomial `∑ a_i X^i` is `∑ (i.choose k) a_i X^(i-k)`.
It is a variant of the usual derivative, and satisfies `k! * (hasse_deriv k f) = derivative^[k] f`.
The main benefit is that is gives an atomic way of talking about expressions such as
`(derivative^[k] f).eval r / k!`, that occur in Taylor expansions, for example.
## Main declarations
In the following, we write `D k` for the `k`-th Hasse derivative `hasse_deriv k`.
* `polynomial.hasse_deriv`: the `k`-th Hasse derivative of a polynomial
* `polynomial.hasse_deriv_zero`: the `0`th Hasse derivative is the identity
* `polynomial.hasse_deriv_one`: the `1`st Hasse derivative is the usual derivative
* `polynomial.factorial_smul_hasse_deriv`: the identity `k! • (D k f) = derivative^[k] f`
* `polynomial.hasse_deriv_comp`: the identity `(D k).comp (D l) = (k+l).choose k • D (k+l)`
* `polynomial.hasse_deriv_mul`:
the "Leibniz rule" `D k (f * g) = ∑ ij in antidiagonal k, D ij.1 f * D ij.2 g`
For the identity principle, see `polynomial.eq_zero_of_hasse_deriv_eq_zero`
in `data/polynomial/taylor.lean`.
## Reference
https://math.fontein.de/2009/08/12/the-hasse-derivative/
-/
noncomputable theory
namespace polynomial
open_locale nat big_operators
open function nat (hiding nsmul_eq_mul)
variables {R : Type*} [semiring R] (k : ℕ) (f : polynomial R)
/-- The `k`th Hasse derivative of a polynomial `∑ a_i X^i` is `∑ (i.choose k) a_i X^(i-k)`.
It satisfies `k! * (hasse_deriv k f) = derivative^[k] f`. -/
def hasse_deriv (k : ℕ) : polynomial R →ₗ[R] polynomial R :=
lsum (λ i, (monomial (i-k)) ∘ₗ distrib_mul_action.to_linear_map R R (i.choose k))
lemma hasse_deriv_apply :
hasse_deriv k f = f.sum (λ i r, monomial (i - k) (↑(i.choose k) * r)) :=
by simpa only [← nsmul_eq_mul]
lemma hasse_deriv_coeff (n : ℕ) :
(hasse_deriv k f).coeff n = (n + k).choose k * f.coeff (n + k) :=
begin
rw [hasse_deriv_apply, coeff_sum, sum_def, finset.sum_eq_single (n + k), coeff_monomial],
{ simp only [if_true, add_tsub_cancel_right, eq_self_iff_true], },
{ intros i hi hink,
rw [coeff_monomial],
by_cases hik : i < k,
{ simp only [nat.choose_eq_zero_of_lt hik, if_t_t, nat.cast_zero, zero_mul], },
{ push_neg at hik, rw if_neg, contrapose! hink,
exact (tsub_eq_iff_eq_add_of_le hik).mp hink, } },
{ intro h, simp only [not_mem_support_iff.mp h, monomial_zero_right, mul_zero, coeff_zero] }
end
lemma hasse_deriv_zero' : hasse_deriv 0 f = f :=
by simp only [hasse_deriv_apply, tsub_zero, nat.choose_zero_right,
nat.cast_one, one_mul, sum_monomial_eq]
@[simp] lemma hasse_deriv_zero : @hasse_deriv R _ 0 = linear_map.id :=
linear_map.ext $ hasse_deriv_zero'
lemma hasse_deriv_one' : hasse_deriv 1 f = derivative f :=
by simp only [hasse_deriv_apply, derivative_apply, monomial_eq_C_mul_X, nat.choose_one_right,
(nat.cast_commute _ _).eq]
@[simp] lemma hasse_deriv_one : @hasse_deriv R _ 1 = derivative :=
linear_map.ext $ hasse_deriv_one'
@[simp] lemma hasse_deriv_monomial (n : ℕ) (r : R) :
hasse_deriv k (monomial n r) = monomial (n - k) (↑(n.choose k) * r) :=
begin
ext i,
simp only [hasse_deriv_coeff, coeff_monomial],
by_cases hnik : n = i + k,
{ rw [if_pos hnik, if_pos, ← hnik], apply tsub_eq_of_eq_add_rev, rwa add_comm },
{ rw [if_neg hnik, mul_zero],
by_cases hkn : k ≤ n,
{ rw [← tsub_eq_iff_eq_add_of_le hkn] at hnik, rw [if_neg hnik] },
{ push_neg at hkn, rw [nat.choose_eq_zero_of_lt hkn, nat.cast_zero, zero_mul, if_t_t] } }
end
lemma hasse_deriv_C (r : R) (hk : 0 < k) : hasse_deriv k (C r) = 0 :=
by rw [← monomial_zero_left, hasse_deriv_monomial, nat.choose_eq_zero_of_lt hk,
nat.cast_zero, zero_mul, monomial_zero_right]
lemma hasse_deriv_apply_one (hk : 0 < k) : hasse_deriv k (1 : polynomial R) = 0 :=
by rw [← C_1, hasse_deriv_C k _ hk]
lemma hasse_deriv_X (hk : 1 < k) : hasse_deriv k (X : polynomial R) = 0 :=
by rw [← monomial_one_one_eq_X, hasse_deriv_monomial, nat.choose_eq_zero_of_lt hk,
nat.cast_zero, zero_mul, monomial_zero_right]
lemma factorial_smul_hasse_deriv :
⇑(k! • @hasse_deriv R _ k) = ((@derivative R _)^[k]) :=
begin
induction k with k ih,
{ rw [hasse_deriv_zero, factorial_zero, iterate_zero, one_smul, linear_map.id_coe], },
ext f n : 2,
rw [iterate_succ_apply', ← ih],
simp only [linear_map.smul_apply, coeff_smul, linear_map.map_smul_of_tower, coeff_derivative,
hasse_deriv_coeff, ← @choose_symm_add _ k],
simp only [nsmul_eq_mul, factorial_succ, mul_assoc, succ_eq_add_one, ← add_assoc,
add_right_comm n 1 k, ← cast_succ],
rw ← (cast_commute (n+1) (f.coeff (n + k + 1))).eq,
simp only [← mul_assoc], norm_cast, congr' 2,
apply @cast_injective ℚ,
have h1 : n + 1 ≤ n + k + 1 := succ_le_succ le_self_add,
have h2 : k + 1 ≤ n + k + 1 := succ_le_succ le_add_self,
have H : ∀ (n : ℕ), (n! : ℚ) ≠ 0, { exact_mod_cast factorial_ne_zero },
-- why can't `field_simp` help me here?
simp only [cast_mul, cast_choose ℚ, h1, h2, -one_div, -mul_eq_zero,
succ_sub_succ_eq_sub, add_tsub_cancel_right, add_tsub_cancel_left] with field_simps,
rw [eq_div_iff_mul_eq (mul_ne_zero (H _) (H _)), eq_comm, div_mul_eq_mul_div,
eq_div_iff_mul_eq (mul_ne_zero (H _) (H _))],
norm_cast,
simp only [factorial_succ, succ_eq_add_one], ring,
end
lemma hasse_deriv_comp (k l : ℕ) :
(@hasse_deriv R _ k).comp (hasse_deriv l) = (k+l).choose k • hasse_deriv (k+l) :=
begin
ext i : 2,
simp only [linear_map.smul_apply, comp_app, linear_map.coe_comp, smul_monomial,
hasse_deriv_apply, mul_one, monomial_eq_zero_iff, sum_monomial_index, mul_zero,
← tsub_add_eq_tsub_tsub, add_comm l k],
rw_mod_cast nsmul_eq_mul,
congr' 2,
by_cases hikl : i < k + l,
{ rw [choose_eq_zero_of_lt hikl, mul_zero],
by_cases hil : i < l,
{ rw [choose_eq_zero_of_lt hil, mul_zero] },
{ push_neg at hil, rw [← tsub_lt_iff_right hil] at hikl,
rw [choose_eq_zero_of_lt hikl , zero_mul], }, },
push_neg at hikl, apply @cast_injective ℚ,
have h1 : l ≤ i := nat.le_of_add_le_right hikl,
have h2 : k ≤ i - l := le_tsub_of_add_le_right hikl,
have h3 : k ≤ k + l := le_self_add,
have H : ∀ (n : ℕ), (n! : ℚ) ≠ 0, { exact_mod_cast factorial_ne_zero },
-- why can't `field_simp` help me here?
simp only [cast_mul, cast_choose ℚ, h1, h2, h3, hikl, -one_div, -mul_eq_zero,
succ_sub_succ_eq_sub, add_tsub_cancel_right, add_tsub_cancel_left] with field_simps,
rw [eq_div_iff_mul_eq, eq_comm, div_mul_eq_mul_div, eq_div_iff_mul_eq, ← tsub_add_eq_tsub_tsub,
add_comm l k],
{ ring, },
all_goals { apply_rules [mul_ne_zero, H] }
end
section
open add_monoid_hom finset.nat
lemma hasse_deriv_mul (f g : polynomial R) :
hasse_deriv k (f * g) = ∑ ij in antidiagonal k, hasse_deriv ij.1 f * hasse_deriv ij.2 g :=
begin
let D := λ k, (@hasse_deriv R _ k).to_add_monoid_hom,
let Φ := @add_monoid_hom.mul (polynomial R) _,
show (comp_hom (D k)).comp Φ f g =
∑ (ij : ℕ × ℕ) in antidiagonal k, ((comp_hom.comp ((comp_hom Φ) (D ij.1))).flip (D ij.2) f) g,
simp only [← finset_sum_apply],
congr' 2, clear f g,
ext m r n s : 4,
simp only [finset_sum_apply, coe_mul_left, coe_comp, flip_apply, comp_app,
hasse_deriv_monomial, linear_map.to_add_monoid_hom_coe, comp_hom_apply_apply, coe_mul,
monomial_mul_monomial],
have aux : ∀ (x : ℕ × ℕ), x ∈ antidiagonal k →
monomial (m - x.1 + (n - x.2)) (↑(m.choose x.1) * r * (↑(n.choose x.2) * s)) =
monomial (m + n - k) (↑(m.choose x.1) * ↑(n.choose x.2) * (r * s)),
{ intros x hx, rw [finset.nat.mem_antidiagonal] at hx, subst hx,
by_cases hm : m < x.1,
{ simp only [nat.choose_eq_zero_of_lt hm, nat.cast_zero, zero_mul, monomial_zero_right], },
by_cases hn : n < x.2,
{ simp only [nat.choose_eq_zero_of_lt hn, nat.cast_zero,
zero_mul, mul_zero, monomial_zero_right], },
push_neg at hm hn,
rw [tsub_add_eq_add_tsub hm, ← add_tsub_assoc_of_le hn, ← tsub_add_eq_tsub_tsub,
add_comm x.2 x.1, mul_assoc, ← mul_assoc r, ← (nat.cast_commute _ r).eq, mul_assoc,
mul_assoc], },
conv_rhs { apply_congr, skip, rw aux _ H, },
rw_mod_cast [← linear_map.map_sum, ← finset.sum_mul, ← nat.add_choose_eq],
end
end
end polynomial
|
cac407f48cb0d162bc76f1956d388fc0884675ca | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/topology/separation.lean | d5e01743085d6f8741c4338f1813df615b31f43f | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 15,674 | 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
Separation properties of topological spaces.
-/
import topology.subset_properties
open set filter
open_locale topological_space
local attribute [instance] classical.prop_decidable -- TODO: use "open_locale classical"
universes u v
variables {α : Type u} {β : Type v} [topological_space α]
section separation
/-- A T₀ space, also known as a Kolmogorov space, is a topological space
where for every pair `x ≠ y`, there is an open set containing one but not the other. -/
class t0_space (α : Type u) [topological_space α] : Prop :=
(t0 : ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U)))
theorem exists_open_singleton_of_open_finset [t0_space α] (s : finset α) (sne : s.nonempty)
(hso : is_open (↑s : set α)) :
∃ x ∈ s, is_open ({x} : set α):=
begin
induction s using finset.strong_induction_on with s ihs,
by_cases hs : set.subsingleton (↑s : set α),
{ rcases sne with ⟨x, hx⟩,
refine ⟨x, hx, _⟩,
have : (↑s : set α) = {x}, from hs.eq_singleton_of_mem hx,
rwa this at hso },
{ dunfold set.subsingleton at hs,
push_neg at hs,
rcases hs with ⟨x, hx, y, hy, hxy⟩,
rcases t0_space.t0 x y hxy with ⟨U, hU, hxyU⟩,
wlog H : x ∈ U ∧ y ∉ U := hxyU using [x y, y x],
obtain ⟨z, hzs, hz⟩ : ∃ z ∈ s.filter (λ z, z ∈ U), is_open ({z} : set α),
{ refine ihs _ (finset.filter_ssubset.2 ⟨y, hy, H.2⟩) ⟨x, finset.mem_filter.2 ⟨hx, H.1⟩⟩ _,
rw [finset.coe_filter],
exact is_open_inter hso hU },
exact ⟨z, (finset.mem_filter.1 hzs).1, hz⟩ }
end
theorem exists_open_singleton_of_fintype [t0_space α] [f : fintype α] [ha : nonempty α] :
∃ x:α, is_open ({x}:set α) :=
begin
refine ha.elim (λ x, _),
have : is_open (↑(finset.univ : finset α) : set α), { simp },
rcases exists_open_singleton_of_open_finset _ ⟨x, finset.mem_univ x⟩ this with ⟨x, _, hx⟩,
exact ⟨x, hx⟩
end
instance subtype.t0_space [t0_space α] {p : α → Prop} : t0_space (subtype p) :=
⟨λ x y hxy, let ⟨U, hU, hxyU⟩ := t0_space.t0 (x:α) y ((not_congr subtype.coe_ext).1 hxy) in
⟨(coe : subtype p → α) ⁻¹' U, is_open_induced hU, hxyU⟩⟩
/-- A T₁ space, also known as a Fréchet space, is a topological space
where every singleton set is closed. Equivalently, for every pair
`x ≠ y`, there is an open set containing `x` and not `y`. -/
class t1_space (α : Type u) [topological_space α] : Prop :=
(t1 : ∀x, is_closed ({x} : set α))
lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) :=
t1_space.t1 x
lemma is_open_ne [t1_space α] {x : α} : is_open {y | y ≠ x} :=
compl_singleton_eq x ▸ is_open_compl_iff.2 (t1_space.t1 x)
instance subtype.t1_space {α : Type u} [topological_space α] [t1_space α] {p : α → Prop} :
t1_space (subtype p) :=
⟨λ ⟨x, hx⟩, is_closed_induced_iff.2 $ ⟨{x}, is_closed_singleton, set.ext $ λ y,
by simp [subtype.coe_ext]⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance t1_space.t0_space [t1_space α] : t0_space α :=
⟨λ x y h, ⟨{z | z ≠ y}, is_open_ne, or.inl ⟨h, not_not_intro rfl⟩⟩⟩
lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ 𝓝 y :=
mem_nhds_sets is_closed_singleton $ by rwa [mem_compl_eq, mem_singleton_iff]
@[simp] lemma closure_singleton [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 α] : Prop :=
(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
@[priority 100] -- see Note [lower instance priority]
instance t2_space.t1_space [t2_space α] : t1_space α :=
⟨λ x, is_open_iff_forall_mem_open.2 $ λ y hxy,
let ⟨u, v, hu, hv, hyu, hxv, huv⟩ := t2_separation (mt mem_singleton_of_eq hxy) in
⟨u, λ z hz1 hz2, (ext_iff.1 huv x).1 ⟨mem_singleton_iff.1 hz2 ▸ hz1, hxv⟩, hu, hyu⟩⟩
lemma eq_of_nhds_ne_bot [ht : t2_space α] {x y : α} (h : 𝓝 x ⊓ 𝓝 y ≠ ⊥) : x = y :=
classical.by_contradiction $ assume : x ≠ y,
let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in
absurd huv $ (inf_ne_bot_iff.1 h (mem_nhds_sets hu hx) (mem_nhds_sets hv hy)).ne_empty
lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, 𝓝 x ⊓ 𝓝 y ≠ ⊥ → x = y :=
⟨assume h, by exactI λ x y, eq_of_nhds_ne_bot,
assume h, ⟨assume x y xy,
have 𝓝 x ⊓ 𝓝 y = ⊥ := classical.by_contradiction (mt h xy),
let ⟨u', hu', v', hv', u'v'⟩ := empty_in_sets_eq_bot.mpr this,
⟨u, uu', uo, hu⟩ := mem_nhds_sets_iff.mp hu',
⟨v, vv', vo, hv⟩ := mem_nhds_sets_iff.mp hv' in
⟨u, v, uo, vo, hu, hv, disjoint.eq_bot $ disjoint.mono uu' vv' u'v'⟩⟩⟩
lemma t2_iff_ultrafilter :
t2_space α ↔ ∀ f {x y : α}, is_ultrafilter f → f ≤ 𝓝 x → f ≤ 𝓝 y → x = y :=
t2_iff_nhds.trans
⟨assume h f x y u fx fy, h $ ne_bot_of_le_ne_bot u.1 (le_inf fx fy),
assume h x y xy,
let ⟨f, hf, uf⟩ := exists_ultrafilter xy in
h f uf (le_trans hf inf_le_left) (le_trans hf inf_le_right)⟩
@[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : 𝓝 a = 𝓝 b ↔ a = b :=
⟨assume h, eq_of_nhds_ne_bot $ by rw [h, inf_idem]; exact nhds_ne_bot, assume h, h ▸ rfl⟩
@[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : 𝓝 a ≤ 𝓝 b ↔ a = b :=
⟨assume h, eq_of_nhds_ne_bot $ by rw [inf_of_le_left h]; exact nhds_ne_bot, assume h, h ▸ le_refl _⟩
lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α}
(hl : l ≠ ⊥) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b :=
eq_of_nhds_ne_bot $ ne_bot_of_le_ne_bot (map_ne_bot hl) $ le_inf ha hb
section lim
variables [nonempty α] [t2_space α] {f : filter α}
lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ 𝓝 a) : lim f = a :=
eq_of_nhds_ne_bot $ ne_bot_of_le_ne_bot hf $ le_inf (lim_spec ⟨_, h⟩) h
@[simp] lemma lim_nhds_eq {a : α} : lim (𝓝 a) = a :=
lim_eq nhds_ne_bot (le_refl _)
@[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) :
lim (𝓝 a ⊓ principal s) = a :=
lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left
end lim
@[priority 100] -- see Note [lower instance priority]
instance t2_space_discrete {α : Type*} [topological_space α] [discrete_topology α] : t2_space α :=
{ t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, mem_insert _ _, mem_insert _ _,
eq_empty_iff_forall_not_mem.2 $ by intros z hz;
cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ }
private lemma separated_by_f {α : Type*} {β : Type*}
[tα : topological_space α] [tβ : topological_space β] [t2_space β]
(f : α → β) (hf : tα ≤ tβ.induced f) {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 {α : Type*} {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 {α : Type*} {β : Type*} [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 inf_le_left h₁)
(λ h₂, separated_by_f prod.snd inf_le_right h₂)⟩
instance Pi.t2_space {α : Type*} {β : α → 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) (infi_le _ i) hi⟩
lemma is_closed_diagonal [t2_space α] : is_closed {p:α×α | p.1 = p.2} :=
is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_ne_bot $ assume : 𝓝 a₁ ⊓ 𝓝 a₂ = ⊥, h $
let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ :=
by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in
begin
change t₁ ∈ 𝓝 a₁ at ht₁,
change t₂ ∈ 𝓝 a₂ at ht₂,
rw [nhds_prod_eq, ←empty_in_sets_eq_bot],
apply filter.sets_of_superset,
apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)),
exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩,
show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩
end
variables [topological_space β]
lemma is_closed_eq [t2_space α] {f g : β → α}
(hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} :=
continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal
lemma diagonal_eq_range_diagonal_map {α : Type*} : {p:α×α | p.1 = p.2} = range (λx, (x,x)) :=
ext $ assume p, iff.intro
(assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩)
(assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx)
lemma prod_subset_compl_diagonal_iff_disjoint {α : Type*} {s t : set α} :
set.prod s t ⊆ - {p:α×α | p.1 = p.2} ↔ s ∩ t = ∅ :=
by rw [eq_empty_iff_forall_not_mem, subset_compl_comm,
diagonal_eq_range_diagonal_map, range_subset_iff]; simp
lemma compact_compact_separated [t2_space α] {s t : set α}
(hs : compact s) (ht : compact t) (hst : s ∩ t = ∅) :
∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ :=
by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst;
exact generalized_tube_lemma hs ht is_closed_diagonal hst
lemma closed_of_compact [t2_space α] (s : set α) (hs : compact s) : is_closed s :=
is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx,
let ⟨u, v, uo, vo, su, xv, uv⟩ :=
compact_compact_separated hs (compact_singleton : compact {x})
(by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in
have v ⊆ -s, from
subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)),
⟨v, this, vo, by simpa using xv⟩
lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ compact s) :
locally_compact_space α :=
⟨assume x n hn,
let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in
let ⟨k, kx, kc⟩ := h x in
-- K is compact but not necessarily contained in N.
-- K \ U is again compact and doesn't contain x, so
-- we may find open sets V, W separating x from K \ U.
-- Then K \ W is a compact neighborhood of x contained in U.
let ⟨v, w, vo, wo, xv, kuw, vw⟩ :=
compact_compact_separated compact_singleton (compact_diff kc uo)
(by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in
have wn : -w ∈ 𝓝 x, from
mem_nhds_sets_iff.mpr
⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩,
⟨k - w,
filter.inter_mem_sets kx wn,
subset.trans (diff_subset_comm.mp kuw) un,
compact_diff kc wo⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α :=
locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩)
end separation
section regularity
section prio
set_option default_priority 100 -- see Note [default priority]
/-- 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 t1_space α : Prop :=
(regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ 𝓝 a ⊓ principal t = ⊥)
end prio
lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ 𝓝 a) :
∃t∈(𝓝 a), t ⊆ s ∧ is_closed t :=
let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in
have ∃t, is_open t ∧ -s' ⊆ t ∧ 𝓝 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_eq_bot $ by rwa [compl_compl],
subset.trans (compl_subset_comm.1 ht₂) h₁,
is_closed_compl_iff.mpr ht₁⟩
instance subtype.regular_space [regular_space α] {p : α → Prop} : regular_space (subtype p) :=
⟨begin
intros s a hs ha,
rcases is_closed_induced_iff.1 hs with ⟨s, hs', rfl⟩,
rcases regular_space.regular hs' ha with ⟨t, ht, hst, hat⟩,
refine ⟨coe ⁻¹' t, is_open_induced ht, preimage_mono hst, _⟩,
rw [nhds_induced, ← comap_principal, ← comap_inf, hat, comap_bot]
end⟩
variable (α)
@[priority 100] -- see Note [lower instance priority]
instance regular_space.t2_space [regular_space α] : t2_space α :=
⟨λ x y hxy,
let ⟨s, hs, hys, hxs⟩ := regular_space.regular is_closed_singleton
(mt mem_singleton_iff.1 hxy),
⟨t, hxt, u, hsu, htu⟩ := empty_in_sets_eq_bot.2 hxs,
⟨v, hvt, hv, hxv⟩ := mem_nhds_sets_iff.1 hxt in
⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys,
eq_empty_of_subset_empty $ λ z ⟨hzv, hzs⟩, htu ⟨hvt hzv, hsu hzs⟩⟩⟩
end regularity
section normality
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A T₄ space, also known as a normal space (although this condition sometimes
omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`,
there exist disjoint open sets containing `C` and `D` respectively. -/
class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop :=
(normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t →
∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v)
end prio
theorem normal_separation [normal_space α] (s t : set α)
(H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) :
∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v :=
normal_space.normal s t H1 H2 H3
@[priority 100] -- see Note [lower instance priority]
instance normal_space.regular_space [normal_space α] : regular_space α :=
{ regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation s {x} hs is_closed_singleton
(λ _ ⟨hx, hy⟩, hxs $ set.mem_of_eq_of_mem (set.eq_of_mem_singleton hy).symm hx) in
⟨u, hu, hsu, filter.empty_in_sets_eq_bot.1 $ filter.mem_inf_sets.2
⟨v, mem_nhds_sets hv (set.singleton_subset_iff.1 hxv), u, filter.mem_principal_self u, set.inter_comm u v ▸ huv⟩⟩ }
-- We can't make this an instance because it could cause an instance loop.
lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α :=
begin
refine ⟨assume s t hs ht st, _⟩,
simp only [disjoint_iff],
exact compact_compact_separated hs.compact ht.compact st.eq_bot
end
end normality
|
d6aa748dea0fbb7277cbca7352c1788e73341368 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /src/Lean/Parser/Syntax.lean | 8c5b951255e72ced7ecc418e95529bee1e900160 | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,568 | 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.Parser.Command
import Lean.Parser.Tactic
namespace Lean
namespace Parser
builtin_initialize
registerBuiltinParserAttribute `builtinSyntaxParser `stx LeadingIdentBehavior.both
registerBuiltinDynamicParserAttribute `stxParser `stx
builtin_initialize
registerBuiltinParserAttribute `builtinPrecParser `prec LeadingIdentBehavior.both
registerBuiltinDynamicParserAttribute `precParser `prec
@[inline] def precedenceParser (rbp : Nat := 0) : Parser :=
categoryParser `prec rbp
@[inline] def syntaxParser (rbp : Nat := 0) : Parser :=
categoryParser `stx rbp
def «precedence» := parser! ":" >> precedenceParser maxPrec
def optPrecedence := optional (atomic «precedence»)
namespace Syntax
@[builtinPrecParser] def numPrec := checkPrec maxPrec >> numLit
@[builtinSyntaxParser] def paren := parser! "(" >> many1 syntaxParser >> ")"
@[builtinSyntaxParser] def cat := parser! ident >> optPrecedence
@[builtinSyntaxParser] def unary := parser! ident >> checkNoWsBefore >> "(" >> many1 syntaxParser >> ")"
@[builtinSyntaxParser] def binary := parser! ident >> checkNoWsBefore >> "(" >> many1 syntaxParser >> ", " >> many1 syntaxParser >> ")"
@[builtinSyntaxParser] def sepBy := parser! "sepBy(" >> many1 syntaxParser >> ", " >> strLit >> optional (", " >> many1 syntaxParser) >> optional (", " >> nonReservedSymbol "allowTrailingSep") >> ")"
@[builtinSyntaxParser] def sepBy1 := parser! "sepBy1(" >> many1 syntaxParser >> ", " >> strLit >> optional (", " >> many1 syntaxParser) >> optional (", " >> nonReservedSymbol "allowTrailingSep") >> ")"
@[builtinSyntaxParser] def atom := parser! strLit
@[builtinSyntaxParser] def nonReserved := parser! "&" >> strLit
end Syntax
namespace Term
@[builtinTermParser] def stx.quot : Parser := parser! "`(stx|" >> toggleInsideQuot syntaxParser >> ")"
@[builtinTermParser] def prec.quot : Parser := parser! "`(prec|" >> toggleInsideQuot precedenceParser >> ")"
@[builtinTermParser] def prio.quot : Parser := parser! "`(prio|" >> toggleInsideQuot priorityParser >> ")"
end Term
namespace Command
def namedName := parser! (atomic ("(" >> nonReservedSymbol "name") >> " := " >> ident >> ")")
def optNamedName := optional namedName
def «prefix» := parser! "prefix"
def «infix» := parser! "infix"
def «infixl» := parser! "infixl"
def «infixr» := parser! "infixr"
def «postfix» := parser! "postfix"
def mixfixKind := «prefix» <|> «infix» <|> «infixl» <|> «infixr» <|> «postfix»
@[builtinCommandParser] def «mixfix» := parser! Term.attrKind >> mixfixKind >> optPrecedence >> optNamedName >> optNamedPrio >> ppSpace >> strLit >> darrow >> termParser
-- NOTE: We use `suppressInsideQuot` in the following parsers because quotations inside them are evaluated in the same stage and
-- thus should be ignored when we use `checkInsideQuot` to prepare the next stage for a builtin syntax change
def identPrec := parser! ident >> optPrecedence
def optKind : Parser := optional ("[" >> ident >> "]")
def notationItem := ppSpace >> withAntiquot (mkAntiquot "notationItem" `Lean.Parser.Command.notationItem) (strLit <|> identPrec)
@[builtinCommandParser] def «notation» := parser! Term.attrKind >> "notation" >> optPrecedence >> optNamedName >> optNamedPrio >> many notationItem >> darrow >> termParser
@[builtinCommandParser] def «macro_rules» := suppressInsideQuot (parser! "macro_rules" >> optKind >> Term.matchAlts)
@[builtinCommandParser] def «syntax» := parser! Term.attrKind >> "syntax " >> optPrecedence >> optNamedName >> optNamedPrio >> many1 syntaxParser >> " : " >> ident
@[builtinCommandParser] def syntaxAbbrev := parser! "syntax " >> ident >> " := " >> many1 syntaxParser
@[builtinCommandParser] def syntaxCat := parser! "declare_syntax_cat " >> ident
def macroArgSimple := parser! ident >> checkNoWsBefore "no space before ':'" >> ":" >> syntaxParser maxPrec
def macroArgSymbol := parser! strLit >> optional (atomic <| checkNoWsBefore >> "%" >> checkNoWsBefore >> ident)
def macroArg := macroArgSymbol <|> atomic macroArgSimple
def macroHead := macroArg
def macroTailTactic : Parser := atomic (" : " >> identEq "tactic") >> darrow >> ("`(" >> toggleInsideQuot Tactic.seq1 >> ")" <|> termParser)
def macroTailCommand : Parser := atomic (" : " >> identEq "command") >> darrow >> ("`(" >> toggleInsideQuot (many1Unbox commandParser) >> ")" <|> termParser)
def macroTailDefault : Parser := atomic (" : " >> ident) >> darrow >> (("`(" >> toggleInsideQuot (categoryParserOfStack 2) >> ")") <|> termParser)
def macroTail := macroTailTactic <|> macroTailCommand <|> macroTailDefault
@[builtinCommandParser] def «macro» := parser! suppressInsideQuot (Term.attrKind >> "macro " >> optPrecedence >> optNamedName >> optNamedPrio >> macroHead >> many macroArg >> macroTail)
@[builtinCommandParser] def «elab_rules» := parser! suppressInsideQuot ("elab_rules" >> optKind >> optional (" : " >> ident) >> Term.matchAlts)
def elabHead := macroHead
def elabArg := macroArg
def elabTail := atomic (" : " >> ident >> optional (" <= " >> ident)) >> darrow >> termParser
@[builtinCommandParser] def «elab» := parser! suppressInsideQuot (Term.attrKind >> "elab " >> optPrecedence >> optNamedName >> optNamedPrio >> elabHead >> many elabArg >> elabTail)
end Command
end Parser
end Lean
|
712bc772de34847e58e56199e8a8f108b636dc85 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/logic/equiv/basic.lean | 87e4de06e370c69b57f457447a65b05dc704a7af | [
"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 | 92,280 | 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.fun_like.equiv
import data.option.basic
import data.prod
import data.quot
import data.sigma.basic
import data.sum.basic
import data.subtype
import logic.function.conjugate
import logic.unique
import tactic.norm_cast
import tactic.simps
/-!
# 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
instance {F} [equiv_like F α β] : has_coe_t F (α ≃ β) :=
⟨λ f, { to_fun := f, inv_fun := equiv_like.inv f, left_inv := equiv_like.left_inv f,
right_inv := equiv_like.right_inv f }⟩
/-- `perm α` is the type of bijections from `α` to itself. -/
@[reducible] def equiv.perm (α : Sort*) := equiv α α
namespace equiv
instance : equiv_like (α ≃ β) α β :=
{ coe := to_fun, inv := inv_fun, left_inv := left_inv, right_inv := right_inv,
coe_injective' := λ e₁ e₂ h₁ h₂, by { cases e₁, cases e₂, congr' } }
instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨to_fun⟩
@[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f :=
rfl
/-- The map `coe_fn : (r ≃ s) → (r → s)` is injective. -/
theorem coe_fn_injective : @function.injective (α ≃ β) (α → β) coe_fn := fun_like.coe_injective
protected lemma coe_inj {e₁ e₂ : α ≃ β} : (e₁ : α → β) = e₂ ↔ e₁ = e₂ := fun_like.coe_fn_eq
@[ext] lemma ext {f g : equiv α β} (H : ∀ x, f x = g x) : f = g := fun_like.ext f g H
protected lemma congr_arg {f : equiv α β} {x x' : α} : x = x' → f x = f x' := fun_like.congr_arg f
protected lemma congr_fun {f g : equiv α β} (h : f = g) (x : α) : f x = g x :=
fun_like.congr_fun h x
lemma ext_iff {f g : equiv α β} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff
@[ext] lemma perm.ext {σ τ : equiv.perm α} (H : ∀ x, σ x = τ x) : σ = τ :=
equiv.ext H
protected lemma perm.congr_arg {f : equiv.perm α} {x x' : α} : x = x' → f x = f x' :=
equiv.congr_arg
protected lemma perm.congr_fun {f g : equiv.perm α} (h : f = g) (x : α) : f x = g x :=
equiv.congr_fun h x
lemma perm.ext_iff {σ τ : equiv.perm α} : σ = τ ↔ ∀ x, σ x = τ x :=
ext_iff
/-- Any type is equivalent to itself. -/
@[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩
instance inhabited' : inhabited (α ≃ α) := ⟨equiv.refl α⟩
/-- Inverse of an equivalence `e : α ≃ β`. -/
@[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩
/-- See Note [custom simps projection] -/
def simps.symm_apply (e : α ≃ β) : β → α := e.symm
initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)
/-- 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 := equiv_like.injective e
protected theorem surjective (e : α ≃ β) : surjective e := equiv_like.surjective e
protected theorem bijective (e : α ≃ β) : bijective e := equiv_like.bijective e
protected theorem subsingleton (e : α ≃ β) [subsingleton β] : subsingleton α :=
e.injective.subsingleton
protected theorem subsingleton.symm (e : α ≃ β) [subsingleton α] : subsingleton β :=
e.symm.injective.subsingleton
lemma subsingleton_congr (e : α ≃ β) : subsingleton α ↔ subsingleton β :=
⟨λ h, by exactI e.symm.subsingleton, λ h, by exactI e.subsingleton⟩
instance equiv_subsingleton_cod [subsingleton β] :
subsingleton (α ≃ β) :=
⟨λ f g, equiv.ext $ λ x, subsingleton.elim _ _⟩
instance equiv_subsingleton_dom [subsingleton α] :
subsingleton (α ≃ β) :=
⟨λ f g, equiv.ext $ λ x, @subsingleton.elim _ (equiv.subsingleton.symm f) _ _⟩
instance perm_unique [subsingleton α] : unique (perm α) :=
unique_of_subsingleton (equiv.refl α)
lemma perm.subsingleton_eq_refl [subsingleton α] (e : perm α) :
e = equiv.refl α := subsingleton.elim _ _
/-- Transfer `decidable_eq` across an equivalence. -/
protected def decidable_eq (e : α ≃ β) [decidable_eq β] : decidable_eq α :=
e.injective.decidable_eq
lemma nonempty_congr (e : α ≃ β) : nonempty α ↔ nonempty β :=
nonempty.congr e e.symm
protected lemma nonempty (e : α ≃ β) [nonempty β] : nonempty α :=
e.nonempty_congr.mpr ‹_›
/-- If `α ≃ β` and `β` is inhabited, then so is `α`. -/
protected def inhabited [inhabited β] (e : α ≃ β) : inhabited α :=
⟨e.symm default⟩
/-- If `α ≃ β` and `β` is a singleton type, then so is `α`. -/
protected def unique [unique β] (e : α ≃ β) : unique α :=
e.symm.surjective.unique
/-- Equivalence between equal types. -/
protected def cast {α β : Sort*} (h : α = β) : α ≃ β :=
⟨cast h, cast h.symm, λ x, by { cases h, refl }, λ x, by { cases h, refl }⟩
@[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g :=
rfl
@[simp] theorem coe_refl : ⇑(equiv.refl α) = id := rfl
@[simp] theorem perm.coe_subsingleton {α : Type*} [subsingleton α] (e : perm α) : ⇑(e) = id :=
by rw [perm.subsingleton_eq_refl e, coe_refl]
theorem refl_apply (x : α) : equiv.refl α x = x := rfl
@[simp] theorem coe_trans (f : α ≃ β) (g : β ≃ γ) : ⇑(f.trans g) = g ∘ f := rfl
theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl
@[simp] theorem apply_symm_apply (e : α ≃ β) (x : β) : e (e.symm x) = x :=
e.right_inv x
@[simp] theorem symm_apply_apply (e : α ≃ β) (x : α) : e.symm (e x) = x :=
e.left_inv x
@[simp] theorem symm_comp_self (e : α ≃ β) : e.symm ∘ e = id := funext e.symm_apply_apply
@[simp] theorem self_comp_symm (e : α ≃ β) : e ∘ e.symm = id := funext e.apply_symm_apply
@[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) :
(f.trans g).symm a = f.symm (g.symm a) := rfl
-- The `simp` attribute is needed to make this a `dsimp` lemma.
-- `simp` will always rewrite with `equiv.symm_symm` before this has a chance to fire.
@[simp, nolint simp_nf] theorem symm_symm_apply (f : α ≃ β) (b : α) : f.symm.symm b = f b := rfl
theorem apply_eq_iff_eq (f : α ≃ β) {x y : α} : f x = f y ↔ x = y := equiv_like.apply_eq_iff_eq f
theorem apply_eq_iff_eq_symm_apply {α β : Sort*} (f : α ≃ β) {x : α} {y : β} :
f x = y ↔ x = f.symm y :=
begin
conv_lhs { rw ←apply_symm_apply f y, },
rw apply_eq_iff_eq,
end
@[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl
@[simp] theorem cast_symm {α β} (h : α = β) : (equiv.cast h).symm = equiv.cast h.symm := rfl
@[simp] theorem cast_refl {α} (h : α = α := rfl) : equiv.cast h = equiv.refl α := rfl
@[simp] theorem cast_trans {α β γ} (h : α = β) (h2 : β = γ) :
(equiv.cast h).trans (equiv.cast h2) = equiv.cast (h.trans h2) :=
ext $ λ x, by { substs h h2, refl }
lemma cast_eq_iff_heq {α β} (h : α = β) {a : α} {b : β} : equiv.cast h a = b ↔ a == b :=
by { subst h, simp }
lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y :=
⟨λ H, by simp [H.symm], λ H, by simp [H]⟩
lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x :=
(eq_comm.trans e.symm_apply_eq).trans eq_comm
@[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by { cases e, refl }
@[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by { cases e, refl }
@[simp] theorem refl_symm : (equiv.refl α).symm = equiv.refl α := rfl
@[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by { cases e, refl }
@[simp] theorem symm_trans_self (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext (by simp)
@[simp] theorem self_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
lemma injective_comp (e : α ≃ β) (f : β → γ) : injective (f ∘ e) ↔ injective f :=
equiv_like.injective_comp e f
lemma comp_injective (f : α → β) (e : β ≃ γ) : injective (e ∘ f) ↔ injective f :=
equiv_like.comp_injective f e
lemma surjective_comp (e : α ≃ β) (f : β → γ) : surjective (f ∘ e) ↔ surjective f :=
equiv_like.surjective_comp e f
lemma comp_surjective (f : α → β) (e : β ≃ γ) : surjective (e ∘ f) ↔ surjective f :=
equiv_like.comp_surjective f e
lemma bijective_comp (e : α ≃ β) (f : β → γ) : bijective (f ∘ e) ↔ bijective f :=
equiv_like.bijective_comp e f
lemma comp_bijective (f : α → β) (e : β ≃ γ) : bijective (e ∘ f) ↔ bijective f :=
equiv_like.comp_bijective f e
/-- If `α` is equivalent to `β` and `γ` is equivalent to `δ`, then the type of equivalences `α ≃ γ`
is equivalent to the type of equivalences `β ≃ δ`. -/
def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) :=
⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm,
assume ac, by { ext x, simp }, assume ac, by { ext x, simp } ⟩
@[simp] lemma equiv_congr_refl {α β} :
(equiv.refl α).equiv_congr (equiv.refl β) = equiv.refl (α ≃ β) := by { ext, refl }
@[simp] lemma equiv_congr_symm {δ} (ab : α ≃ β) (cd : γ ≃ δ) :
(ab.equiv_congr cd).symm = ab.symm.equiv_congr cd.symm := by { ext, refl }
@[simp] lemma equiv_congr_trans {δ ε ζ} (ab : α ≃ β) (de : δ ≃ ε) (bc : β ≃ γ) (ef : ε ≃ ζ) :
(ab.equiv_congr de).trans (bc.equiv_congr ef) = (ab.trans bc).equiv_congr (de.trans ef) :=
by { ext, refl }
@[simp] lemma equiv_congr_refl_left {α β γ} (bg : β ≃ γ) (e : α ≃ β) :
(equiv.refl α).equiv_congr bg e = e.trans bg := rfl
@[simp] lemma equiv_congr_refl_right {α β} (ab e : α ≃ β) :
ab.equiv_congr (equiv.refl β) e = ab.symm.trans e := rfl
@[simp] lemma equiv_congr_apply_apply {δ} (ab : α ≃ β) (cd : γ ≃ δ) (e : α ≃ γ) (x) :
ab.equiv_congr cd e x = cd (e (ab.symm x)) := rfl
section perm_congr
variables {α' β' : Type*} (e : α' ≃ β')
/-- If `α` is equivalent to `β`, then `perm α` is equivalent to `perm β`. -/
def perm_congr : perm α' ≃ perm β' :=
equiv_congr e e
lemma perm_congr_def (p : equiv.perm α') :
e.perm_congr p = (e.symm.trans p).trans e := rfl
@[simp] lemma perm_congr_refl :
e.perm_congr (equiv.refl _) = equiv.refl _ :=
by simp [perm_congr_def]
@[simp] lemma perm_congr_symm :
e.perm_congr.symm = e.symm.perm_congr := rfl
@[simp] lemma perm_congr_apply (p : equiv.perm α') (x) :
e.perm_congr p x = e (p (e.symm x)) := rfl
lemma perm_congr_symm_apply (p : equiv.perm β') (x) :
e.perm_congr.symm p x = e.symm (p (e x)) := rfl
lemma perm_congr_trans (p p' : equiv.perm α') :
(e.perm_congr p).trans (e.perm_congr p') = e.perm_congr (p.trans p') :=
by { ext, simp }
end perm_congr
/-- If `α` is an empty type, then it is equivalent to the `empty` type. -/
def equiv_empty (α : Sort u) [is_empty α] : α ≃ empty :=
⟨is_empty_elim, λ e, e.rec _, is_empty_elim, λ e, e.rec _⟩
/-- `α` is equivalent to an empty type iff `α` is empty. -/
def equiv_empty_equiv (α : Sort u) : (α ≃ empty) ≃ is_empty α :=
⟨λ e, function.is_empty e, @equiv_empty α, λ e, ext $ λ x, (e x).elim, λ p, rfl⟩
/-- `false` is equivalent to `empty`. -/
def false_equiv_empty : false ≃ empty :=
equiv_empty _
/-- If `α` is an empty type, then it is equivalent to the `pempty` type in any universe. -/
def {u' v'} equiv_pempty (α : Sort v') [is_empty α] : α ≃ pempty.{u'} :=
⟨is_empty_elim, λ e, e.rec _, is_empty_elim, λ e, e.rec _⟩
/-- `false` is equivalent to `pempty`. -/
def false_equiv_pempty : false ≃ pempty :=
equiv_pempty _
/-- `empty` is equivalent to `pempty`. -/
def empty_equiv_pempty : empty ≃ pempty :=
equiv_pempty _
/-- `pempty` types from any two universes are equivalent. -/
def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} :=
equiv_pempty _
/-- The `Sort` of proofs of a true proposition is equivalent to `punit`. -/
def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit :=
⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩
/-- The `Sort` of proofs of a false proposition is equivalent to `pempty`. -/
def prop_equiv_pempty {p : Prop} (h : ¬p) : p ≃ pempty :=
⟨λ x, absurd x h, λ x, by cases x, λ x, absurd x h, λ x, by cases x⟩
/-- `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⟩
/-- `pprod α β` is equivalent to `α × β` -/
@[simps apply symm_apply]
def pprod_equiv_prod {α β : Type*} : pprod α β ≃ α × β :=
{ to_fun := λ x, (x.1, x.2),
inv_fun := λ x, ⟨x.1, x.2⟩,
left_inv := λ ⟨x, y⟩, rfl,
right_inv := λ ⟨x, y⟩, rfl }
/-- equivalence of propositions is the same as iff -/
def of_iff {P Q : Prop} (h : P ↔ Q) : P ≃ Q :=
{ to_fun := h.mp,
inv_fun := h.mpr,
left_inv := λ x, rfl,
right_inv := λ y, rfl }
/-- If `α₁` is equivalent to `α₂` and `β₁` is equivalent to `β₂`, then the type of maps `α₁ → β₁`
is equivalent to the type of maps `α₂ → β₂`. -/
@[congr, simps apply] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(α₁ → β₁) ≃ (α₂ → β₂) :=
{ to_fun := λ f, e₂ ∘ f ∘ e₁.symm,
inv_fun := λ f, e₂.symm ∘ f ∘ e₁,
left_inv := λ f, funext $ λ x, by simp,
right_inv := λ f, funext $ λ x, by simp }
lemma arrow_congr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*}
(ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) :
arrow_congr ea ec (g ∘ f) = (arrow_congr eb ec g) ∘ (arrow_congr ea eb f) :=
by { ext, simp only [comp, arrow_congr_apply, eb.symm_apply_apply] }
@[simp] lemma arrow_congr_refl {α β : Sort*} :
arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl
@[simp] lemma arrow_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') :=
rfl
@[simp] lemma arrow_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm :=
rfl
/--
A version of `equiv.arrow_congr` in `Type`, rather than `Sort`.
The `equiv_rw` tactic is not able to use the default `Sort` level `equiv.arrow_congr`,
because Lean's universe rules will not unify `?l_1` with `imax (1 ?m_1)`.
-/
@[congr, simps apply]
def arrow_congr' {α₁ β₁ α₂ β₂ : Type*} (hα : α₁ ≃ α₂) (hβ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) :=
equiv.arrow_congr hα hβ
@[simp] lemma arrow_congr'_refl {α β : Type*} :
arrow_congr' (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl
@[simp] lemma arrow_congr'_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Type*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
arrow_congr' (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr' e₁ e₁').trans (arrow_congr' e₂ e₂') :=
rfl
@[simp] lemma arrow_congr'_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(arrow_congr' e₁ e₂).symm = arrow_congr' e₁.symm e₂.symm :=
rfl
/-- Conjugate a map `f : α → α` by an equivalence `α ≃ β`. -/
@[simps apply]
def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrow_congr e e
@[simp] lemma conj_refl : conj (equiv.refl α) = equiv.refl (α → α) := rfl
@[simp] lemma conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl
@[simp] lemma conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) :
(e₁.trans e₂).conj = e₁.conj.trans e₂.conj :=
rfl
-- This should not be a simp lemma as long as `(∘)` is reducible:
-- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using
-- `f₁ := g` and `f₂ := λ x, x`. This causes nontermination.
lemma conj_comp (e : α ≃ β) (f₁ f₂ : α → α) :
e.conj (f₁ ∘ f₂) = (e.conj f₁) ∘ (e.conj f₂) :=
by apply arrow_congr_comp
lemma eq_comp_symm {α β γ} (e : α ≃ β) (f : β → γ) (g : α → γ) :
f = g ∘ e.symm ↔ f ∘ e = g :=
(e.arrow_congr (equiv.refl γ)).symm_apply_eq.symm
lemma comp_symm_eq {α β γ} (e : α ≃ β) (f : β → γ) (g : α → γ) :
g ∘ e.symm = f ↔ g = f ∘ e :=
(e.arrow_congr (equiv.refl γ)).eq_symm_apply.symm
lemma eq_symm_comp {α β γ} (e : α ≃ β) (f : γ → α) (g : γ → β) :
f = e.symm ∘ g ↔ e ∘ f = g :=
((equiv.refl γ).arrow_congr e).eq_symm_apply
lemma symm_comp_eq {α β γ} (e : α ≃ β) (f : γ → α) (g : γ → β) :
e.symm ∘ g = f ↔ g = e ∘ f :=
((equiv.refl γ).arrow_congr e).symm_apply_eq
section binary_op
variables {α₁ β₁ : Type*} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁)
lemma semiconj_conj (f : α₁ → α₁) : semiconj e f (e.conj f) := λ x, by simp
lemma semiconj₂_conj : semiconj₂ e f (e.arrow_congr e.conj f) := λ x y, by simp
instance [is_associative α₁ f] :
is_associative β₁ (e.arrow_congr (e.arrow_congr e) f) :=
(e.semiconj₂_conj f).is_associative_right e.surjective
instance [is_idempotent α₁ f] :
is_idempotent β₁ (e.arrow_congr (e.arrow_congr e) f) :=
(e.semiconj₂_conj f).is_idempotent_right e.surjective
instance [is_left_cancel α₁ f] :
is_left_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) :=
⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_left_cancel.left_cancel _ f _ x y z⟩
instance [is_right_cancel α₁ f] :
is_right_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) :=
⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_right_cancel.right_cancel _ f _ x y z⟩
end binary_op
/-- `punit` sorts in any two universes are equivalent. -/
def punit_equiv_punit : punit.{v} ≃ punit.{w} :=
⟨λ _, punit.star, λ _, punit.star, λ u, by { cases u, refl }, λ u, by { cases u, reflexivity }⟩
section
/-- The sort of maps to `punit.{v}` is equivalent to `punit.{w}`. -/
def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} :=
⟨λ f, punit.star, λ u f, punit.star,
λ f, by { funext x, cases f x, refl }, λ u, by { cases u, reflexivity }⟩
/-- If `α` is `subsingleton` and `a : α`, then the type of dependent functions `Π (i : α), β
i` is equivalent to `β i`. -/
@[simps]
def Pi_subsingleton {α} (β : α → Sort*) [subsingleton α] (a : α) : (Π a', β a') ≃ β a :=
{ to_fun := eval a,
inv_fun := λ x b, cast (congr_arg β $ subsingleton.elim a b) x,
left_inv := λ f, funext $ λ b, by { rw subsingleton.elim b a, reflexivity },
right_inv := λ b, rfl }
/-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/
@[simps { fully_applied := ff }] def fun_unique (α β) [unique α] : (α → β) ≃ β :=
Pi_subsingleton _ default
/-- The sort of maps from `punit` is equivalent to the codomain. -/
def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α :=
fun_unique _ _
/-- The sort of maps from `true` is equivalent to the codomain. -/
def true_arrow_equiv (α : Sort*) : (true → α) ≃ α :=
fun_unique _ _
/-- The sort of maps from a type that `is_empty` is equivalent to `punit`. -/
def arrow_punit_of_is_empty (α β : Sort*) [is_empty α] : (α → β) ≃ punit.{u} :=
⟨λ f, punit.star, λ u, is_empty_elim, λ f, funext is_empty_elim, λ u, by { cases u, refl }⟩
/-- The sort of maps from `empty` is equivalent to `punit`. -/
def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} :=
arrow_punit_of_is_empty _ _
/-- The sort of maps from `pempty` is equivalent to `punit`. -/
def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} :=
arrow_punit_of_is_empty _ _
/-- The sort of maps from `false` is equivalent to `punit`. -/
def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} :=
arrow_punit_of_is_empty _ _
end
/-- Product of two equivalences. If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then `α₁ × β₁ ≃ α₂ × β₂`. -/
@[congr, simps apply]
def prod_congr {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ :=
⟨prod.map e₁ e₂, prod.map e₁.symm e₂.symm, λ ⟨a, b⟩, by simp, λ ⟨a, b⟩, by simp⟩
@[simp] theorem prod_congr_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(prod_congr e₁ e₂).symm = prod_congr e₁.symm e₂.symm :=
rfl
/-- Type product is commutative up to an equivalence: `α × β ≃ β × α`. -/
@[simps apply] def prod_comm (α β : Type*) : α × β ≃ β × α :=
⟨prod.swap, prod.swap, λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩
@[simp] lemma prod_comm_symm (α β) : (prod_comm α β).symm = prod_comm β α := rfl
/-- Type product is associative up to an equivalence. -/
@[simps] def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) :=
⟨λ p, (p.1.1, p.1.2, p.2), λp, ((p.1, p.2.1), p.2.2), λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩
/-- Functions on `α × β` are equivalent to functions `α → β → γ`. -/
@[simps {fully_applied := ff}] def curry (α β γ : Type*) :
(α × β → γ) ≃ (α → β → γ) :=
{ to_fun := curry,
inv_fun := uncurry,
left_inv := uncurry_curry,
right_inv := curry_uncurry }
section
/-- `punit` is a right identity for type product up to an equivalence. -/
@[simps] def prod_punit (α : Type*) : α × punit.{u+1} ≃ α :=
⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩
/-- `punit` is a left identity for type product up to an equivalence. -/
@[simps] def punit_prod (α : Type*) : punit.{u+1} × α ≃ α :=
calc punit × α ≃ α × punit : prod_comm _ _
... ≃ α : prod_punit _
/-- `empty` type is a right absorbing element for type product up to an equivalence. -/
def prod_empty (α : Type*) : α × empty ≃ empty :=
equiv_empty _
/-- `empty` type is a left absorbing element for type product up to an equivalence. -/
def empty_prod (α : Type*) : empty × α ≃ empty :=
equiv_empty _
/-- `pempty` type is a right absorbing element for type product up to an equivalence. -/
def prod_pempty (α : Type*) : α × pempty ≃ pempty :=
equiv_pempty _
/-- `pempty` type is a left absorbing element for type product up to an equivalence. -/
def pempty_prod (α : Type*) : pempty × α ≃ pempty :=
equiv_pempty _
end
section
open sum
/-- `psum` is equivalent to `sum`. -/
def psum_equiv_sum (α β : Type*) : psum α β ≃ α ⊕ β :=
⟨λ s, psum.cases_on s inl inr,
λ s, sum.cases_on s psum.inl psum.inr,
λ s, by cases s; refl,
λ s, by cases s; refl⟩
/-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕ β ≃ α' ⊕ β'`. -/
@[simps apply]
def sum_congr {α₁ β₁ α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ :=
⟨sum.map ea eb, sum.map ea.symm eb.symm, λ x, by simp, λ x, by simp⟩
@[simp] lemma sum_congr_trans {α₁ α₂ β₁ β₂ γ₁ γ₂ : Sort*}
(e : α₁ ≃ β₁) (f : α₂ ≃ β₂) (g : β₁ ≃ γ₁) (h : β₂ ≃ γ₂) :
(equiv.sum_congr e f).trans (equiv.sum_congr g h) = (equiv.sum_congr (e.trans g) (f.trans h)) :=
by { ext i, cases i; refl }
@[simp] lemma sum_congr_symm {α β γ δ : Sort*} (e : α ≃ β) (f : γ ≃ δ) :
(equiv.sum_congr e f).symm = (equiv.sum_congr (e.symm) (f.symm)) :=
rfl
@[simp] lemma sum_congr_refl {α β : Sort*} :
equiv.sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) :=
by { ext i, cases i; refl }
namespace perm
/-- Combine a permutation of `α` and of `β` into a permutation of `α ⊕ β`. -/
@[reducible]
def sum_congr {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) : equiv.perm (α ⊕ β) :=
equiv.sum_congr ea eb
@[simp] lemma sum_congr_apply {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) (x : α ⊕ β) :
sum_congr ea eb x = sum.map ⇑ea ⇑eb x := equiv.sum_congr_apply ea eb x
@[simp] lemma sum_congr_trans {α β : Sort*}
(e : equiv.perm α) (f : equiv.perm β) (g : equiv.perm α) (h : equiv.perm β) :
(sum_congr e f).trans (sum_congr g h) = sum_congr (e.trans g) (f.trans h) :=
equiv.sum_congr_trans e f g h
@[simp] lemma sum_congr_symm {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) :
(sum_congr e f).symm = sum_congr (e.symm) (f.symm) :=
equiv.sum_congr_symm e f
@[simp] lemma sum_congr_refl {α β : Sort*} :
sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) :=
equiv.sum_congr_refl
end perm
/-- `bool` is equivalent the sum of two `punit`s. -/
def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} :=
⟨λ b, cond b (inr punit.star) (inl punit.star),
λ s, sum.rec_on s (λ_, ff) (λ_, tt),
λ b, by cases b; refl,
λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩
/-- `Prop` is noncomputably equivalent to `bool`. -/
noncomputable def Prop_equiv_bool : Prop ≃ bool :=
⟨λ p, @to_bool p (classical.prop_decidable _),
λ b, b, λ p, by simp, λ b, by simp⟩
/-- Sum of types is commutative up to an equivalence. -/
@[simps apply]
def sum_comm (α β : Type*) : α ⊕ β ≃ β ⊕ α :=
⟨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 (α β γ : Type*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) :=
⟨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] lemma sum_assoc_apply_inl_inl {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl
@[simp] lemma sum_assoc_apply_inl_inr {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) :=
rfl
@[simp] lemma sum_assoc_apply_inr {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl
@[simp] lemma sum_assoc_symm_apply_inl {α β γ} (a) : (sum_assoc α β γ).symm (inl a) = inl (inl a) :=
rfl
@[simp] lemma sum_assoc_symm_apply_inr_inl {α β γ} (b) :
(sum_assoc α β γ).symm (inr (inl b)) = inl (inr b) := rfl
@[simp] lemma sum_assoc_symm_apply_inr_inr {α β γ} (c) :
(sum_assoc α β γ).symm (inr (inr c)) = inr c := rfl
/-- Sum with `empty` is equivalent to the original type. -/
@[simps symm_apply] def sum_empty (α β : Type*) [is_empty β] : α ⊕ β ≃ α :=
⟨sum.elim id is_empty_elim,
inl,
λ s, by { rcases s with _ | x, refl, exact is_empty_elim x },
λ a, rfl⟩
@[simp] lemma sum_empty_apply_inl {α β : Type*} [is_empty β] (a : α) :
sum_empty α β (sum.inl a) = a := rfl
/-- The sum of `empty` with any `Sort*` is equivalent to the right summand. -/
@[simps symm_apply] def empty_sum (α β : Type*) [is_empty α] : α ⊕ β ≃ β :=
(sum_comm _ _).trans $ sum_empty _ _
@[simp] lemma empty_sum_apply_inr {α β : Type*} [is_empty α] (b : β) :
empty_sum α β (sum.inr b) = b := rfl
/-- `option α` is equivalent to `α ⊕ punit` -/
def option_equiv_sum_punit (α : Type*) : option α ≃ α ⊕ punit.{u+1} :=
⟨λ o, o.elim (inr punit.star) inl,
λ s, s.elim some (λ _, none),
λ 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 `α`. -/
@[simps] 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 _ _ }
/-- The product over `option α` of `β a` is the binary product of the
product over `α` of `β (some α)` and `β none` -/
@[simps] def pi_option_equiv_prod {α : Type*} {β : option α → Type*} :
(Π a : option α, β a) ≃ (β none × Π a : α, β (some a)) :=
{ to_fun := λ f, (f none, λ a, f (some a)),
inv_fun := λ x a, option.cases_on a x.fst x.snd,
left_inv := λ f, funext $ λ a, by cases a; refl,
right_inv := λ x, by simp }
/-- `α ⊕ β` 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_fiber_equiv f` for `f : α → β` is the natural equivalence between
the type of all fibres of `f` and the total space `α`. -/
-- See also `equiv.sigma_preimage_equiv`.
@[simps]
def sigma_fiber_equiv {α β : Type*} (f : α → β) :
(Σ y : β, {x // f x = y}) ≃ α :=
⟨λ x, ↑x.2, λ x, ⟨f x, x, rfl⟩, λ ⟨y, x, rfl⟩, rfl, λ x, 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 `α`.
See `subtype_or_equiv` for sum types over subtypes `{x // p x}` and `{x // q x}`
that are not necessarily `is_compl p q`. -/
def sum_compl {α : Type*} (p : α → Prop) [decidable_pred p] :
{a // p a} ⊕ {a // ¬ p a} ≃ α :=
{ to_fun := sum.elim coe coe,
inv_fun := λ a, if h : p a then sum.inl ⟨a, h⟩ else sum.inr ⟨a, h⟩,
left_inv := by { rintros (⟨x,hx⟩|⟨x,hx⟩); dsimp; [rw dif_pos, rw dif_neg], },
right_inv := λ a, by { dsimp, split_ifs; refl } }
@[simp] lemma sum_compl_apply_inl {α : Type*} (p : α → Prop) [decidable_pred p]
(x : {a // p a}) :
sum_compl p (sum.inl x) = x := rfl
@[simp] lemma sum_compl_apply_inr {α : Type*} (p : α → Prop) [decidable_pred p]
(x : {a // ¬ p a}) :
sum_compl p (sum.inr x) = x := rfl
@[simp] lemma sum_compl_apply_symm_of_pos {α : Type*} (p : α → Prop) [decidable_pred p]
(a : α) (h : p a) :
(sum_compl p).symm a = sum.inl ⟨a, h⟩ := dif_pos h
@[simp] lemma sum_compl_apply_symm_of_neg {α : Type*} (p : α → Prop) [decidable_pred p]
(a : α) (h : ¬ p a) :
(sum_compl p).symm a = sum.inr ⟨a, h⟩ := dif_neg h
/-- Combines an `equiv` between two subtypes with an `equiv` between their complements to form a
permutation. -/
def subtype_congr {α : Type*} {p q : α → Prop} [decidable_pred p] [decidable_pred q]
(e : {x // p x} ≃ {x // q x}) (f : {x // ¬p x} ≃ {x // ¬q x}) : perm α :=
(sum_compl p).symm.trans ((sum_congr e f).trans
(sum_compl q))
open equiv
variables {ε : Type*} {p : ε → Prop} [decidable_pred p]
variables (ep ep' : perm {a // p a}) (en en' : perm {a // ¬ p a})
/-- Combining permutations on `ε` that permute only inside or outside the subtype
split induced by `p : ε → Prop` constructs a permutation on `ε`. -/
def perm.subtype_congr : equiv.perm ε :=
perm_congr (sum_compl p) (sum_congr ep en)
lemma perm.subtype_congr.apply (a : ε) :
ep.subtype_congr en a = if h : p a then ep ⟨a, h⟩ else en ⟨a, h⟩ :=
by { by_cases h : p a; simp [perm.subtype_congr, h] }
@[simp] lemma perm.subtype_congr.left_apply {a : ε} (h : p a) :
ep.subtype_congr en a = ep ⟨a, h⟩ :=
by simp [perm.subtype_congr.apply, h]
@[simp] lemma perm.subtype_congr.left_apply_subtype (a : {a // p a}) :
ep.subtype_congr en a = ep a :=
by { convert perm.subtype_congr.left_apply _ _ a.property, simp }
@[simp] lemma perm.subtype_congr.right_apply {a : ε} (h : ¬ p a) :
ep.subtype_congr en a = en ⟨a, h⟩ :=
by simp [perm.subtype_congr.apply, h]
@[simp] lemma perm.subtype_congr.right_apply_subtype (a : {a // ¬ p a}) :
ep.subtype_congr en a = en a :=
by { convert perm.subtype_congr.right_apply _ _ a.property, simp }
@[simp] lemma perm.subtype_congr.refl :
perm.subtype_congr (equiv.refl {a // p a}) (equiv.refl {a // ¬ p a}) = equiv.refl ε :=
by { ext x, by_cases h : p x; simp [h] }
@[simp] lemma perm.subtype_congr.symm :
(ep.subtype_congr en).symm = perm.subtype_congr ep.symm en.symm :=
begin
ext x,
by_cases h : p x,
{ have : p (ep.symm ⟨x, h⟩) := subtype.property _,
simp [perm.subtype_congr.apply, h, symm_apply_eq, this] },
{ have : ¬ p (en.symm ⟨x, h⟩) := subtype.property (en.symm _),
simp [perm.subtype_congr.apply, h, symm_apply_eq, this] }
end
@[simp] lemma perm.subtype_congr.trans :
(ep.subtype_congr en).trans (ep'.subtype_congr en') =
perm.subtype_congr (ep.trans ep') (en.trans en') :=
begin
ext x,
by_cases h : p x,
{ have : p (ep ⟨x, h⟩) := subtype.property _,
simp [perm.subtype_congr.apply, h, this] },
{ have : ¬ p (en ⟨x, h⟩) := subtype.property (en _),
simp [perm.subtype_congr.apply, h, symm_apply_eq, this] }
end
end sum_compl
section subtype_preimage
variables (p : α → Prop) [decidable_pred p] (x₀ : {a // p a} → β)
/-- For a fixed function `x₀ : {a // p a} → β` defined on a subtype of `α`,
the subtype of functions `x : α → β` that agree with `x₀` on the subtype `{a // p a}`
is naturally equivalent to the type of functions `{a // ¬ p a} → β`. -/
@[simps]
def subtype_preimage :
{x : α → β // x ∘ coe = x₀} ≃ ({a // ¬ p a} → β) :=
{ to_fun := λ (x : {x : α → β // x ∘ coe = x₀}) a, (x : α → β) a,
inv_fun := λ x, ⟨λ a, if h : p a then x₀ ⟨a, h⟩ else x ⟨a, h⟩,
funext $ λ ⟨a, h⟩, dif_pos h⟩,
left_inv := λ ⟨x, hx⟩, subtype.val_injective $ funext $ λ a,
(by { dsimp, split_ifs; [ rw ← hx, skip ]; refl }),
right_inv := λ x, funext $ λ ⟨a, h⟩,
show dite (p a) _ _ = _, by { dsimp, rw [dif_neg h] } }
lemma subtype_preimage_symm_apply_coe_pos (x : {a // ¬ p a} → β) (a : α) (h : p a) :
((subtype_preimage p x₀).symm x : α → β) a = x₀ ⟨a, h⟩ :=
dif_pos h
lemma subtype_preimage_symm_apply_coe_neg (x : {a // ¬ p a} → β) (a : α) (h : ¬ p a) :
((subtype_preimage p x₀).symm x : α → β) a = x ⟨a, h⟩ :=
dif_neg h
end subtype_preimage
section
/-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Π a, β₁ a` and
`Π a, β₂ a`. -/
def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) :=
⟨λ H a, F a (H a), λ H a, (F a).symm (H a),
λ H, funext $ by simp, λ H, funext $ by simp⟩
/-- Dependent `curry` equivalence: the type of dependent functions on `Σ i, β i` is equivalent
to the type of dependent functions of two arguments (i.e., functions to the space of functions).
This is `sigma.curry` and `sigma.uncurry` together as an equiv. -/
def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) :
(Π x : Σ i, β i, γ x.1 x.2) ≃ (Π a b, γ a b) :=
{ to_fun := sigma.curry,
inv_fun := sigma.uncurry,
left_inv := sigma.uncurry_curry,
right_inv := sigma.curry_uncurry }
end
section
/-- A `psigma`-type is equivalent to the corresponding `sigma`-type. -/
@[simps apply symm_apply] def psigma_equiv_sigma {α} (β : α → Type*) : (Σ' 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 psigma_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 (psigma.mk a) $ symm_apply_apply (F a) b,
λ ⟨a, b⟩, congr_arg (psigma.mk a) $ apply_symm_apply (F a) b⟩
@[simp] lemma psigma_congr_right_trans {α} {β₁ β₂ β₃ : α → Sort*}
(F : Π a, β₁ a ≃ β₂ a) (G : Π a, β₂ a ≃ β₃ a) :
(psigma_congr_right F).trans (psigma_congr_right G) =
psigma_congr_right (λ a, (F a).trans (G a)) :=
by { ext1 x, cases x, refl }
@[simp] lemma psigma_congr_right_symm {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) :
(psigma_congr_right F).symm = psigma_congr_right (λ a, (F a).symm) :=
by { ext1 x, cases x, refl }
@[simp] lemma psigma_congr_right_refl {α} {β : α → Sort*} :
(psigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ' a, β a) :=
by { ext1 x, cases x, refl }
/-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ a, β₁ a` and
`Σ a, β₂ a`. -/
@[simps apply]
def sigma_congr_right {α} {β₁ β₂ : α → Type*} (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 {α} {β₁ β₂ β₃ : α → Type*}
(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 {α} {β₁ β₂ : α → Type*} (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 {α} {β : α → Type*} :
(sigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ a, β a) :=
by { ext1 x, cases x, refl }
/-- A `psigma` with `Prop` fibers is equivalent to the subtype. -/
def psigma_equiv_subtype {α : Type v} (P : α → Prop) :
(Σ' i, P i) ≃ subtype P :=
{ to_fun := λ x, ⟨x.1, x.2⟩,
inv_fun := λ x, ⟨x.1, x.2⟩,
left_inv := λ x, by { cases x, refl, },
right_inv := λ x, by { cases x, refl, }, }
/-- A `sigma` with `plift` fibers is equivalent to the subtype. -/
def sigma_plift_equiv_subtype {α : Type v} (P : α → Prop) :
(Σ i, plift (P i)) ≃ subtype P :=
((psigma_equiv_sigma _).symm.trans (psigma_congr_right (λ a, equiv.plift))).trans
(psigma_equiv_subtype P)
/--
A `sigma` with `λ i, ulift (plift (P i))` fibers is equivalent to `{ x // P x }`.
Variant of `sigma_plift_equiv_subtype`.
-/
def sigma_ulift_plift_equiv_subtype {α : Type v} (P : α → Prop) :
(Σ i, ulift (plift (P i))) ≃ subtype P :=
(sigma_congr_right (λ a, equiv.ulift)).trans (sigma_plift_equiv_subtype P)
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 α β)
/-- Dependent product of types is associative up to an equivalence. -/
def sigma_assoc {α : Type*} {β : α → Type*} (γ : Π (a : α), β a → Type*) :
(Σ (ab : Σ (a : α), β a), γ ab.1 ab.2) ≃ Σ (a : α), (Σ (b : β a), γ a b) :=
{ to_fun := λ x, ⟨x.1.1, ⟨x.1.2, x.2⟩⟩,
inv_fun := λ x, ⟨⟨x.1, x.2.1⟩, x.2.2⟩,
left_inv := λ ⟨⟨a, b⟩, c⟩, rfl,
right_inv := λ ⟨a, ⟨b, c⟩⟩, rfl }
end
section prod_congr
variables {α₁ β₁ β₂ : Type*} (e : α₁ → β₁ ≃ β₂)
/-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence
between `β₁ × α₁` and `β₂ × α₁`. -/
def prod_congr_left : β₁ × α₁ ≃ β₂ × α₁ :=
{ to_fun := λ ab, ⟨e ab.2 ab.1, ab.2⟩,
inv_fun := λ ab, ⟨(e ab.2).symm ab.1, ab.2⟩,
left_inv := by { rintros ⟨a, b⟩, simp },
right_inv := by { rintros ⟨a, b⟩, simp } }
@[simp] lemma prod_congr_left_apply (b : β₁) (a : α₁) :
prod_congr_left e (b, a) = (e a b, a) := rfl
lemma prod_congr_refl_right (e : β₁ ≃ β₂) :
prod_congr e (equiv.refl α₁) = prod_congr_left (λ _, e) :=
by { ext ⟨a, b⟩ : 1, simp }
/-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence
between `α₁ × β₁` and `α₁ × β₂`. -/
def prod_congr_right : α₁ × β₁ ≃ α₁ × β₂ :=
{ to_fun := λ ab, ⟨ab.1, e ab.1 ab.2⟩,
inv_fun := λ ab, ⟨ab.1, (e ab.1).symm ab.2⟩,
left_inv := by { rintros ⟨a, b⟩, simp },
right_inv := by { rintros ⟨a, b⟩, simp } }
@[simp] lemma prod_congr_right_apply (a : α₁) (b : β₁) :
prod_congr_right e (a, b) = (a, e a b) := rfl
lemma prod_congr_refl_left (e : β₁ ≃ β₂) :
prod_congr (equiv.refl α₁) e = prod_congr_right (λ _, e) :=
by { ext ⟨a, b⟩ : 1, simp }
@[simp] lemma prod_congr_left_trans_prod_comm :
(prod_congr_left e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_right e) :=
by { ext ⟨a, b⟩ : 1, simp }
@[simp] lemma prod_congr_right_trans_prod_comm :
(prod_congr_right e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_left e) :=
by { ext ⟨a, b⟩ : 1, simp }
lemma sigma_congr_right_sigma_equiv_prod :
(sigma_congr_right e).trans (sigma_equiv_prod α₁ β₂) =
(sigma_equiv_prod α₁ β₁).trans (prod_congr_right e) :=
by { ext ⟨a, b⟩ : 1, simp }
lemma sigma_equiv_prod_sigma_congr_right :
(sigma_equiv_prod α₁ β₁).symm.trans (sigma_congr_right e) =
(prod_congr_right e).trans (sigma_equiv_prod α₁ β₂).symm :=
by { ext ⟨a, b⟩ : 1, simp }
/-- A family of equivalences between fibers gives an equivalence between domains. -/
-- See also `equiv.of_preimage_equiv`.
@[simps]
def of_fiber_equiv {α β γ : Type*} {f : α → γ} {g : β → γ}
(e : Π c, {a // f a = c} ≃ {b // g b = c}) :
α ≃ β :=
(sigma_fiber_equiv f).symm.trans $ (equiv.sigma_congr_right e).trans (sigma_fiber_equiv g)
lemma of_fiber_equiv_map {α β γ} {f : α → γ} {g : β → γ}
(e : Π c, {a // f a = c} ≃ {b // g b = c}) (a : α) : g (of_fiber_equiv e a) = f a :=
(_ : {b // g b = _}).prop
/-- A variation on `equiv.prod_congr` where the equivalence in the second component can depend
on the first component. A typical example is a shear mapping, explaining the name of this
declaration. -/
@[simps {fully_applied := ff}]
def prod_shear {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : α₁ → β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ :=
{ to_fun := λ x : α₁ × β₁, (e₁ x.1, e₂ x.1 x.2),
inv_fun := λ y : α₂ × β₂, (e₁.symm y.1, (e₂ $ e₁.symm y.1).symm y.2),
left_inv := by { rintro ⟨x₁, y₁⟩, simp only [symm_apply_apply] },
right_inv := by { rintro ⟨x₁, y₁⟩, simp only [apply_symm_apply] } }
end prod_congr
namespace perm
variables {α₁ β₁ β₂ : Type*} [decidable_eq α₁] (a : α₁) (e : perm β₁)
/-- `prod_extend_right a e` extends `e : perm β` to `perm (α × β)` by sending `(a, b)` to
`(a, e b)` and keeping the other `(a', b)` fixed. -/
def prod_extend_right : perm (α₁ × β₁) :=
{ to_fun := λ ab, if ab.fst = a then (a, e ab.snd) else ab,
inv_fun := λ ab, if ab.fst = a then (a, e.symm ab.snd) else ab,
left_inv := by { rintros ⟨k', x⟩, dsimp only, split_ifs with h; simp [h] },
right_inv := by { rintros ⟨k', x⟩, dsimp only, split_ifs with h; simp [h] } }
@[simp] lemma prod_extend_right_apply_eq (b : β₁) :
prod_extend_right a e (a, b) = (a, e b) := if_pos rfl
lemma prod_extend_right_apply_ne {a a' : α₁} (h : a' ≠ a) (b : β₁) :
prod_extend_right a e (a', b) = (a', b) := if_neg h
lemma eq_of_prod_extend_right_ne {e : perm β₁} {a a' : α₁} {b : β₁}
(h : prod_extend_right a e (a', b) ≠ (a', b)) : a' = a :=
by { contrapose! h, exact prod_extend_right_apply_ne _ h _ }
@[simp] lemma fst_prod_extend_right (ab : α₁ × β₁) :
(prod_extend_right a e ab).fst = ab.fst :=
begin
rw [prod_extend_right, coe_fn_mk],
split_ifs with h,
{ rw h },
{ refl }
end
end perm
section
/-- The type of functions to a product `α × β` is equivalent to the type of pairs of functions
`γ → α` and `γ → β`. -/
def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) :=
⟨λ f, (λ c, (f c).1, λ c, (f c).2),
λ p c, (p.1 c, p.2 c),
λ f, funext $ λ c, prod.mk.eta,
λ p, by { cases p, refl }⟩
open sum
/-- The type of functions on a sum type `α ⊕ β` is equivalent to the type of pairs of functions
on `α` and on `β`. -/
def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) :=
⟨λ f, (f ∘ inl, f ∘ inr),
λ p, sum.elim p.1 p.2,
λ f, by { ext ⟨⟩; refl },
λ p, by { cases p, refl }⟩
@[simp] lemma sum_arrow_equiv_prod_arrow_apply_fst {α β γ} (f : (α ⊕ β) → γ) (a : α) :
(sum_arrow_equiv_prod_arrow α β γ f).1 a = f (inl a) := rfl
@[simp] lemma sum_arrow_equiv_prod_arrow_apply_snd {α β γ} (f : (α ⊕ β) → γ) (b : β) :
(sum_arrow_equiv_prod_arrow α β γ f).2 b = f (inr b) := rfl
@[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inl {α β γ} (f : α → γ) (g : β → γ) (a : α) :
((sum_arrow_equiv_prod_arrow α β γ).symm (f, g)) (inl a) = f a := rfl
@[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inr {α β γ} (f : α → γ) (g : β → γ) (b : β) :
((sum_arrow_equiv_prod_arrow α β γ).symm (f, g)) (inr b) = g b := rfl
/-- 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
/-- An indexed sum of disjoint sums of types is equivalent to the sum of the indexed sums. -/
@[simps] def sigma_sum_distrib {ι : Type*} (α β : ι → Type*) :
(Σ i, α i ⊕ β i) ≃ (Σ i, α i) ⊕ Σ i, β i :=
⟨λ p, sum.cases_on p.2 (λ x, sum.inl ⟨_, x⟩) (λ x, sum.inr ⟨_, x⟩),
sum.elim (sigma.map id (λ _, sum.inl)) (sigma.map id (λ _, sum.inr)),
λ p, by { rcases p with ⟨i, (a | b)⟩; refl },
λ p, by { rcases p with (⟨i, a⟩ | ⟨i, b⟩); refl }⟩
/-- 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 }⟩
/-- An equivalence that separates out the 0th fiber of `(Σ (n : ℕ), f n)`. -/
def sigma_nat_succ (f : ℕ → Type u) :
(Σ n, f n) ≃ f 0 ⊕ Σ n, f (n + 1) :=
⟨λ x, @sigma.cases_on ℕ f (λ _, f 0 ⊕ Σ n, f (n + 1)) x (λ n, @nat.cases_on (λ i, f i → (f 0 ⊕
Σ (n : ℕ), f (n + 1))) n (λ (x : f 0), sum.inl x) (λ (n : ℕ) (x : f n.succ), sum.inr ⟨n, x⟩)),
sum.elim (sigma.mk 0) (sigma.map nat.succ (λ _, id)),
by { rintro ⟨(n | n), x⟩; refl }, by { rintro (x | ⟨n, x⟩); 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 `α × α`. -/
@[simps] def bool_arrow_equiv_prod (α : Type u) : (bool → α) ≃ α × α :=
{ to_fun := λ f, (f tt, f ff),
inv_fun := λ p b, cond b p.1 p.2,
left_inv := λ f, funext $ bool.forall_bool.2 ⟨rfl, rfl⟩,
right_inv := λ ⟨x, y⟩, rfl }
end
section
open sum nat
/-- The set of natural numbers is equivalent to `ℕ ⊕ punit`. -/
def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} :=
⟨λ n, match n with zero := inr punit.star | succ a := inl a end,
λ s, match s with inl n := succ n | inr punit.star := zero end,
λ n, begin cases n, repeat { refl } end,
λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩
/-- `ℕ ⊕ punit` is equivalent to `ℕ`. -/
def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ :=
nat_equiv_nat_sum_punit.symm
/-- The type of integer numbers is equivalent to `ℕ ⊕ ℕ`. -/
def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ :=
by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl}
end
/-- An equivalence between `α` and `β` generates an equivalence between `list α` and `list β`. -/
def list_equiv_of_equiv {α β : Type*} (e : α ≃ β) : list α ≃ list β :=
{ to_fun := list.map e,
inv_fun := list.map e.symm,
left_inv := λ l, by rw [list.map_map, e.symm_comp_self, list.map_id],
right_inv := λ l, by rw [list.map_map, e.self_comp_symm, list.map_id] }
/-- `fin n` is equivalent to `{m // m < n}`. -/
def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} :=
⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩
/-- If `α` is equivalent to `β`, then `unique α` is equivalent to `unique β`. -/
def unique_congr (e : α ≃ β) : unique α ≃ unique β :=
{ to_fun := λ h, @equiv.unique _ _ h e.symm,
inv_fun := λ h, @equiv.unique _ _ h e,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
/-- If `α` is equivalent to `β`, then `is_empty α` is equivalent to `is_empty β`. -/
lemma is_empty_congr (e : α ≃ β) : is_empty α ↔ is_empty β :=
⟨λ h, @function.is_empty _ _ h e.symm, λ h, @function.is_empty _ _ h e⟩
protected lemma is_empty (e : α ≃ β) [is_empty β] : is_empty α :=
e.is_empty_congr.mpr ‹_›
section
open subtype
/-- If `α` is equivalent to `β` and the predicates `p : α → Prop` and `q : β → Prop` are equivalent
at corresponding points, then `{a // p a}` is equivalent to `{b // q b}`.
For the statement where `α = β`, that is, `e : perm α`, see `perm.subtype_perm`. -/
def subtype_equiv {p : α → Prop} {q : β → Prop}
(e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} :=
⟨λ x, ⟨e x, (h _).1 x.2⟩,
λ y, ⟨e.symm y, (h _).2 (by { simp, exact y.2 })⟩,
λ ⟨x, h⟩, subtype.ext_val $ by simp,
λ ⟨y, h⟩, subtype.ext_val $ by simp⟩
@[simp] lemma subtype_equiv_refl {p : α → Prop}
(h : ∀ a, p a ↔ p (equiv.refl _ a) := λ a, iff.rfl) :
(equiv.refl α).subtype_equiv h = equiv.refl {a : α // p a} :=
by { ext, refl }
@[simp] lemma subtype_equiv_symm {p : α → Prop} {q : β → Prop} (e : α ≃ β)
(h : ∀ (a : α), p a ↔ q (e a)) :
(e.subtype_equiv h).symm = e.symm.subtype_equiv (λ a, by
{ convert (h $ e.symm a).symm,
exact (e.apply_symm_apply a).symm }) :=
rfl
@[simp] lemma subtype_equiv_trans {p : α → Prop} {q : β → Prop} {r : γ → Prop}
(e : α ≃ β) (f : β ≃ γ)
(h : ∀ (a : α), p a ↔ q (e a)) (h' : ∀ (b : β), q b ↔ r (f b)):
(e.subtype_equiv h).trans (f.subtype_equiv h') =
(e.trans f).subtype_equiv (λ a, (h a).trans (h' $ e a)) :=
rfl
@[simp] lemma subtype_equiv_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β)
(h : ∀ (a : α), p a ↔ q (e a)) (x : {x // p x}) :
e.subtype_equiv h x = ⟨e x, (h _).1 x.2⟩ :=
rfl
/-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to
`{x // q x}`. -/
@[simps]
def subtype_equiv_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : {x // p x} ≃ {x // q x} :=
subtype_equiv (equiv.refl _) e
/-- If `α ≃ β`, then for any predicate `p : β → Prop` the subtype `{a // p (e a)}` is equivalent
to the subtype `{b // p b}`. -/
def subtype_equiv_of_subtype {p : β → Prop} (e : α ≃ β) :
{a : α // p (e a)} ≃ {b : β // p b} :=
subtype_equiv e $ by simp
/-- If `α ≃ β`, then for any predicate `p : α → Prop` the subtype `{a // p a}` is equivalent
to the subtype `{b // p (e.symm b)}`. This version is used by `equiv_rw`. -/
def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) :
{a : α // p a} ≃ {b : β // p (e.symm b)} :=
e.symm.subtype_equiv_of_subtype.symm
/-- If two predicates are equal, then the corresponding subtypes are equivalent. -/
def subtype_equiv_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q :=
subtype_equiv (equiv.refl α) (assume a, h ▸ iff.rfl)
/-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. This
version allows the “inner” predicate to depend on `h : p a`. -/
def subtype_subtype_equiv_subtype_exists {α : Type u} (p : α → Prop) (q : subtype p → Prop) :
subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } :=
⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩,
λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by { cases ha, exact ha_h }⟩,
assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩
@[simp] lemma subtype_subtype_equiv_subtype_exists_apply {α : Type u} (p : α → Prop)
(q : subtype p → Prop) (a) : (subtype_subtype_equiv_subtype_exists p q a : α) = a :=
by { cases a, cases a_val, refl }
/-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. -/
def subtype_subtype_equiv_subtype_inter {α : Type u} (p q : α → Prop) :
{x : subtype p // q x.1} ≃ subtype (λ x, p x ∧ q x) :=
(subtype_subtype_equiv_subtype_exists p _).trans $
subtype_equiv_right $ λ x, exists_prop
@[simp] lemma subtype_subtype_equiv_subtype_inter_apply {α : Type u} (p q : α → Prop) (a) :
(subtype_subtype_equiv_subtype_inter p q a : α) = a :=
by { cases a, cases a_val, refl }
/-- If the outer subtype has more restrictive predicate than the inner one,
then we can drop the latter. -/
def subtype_subtype_equiv_subtype {α : Type u} {p q : α → Prop} (h : ∀ {x}, q x → p x) :
{x : subtype p // q x.1} ≃ subtype q :=
(subtype_subtype_equiv_subtype_inter p _).trans $
subtype_equiv_right $
assume x,
⟨and.right, λ h₁, ⟨h h₁, h₁⟩⟩
@[simp] lemma subtype_subtype_equiv_subtype_apply {α : Type u} {p q : α → Prop} (h : ∀ x, q x → p x)
(a : {x : subtype p // q x.1}) :
(subtype_subtype_equiv_subtype h a : α) = a :=
by { cases a, cases a_val, refl }
/-- If a proposition holds for all elements, then the subtype is
equivalent to the original type. -/
@[simps apply symm_apply]
def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ x, p x) :
subtype p ≃ α :=
⟨λ x, x, λ x, ⟨x, h x⟩, λ x, subtype.eq rfl, λ x, rfl⟩
/-- A subtype of a sigma-type is a sigma-type over a subtype. -/
def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) :
{ y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 :=
⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩,
λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩,
λ ⟨⟨x, h⟩, y⟩, rfl,
λ ⟨⟨x, y⟩, h⟩, rfl⟩
/-- A sigma type over a subtype is equivalent to the sigma set over the original type,
if the fiber is empty outside of the subset -/
def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop)
(h : ∀ x, p x → q x) :
(Σ x : subtype q, p x) ≃ Σ x : α, p x :=
(subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ λ x, h x.1 x.2
/-- If a predicate `p : β → Prop` is true on the range of a map `f : α → β`, then
`Σ y : {y // p y}, {x // f x = y}` is equivalent to `α`. -/
def sigma_subtype_fiber_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_fiber_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_fiber_equiv_subtype {α : Type u} {β : Type v} (f : α → β)
{p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) :
(Σ y : subtype q, {x : α // f x = y}) ≃ subtype p :=
calc (Σ y : subtype q, {x : α // f x = y}) ≃
Σ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} :
begin
apply sigma_congr_right,
assume y,
symmetry,
refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_equiv_right _),
assume x,
exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', λ h', ⟨(h x).2 (h'.symm ▸ y.2), subtype.eq h'⟩⟩
end
... ≃ subtype p : sigma_fiber_equiv (λ x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q))
/-- A sigma type over an `option` is equivalent to the sigma set over the original type,
if the fiber is empty at none. -/
def sigma_option_equiv_of_some {α : Type u} (p : option α → Type v) (h : p none → false) :
(Σ x : option α, p x) ≃ (Σ x : α, p (some x)) :=
begin
have h' : ∀ x, p x → x.is_some,
{ intro x,
cases x,
{ intro n, exfalso, exact h n },
{ intro s, exact rfl } },
exact (sigma_subtype_equiv_of_subset _ _ h').symm.trans
(sigma_congr_left' (option_is_some_equiv α)),
end
/-- The `pi`-type `Π i, π i` is equivalent to the type of sections `f : ι → Σ i, π i` of the
`sigma` type such that for all `i` we have `(f i).fst = i`. -/
def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) :
(Π i, π i) ≃ {f : ι → Σ i, π i // ∀ i, (f i).1 = i } :=
⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end,
assume f, funext $ assume i, rfl,
assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $
eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩
/-- The set of functions `f : Π a, β a` such that for all `a` we have `p a (f a)` is equivalent
to the set of functions `Π a, {b : β a // p a b}`. -/
def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} :
{f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } :=
⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩,
by { rintro ⟨f, h⟩, refl },
by { rintro f, funext a, exact subtype.ext_val rfl }⟩
/-- A subtype of a product defined by componentwise conditions
is equivalent to a product of subtypes. -/
def subtype_prod_equiv_prod {α : Type u} {β : Type v} {p : α → Prop} {q : β → Prop} :
{c : α × β // p c.1 ∧ q c.2} ≃ ({a // p a} × {b // q b}) :=
⟨λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩,
λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩,
λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl,
λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl⟩
/-- A subtype of a `prod` is equivalent to a sigma type whose fibers are subtypes. -/
def subtype_prod_equiv_sigma_subtype {α β : Type*} (p : α → β → Prop) :
{x : α × β // p x.1 x.2} ≃ Σ a, {b : β // p a b} :=
{ to_fun := λ x, ⟨x.1.1, x.1.2, x.prop⟩,
inv_fun := λ x, ⟨⟨x.1, x.2⟩, x.2.prop⟩,
left_inv := λ x, by ext; refl,
right_inv := λ ⟨a, b, pab⟩, rfl }
/-- The type `Π (i : α), β i` can be split as a product by separating the indices in `α`
depending on whether they satisfy a predicate `p` or not. -/
@[simps] def pi_equiv_pi_subtype_prod
{α : Type*} (p : α → Prop) (β : α → Type*) [decidable_pred p] :
(Π (i : α), β i) ≃ (Π (i : {x // p x}), β i) × (Π (i : {x // ¬ p x}), β i) :=
{ to_fun := λ f, (λ x, f x, λ x, f x),
inv_fun := λ f x, if h : p x then f.1 ⟨x, h⟩ else f.2 ⟨x, h⟩,
right_inv := begin
rintros ⟨f, g⟩,
ext1;
{ ext y,
rcases y,
simp only [y_property, dif_pos, dif_neg, not_false_iff, subtype.coe_mk],
refl },
end,
left_inv := λ f, begin
ext x,
by_cases h : p x;
{ simp only [h, dif_neg, dif_pos, not_false_iff],
refl },
end }
end
section subtype_equiv_codomain
variables {X : Type*} {Y : Type*} [decidable_eq X] {x : X}
/-- The type of all functions `X → Y` with prescribed values for all `x' ≠ x`
is equivalent to the codomain `Y`. -/
def subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : {g : X → Y // g ∘ coe = f} ≃ Y :=
(subtype_preimage _ f).trans $
@fun_unique {x' // ¬ x' ≠ x} _ $
show unique {x' // ¬ x' ≠ x}, from @equiv.unique _ _
(show unique {x' // x' = x}, from
{ default := ⟨x, rfl⟩, uniq := λ ⟨x', h⟩, subtype.val_injective h })
(subtype_equiv_right $ λ a, not_not)
@[simp] lemma coe_subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) :
(subtype_equiv_codomain f : {g : X → Y // g ∘ coe = f} → Y) = λ g, (g : X → Y) x := rfl
@[simp] lemma subtype_equiv_codomain_apply (f : {x' // x' ≠ x} → Y)
(g : {g : X → Y // g ∘ coe = f}) :
subtype_equiv_codomain f g = (g : X → Y) x := rfl
lemma coe_subtype_equiv_codomain_symm (f : {x' // x' ≠ x} → Y) :
((subtype_equiv_codomain f).symm : Y → {g : X → Y // g ∘ coe = f}) =
λ y, ⟨λ x', if h : x' ≠ x then f ⟨x', h⟩ else y,
by { funext x', dsimp, erw [dif_pos x'.2, subtype.coe_eta] }⟩ := rfl
@[simp] lemma subtype_equiv_codomain_symm_apply (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) :
((subtype_equiv_codomain f).symm y : X → Y) x' = if h : x' ≠ x then f ⟨x', h⟩ else y :=
rfl
@[simp] lemma subtype_equiv_codomain_symm_apply_eq (f : {x' // x' ≠ x} → Y) (y : Y) :
((subtype_equiv_codomain f).symm y : X → Y) x = y :=
dif_neg (not_not.mpr rfl)
lemma subtype_equiv_codomain_symm_apply_ne (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) (h : x' ≠ x) :
((subtype_equiv_codomain f).symm y : X → Y) x' = f ⟨x', h⟩ :=
dif_pos h
end subtype_equiv_codomain
/-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/
@[simps apply]
noncomputable def of_bijective (f : α → β) (hf : bijective f) : α ≃ β :=
{ to_fun := f,
inv_fun := function.surj_inv hf.surjective,
left_inv := function.left_inverse_surj_inv hf,
right_inv := function.right_inverse_surj_inv _}
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
instance : can_lift (α → β) (α ≃ β) :=
{ coe := coe_fn,
cond := bijective,
prf := λ f hf, ⟨of_bijective f hf, rfl⟩ }
section
variables {α' β' : Type*} (e : perm α') {p : β' → Prop} [decidable_pred p]
(f : α' ≃ subtype p)
/--
Extend the domain of `e : equiv.perm α` to one that is over `β` via `f : α → subtype p`,
where `p : β → Prop`, permuting only the `b : β` that satisfy `p b`.
This can be used to extend the domain across a function `f : α → β`,
keeping everything outside of `set.range f` fixed. For this use-case `equiv` given by `f` can
be constructed by `equiv.of_left_inverse'` or `equiv.of_left_inverse` when there is a known
inverse, or `equiv.of_injective` in the general case.`.
-/
def perm.extend_domain : perm β' :=
(perm_congr f e).subtype_congr (equiv.refl _)
@[simp] lemma perm.extend_domain_apply_image (a : α') :
e.extend_domain f (f a) = f (e a) :=
by simp [perm.extend_domain]
lemma perm.extend_domain_apply_subtype {b : β'} (h : p b) :
e.extend_domain f b = f (e (f.symm ⟨b, h⟩)) :=
by simp [perm.extend_domain, h]
lemma perm.extend_domain_apply_not_subtype {b : β'} (h : ¬ p b) :
e.extend_domain f b = b :=
by simp [perm.extend_domain, h]
@[simp] lemma perm.extend_domain_refl : perm.extend_domain (equiv.refl _) f = equiv.refl _ :=
by simp [perm.extend_domain]
@[simp] lemma perm.extend_domain_symm :
(e.extend_domain f).symm = perm.extend_domain e.symm f := rfl
lemma perm.extend_domain_trans (e e' : perm α') :
(e.extend_domain f).trans (e'.extend_domain f) = perm.extend_domain (e.trans e') f :=
by simp [perm.extend_domain, perm_congr_trans]
end
/-- Subtype of the quotient is equivalent to the quotient of the subtype. Let `α` be a setoid with
equivalence relation `~`. Let `p₂` be a predicate on the quotient type `α/~`, and `p₁` be the lift
of this predicate to `α`: `p₁ a ↔ p₂ ⟦a⟧`. Let `~₂` be the restriction of `~` to `{x // p₁ x}`.
Then `{x // p₂ x}` is equivalent to the quotient of `{x // p₁ x}` by `~₂`. -/
def subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α]
[s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧)
(h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) :
{x // p₂ x} ≃ quotient s₂ :=
{ to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧)
(λ a b hab, hfunext (by rw quotient.sound hab)
(λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2,
inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x}))
(λ a b hab, subtype.ext_val (quotient.sound ((h _ _).1 hab))),
left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha,
right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) }
@[simp] lemma subtype_quotient_equiv_quotient_subtype_mk (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 hx) :
subtype_quotient_equiv_quotient_subtype p₁ p₂ hp₂ h ⟨⟦x⟧, hx⟩ = ⟦⟨x, (hp₂ _).2 hx⟩⟧ := rfl
@[simp] lemma subtype_quotient_equiv_quotient_subtype_symm_mk (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) :
(subtype_quotient_equiv_quotient_subtype p₁ p₂ hp₂ h).symm ⟦x⟧ = ⟨⟦x⟧, (hp₂ _).1 x.prop⟩ := rfl
section swap
variable [decidable_eq α]
/-- A helper function for `equiv.swap`. -/
def swap_core (a b r : α) : α :=
if r = a then b
else if r = b then a
else r
theorem swap_core_self (r a : α) : swap_core a a r = r :=
by { unfold swap_core, split_ifs; cc }
theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r :=
by { unfold swap_core, split_ifs; cc }
theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r :=
by { unfold swap_core, split_ifs; cc }
/-- `swap a b` is the permutation that swaps `a` and `b` and
leaves other values as is. -/
def swap (a b : α) : perm α :=
⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩
@[simp] theorem swap_self (a : α) : swap a a = equiv.refl _ :=
ext $ λ r, swap_core_self r a
theorem swap_comm (a b : α) : swap a b = swap b a :=
ext $ λ r, swap_core_comm r _ _
theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x :=
rfl
@[simp] theorem swap_apply_left (a b : α) : swap a b a = b :=
if_pos rfl
@[simp] theorem swap_apply_right (a b : α) : swap a b b = a :=
by { by_cases h : b = a; simp [swap_apply_def, h], }
theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x :=
by simp [swap_apply_def] {contextual := tt}
@[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ :=
ext $ λ x, swap_core_swap_core _ _ _
@[simp] lemma symm_swap (a b : α) : (swap a b).symm = swap a b := rfl
@[simp] lemma swap_eq_refl_iff {x y : α} : swap x y = equiv.refl _ ↔ x = y :=
begin
refine ⟨λ h, (equiv.refl _).injective _, λ h, h ▸ (swap_self _)⟩,
rw [←h, swap_apply_left, h, refl_apply]
end
theorem swap_comp_apply {a b x : α} (π : perm α) :
π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x :=
by { cases π, refl }
lemma swap_eq_update (i j : α) :
(equiv.swap i j : α → α) = update (update id j i) i j :=
funext $ λ x, by rw [update_apply _ i j, update_apply _ j i, equiv.swap_apply_def, id.def]
lemma comp_swap_eq_update (i j : α) (f : α → β) :
f ∘ equiv.swap i j = update (update f j (f i)) i (f j) :=
by rw [swap_eq_update, comp_update, comp_update, comp.right_id]
@[simp] lemma symm_trans_swap_trans [decidable_eq β] (a b : α) (e : α ≃ β) :
(e.symm.trans (swap a b)).trans e = swap (e a) (e b) :=
equiv.ext (λ x, begin
have : ∀ a, e.symm x = a ↔ x = e a :=
λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * },
simp [swap_apply_def, this],
split_ifs; simp
end)
@[simp] lemma trans_swap_trans_symm [decidable_eq β] (a b : β)
(e : α ≃ β) : (e.trans (swap a b)).trans e.symm = swap (e.symm a) (e.symm b) :=
symm_trans_swap_trans a b e.symm
@[simp] lemma swap_apply_self (i j a : α) :
swap i j (swap i j a) = a :=
by rw [← equiv.trans_apply, equiv.swap_swap, equiv.refl_apply]
/-- A function is invariant to a swap if it is equal at both elements -/
lemma apply_swap_eq_self {v : α → β} {i j : α} (hv : v i = v j) (k : α) : v (swap i j k) = v k :=
begin
by_cases hi : k = i, { rw [hi, swap_apply_left, hv] },
by_cases hj : k = j, { rw [hj, swap_apply_right, hv] },
rw swap_apply_of_ne_of_ne hi hj,
end
lemma swap_apply_eq_iff {x y z w : α} :
swap x y z = w ↔ z = swap x y w :=
by rw [apply_eq_iff_eq_symm_apply, symm_swap]
lemma swap_apply_ne_self_iff {a b x : α} : swap a b x ≠ x ↔ a ≠ b ∧ (x = a ∨ x = b) :=
begin
by_cases hab : a = b,
{ simp [hab] },
by_cases hax : x = a,
{ simp [hax, eq_comm] },
by_cases hbx : x = b,
{ simp [hbx] },
simp [hab, hax, hbx, swap_apply_of_ne_of_ne]
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
end equiv
namespace function.involutive
/-- Convert an involutive function `f` to a permutation with `to_fun = inv_fun = f`. -/
def to_perm (f : α → α) (h : involutive f) : equiv.perm α :=
⟨f, f, h.left_inverse, h.right_inverse⟩
@[simp] lemma coe_to_perm {f : α → α} (h : involutive f) : (h.to_perm f : α → α) = f := rfl
@[simp] lemma to_perm_symm {f : α → α} (h : involutive f) : (h.to_perm f).symm = h.to_perm f := rfl
lemma to_perm_involutive {f : α → α} (h : involutive f) : involutive (h.to_perm f) := h
end function.involutive
lemma plift.eq_up_iff_down_eq {x : plift α} {y : α} : x = plift.up y ↔ x.down = y :=
equiv.plift.eq_symm_apply
lemma function.injective.map_swap {α β : Type*} [decidable_eq α] [decidable_eq β]
{f : α → β} (hf : function.injective f) (x y z : α) :
f (equiv.swap x y z) = equiv.swap (f x) (f y) (f z) :=
begin
conv_rhs { rw equiv.swap_apply_def },
split_ifs with h₁ h₂,
{ rw [hf h₁, equiv.swap_apply_left] },
{ rw [hf h₂, equiv.swap_apply_right] },
{ rw [equiv.swap_apply_of_ne_of_ne (mt (congr_arg f) h₁) (mt (congr_arg f) h₂)] }
end
namespace equiv
protected lemma exists_unique_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β)
(h : ∀{x}, p x ↔ q (f x)) : (∃! x, p x) ↔ ∃! y, q y :=
begin
split,
{ rintro ⟨a, ha₁, ha₂⟩,
exact ⟨f a, h.1 ha₁, λ b hb, f.symm_apply_eq.1 (ha₂ (f.symm b) (h.2 (by simpa using hb)))⟩ },
{ rintro ⟨b, hb₁, hb₂⟩,
exact ⟨f.symm b, h.2 (by simpa using hb₁), λ y hy, (eq_symm_apply f).2 (hb₂ _ (h.1 hy))⟩ }
end
protected lemma exists_unique_congr_left' {p : α → Prop} (f : α ≃ β) :
(∃! x, p x) ↔ (∃! y, p (f.symm y)) :=
equiv.exists_unique_congr f (λx, by simp)
protected lemma exists_unique_congr_left {p : β → Prop} (f : α ≃ β) :
(∃! x, p (f x)) ↔ (∃! y, p y) :=
(equiv.exists_unique_congr_left' f.symm).symm
protected lemma forall_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β)
(h : ∀{x}, p x ↔ q (f x)) : (∀x, p x) ↔ (∀y, q y) :=
begin
split; intros h₂ x,
{ rw [←f.right_inv x], apply h.mp, apply h₂ },
apply h.mpr, apply h₂
end
protected lemma forall_congr' {p : α → Prop} {q : β → Prop} (f : α ≃ β)
(h : ∀{x}, p (f.symm x) ↔ q x) : (∀x, p x) ↔ (∀y, q y) :=
(equiv.forall_congr f.symm (λ x, h.symm)).symm
-- We next build some higher arity versions of `equiv.forall_congr`.
-- Although they appear to just be repeated applications of `equiv.forall_congr`,
-- unification of metavariables works better with these versions.
-- In particular, they are necessary in `equiv_rw`.
-- (Stopping at ternary functions seems reasonable: at least in 1-categorical mathematics,
-- it's rare to have axioms involving more than 3 elements at once.)
universes ua1 ua2 ub1 ub2 ug1 ug2
variables {α₁ : Sort ua1} {α₂ : Sort ua2}
{β₁ : Sort ub1} {β₂ : Sort ub2}
{γ₁ : Sort ug1} {γ₂ : Sort ug2}
protected lemma forall₂_congr {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂)
(eβ : β₁ ≃ β₂) (h : ∀{x y}, p x y ↔ q (eα x) (eβ y)) :
(∀x y, p x y) ↔ (∀x y, q x y) :=
begin
apply equiv.forall_congr,
intros,
apply equiv.forall_congr,
intros,
apply h,
end
protected lemma forall₂_congr' {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂)
(eβ : β₁ ≃ β₂) (h : ∀{x y}, p (eα.symm x) (eβ.symm y) ↔ q x y) :
(∀x y, p x y) ↔ (∀x y, q x y) :=
(equiv.forall₂_congr eα.symm eβ.symm (λ x y, h.symm)).symm
protected lemma forall₃_congr {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop}
(eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂)
(h : ∀{x y z}, p x y z ↔ q (eα x) (eβ y) (eγ z)) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) :=
begin
apply equiv.forall₂_congr,
intros,
apply equiv.forall_congr,
intros,
apply h,
end
protected lemma forall₃_congr' {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop}
(eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂)
(h : ∀{x y z}, p (eα.symm x) (eβ.symm y) (eγ.symm z) ↔ q x y z) :
(∀x y z, p x y z) ↔ (∀x y z, q x y z) :=
(equiv.forall₃_congr eα.symm eβ.symm eγ.symm (λ x y z, h.symm)).symm
protected lemma forall_congr_left' {p : α → Prop} (f : α ≃ β) :
(∀x, p x) ↔ (∀y, p (f.symm y)) :=
equiv.forall_congr f (λx, by simp)
protected lemma forall_congr_left {p : β → Prop} (f : α ≃ β) :
(∀x, p (f x)) ↔ (∀y, p y) :=
(equiv.forall_congr_left' f.symm).symm
protected lemma exists_congr_left {α β} (f : α ≃ β) {p : α → Prop} :
(∃ a, p a) ↔ (∃ b, p (f.symm b)) :=
⟨λ ⟨a, h⟩, ⟨f a, by simpa using h⟩, λ ⟨b, h⟩, ⟨_, h⟩⟩
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₁)
@[simp] lemma coe_Pi_congr_symm :
((h₁.Pi_congr h₂).symm : (Π b, Z b) → (Π a, W a)) = λ f a, (h₂ a).symm (f (h₁ a)) :=
rfl
lemma Pi_congr_symm_apply (f : Π b, Z b) :
(h₁.Pi_congr h₂).symm f = λ a, (h₂ a).symm (f (h₁ a)) :=
rfl
@[simp] lemma Pi_congr_apply_apply (f : Π a, W a) (a : α) :
h₁.Pi_congr h₂ f (h₁ a) = h₂ a (f a) :=
begin
change cast _ ((h₂ (h₁.symm (h₁ a))) (f (h₁.symm (h₁ a)))) = (h₂ a) (f a),
generalize_proofs hZa,
revert hZa,
rw h₁.symm_apply_apply a,
simp,
end
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
@[simp] lemma coe_Pi_congr' :
(h₁.Pi_congr' h₂ : (Π a, W a) → (Π b, Z b)) = λ f b, h₂ b $ f $ h₁.symm b :=
rfl
lemma Pi_congr'_apply (f : Π a, W a) :
h₁.Pi_congr' h₂ f = λ b, h₂ b $ f $ h₁.symm b :=
rfl
@[simp] lemma Pi_congr'_symm_apply_symm_apply (f : Π b, Z b) (b : β) :
(h₁.Pi_congr' h₂).symm f (h₁.symm b) = (h₂ b).symm (f b) :=
begin
change cast _ ((h₂ (h₁ (h₁.symm b))).symm (f (h₁ (h₁.symm b)))) = (h₂ b).symm (f b),
generalize_proofs hWb,
revert hWb,
generalize hb : h₁ (h₁.symm b) = b',
rw h₁.apply_symm_apply b at hb,
subst hb,
simp,
end
end
end equiv
lemma function.injective.swap_apply [decidable_eq α] [decidable_eq β] {f : α → β}
(hf : function.injective f) (x y z : α) :
equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) :=
begin
by_cases hx : z = x, by simp [hx],
by_cases hy : z = y, by simp [hy],
rw [equiv.swap_apply_of_ne_of_ne hx hy, equiv.swap_apply_of_ne_of_ne (hf.ne hx) (hf.ne hy)]
end
lemma function.injective.swap_comp [decidable_eq α] [decidable_eq β] {f : α → β}
(hf : function.injective f) (x y : α) :
equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y :=
funext $ λ z, hf.swap_apply _ _ _
/-- If both `α` and `β` are singletons, then `α ≃ β`. -/
def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β :=
{ to_fun := λ _, default,
inv_fun := λ _, default,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
/-- If `α` is a singleton, then it is equivalent to any `punit`. -/
def equiv_punit_of_unique [unique α] : α ≃ punit.{v} :=
equiv_of_unique_of_unique
/-- If `α` is a subsingleton, then it is equivalent to `α × α`. -/
def subsingleton_prod_self_equiv {α : Type*} [subsingleton α] : α × α ≃ α :=
{ to_fun := λ p, p.1,
inv_fun := λ a, (a, a),
left_inv := λ p, subsingleton.elim _ _,
right_inv := λ p, subsingleton.elim _ _, }
/-- To give an equivalence between two subsingleton types, it is sufficient to give any two
functions between them. -/
def equiv_of_subsingleton_of_subsingleton [subsingleton α] [subsingleton β]
(f : α → β) (g : β → α) : α ≃ β :=
{ to_fun := f,
inv_fun := g,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
/-- A nonempty subsingleton type is (noncomputably) equivalent to `punit`. -/
noncomputable
def equiv.punit_of_nonempty_of_subsingleton {α : Sort*} [h : nonempty α] [subsingleton α] :
α ≃ punit.{v} :=
equiv_of_subsingleton_of_subsingleton
(λ _, punit.star) (λ _, h.some)
/-- `unique (unique α)` is equivalent to `unique α`. -/
def unique_unique_equiv : unique (unique α) ≃ unique α :=
equiv_of_subsingleton_of_subsingleton (λ h, h.default)
(λ h, { default := h, uniq := λ _, subsingleton.elim _ _ })
namespace quot
/-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces,
if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/
protected def congr {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β)
(eq : ∀a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) :
quot ra ≃ quot rb :=
{ to_fun := quot.map e (assume a₁ a₂, (eq a₁ a₂).1),
inv_fun := quot.map e.symm
(assume b₁ b₂ h,
(eq (e.symm b₁) (e.symm b₂)).2
((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)),
left_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.symm_apply_apply] },
right_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.apply_symm_apply] } }
@[simp]
lemma congr_mk {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β)
(eq : ∀ (a₁ a₂ : α), ra a₁ a₂ ↔ rb (e a₁) (e a₂)) (a : α) :
quot.congr e eq (quot.mk ra a) = quot.mk rb (e a) := rfl
/-- 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
@[simp]
lemma congr_mk {ra : setoid α} {rb : setoid β} (e : α ≃ β)
(eq : ∀ (a₁ a₂ : α), setoid.r a₁ a₂ ↔ setoid.r (e a₁) (e a₂)) (a : α):
quotient.congr e eq (quotient.mk a) = quotient.mk (e a) :=
rfl
/-- 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
namespace function
lemma update_comp_equiv {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α)
(a : α) (v : β) :
update f a v ∘ g = update (f ∘ g) (g.symm a) v :=
by rw [← update_comp_eq_of_injective _ g.injective, g.apply_symm_apply]
lemma update_apply_equiv_apply {α β α' : Sort*} [decidable_eq α'] [decidable_eq α]
(f : α → β) (g : α' ≃ α) (a : α) (v : β) (a' : α') :
update f a v (g a') = update (f ∘ g) (g.symm a) v a' :=
congr_fun (update_comp_equiv f g a v) a'
lemma Pi_congr_left'_update [decidable_eq α] [decidable_eq β]
(P : α → Sort*) (e : α ≃ β) (f : Π a, P a) (b : β) (x : P (e.symm b)) :
e.Pi_congr_left' P (update f (e.symm b) x) = update (e.Pi_congr_left' P f) b x :=
begin
ext b',
rcases eq_or_ne b' b with rfl | h,
{ simp, },
{ simp [h], },
end
lemma Pi_congr_left'_symm_update [decidable_eq α] [decidable_eq β]
(P : α → Sort*) (e : α ≃ β) (f : Π b, P (e.symm b)) (b : β) (x : P (e.symm b)) :
(e.Pi_congr_left' P).symm (update f b x) = update ((e.Pi_congr_left' P).symm f) (e.symm b) x :=
by simp [(e.Pi_congr_left' P).symm_apply_eq, Pi_congr_left'_update]
end function
|
83a1d5e7a317a96d8a2a799646c21ccbcbf927fa | 0408d6ea582e97d5cc55ac8a0980d26df896ce66 | /src/norm_cast.lean | cb03e5006e3d933f920bb18b8c566555d5307bfd | [] | no_license | lean-forward/coe_tactic | bba94535c7fb6ef65fcd81bedc28062b238a1594 | d5c30df244c3402de6323a538e99b5324779a2cb | refs/heads/master | 1,588,474,971,049 | 1,557,135,293,000 | 1,557,135,293,000 | 178,387,237 | 1 | 0 | null | 1,556,542,286,000 | 1,553,856,413,000 | Lean | UTF-8 | Lean | false | false | 14,595 | lean | /-
Copyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Paul-Nicolas Madelaine
Normalizing casts in arithmetic expressions.
-/
import tactic.basic tactic.interactive tactic.converter.interactive
import data.complex.basic data.nat.enat
namespace tactic
/-
This is a work around to the fact that in some cases
mk_instance times out instead of failing
example: has_lift_t ℤ ℕ
mk_instance' is used when we assume the type class search
should end instantly
-/
meta def mk_instance' (e : expr) : tactic expr :=
try_for 1000 (mk_instance e)
end tactic
namespace norm_cast
open tactic expr
private meta def new_name : name → name
| name.anonymous := name.mk_string "norm_cast" name.anonymous
| (name.mk_string s n) := name.mk_string s (new_name n)
| (name.mk_numeral i n) := name.mk_numeral i (new_name n)
/-
let ty an expression of the shape Π (x1 : t1) ... (x2 : tn), a = b
let e an expression of type ty
then flip_equation ty returns a couple (new_ty, f) such that
new_ty = Π A1 .. An, b = a
f e = λ (x1 : t1) ... (xn : tn), eq.symm (e x1 ... xn)
if ty is not of the correct shape, then the tactic fails
-/
private meta def flip_equation : expr → tactic (expr × (expr → expr))
| (pi n bi d b) := do
(ty, f) ← flip_equation $ instantiate_var b (local_const n n bi d),
return $ (
pi n bi d $ abstract_local ty n,
λ e, lam n bi d $ abstract_local ( f $ e (local_const n n bi d) ) n
)
| ty := do
`(%%a = %%b) ← return ty | failure,
α ← infer_type a,
symm ← to_expr ``(@eq.symm %%α %%a %%b),
new_ty ← to_expr ``(%%b = %%a),
return (new_ty, symm)
private meta def after_set (decl : name) (prio : ℕ) (pers : bool) : tactic unit :=
do
(declaration.thm n l ty task_e) ← get_decl decl | failed,
let new_n := new_name n,
( do
/-
equation lemmas have to be flipped before
being added to the set of norm_cast lemmas
-/
(new_ty, f) ← flip_equation ty,
let task_new_e := task.map f task_e,
add_decl (declaration.thm new_n l new_ty task_new_e)
) <|> ( do
add_decl (declaration.thm new_n l ty task_e)
)
private meta def mk_cache : list name → tactic simp_lemmas :=
monad.foldl (λ s, s.add_simp ∘ new_name) simp_lemmas.mk
/--
This is an attribute for simplification rules that are going to be
used to normalize casts.
Equation lemmas are compositional lemmas of the shape
Π ..., ↑(P a1 ... an) = P ↑a1 ... ↑an
Equivalence lemmas are of the shape
Π ..., P ↑a ↑b ↔ P a b
Note that the goal of normalization is to move casts "upwards" in the
expression, but compositional rules are written in a "downwards"
fashion.
-/
@[user_attribute]
meta def norm_cast_attr : user_attribute simp_lemmas :=
{
name := `norm_cast,
descr := "attribute for cast normalization",
after_set := some after_set,
cache_cfg := {
mk_cache := mk_cache,
dependencies := [],
}
}
/--
This is an attribute given to the lemmas of the shape
Π ..., ↑↑a = ↑a or Π ..., ↑a = a
They are used in a heuristic to infer intermediate casts.
-/
@[user_attribute]
meta def simp_cast_attr : user_attribute simp_lemmas :=
{
name := `simp_cast,
descr := "attribute for cast simplification",
after_set := none,
cache_cfg := {
mk_cache := monad.foldl simp_lemmas.add_simp simp_lemmas.mk,
dependencies := [],
}
}
/-
This is an auxiliary function that proves e = new_e
using only simp_cast lemmas
-/
private meta def aux_simp (e new_e : expr) : tactic expr :=
do
s ← simp_cast_attr.get_cache,
(e', pr) ← s.rewrite new_e,
is_def_eq e e',
mk_eq_symm pr
/-
This is the main heuristic used alongside the norm_cast lemmas.
An expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ)
is rewritten as: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ)
when the simp_cast lemmas can prove that (↑(x : α) : γ) = (↑(↑(x : α) : β) : γ)
-/
private meta def heur (_ : unit) (e : expr) : tactic (unit × expr × expr) :=
match e with
| (app (expr.app op x) y) :=
do
`(@coe %%α %%δ %%coe1 %%xx) ← return x,
`(@coe %%β %%γ %%coe2 %%yy) ← return y,
success_if_fail $ is_def_eq α β,
is_def_eq δ γ,
(do
coe3 ← mk_app `has_lift_t [α, β] >>= mk_instance',
new_x ← to_expr ``(@coe %%β %%δ %%coe2 (@coe %%α %%β %%coe3 %%xx)),
let new_e := app (app op new_x) y,
eq_x ← aux_simp x new_x,
pr ← mk_congr_arg op eq_x,
pr ← mk_congr_fun pr y,
return ((), new_e, pr)
) <|> (do
coe3 ← mk_app `has_lift_t [β, α] >>= mk_instance',
new_y ← to_expr ``(@coe %%α %%δ %%coe1 (@coe %%β %%α %%coe3 %%yy)),
let new_e := app (app op x) new_y,
eq_y ← aux_simp y new_y,
pr ← mk_congr_arg (app op x) eq_y,
return ((), new_e, pr)
)
| _ := failed
end
-- simpa is used to discharge proofs
private meta def prove : tactic unit :=
tactic.interactive.simpa none ff [] [] none
private meta def post (_ : unit) (e : expr) : tactic (unit × expr × expr) :=
do
s ← norm_cast_attr.get_cache,
r ← mcond (is_prop e) (return `iff) (return `eq),
(new_e, pr) ← s.rewrite e prove r,
pr ← match r with
|`iff := mk_app `propext [pr]
| _ := return pr
end,
return ((), new_e, pr)
/-
This is a function to pre-process numerals:
- (1 : α) is rewritten as ((1 : ℕ) : α)
- (0 : α) is rewritten as ((0 : ℕ) : α)
-/
private meta def aux_num (_ : unit) (e : expr) : tactic (unit × expr × expr) :=
match e with
| `(0 : ℕ) := failed
| `(1 : ℕ) := failed
| `(@has_zero.zero %%α %%h) := do
coe_nat ← to_expr ``(has_lift_t ℕ %%α) >>= mk_instance',
new_e ← to_expr ``(@coe ℕ %%α %%coe_nat 0),
pr ← aux_simp e new_e,
return ((), new_e, pr)
| `(@has_one.one %%α %%h) := do
coe_nat ← to_expr ``(has_lift_t ℕ %%α) >>= mk_instance',
new_e ← to_expr ``(@coe ℕ %%α %%coe_nat 1),
pr ← aux_simp e new_e,
return ((), new_e, pr)
| _ := failed
end
/-
Core function
-/
meta def derive (e : expr) : tactic (expr × expr) :=
do
e ← instantiate_mvars e,
let cfg : simp_config := {fail_if_unchanged := ff},
-- step 1: pre-processing numerals
((), new_e, pr1) ← simplify_bottom_up () aux_num e cfg,
-- step 2: casts are moved outwards as much as possible using norm_cast lemmas
((), new_e, pr2) ← simplify_bottom_up () (λ a e, post a e <|> heur a e) new_e cfg,
-- step 3: casts are simplified using simp_cast lemmas
s ← simp_cast_attr.get_cache,
(new_e, pr3) ← simplify s [] new_e cfg,
guard (¬ new_e =ₐ e),
pr ← mk_eq_trans pr2 pr3 >>= mk_eq_trans pr1,
return (new_e, pr)
end norm_cast
namespace tactic
open tactic expr
open norm_cast
private meta def aux_mod_cast (e : expr) : tactic expr :=
match e with
| local_const _ lc _ _ := do
e ← get_local lc,
replace_at derive [e] tt,
get_local lc
| e := do
t ← infer_type e,
e ← assertv `this t e,
replace_at derive [e] tt,
get_local `this
end
meta def exact_mod_cast (e : expr) : tactic unit :=
( do
new_e ← aux_mod_cast e,
exact new_e
) <|> fail "exact_mod_cast failed"
meta def apply_mod_cast (e : expr) : tactic (list (name × expr)) :=
( do
new_e ← aux_mod_cast e,
apply new_e
) <|> fail "apply_mod_cast failed"
meta def assumption_mod_cast : tactic unit :=
do {
let cfg : simp_config := {
fail_if_unchanged := ff,
canonize_instances := ff,
canonize_proofs := ff,
proj := ff
},
ctx ← local_context,
replace_at derive ctx tt,
assumption
} <|> fail "assumption_mod_cast failed"
end tactic
namespace tactic.interactive
open tactic interactive tactic.interactive interactive.types expr lean.parser
open norm_cast
local postfix `?`:9001 := optional
/--
Normalize casts at the given locations by moving them "upwards".
As opposed to simp, norm_cast can be used without necessarily
closing the goal.
-/
meta def norm_cast (loc : parse location) : tactic unit :=
do
ns ← loc.get_locals,
tt ← replace_at derive ns loc.include_goal
| fail "norm_cast failed to simplify",
when loc.include_goal $ try tactic.reflexivity,
when loc.include_goal $ try tactic.triv,
when (¬ ns.empty) $ try tactic.contradiction
/--
Rewrite with the given rule and normalize casts between steps.
-/
meta def rw_mod_cast (rs : parse rw_rules) (loc : parse location) : tactic unit :=
( do
let cfg_norm : simp_config := {},
let cfg_rw : rewrite_cfg := {},
ns ← loc.get_locals,
monad.mapm' (λ r : rw_rule, do
save_info r.pos,
replace_at derive ns loc.include_goal,
rw ⟨[r], none⟩ loc {}
) rs.rules,
replace_at derive ns loc.include_goal,
skip
) <|> fail "rw_mod_cast failed"
/--
Normalize the goal and the givin expression,
then close the goal with exact.
-/
meta def exact_mod_cast (e : parse texpr) : tactic unit :=
do
e ← i_to_expr e <|> do {
ty ← target,
e ← i_to_expr_strict ``(%%e : %%ty),
pty ← pp ty, ptgt ← pp e,
fail ("exact_mod_cast failed, expression type not directly " ++
"inferrable. Try:\n\nexact_mod_cast ...\nshow " ++
to_fmt pty ++ ",\nfrom " ++ ptgt : format)
},
tactic.exact_mod_cast e
/--
Normalize the goal and the given expression,
then apply the expression to the goal.
-/
meta def apply_mod_cast (e : parse texpr) : tactic unit :=
do
e ← i_to_expr_for_apply e,
concat_tags $ tactic.apply_mod_cast e
/--
Normalize the goal and every expression in the local context,
then close the goal with assumption.
-/
meta def assumption_mod_cast : tactic unit :=
tactic.assumption_mod_cast
end tactic.interactive
namespace conv.interactive
open conv tactic tactic.interactive interactive interactive.types
open norm_cast (derive)
meta def norm_cast : conv unit := replace_lhs derive
end conv.interactive
/- simp_cast lemmas -/
attribute [simp_cast] nat.cast_zero
attribute [simp_cast] int.coe_nat_zero
attribute [simp_cast] int.cast_zero
attribute [simp_cast] rat.cast_zero
attribute [simp_cast] complex.of_real_zero
attribute [simp_cast] nat.cast_one
attribute [simp_cast] int.coe_nat_one
attribute [simp_cast] int.cast_one
attribute [simp_cast] rat.cast_one
attribute [simp_cast] complex.of_real_one
attribute [simp_cast] nat.cast_id
attribute [simp_cast] int.cast_id
attribute [simp_cast] rat.cast_id
attribute [simp_cast] int.cast_coe_nat
attribute [simp_cast] int.cast_coe_nat'
attribute [simp_cast] rat.cast_coe_nat
attribute [simp_cast] rat.cast_coe_int
attribute [simp_cast] complex.of_real_int_cast
attribute [simp_cast] complex.of_real_nat_cast
attribute [simp_cast] complex.of_real_rat_cast
attribute [simp_cast] enat.coe_zero
attribute [simp_cast] enat.coe_one
attribute [simp_cast] enat.coe_get
attribute [simp_cast] rat.coe_nat_num
attribute [simp_cast] rat.coe_int_num
attribute [simp_cast] rat.coe_nat_denom
/- compositional norm_cast lemmas -/
attribute [norm_cast] nat.cast_succ
attribute [norm_cast] int.coe_nat_succ
attribute [norm_cast] nat.cast_add
attribute [norm_cast] int.coe_nat_add
attribute [norm_cast] int.cast_add
attribute [norm_cast] rat.cast_add
attribute [norm_cast] complex.of_real_add
attribute [norm_cast] enat.coe_add
attribute [norm_cast] int.cast_neg_succ_of_nat
attribute [norm_cast] int.cast_neg_of_nat
attribute [norm_cast] int.cast_neg
attribute [norm_cast] rat.cast_neg
attribute [norm_cast] complex.of_real_neg
attribute [norm_cast] nat.cast_sub
attribute [norm_cast] int.cast_sub_nat_nat
attribute [norm_cast] int.coe_nat_sub
attribute [norm_cast] int.cast_sub
attribute [norm_cast] rat.cast_sub
attribute [norm_cast] complex.of_real_sub
attribute [norm_cast] nat.cast_mul
attribute [norm_cast] int.coe_nat_mul
attribute [norm_cast] int.cast_mul
attribute [norm_cast] rat.cast_mul
attribute [norm_cast] complex.of_real_mul
attribute [norm_cast] rat.cast_inv
attribute [norm_cast] complex.of_real_inv
attribute [norm_cast] int.coe_nat_div
attribute [norm_cast] rat.cast_div
attribute [norm_cast] complex.of_real_div
attribute [norm_cast] nat.cast_min
attribute [norm_cast] int.cast_min
attribute [norm_cast] rat.cast_min
attribute [norm_cast] nat.cast_max
attribute [norm_cast] int.cast_max
attribute [norm_cast] rat.cast_max
attribute [norm_cast] int.coe_nat_abs
attribute [norm_cast] int.cast_abs
attribute [norm_cast] rat.cast_abs
attribute [norm_cast] nat.cast_pow
attribute [norm_cast] int.coe_nat_pow
attribute [norm_cast] int.cast_pow
attribute [norm_cast] rat.cast_pow
attribute [norm_cast] complex.of_real_pow
attribute [norm_cast] complex.of_real_fpow
attribute [norm_cast] nat.cast_bit0
@[norm_cast] lemma int.coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp}
attribute [norm_cast] int.cast_bit0
attribute [norm_cast] rat.cast_bit0
attribute [norm_cast] complex.of_real_bit0
attribute [norm_cast] nat.cast_bit1
@[norm_cast] lemma int.coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp}
attribute [norm_cast] int.cast_bit1
attribute [norm_cast] rat.cast_bit1
attribute [norm_cast] complex.of_real_bit1
@[norm_cast]
lemma ite_lemma {α β : Type} [has_coe α β] {c : Prop} [decidable c] {a b : α} :
↑(ite c a b) = ite c (↑a : β) (↑b : β) :=
if h : c then
by simp [h]
else
by simp [h]
/- equivalence norm_cast lemmas -/
attribute [norm_cast] nat.cast_inj
attribute [norm_cast] int.coe_nat_inj'
attribute [norm_cast] int.cast_inj
attribute [norm_cast] rat.cast_inj
attribute [norm_cast] complex.of_real_inj
attribute [norm_cast] nat.cast_le
attribute [norm_cast] int.coe_nat_le
attribute [norm_cast] int.cast_le
attribute [norm_cast] rat.cast_le
attribute [norm_cast] enat.coe_le_coe
attribute [norm_cast] nat.cast_lt
attribute [norm_cast] int.coe_nat_lt
attribute [norm_cast] int.cast_lt
attribute [norm_cast] rat.cast_lt
attribute [norm_cast] enat.coe_lt_coe
attribute [norm_cast] int.coe_nat_dvd
/- special lemmas to unfold ≥, > and ≠ -/
@[norm_cast] lemma ge_from_le {α} [has_le α] : ∀ (x y : α), x ≥ y ↔ y ≤ x := by simp
@[norm_cast] lemma gt_from_lt {α} [has_lt α] : ∀ (x y : α), x > y ↔ y < x := by simp
@[norm_cast] lemma ne_from_not_eq {α} : ∀ (x y : α), x ≠ y ↔ ¬(x = y) := by simp
|
2a55b268d7c16b94a5170fbc59e40a061549c9a4 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/algebra/ordered_group.lean | 6138629454da42f64ce39c3743f4363afa95e103 | [
"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 | 35,661 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl
-/
import algebra.ordered_monoid
/-!
# Ordered groups
This file develops the basics of ordered groups.
## Implementation details
Unfortunately, the number of `'` appended to lemmas in this file
may differ between the multiplicative and the additive version of a lemma.
The reason is that we did not want to change existing names in the library.
-/
set_option old_structure_cmd true
universe u
variable {α : Type u}
/-- An ordered additive commutative group is an additive commutative group
with a partial order in which addition is strictly monotone. -/
@[protect_proj, ancestor add_comm_group partial_order]
class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α :=
(add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b)
/-- An ordered commutative group is an commutative group
with a partial order in which multiplication is strictly monotone. -/
@[protect_proj, ancestor comm_group partial_order]
class ordered_comm_group (α : Type u) extends comm_group α, partial_order α :=
(mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b)
attribute [to_additive] ordered_comm_group
@[to_additive]
instance units.covariant_class [ordered_comm_monoid α] :
covariant_class (units α) (units α) (*) (≤) :=
{ covc := λ a b c bc, by {
rcases le_iff_eq_or_lt.mp bc with ⟨rfl, h⟩,
{ exact rfl.le },
refine le_iff_eq_or_lt.mpr (or.inr _),
refine units.coe_lt_coe.mp _,
cases lt_iff_le_and_ne.mp (units.coe_lt_coe.mpr h) with lef rig,
exact lt_of_le_of_ne (mul_le_mul_left' lef ↑a) (λ hg, rig ((units.mul_right_inj a).mp hg)) } }
/--The units of an ordered commutative monoid form an ordered commutative group. -/
@[to_additive]
instance units.ordered_comm_group [ordered_comm_monoid α] : ordered_comm_group (units α) :=
{ mul_le_mul_left := λ a b h c, mul_le_mul_left' h _,
.. units.partial_order,
.. (infer_instance : comm_group (units α)) }
section ordered_comm_group
variables [ordered_comm_group α] {a b c d : α}
@[to_additive ordered_add_comm_group.add_lt_add_left]
lemma ordered_comm_group.mul_lt_mul_left' (a b : α) (h : a < b) (c : α) : c * a < c * b :=
begin
rw lt_iff_le_not_le at h ⊢,
split,
{ apply ordered_comm_group.mul_le_mul_left _ _ h.1 },
{ intro w,
replace w : c⁻¹ * (c * b) ≤ c⁻¹ * (c * a) := ordered_comm_group.mul_le_mul_left _ _ w _,
simp only [mul_one, mul_comm, mul_left_inv, mul_left_comm] at w,
exact h.2 w },
end
@[to_additive ordered_add_comm_group.le_of_add_le_add_left]
lemma ordered_comm_group.le_of_mul_le_mul_left (h : a * b ≤ a * c) : b ≤ c :=
have a⁻¹ * (a * b) ≤ a⁻¹ * (a * c), from ordered_comm_group.mul_le_mul_left _ _ h _,
begin simp [inv_mul_cancel_left] at this, assumption end
@[to_additive]
lemma ordered_comm_group.lt_of_mul_lt_mul_left (h : a * b < a * c) : b < c :=
have a⁻¹ * (a * b) < a⁻¹ * (a * c), from ordered_comm_group.mul_lt_mul_left' _ _ h _,
begin simp [inv_mul_cancel_left] at this, assumption end
@[priority 100, to_additive] -- see Note [lower instance priority]
instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u)
[s : ordered_comm_group α] :
ordered_cancel_comm_monoid α :=
{ mul_left_cancel := @mul_left_cancel α _,
le_of_mul_le_mul_left := @ordered_comm_group.le_of_mul_le_mul_left α _,
..s }
@[priority 100, to_additive]
instance ordered_comm_group.has_exists_mul_of_le (α : Type u)
[ordered_comm_group α] :
has_exists_mul_of_le α :=
⟨λ a b hab, ⟨b * a⁻¹, (mul_inv_cancel_comm_assoc a b).symm⟩⟩
@[to_additive neg_le_neg]
lemma inv_le_inv' (h : a ≤ b) : b⁻¹ ≤ a⁻¹ :=
have 1 ≤ a⁻¹ * b, from mul_left_inv a ▸ mul_le_mul_left' h _,
have 1 * b⁻¹ ≤ a⁻¹ * b * b⁻¹, from mul_le_mul_right' this _,
by rwa [mul_inv_cancel_right, one_mul] at this
@[to_additive]
lemma le_of_inv_le_inv (h : b⁻¹ ≤ a⁻¹) : a ≤ b :=
suffices (a⁻¹)⁻¹ ≤ (b⁻¹)⁻¹, from
begin simp [inv_inv] at this, assumption end,
inv_le_inv' h
@[to_additive]
lemma one_le_of_inv_le_one (h : a⁻¹ ≤ 1) : 1 ≤ a :=
have a⁻¹ ≤ 1⁻¹, by rwa one_inv,
le_of_inv_le_inv this
@[to_additive]
lemma inv_le_one_of_one_le (h : 1 ≤ a) : a⁻¹ ≤ 1 :=
have a⁻¹ ≤ 1⁻¹, from inv_le_inv' h,
by rwa one_inv at this
@[to_additive nonpos_of_neg_nonneg]
lemma le_one_of_one_le_inv (h : 1 ≤ a⁻¹) : a ≤ 1 :=
have 1⁻¹ ≤ a⁻¹, by rwa one_inv,
le_of_inv_le_inv this
@[to_additive neg_nonneg_of_nonpos]
lemma one_le_inv_of_le_one (h : a ≤ 1) : 1 ≤ a⁻¹ :=
have 1⁻¹ ≤ a⁻¹, from inv_le_inv' h,
by rwa one_inv at this
@[to_additive neg_lt_neg]
lemma inv_lt_inv' (h : a < b) : b⁻¹ < a⁻¹ :=
have 1 < a⁻¹ * b, from mul_left_inv a ▸ mul_lt_mul_left' h (a⁻¹),
have 1 * b⁻¹ < a⁻¹ * b * b⁻¹, from mul_lt_mul_right' this (b⁻¹),
by rwa [mul_inv_cancel_right, one_mul] at this
@[to_additive]
lemma lt_of_inv_lt_inv (h : b⁻¹ < a⁻¹) : a < b :=
inv_inv a ▸ inv_inv b ▸ inv_lt_inv' h
@[to_additive]
lemma one_lt_of_inv_inv (h : a⁻¹ < 1) : 1 < a :=
have a⁻¹ < 1⁻¹, by rwa one_inv,
lt_of_inv_lt_inv this
@[to_additive]
lemma inv_inv_of_one_lt (h : 1 < a) : a⁻¹ < 1 :=
have a⁻¹ < 1⁻¹, from inv_lt_inv' h,
by rwa one_inv at this
@[to_additive neg_of_neg_pos]
lemma inv_of_one_lt_inv (h : 1 < a⁻¹) : a < 1 :=
have 1⁻¹ < a⁻¹, by rwa one_inv,
lt_of_inv_lt_inv this
@[to_additive neg_pos_of_neg]
lemma one_lt_inv_of_inv (h : a < 1) : 1 < a⁻¹ :=
have 1⁻¹ < a⁻¹, from inv_lt_inv' h,
by rwa one_inv at this
@[to_additive]
lemma le_inv_of_le_inv (h : a ≤ b⁻¹) : b ≤ a⁻¹ :=
begin
have h := inv_le_inv' h,
rwa inv_inv at h
end
@[to_additive]
lemma inv_le_of_inv_le (h : a⁻¹ ≤ b) : b⁻¹ ≤ a :=
begin
have h := inv_le_inv' h,
rwa inv_inv at h
end
@[to_additive]
lemma lt_inv_of_lt_inv (h : a < b⁻¹) : b < a⁻¹ :=
begin
have h := inv_lt_inv' h,
rwa inv_inv at h
end
@[to_additive]
lemma inv_lt_of_inv_lt (h : a⁻¹ < b) : b⁻¹ < a :=
begin
have h := inv_lt_inv' h,
rwa inv_inv at h
end
@[to_additive]
lemma mul_le_of_le_inv_mul (h : b ≤ a⁻¹ * c) : a * b ≤ c :=
begin
have h := mul_le_mul_left' h a,
rwa mul_inv_cancel_left at h
end
@[to_additive]
lemma le_inv_mul_of_mul_le (h : a * b ≤ c) : b ≤ a⁻¹ * c :=
begin
have h := mul_le_mul_left' h a⁻¹,
rwa inv_mul_cancel_left at h
end
@[to_additive]
lemma le_mul_of_inv_mul_le (h : b⁻¹ * a ≤ c) : a ≤ b * c :=
begin
have h := mul_le_mul_left' h b,
rwa mul_inv_cancel_left at h
end
@[to_additive]
lemma inv_mul_le_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c :=
begin
have h := mul_le_mul_left' h b⁻¹,
rwa inv_mul_cancel_left at h
end
@[to_additive]
lemma le_mul_of_inv_mul_le_left (h : b⁻¹ * a ≤ c) : a ≤ b * c :=
le_mul_of_inv_mul_le h
@[to_additive]
lemma inv_mul_le_left_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c :=
inv_mul_le_of_le_mul h
@[to_additive]
lemma le_mul_of_inv_mul_le_right (h : c⁻¹ * a ≤ b) : a ≤ b * c :=
by { rw mul_comm, exact le_mul_of_inv_mul_le h }
@[to_additive]
lemma inv_mul_le_right_of_le_mul (h : a ≤ b * c) : c⁻¹ * a ≤ b :=
by { rw mul_comm at h, apply inv_mul_le_left_of_le_mul h }
@[to_additive]
lemma mul_lt_of_lt_inv_mul (h : b < a⁻¹ * c) : a * b < c :=
begin
have h := mul_lt_mul_left' h a,
rwa mul_inv_cancel_left at h
end
@[to_additive]
lemma lt_inv_mul_of_mul_lt (h : a * b < c) : b < a⁻¹ * c :=
begin
have h := mul_lt_mul_left' h (a⁻¹),
rwa inv_mul_cancel_left at h
end
@[to_additive]
lemma lt_mul_of_inv_mul_lt (h : b⁻¹ * a < c) : a < b * c :=
begin
have h := mul_lt_mul_left' h b,
rwa mul_inv_cancel_left at h
end
@[to_additive]
lemma inv_mul_lt_of_lt_mul (h : a < b * c) : b⁻¹ * a < c :=
begin
have h := mul_lt_mul_left' h (b⁻¹),
rwa inv_mul_cancel_left at h
end
@[to_additive]
lemma lt_mul_of_inv_mul_lt_left (h : b⁻¹ * a < c) : a < b * c :=
lt_mul_of_inv_mul_lt h
@[to_additive]
lemma inv_mul_lt_left_of_lt_mul (h : a < b * c) : b⁻¹ * a < c :=
inv_mul_lt_of_lt_mul h
@[to_additive]
lemma lt_mul_of_inv_mul_lt_right (h : c⁻¹ * a < b) : a < b * c :=
by { rw mul_comm, exact lt_mul_of_inv_mul_lt h }
@[to_additive]
lemma inv_mul_lt_right_of_lt_mul (h : a < b * c) : c⁻¹ * a < b :=
by { rw mul_comm at h, exact inv_mul_lt_of_lt_mul h }
@[simp, to_additive]
lemma inv_lt_one_iff_one_lt : a⁻¹ < 1 ↔ 1 < a :=
⟨ one_lt_of_inv_inv, inv_inv_of_one_lt ⟩
@[simp, to_additive]
lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
have a * b * a⁻¹ ≤ a * b * b⁻¹ ↔ a⁻¹ ≤ b⁻¹, from mul_le_mul_iff_left _,
by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] }
@[to_additive neg_le]
lemma inv_le' : a⁻¹ ≤ b ↔ b⁻¹ ≤ a :=
have a⁻¹ ≤ (b⁻¹)⁻¹ ↔ b⁻¹ ≤ a, from inv_le_inv_iff,
by rwa inv_inv at this
@[to_additive le_neg]
lemma le_inv' : a ≤ b⁻¹ ↔ b ≤ a⁻¹ :=
have (a⁻¹)⁻¹ ≤ b⁻¹ ↔ b ≤ a⁻¹, from inv_le_inv_iff,
by rwa inv_inv at this
@[to_additive neg_le_iff_add_nonneg]
lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ b * a :=
(mul_le_mul_iff_right a).symm.trans $ by rw inv_mul_self
@[to_additive neg_le_iff_add_nonneg']
lemma inv_le_iff_one_le_mul' : a⁻¹ ≤ b ↔ 1 ≤ a * b :=
(mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma inv_lt_iff_one_lt_mul : a⁻¹ < b ↔ 1 < b * a :=
(mul_lt_mul_iff_right a).symm.trans $ by rw inv_mul_self
@[to_additive]
lemma inv_lt_iff_one_lt_mul' : a⁻¹ < b ↔ 1 < a * b :=
(mul_lt_mul_iff_left a).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma le_inv_iff_mul_le_one : a ≤ b⁻¹ ↔ a * b ≤ 1 :=
(mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self
@[to_additive]
lemma le_inv_iff_mul_le_one' : a ≤ b⁻¹ ↔ b * a ≤ 1 :=
(mul_le_mul_iff_left b).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma lt_inv_iff_mul_lt_one : a < b⁻¹ ↔ a * b < 1 :=
(mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_self
@[to_additive]
lemma lt_inv_iff_mul_lt_one' : a < b⁻¹ ↔ b * a < 1 :=
(mul_lt_mul_iff_left b).symm.trans $ by rw mul_inv_self
@[simp, to_additive neg_nonpos]
lemma inv_le_one' : a⁻¹ ≤ 1 ↔ 1 ≤ a :=
have a⁻¹ ≤ 1⁻¹ ↔ 1 ≤ a, from inv_le_inv_iff,
by rwa one_inv at this
@[simp, to_additive neg_nonneg]
lemma one_le_inv' : 1 ≤ a⁻¹ ↔ a ≤ 1 :=
have 1⁻¹ ≤ a⁻¹ ↔ a ≤ 1, from inv_le_inv_iff,
by rwa one_inv at this
@[to_additive]
lemma inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a :=
le_trans (inv_le_one'.2 h) h
@[to_additive]
lemma self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ :=
le_trans h (one_le_inv'.2 h)
@[simp, to_additive]
lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a :=
have a * b * a⁻¹ < a * b * b⁻¹ ↔ a⁻¹ < b⁻¹, from mul_lt_mul_iff_left _,
by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] }
@[to_additive neg_lt_zero]
lemma inv_lt_one' : a⁻¹ < 1 ↔ 1 < a :=
have a⁻¹ < 1⁻¹ ↔ 1 < a, from inv_lt_inv_iff,
by rwa one_inv at this
@[to_additive neg_pos]
lemma one_lt_inv' : 1 < a⁻¹ ↔ a < 1 :=
have 1⁻¹ < a⁻¹ ↔ a < 1, from inv_lt_inv_iff,
by rwa one_inv at this
@[to_additive neg_lt]
lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a :=
have a⁻¹ < (b⁻¹)⁻¹ ↔ b⁻¹ < a, from inv_lt_inv_iff,
by rwa inv_inv at this
@[to_additive lt_neg]
lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ :=
have (a⁻¹)⁻¹ < b⁻¹ ↔ b < a⁻¹, from inv_lt_inv_iff,
by rwa inv_inv at this
@[to_additive]
lemma inv_lt_self (h : 1 < a) : a⁻¹ < a :=
(inv_lt_one'.2 h).trans h
@[to_additive]
lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c :=
have a⁻¹ * (a * b) ≤ a⁻¹ * c ↔ a * b ≤ c, from mul_le_mul_iff_left _,
by rwa inv_mul_cancel_left at this
@[simp, to_additive]
lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c :=
have b⁻¹ * a ≤ b⁻¹ * (b * c) ↔ a ≤ b * c, from mul_le_mul_iff_left _,
by rwa inv_mul_cancel_left at this
@[to_additive]
lemma mul_inv_le_iff_le_mul : a * c⁻¹ ≤ b ↔ a ≤ b * c :=
by rw [mul_comm a, mul_comm b, inv_mul_le_iff_le_mul]
@[simp, to_additive]
lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c :=
by rw [← inv_mul_le_iff_le_mul, mul_comm]
@[to_additive]
lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c :=
by rw [inv_mul_le_iff_le_mul, mul_comm]
@[simp, to_additive]
lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c :=
have a⁻¹ * (a * b) < a⁻¹ * c ↔ a * b < c, from mul_lt_mul_iff_left _,
by rwa inv_mul_cancel_left at this
@[simp, to_additive]
lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c :=
have b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c, from mul_lt_mul_iff_left _,
by rwa inv_mul_cancel_left at this
@[to_additive]
lemma inv_mul_lt_iff_lt_mul_right : c⁻¹ * a < b ↔ a < b * c :=
by rw [inv_mul_lt_iff_lt_mul, mul_comm]
@[to_additive add_neg_le_add_neg_iff]
lemma div_le_div_iff' : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b :=
begin
split ; intro h,
have := mul_le_mul_right' (mul_le_mul_right' h b) d,
rwa [inv_mul_cancel_right, mul_assoc _ _ b, mul_comm _ b, ← mul_assoc, inv_mul_cancel_right]
at this,
have := mul_le_mul_right' (mul_le_mul_right' h d⁻¹) b⁻¹,
rwa [mul_inv_cancel_right, _root_.mul_assoc, _root_.mul_comm d⁻¹ b⁻¹, ← mul_assoc,
mul_inv_cancel_right] at this,
end
@[simp, to_additive] lemma div_le_self_iff (a : α) {b : α} : a / b ≤ a ↔ 1 ≤ b :=
by simp [div_eq_mul_inv]
@[simp, to_additive] lemma div_lt_self_iff (a : α) {b : α} : a / b < a ↔ 1 < b :=
by simp [div_eq_mul_inv]
/-- Pullback an `ordered_comm_group` under an injective map. -/
@[to_additive function.injective.ordered_add_comm_group
"Pullback an `ordered_add_comm_group` under an injective map."]
def function.injective.ordered_comm_group {β : Type*}
[has_one β] [has_mul β] [has_inv β] [has_div β]
(f : β → α) (hf : function.injective f) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y)
(inv : ∀ x, f (x⁻¹) = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
ordered_comm_group β :=
{ ..partial_order.lift f hf,
..hf.ordered_comm_monoid f one mul,
..hf.comm_group f one mul inv div }
end ordered_comm_group
section ordered_add_comm_group
variables [ordered_add_comm_group α] {a b c d : α}
lemma sub_le_sub (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c :=
by simpa only [sub_eq_add_neg] using add_le_add hab (neg_le_neg hcd)
lemma sub_lt_sub (hab : a < b) (hcd : c < d) : a - d < b - c :=
by simpa only [sub_eq_add_neg] using add_lt_add hab (neg_lt_neg hcd)
alias sub_le_self_iff ↔ _ sub_le_self
alias sub_lt_self_iff ↔ _ sub_lt_self
lemma sub_le_sub_iff : a - b ≤ c - d ↔ a + d ≤ c + b :=
by simpa only [sub_eq_add_neg] using add_neg_le_add_neg_iff
@[simp]
lemma sub_le_sub_iff_left (a : α) {b c : α} : a - b ≤ a - c ↔ c ≤ b :=
by rw [sub_eq_add_neg, sub_eq_add_neg, add_le_add_iff_left, neg_le_neg_iff]
lemma sub_le_sub_left (h : a ≤ b) (c : α) : c - b ≤ c - a :=
(sub_le_sub_iff_left c).2 h
@[simp]
lemma sub_le_sub_iff_right (c : α) : a - c ≤ b - c ↔ a ≤ b :=
by simpa only [sub_eq_add_neg] using add_le_add_iff_right _
lemma sub_le_sub_right (h : a ≤ b) (c : α) : a - c ≤ b - c :=
(sub_le_sub_iff_right c).2 h
@[simp]
lemma sub_lt_sub_iff_left (a : α) {b c : α} : a - b < a - c ↔ c < b :=
by rw [sub_eq_add_neg, sub_eq_add_neg, add_lt_add_iff_left, neg_lt_neg_iff]
lemma sub_lt_sub_left (h : a < b) (c : α) : c - b < c - a :=
(sub_lt_sub_iff_left c).2 h
@[simp]
lemma sub_lt_sub_iff_right (c : α) : a - c < b - c ↔ a < b :=
by simpa only [sub_eq_add_neg] using add_lt_add_iff_right _
lemma sub_lt_sub_right (h : a < b) (c : α) : a - c < b - c :=
(sub_lt_sub_iff_right c).2 h
@[simp] lemma sub_nonneg : 0 ≤ a - b ↔ b ≤ a :=
by rw [← sub_self a, sub_le_sub_iff_left]
alias sub_nonneg ↔ le_of_sub_nonneg sub_nonneg_of_le
@[simp] lemma sub_nonpos : a - b ≤ 0 ↔ a ≤ b :=
by rw [← sub_self b, sub_le_sub_iff_right]
alias sub_nonpos ↔ le_of_sub_nonpos sub_nonpos_of_le
@[simp] lemma sub_pos : 0 < a - b ↔ b < a :=
by rw [← sub_self a, sub_lt_sub_iff_left]
alias sub_pos ↔ lt_of_sub_pos sub_pos_of_lt
@[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b :=
by rw [← sub_self b, sub_lt_sub_iff_right]
alias sub_lt_zero ↔ lt_of_sub_neg sub_neg_of_lt
lemma le_sub_iff_add_le' : b ≤ c - a ↔ a + b ≤ c :=
by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le]
lemma le_sub_iff_add_le : a ≤ c - b ↔ a + b ≤ c :=
by rw [le_sub_iff_add_le', add_comm]
alias le_sub_iff_add_le ↔ add_le_of_le_sub_right le_sub_right_of_add_le
lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c :=
by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add]
alias le_sub_iff_add_le' ↔ add_le_of_le_sub_left le_sub_left_of_add_le
lemma sub_le_iff_le_add : a - c ≤ b ↔ a ≤ b + c :=
by rw [sub_le_iff_le_add', add_comm]
@[simp] lemma neg_le_sub_iff_le_add : -b ≤ a - c ↔ c ≤ a + b :=
le_sub_iff_add_le.trans neg_add_le_iff_le_add'
lemma neg_le_sub_iff_le_add' : -a ≤ b - c ↔ c ≤ a + b :=
by rw [neg_le_sub_iff_le_add, add_comm]
lemma sub_le : a - b ≤ c ↔ a - c ≤ b :=
sub_le_iff_le_add'.trans sub_le_iff_le_add.symm
theorem le_sub : a ≤ b - c ↔ c ≤ b - a :=
le_sub_iff_add_le'.trans le_sub_iff_add_le.symm
lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c :=
by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt]
alias lt_sub_iff_add_lt' ↔ add_lt_of_lt_sub_left lt_sub_left_of_add_lt
lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c :=
by rw [lt_sub_iff_add_lt', add_comm]
alias lt_sub_iff_add_lt ↔ add_lt_of_lt_sub_right lt_sub_right_of_add_lt
lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c :=
by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add]
alias sub_lt_iff_lt_add' ↔ lt_add_of_sub_left_lt sub_left_lt_of_lt_add
lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c :=
by rw [sub_lt_iff_lt_add', add_comm]
alias sub_lt_iff_lt_add ↔ lt_add_of_sub_right_lt sub_right_lt_of_lt_add
@[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b :=
lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right
lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b :=
by rw [neg_lt_sub_iff_lt_add, add_comm]
lemma sub_lt : a - b < c ↔ a - c < b :=
sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm
theorem lt_sub : a < b - c ↔ c < b - a :=
lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm
end ordered_add_comm_group
/-!
### Linearly ordered commutative groups
-/
/-- A linearly ordered additive commutative group is an
additive commutative group with a linear order in which
addition is monotone. -/
@[protect_proj, ancestor add_comm_group linear_order]
class linear_ordered_add_comm_group (α : Type u) extends add_comm_group α, linear_order α :=
(add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b)
/-- A linearly ordered commutative monoid with an additively absorbing `⊤` element.
Instances should include number systems with an infinite element adjoined.` -/
@[protect_proj, ancestor linear_ordered_add_comm_monoid_with_top sub_neg_monoid nontrivial]
class linear_ordered_add_comm_group_with_top (α : Type*)
extends linear_ordered_add_comm_monoid_with_top α, sub_neg_monoid α, nontrivial α :=
(neg_top : - (⊤ : α) = ⊤)
(add_neg_cancel : ∀ a:α, a ≠ ⊤ → a + (- a) = 0)
/-- A linearly ordered commutative group is a
commutative group with a linear order in which
multiplication is monotone. -/
@[protect_proj, ancestor comm_group linear_order, to_additive]
class linear_ordered_comm_group (α : Type u) extends comm_group α, linear_order α :=
(mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b)
section linear_ordered_comm_group
variables [linear_ordered_comm_group α] {a b c : α}
@[priority 100, to_additive] -- see Note [lower instance priority]
instance linear_ordered_comm_group.to_ordered_comm_group : ordered_comm_group α :=
{ ..‹linear_ordered_comm_group α› }
@[priority 100, to_additive] -- see Note [lower instance priority]
instance linear_ordered_comm_group.to_linear_ordered_cancel_comm_monoid :
linear_ordered_cancel_comm_monoid α :=
{ le_of_mul_le_mul_left := λ x y z, le_of_mul_le_mul_left',
mul_left_cancel := λ x y z, mul_left_cancel,
..‹linear_ordered_comm_group α› }
/-- Pullback a `linear_ordered_comm_group` under an injective map. -/
@[to_additive function.injective.linear_ordered_add_comm_group
"Pullback a `linear_ordered_add_comm_group` under an injective map."]
def function.injective.linear_ordered_comm_group {β : Type*}
[has_one β] [has_mul β] [has_inv β] [has_div β]
(f : β → α) (hf : function.injective f) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y)
(inv : ∀ x, f (x⁻¹) = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
linear_ordered_comm_group β :=
{ ..linear_order.lift f hf,
..hf.ordered_comm_group f one mul inv div }
@[to_additive linear_ordered_add_comm_group.add_lt_add_left]
lemma linear_ordered_comm_group.mul_lt_mul_left'
(a b : α) (h : a < b) (c : α) : c * a < c * b :=
ordered_comm_group.mul_lt_mul_left' a b h c
@[to_additive min_neg_neg]
lemma min_inv_inv' (a b : α) : min (a⁻¹) (b⁻¹) = (max a b)⁻¹ :=
eq.symm $ @monotone.map_max α (order_dual α) _ _ has_inv.inv a b $ λ a b, inv_le_inv'
@[to_additive max_neg_neg]
lemma max_inv_inv' (a b : α) : max (a⁻¹) (b⁻¹) = (min a b)⁻¹ :=
eq.symm $ @monotone.map_min α (order_dual α) _ _ has_inv.inv a b $ λ a b, inv_le_inv'
@[to_additive min_sub_sub_right]
lemma min_div_div_right' (a b c : α) : min (a / c) (b / c) = min a b / c :=
by simpa only [div_eq_mul_inv] using min_mul_mul_right a b (c⁻¹)
@[to_additive max_sub_sub_right]
lemma max_div_div_right' (a b c : α) : max (a / c) (b / c) = max a b / c :=
by simpa only [div_eq_mul_inv] using max_mul_mul_right a b (c⁻¹)
@[to_additive min_sub_sub_left]
lemma min_div_div_left' (a b c : α) : min (a / b) (a / c) = a / max b c :=
by simp only [div_eq_mul_inv, min_mul_mul_left, min_inv_inv']
@[to_additive max_sub_sub_left]
lemma max_div_div_left' (a b c : α) : max (a / b) (a / c) = a / min b c :=
by simp only [div_eq_mul_inv, max_mul_mul_left, max_inv_inv']
@[to_additive max_zero_sub_eq_self]
lemma max_one_div_eq_self' (a : α) : max a 1 / max (a⁻¹) 1 = a :=
begin
rcases le_total a 1,
{ rw [max_eq_right h, max_eq_left, one_div, inv_inv], { rwa [le_inv', one_inv] } },
{ rw [max_eq_left, max_eq_right, div_eq_mul_inv, one_inv, mul_one],
{ rwa [inv_le', one_inv] }, exact h }
end
@[to_additive eq_zero_of_neg_eq]
lemma eq_one_of_inv_eq' (h : a⁻¹ = a) : a = 1 :=
match lt_trichotomy a 1 with
| or.inl h₁ :=
have 1 < a, from h ▸ one_lt_inv_of_inv h₁,
absurd h₁ this.asymm
| or.inr (or.inl h₁) := h₁
| or.inr (or.inr h₁) :=
have a < 1, from h ▸ inv_inv_of_one_lt h₁,
absurd h₁ this.asymm
end
@[to_additive exists_zero_lt]
lemma exists_one_lt' [nontrivial α] : ∃ (a:α), 1 < a :=
begin
obtain ⟨y, hy⟩ := decidable.exists_ne (1 : α),
cases hy.lt_or_lt,
{ exact ⟨y⁻¹, one_lt_inv'.mpr h⟩ },
{ exact ⟨y, h⟩ }
end
@[priority 100, to_additive] -- see Note [lower instance priority]
instance linear_ordered_comm_group.to_no_top_order [nontrivial α] :
no_top_order α :=
⟨ begin
obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt',
exact λ a, ⟨a * y, lt_mul_of_one_lt_right' a hy⟩
end ⟩
@[priority 100, to_additive] -- see Note [lower instance priority]
instance linear_ordered_comm_group.to_no_bot_order [nontrivial α] : no_bot_order α :=
⟨ begin
obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt',
exact λ a, ⟨a / y, (div_lt_self_iff a).mpr hy⟩
end ⟩
end linear_ordered_comm_group
section linear_ordered_add_comm_group
variables [linear_ordered_add_comm_group α] {a b c : α}
@[simp]
lemma sub_le_sub_flip : a - b ≤ b - a ↔ a ≤ b :=
begin
rw [sub_le_iff_le_add, sub_add_eq_add_sub, le_sub_iff_add_le],
split,
{ intro h,
by_contra H,
rw not_le at H,
apply not_lt.2 h,
exact add_lt_add H H, },
{ intro h,
exact add_le_add h h, }
end
lemma le_of_forall_pos_le_add [densely_ordered α] (h : ∀ ε : α, 0 < ε → a ≤ b + ε) : a ≤ b :=
le_of_forall_le_of_dense $ λ c hc,
calc a ≤ b + (c - b) : h _ (sub_pos_of_lt hc)
... = c : add_sub_cancel'_right _ _
lemma le_iff_forall_pos_le_add [densely_ordered α] : a ≤ b ↔ ∀ ε, 0 < ε → a ≤ b + ε :=
⟨λ h ε ε_pos, le_add_of_le_of_nonneg h ε_pos.le, le_of_forall_pos_le_add⟩
lemma le_of_forall_pos_lt_add (h : ∀ ε : α, 0 < ε → a < b + ε) : a ≤ b :=
le_of_not_lt $ λ h₁, by simpa using h _ (sub_pos_of_lt h₁)
lemma le_iff_forall_pos_lt_add : a ≤ b ↔ ∀ ε, 0 < ε → a < b + ε :=
⟨λ h ε, lt_add_of_le_of_pos h, le_of_forall_pos_lt_add⟩
/-- `abs a` is the absolute value of `a`. -/
def abs (a : α) : α := max a (-a)
lemma abs_choice (x : α) : abs x = x ∨ abs x = -x := max_choice _ _
lemma abs_of_nonneg (h : 0 ≤ a) : abs a = a :=
max_eq_left $ (neg_nonpos.2 h).trans h
lemma abs_of_pos (h : 0 < a) : abs a = a :=
abs_of_nonneg h.le
lemma abs_of_nonpos (h : a ≤ 0) : abs a = -a :=
max_eq_right $ h.trans (neg_nonneg.2 h)
lemma abs_of_neg (h : a < 0) : abs a = -a :=
abs_of_nonpos h.le
@[simp] lemma abs_zero : abs 0 = (0:α) :=
abs_of_nonneg le_rfl
@[simp] lemma abs_neg (a : α) : abs (-a) = abs a :=
begin unfold abs, rw [max_comm, neg_neg] end
@[simp] lemma abs_pos : 0 < abs a ↔ a ≠ 0 :=
begin
rcases lt_trichotomy a 0 with (ha|rfl|ha),
{ simp [abs_of_neg ha, neg_pos, ha.ne, ha] },
{ simp },
{ simp [abs_of_pos ha, ha, ha.ne.symm] }
end
lemma abs_pos_of_pos (h : 0 < a) : 0 < abs a := abs_pos.2 h.ne.symm
lemma abs_pos_of_neg (h : a < 0) : 0 < abs a := abs_pos.2 h.ne
lemma abs_sub (a b : α) : abs (a - b) = abs (b - a) :=
by rw [← neg_sub, abs_neg]
lemma abs_le' : abs a ≤ b ↔ a ≤ b ∧ -a ≤ b := max_le_iff
lemma abs_le : abs a ≤ b ↔ - b ≤ a ∧ a ≤ b :=
by rw [abs_le', and.comm, neg_le]
lemma neg_le_of_abs_le (h : abs a ≤ b) : -b ≤ a := (abs_le.mp h).1
lemma le_of_abs_le (h : abs a ≤ b) : a ≤ b := (abs_le.mp h).2
lemma le_abs : a ≤ abs b ↔ a ≤ b ∨ a ≤ -b := le_max_iff
lemma le_abs_self (a : α) : a ≤ abs a := le_max_left _ _
lemma neg_le_abs_self (a : α) : -a ≤ abs a := le_max_right _ _
lemma abs_nonneg (a : α) : 0 ≤ abs a :=
(le_total 0 a).elim (λ h, h.trans (le_abs_self a)) (λ h, (neg_nonneg.2 h).trans $ neg_le_abs_self a)
@[simp] lemma abs_abs (a : α) : abs (abs a) = abs a :=
abs_of_nonneg $ abs_nonneg a
@[simp] lemma abs_eq_zero : abs a = 0 ↔ a = 0 :=
decidable.not_iff_not.1 $ ne_comm.trans $ (abs_nonneg a).lt_iff_ne.symm.trans abs_pos
@[simp] lemma abs_nonpos_iff {a : α} : abs a ≤ 0 ↔ a = 0 :=
(abs_nonneg a).le_iff_eq.trans abs_eq_zero
lemma abs_lt : abs a < b ↔ - b < a ∧ a < b :=
max_lt_iff.trans $ and.comm.trans $ by rw [neg_lt]
lemma neg_lt_of_abs_lt (h : abs a < b) : -b < a := (abs_lt.mp h).1
lemma lt_of_abs_lt (h : abs a < b) : a < b := (abs_lt.mp h).2
lemma lt_abs : a < abs b ↔ a < b ∨ a < -b := lt_max_iff
lemma max_sub_min_eq_abs' (a b : α) : max a b - min a b = abs (a - b) :=
begin
cases le_total a b with ab ba,
{ rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos },
{ rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], rwa sub_nonneg }
end
lemma max_sub_min_eq_abs (a b : α) : max a b - min a b = abs (b - a) :=
by { rw [abs_sub], exact max_sub_min_eq_abs' _ _ }
lemma abs_add (a b : α) : abs (a + b) ≤ abs a + abs b :=
abs_le.2 ⟨(neg_add (abs a) (abs b)).symm ▸
add_le_add (neg_le.2 $ neg_le_abs_self _) (neg_le.2 $ neg_le_abs_self _),
add_le_add (le_abs_self _) (le_abs_self _)⟩
lemma abs_sub_le_iff : abs (a - b) ≤ c ↔ a - b ≤ c ∧ b - a ≤ c :=
by rw [abs_le, neg_le_sub_iff_le_add, @sub_le_iff_le_add' _ _ b, and_comm]
lemma abs_sub_lt_iff : abs (a - b) < c ↔ a - b < c ∧ b - a < c :=
by rw [abs_lt, neg_lt_sub_iff_lt_add, @sub_lt_iff_lt_add' _ _ b, and_comm]
lemma sub_le_of_abs_sub_le_left (h : abs (a - b) ≤ c) : b - c ≤ a :=
sub_le.1 $ (abs_sub_le_iff.1 h).2
lemma sub_le_of_abs_sub_le_right (h : abs (a - b) ≤ c) : a - c ≤ b :=
sub_le_of_abs_sub_le_left (abs_sub a b ▸ h)
lemma sub_lt_of_abs_sub_lt_left (h : abs (a - b) < c) : b - c < a :=
sub_lt.1 $ (abs_sub_lt_iff.1 h).2
lemma sub_lt_of_abs_sub_lt_right (h : abs (a - b) < c) : a - c < b :=
sub_lt_of_abs_sub_lt_left (abs_sub a b ▸ h)
lemma abs_sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) :=
sub_le_iff_le_add.2 $
calc abs a = abs (a - b + b) : by rw [sub_add_cancel]
... ≤ abs (a - b) + abs b : abs_add _ _
lemma abs_abs_sub_abs_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) :=
abs_sub_le_iff.2 ⟨abs_sub_abs_le_abs_sub _ _, by rw abs_sub; apply abs_sub_abs_le_abs_sub⟩
lemma eq_or_eq_neg_of_abs_eq (h : abs a = b) : a = b ∨ a = -b :=
by simpa only [← h, eq_comm, eq_neg_iff_eq_neg] using abs_choice a
lemma abs_eq (hb : 0 ≤ b) : abs a = b ↔ a = b ∨ a = -b :=
begin
refine ⟨eq_or_eq_neg_of_abs_eq, _⟩,
rintro (rfl|rfl); simp only [abs_neg, abs_of_nonneg hb]
end
lemma abs_eq_abs : abs a = abs b ↔ a = b ∨ a = -b :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ obtain rfl | rfl := eq_or_eq_neg_of_abs_eq h;
simpa only [neg_eq_iff_neg_eq, neg_inj, or.comm, @eq_comm _ (-b)] using abs_choice b },
{ cases h; simp only [h, abs_neg] },
end
lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : abs b ≤ max (abs a) (abs c) :=
abs_le'.2
⟨by simp [hbc.trans (le_abs_self c)],
by simp [(neg_le_neg hab).trans (neg_le_abs_self a)]⟩
theorem abs_le_abs (h₀ : a ≤ b) (h₁ : -a ≤ b) : abs a ≤ abs b :=
(abs_le'.2 ⟨h₀, h₁⟩).trans (le_abs_self b)
lemma abs_max_sub_max_le_abs (a b c : α) : abs (max a c - max b c) ≤ abs (a - b) :=
begin
simp_rw [abs_le, le_sub_iff_add_le, sub_le_iff_le_add, ← max_add_add_left],
split; apply max_le_max; simp only [← le_sub_iff_add_le, ← sub_le_iff_le_add, sub_self, neg_le,
neg_le_abs_self, neg_zero, abs_nonneg, le_abs_self]
end
lemma eq_of_abs_sub_eq_zero {a b : α} (h : abs (a - b) = 0) : a = b :=
sub_eq_zero.1 $ abs_eq_zero.1 h
lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) :=
sup_ind _ _ h1 h2
lemma abs_sub_le (a b c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) :=
calc
abs (a - c) = abs (a - b + (b - c)) : by rw [sub_add_sub_cancel]
... ≤ abs (a - b) + abs (b - c) : abs_add _ _
lemma abs_add_three (a b c : α) : abs (a + b + c) ≤ abs a + abs b + abs c :=
(abs_add _ _).trans (add_le_add_right (abs_add _ _) _)
lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub)
(hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb :=
abs_sub_le_iff.2 ⟨sub_le_sub hau hbl, sub_le_sub hbu hal⟩
lemma eq_of_abs_sub_nonpos (h : abs (a - b) ≤ 0) : a = b :=
eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b)))
instance with_top.linear_ordered_add_comm_group_with_top :
linear_ordered_add_comm_group_with_top (with_top α) :=
{ neg := option.map (λ a : α, -a),
neg_top := @option.map_none _ _ (λ a : α, -a),
add_neg_cancel := begin
rintro (a | a) ha,
{ exact (ha rfl).elim },
exact with_top.coe_add.symm.trans (with_top.coe_eq_coe.2 (add_neg_self a)),
end,
.. with_top.linear_ordered_add_comm_monoid_with_top,
.. option.nontrivial }
end linear_ordered_add_comm_group
/-- This is not so much a new structure as a construction mechanism
for ordered groups, by specifying only the "positive cone" of the group. -/
class nonneg_add_comm_group (α : Type*) extends add_comm_group α :=
(nonneg : α → Prop)
(pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a))
(pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac)
(zero_nonneg : nonneg 0)
(add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b))
(nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0)
namespace nonneg_add_comm_group
variable [s : nonneg_add_comm_group α]
include s
@[reducible, priority 100] -- see Note [lower instance priority]
instance to_ordered_add_comm_group : ordered_add_comm_group α :=
{ le := λ a b, nonneg (b - a),
lt := λ a b, pos (b - a),
lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp,
le_refl := λ a, by simp [zero_nonneg],
le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg];
rw ← sub_add_sub_cancel; exact add_nonneg nbc nab,
le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $
nonneg_antisymm nba (by rw neg_sub; exact nab),
add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab,
..s }
theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a :=
show _ ↔ nonneg _, by simp
theorem pos_def {a : α} : pos a ↔ 0 < a :=
show _ ↔ pos _, by simp
theorem not_zero_pos : ¬ pos (0 : α) :=
mt pos_def.1 (lt_irrefl _)
theorem zero_lt_iff_nonneg_nonneg {a : α} :
0 < a ↔ nonneg a ∧ ¬ nonneg (-a) :=
pos_def.symm.trans (pos_iff _)
theorem nonneg_total_iff :
(∀ a : α, nonneg a ∨ nonneg (-a)) ↔
(∀ a b : α, a ≤ b ∨ b ≤ a) :=
⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this,
λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩
/--
A `nonneg_add_comm_group` is a `linear_ordered_add_comm_group`
if `nonneg` is total and decidable.
-/
def to_linear_ordered_add_comm_group
[decidable_pred (@nonneg α _)]
(nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a))
: linear_ordered_add_comm_group α :=
{ le := (≤),
lt := (<),
le_total := nonneg_total_iff.1 nonneg_total,
decidable_le := by apply_instance,
decidable_lt := by apply_instance,
..@nonneg_add_comm_group.to_ordered_add_comm_group _ s }
end nonneg_add_comm_group
namespace order_dual
instance [ordered_add_comm_group α] : ordered_add_comm_group (order_dual α) :=
{ add_left_neg := λ a : α, add_left_neg a,
sub := λ a b, (a - b : α),
..order_dual.ordered_add_comm_monoid,
..show add_comm_group α, by apply_instance }
instance [linear_ordered_add_comm_group α] :
linear_ordered_add_comm_group (order_dual α) :=
{ add_le_add_left := λ a b h c, by exact add_le_add_left h _,
..order_dual.linear_order α,
..show add_comm_group α, by apply_instance }
end order_dual
namespace prod
variables {G H : Type*}
@[to_additive]
instance [ordered_comm_group G] [ordered_comm_group H] :
ordered_comm_group (G × H) :=
{ .. prod.comm_group, .. prod.partial_order G H, .. prod.ordered_cancel_comm_monoid }
end prod
section type_tags
instance [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) :=
{ ..multiplicative.comm_group,
..multiplicative.ordered_comm_monoid }
instance [ordered_comm_group α] : ordered_add_comm_group (additive α) :=
{ ..additive.add_comm_group,
..additive.ordered_add_comm_monoid }
instance [linear_ordered_add_comm_group α] : linear_ordered_comm_group (multiplicative α) :=
{ ..multiplicative.linear_order,
..multiplicative.ordered_comm_group }
instance [linear_ordered_comm_group α] : linear_ordered_add_comm_group (additive α) :=
{ ..additive.linear_order,
..additive.ordered_add_comm_group }
end type_tags
|
f3e1c710096c1bcb37db39663ac7d709bf53770c | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/category_theory/closed/zero.lean | 04f35974b8dc308ec94d867b835ec7e146dc9365 | [
"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 | 2,094 | 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.closed.cartesian
import category_theory.limits.shapes.zero
import category_theory.punit
import category_theory.conj
/-!
# A cartesian closed category with zero object is trivial
A cartesian closed category with zero object is trivial: it is equivalent to the category with one
object and one morphism.
## References
* https://mathoverflow.net/a/136480
-/
universes v u
noncomputable theory
namespace category_theory
open category limits
variables {C : Type u} [category.{v} C]
variables [has_finite_products C] [cartesian_closed C]
/--
If a cartesian closed category has an initial object which is isomorphic to the terminal object,
then each homset has exactly one element.
-/
def unique_homset_of_initial_iso_terminal [has_initial C] (i : ⊥_ C ≅ ⊤_ C) (X Y : C) :
unique (X ⟶ Y) :=
equiv.unique $
calc (X ⟶ Y) ≃ (X ⨯ ⊤_ C ⟶ Y) : iso.hom_congr (prod.right_unitor _).symm (iso.refl _)
... ≃ (X ⨯ ⊥_ C ⟶ Y) : iso.hom_congr (prod.map_iso (iso.refl _) i.symm) (iso.refl _)
... ≃ (⊥_ C ⟶ Y ^^ X) : (exp.adjunction _).hom_equiv _ _
open_locale zero_object
/-- If a cartesian closed category has a zero object, each homset has exactly one element. -/
def unique_homset_of_zero [has_zero_object C] (X Y : C) :
unique (X ⟶ Y) :=
begin
haveI : has_initial C := has_zero_object.has_initial,
apply unique_homset_of_initial_iso_terminal _ X Y,
refine ⟨default, (default : ⊤_ C ⟶ 0) ≫ default, _, _⟩; simp
end
local attribute [instance] unique_homset_of_zero
/--
A cartesian closed category with a zero object is equivalent to the category with one object and
one morphism.
-/
def equiv_punit [has_zero_object C] : C ≌ discrete punit :=
equivalence.mk
(functor.star C)
(functor.from_punit 0)
(nat_iso.of_components
(λ X, { hom := default, inv := default })
(λ X Y f, dec_trivial))
(functor.punit_ext _ _)
end category_theory
|
3ab1f7baaac38cd6df7ec88abdadff94ab6c9020 | cf39355caa609c0f33405126beee2739aa3cb77e | /library/init/data/list/basic.lean | 2f77bc0bab6c887ffc39857aa7c12fc92fc5d637 | [
"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 | 11,067 | 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.logic init.data.nat.basic init.data.bool.basic init.propext
open decidable list
universes u v w
instance (α : Type u) : inhabited (list α) :=
⟨list.nil⟩
variables {α : Type u} {β : Type v} {γ : Type w}
namespace list
protected def has_dec_eq [s : decidable_eq α] : decidable_eq (list α)
| [] [] := is_true rfl
| (a::as) [] := is_false (λ h, list.no_confusion h)
| [] (b::bs) := is_false (λ h, list.no_confusion h)
| (a::as) (b::bs) :=
match s a b with
| is_true hab :=
match has_dec_eq as bs with
| is_true habs := is_true (eq.subst hab (eq.subst habs rfl))
| is_false nabs := is_false (λ h, list.no_confusion h (λ _ habs, absurd habs nabs))
end
| is_false nab := is_false (λ h, list.no_confusion h (λ hab _, absurd hab nab))
end
instance [decidable_eq α] : decidable_eq (list α) :=
list.has_dec_eq
@[simp] protected def append : list α → list α → list α
| [] l := l
| (h :: s) t := h :: (append s t)
instance : has_append (list α) :=
⟨list.append⟩
protected def mem : α → list α → Prop
| a [] := false
| a (b :: l) := a = b ∨ mem a l
instance : has_mem α (list α) :=
⟨list.mem⟩
instance decidable_mem [decidable_eq α] (a : α) : ∀ (l : list α), decidable (a ∈ l)
| [] := is_false not_false
| (b::l) :=
if h₁ : a = b then is_true (or.inl h₁)
else match decidable_mem l with
| is_true h₂ := is_true (or.inr h₂)
| is_false h₂ := is_false (not_or h₁ h₂)
end
instance : has_emptyc (list α) :=
⟨list.nil⟩
protected def erase {α} [decidable_eq α] : list α → α → list α
| [] b := []
| (a::l) b := if a = b then l else a :: erase l b
protected def bag_inter {α} [decidable_eq α] : list α → list α → list α
| [] _ := []
| _ [] := []
| (a::l₁) l₂ := if a ∈ l₂ then a :: bag_inter l₁ (l₂.erase a) else bag_inter l₁ l₂
protected def diff {α} [decidable_eq α] : list α → list α → list α
| l [] := l
| l₁ (a::l₂) := if a ∈ l₁ then diff (l₁.erase a) l₂ else diff l₁ l₂
@[simp] def length : list α → nat
| [] := 0
| (a :: l) := length l + 1
def empty : list α → bool
| [] := tt
| (_ :: _) := ff
open option nat
@[simp] def nth : list α → nat → option α
| [] n := none
| (a :: l) 0 := some a
| (a :: l) (n+1) := nth l n
@[simp] def nth_le : Π (l : list α) (n), n < l.length → α
| [] n h := absurd h n.not_lt_zero
| (a :: l) 0 h := a
| (a :: l) (n+1) h := nth_le l n (le_of_succ_le_succ h)
@[simp] def head [inhabited α] : list α → α
| [] := default
| (a :: l) := a
@[simp] def tail : list α → list α
| [] := []
| (a :: l) := l
def reverse_core : list α → list α → list α
| [] r := r
| (a::l) r := reverse_core l (a::r)
def reverse : list α → list α :=
λ l, reverse_core l []
@[simp] def map (f : α → β) : list α → list β
| [] := []
| (a :: l) := f a :: map l
@[simp] def map₂ (f : α → β → γ) : list α → list β → list γ
| [] _ := []
| _ [] := []
| (x::xs) (y::ys) := f x y :: map₂ xs ys
def map_with_index_core (f : ℕ → α → β) : ℕ → list α → list β
| k [] := []
| k (a::as) := f k a::(map_with_index_core (k+1) as)
/-- Given a function `f : ℕ → α → β` and `as : list α`, `as = [a₀, a₁, ...]`, returns the list
`[f 0 a₀, f 1 a₁, ...]`. -/
def map_with_index (f : ℕ → α → β) (as : list α) : list β :=
map_with_index_core f 0 as
def join : list (list α) → list α
| [] := []
| (l :: ls) := l ++ join ls
def filter_map (f : α → option β) : list α → list β
| [] := []
| (a::l) :=
match f a with
| none := filter_map l
| some b := b :: filter_map l
end
def filter (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then a :: filter l else filter l
def partition (p : α → Prop) [decidable_pred p] : list α → list α × list α
| [] := ([], [])
| (a::l) := let (l₁, l₂) := partition l in if p a then (a :: l₁, l₂) else (l₁, a :: l₂)
def drop_while (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then drop_while l else a::l
/-- `after p xs` is the suffix of `xs` after the first element that satisfies
`p`, not including that element.
```lean
after (eq 1) [0, 1, 2, 3] = [2, 3]
drop_while (not ∘ eq 1) [0, 1, 2, 3] = [1, 2, 3]
```
-/
def after (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (x :: xs) := if p x then xs else after xs
def span (p : α → Prop) [decidable_pred p] : list α → list α × list α
| [] := ([], [])
| (a::xs) := if p a then let (l, r) := span xs in (a :: l, r) else ([], a::xs)
def find_index (p : α → Prop) [decidable_pred p] : list α → nat
| [] := 0
| (a::l) := if p a then 0 else succ (find_index l)
def index_of [decidable_eq α] (a : α) : list α → nat := find_index (eq a)
def remove_all [decidable_eq α] (xs ys : list α) : list α :=
filter (∉ ys) xs
def update_nth : list α → ℕ → α → list α
| (x::xs) 0 a := a :: xs
| (x::xs) (i+1) a := x :: update_nth xs i a
| [] _ _ := []
def remove_nth : list α → ℕ → list α
| [] _ := []
| (x::xs) 0 := xs
| (x::xs) (i+1) := x :: remove_nth xs i
@[simp] def drop : ℕ → list α → list α
| 0 a := a
| (succ n) [] := []
| (succ n) (x::r) := drop n r
@[simp] def take : ℕ → list α → list α
| 0 a := []
| (succ n) [] := []
| (succ n) (x :: r) := x :: take n r
@[simp] def foldl (f : α → β → α) : α → list β → α
| a [] := a
| a (b :: l) := foldl (f a b) l
@[simp] def foldr (f : α → β → β) (b : β) : list α → β
| [] := b
| (a :: l) := f a (foldr l)
def any (l : list α) (p : α → bool) : bool :=
foldr (λ a r, p a || r) ff l
def all (l : list α) (p : α → bool) : bool :=
foldr (λ a r, p a && r) tt l
def bor (l : list bool) : bool := any l id
def band (l : list bool) : bool := all l id
def zip_with (f : α → β → γ) : list α → list β → list γ
| (x::xs) (y::ys) := f x y :: zip_with xs ys
| _ _ := []
def zip : list α → list β → list (prod α β) :=
zip_with prod.mk
def unzip : list (α × β) → list α × list β
| [] := ([], [])
| ((a, b) :: t) := match unzip t with (al, bl) := (a::al, b::bl) end
protected def insert [decidable_eq α] (a : α) (l : list α) : list α :=
if a ∈ l then l else a :: l
instance [decidable_eq α] : has_insert α (list α) :=
⟨list.insert⟩
instance : has_singleton α (list α) := ⟨λ x, [x]⟩
instance [decidable_eq α] : is_lawful_singleton α (list α) :=
⟨λ x, show (if x ∈ ([] : list α) then [] else [x]) = [x], from if_neg not_false⟩
protected def union [decidable_eq α] (l₁ l₂ : list α) : list α :=
foldr insert l₂ l₁
instance [decidable_eq α] : has_union (list α) :=
⟨list.union⟩
protected def inter [decidable_eq α] (l₁ l₂ : list α) : list α :=
filter (∈ l₂) l₁
instance [decidable_eq α] : has_inter (list α) :=
⟨list.inter⟩
@[simp] def repeat (a : α) : ℕ → list α
| 0 := []
| (succ n) := a :: repeat n
def range_core : ℕ → list ℕ → list ℕ
| 0 l := l
| (succ n) l := range_core n (n :: l)
def range (n : ℕ) : list ℕ :=
range_core n []
def iota : ℕ → list ℕ
| 0 := []
| (succ n) := succ n :: iota n
def enum_from : ℕ → list α → list (ℕ × α)
| n [] := nil
| n (x :: xs) := (n, x) :: enum_from (n + 1) xs
def enum : list α → list (ℕ × α) := enum_from 0
@[simp] def last : Π l : list α, l ≠ [] → α
| [] h := absurd rfl h
| [a] h := a
| (a::b::l) h := last (b::l) (λ h, list.no_confusion h)
def ilast [inhabited α] : list α → α
| [] := arbitrary α
| [a] := a
| [a, b] := b
| (a::b::l) := ilast l
def init : list α → list α
| [] := []
| [a] := []
| (a::l) := a::init l
def intersperse (sep : α) : list α → list α
| [] := []
| [x] := [x]
| (x::xs) := x::sep::intersperse xs
def intercalate (sep : list α) (xs : list (list α)) : list α :=
join (intersperse sep xs)
@[inline] protected def bind {α : Type u} {β : Type v} (a : list α) (b : α → list β) : list β :=
join (map b a)
@[inline] protected def ret {α : Type u} (a : α) : list α :=
[a]
protected def lt [has_lt α] : list α → list α → Prop
| [] [] := false
| [] (b::bs) := true
| (a::as) [] := false
| (a::as) (b::bs) := a < b ∨ (¬ b < a ∧ lt as bs)
instance [has_lt α] : has_lt (list α) :=
⟨list.lt⟩
instance has_decidable_lt [has_lt α] [h : decidable_rel ((<) : α → α → Prop)] : Π l₁ l₂ : list α, decidable (l₁ < l₂)
| [] [] := is_false not_false
| [] (b::bs) := is_true trivial
| (a::as) [] := is_false not_false
| (a::as) (b::bs) :=
match h a b with
| is_true h₁ := is_true (or.inl h₁)
| is_false h₁ :=
match h b a with
| is_true h₂ := is_false (λ h, or.elim h (λ h, absurd h h₁) (λ ⟨h, _⟩, absurd h₂ h))
| is_false h₂ :=
match has_decidable_lt as bs with
| is_true h₃ := is_true (or.inr ⟨h₂, h₃⟩)
| is_false h₃ := is_false (λ h, or.elim h (λ h, absurd h h₁) (λ ⟨_, h⟩, absurd h h₃))
end
end
end
@[reducible] protected def le [has_lt α] (a b : list α) : Prop :=
¬ b < a
instance [has_lt α] : has_le (list α) :=
⟨list.le⟩
instance has_decidable_le [has_lt α] [h : decidable_rel ((<) : α → α → Prop)] : Π l₁ l₂ : list α, decidable (l₁ ≤ l₂) :=
λ a b, not.decidable
lemma le_eq_not_gt [has_lt α] : ∀ l₁ l₂ : list α, (l₁ ≤ l₂) = ¬ (l₂ < l₁) :=
λ l₁ l₂, rfl
lemma lt_eq_not_ge [has_lt α] [decidable_rel ((<) : α → α → Prop)] : ∀ l₁ l₂ : list α, (l₁ < l₂) = ¬ (l₂ ≤ l₁) :=
λ l₁ l₂,
show (l₁ < l₂) = ¬ ¬ (l₁ < l₂), from
eq.subst (propext (not_not_iff (l₁ < l₂))).symm rfl
/-- `is_prefix_of l₁ l₂` returns `tt` iff `l₁` is a prefix of `l₂`. -/
def is_prefix_of [decidable_eq α] : list α → list α → bool
| [] _ := tt
| _ [] := ff
| (a::as) (b::bs) := to_bool (a = b) && is_prefix_of as bs
/-- `is_suffix_of l₁ l₂` returns `tt` iff `l₁` is a suffix of `l₂`. -/
def is_suffix_of [decidable_eq α] (l₁ l₂ : list α) : bool :=
is_prefix_of l₁.reverse l₂.reverse
end list
namespace bin_tree
private def to_list_aux : bin_tree α → list α → list α
| empty as := as
| (leaf a) as := a::as
| (node l r) as := to_list_aux l (to_list_aux r as)
def to_list (t : bin_tree α) : list α :=
to_list_aux t []
end bin_tree
|
fbf516659340dbe1b4d0a478b7013106e2bf1d30 | 59a4b050600ed7b3d5826a8478db0a9bdc190252 | /src/category_theory/natural_isomorphism.lean | dd767a61d9bce1d923713e66a7553213cdcc1d94 | [] | no_license | rwbarton/lean-category-theory | f720268d800b62a25d69842ca7b5d27822f00652 | 00df814d463406b7a13a56f5dcda67758ba1b419 | refs/heads/master | 1,585,366,296,767 | 1,536,151,349,000 | 1,536,151,349,000 | 147,652,096 | 0 | 0 | null | 1,536,226,960,000 | 1,536,226,960,000 | null | UTF-8 | Lean | false | false | 2,451 | 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
import category_theory.isomorphism
import category_theory.functor_category
import category_theory.tactics.obviously
open category_theory
namespace category_theory.nat_iso
universes u₁ u₂ v₁ v₂
variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D]
include 𝒞 𝒟
def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F X ≅ G X :=
{ hom := (α : F ⟶ G) X,
inv := (α.symm : G ⟶ F) X,
hom_inv_id' := begin rw ← functor.category.comp_app, rw iso.hom_inv_id, tidy, end,
inv_hom_id' := begin rw ← functor.category.comp_app, rw iso.inv_hom_id, tidy, end }
instance {F G : C ⥤ D} : has_coe_to_fun (F ≅ G) :=
{ F := λ α, Π X : C, (F X) ≅ (G X),
coe := λ α, app α }
@[simp,search] lemma comp_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) :
((α ≪≫ β) : F ⟹ H) X = α X ≪≫ β X := rfl
@[simp] lemma hom_eq_coe {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.hom X = (α : F ⟶ G) X := rfl
@[simp] lemma inv_eq_symm_coe {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.inv X = (α.symm : G ⟶ F) X := rfl
variables {F G : C ⥤ D}
instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso ((α : F ⟶ G) X) :=
{ inv := α.inv X }
instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso ((α.symm : G ⟶ F) X) :=
{ inv := α.hom X }
variables {X Y : C}
@[simp,search] lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : ((α.symm : G ⟶ F) X) ≫ (F.map f) ≫ ((α : F ⟶ G) Y) = G.map f := by obviously
@[simp,search] lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : ((α : F ⟶ G) X) ≫ (G.map f) ≫ ((α.symm : G ⟶ F) Y) = F.map f := by obviously
def from_components
(app : ∀ X : C, (F X) ≅ (G X))
(naturality : ∀ {X Y : C} (f : X ⟶ Y), (F.map f) ≫ ((app Y) : F Y ⟶ G Y) = ((app X) : F X ⟶ G X) ≫ (G.map f)) : F ≅ G :=
{ hom := { app := λ X, ((app X) : F X ⟶ G X), },
inv := { app := λ X, ((app X).symm : G X ⟶ F X),
naturality' := λ X Y f, begin
let p := congr_arg (λ f, (app X).inv ≫ (f ≫ (app Y).inv)) (eq.symm (naturality f)),
obviously,
end } }
end category_theory.nat_iso |
e0675d4b8dc5c16b34c44a045e8cc6970fbbd5c5 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/measure_theory/integral/circle_integral.lean | ce34938bd33276f3b5f0e93c251e04e7f60d927f | [
"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 | 29,721 | 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 measure_theory.integral.interval_integral
import analysis.normed_space.pointwise
import analysis.special_functions.non_integrable
import analysis.analytic.basic
/-!
# Integral over a circle in `ℂ`
In this file we define `∮ z in C(c, R), f z` to be the integral $\oint_{|z-c|=|R|} f(z)\,dz$ and
prove some properties of this integral. We give definition and prove most lemmas for a function
`f : ℂ → E`, where `E` is a complex Banach space. For this reason,
some lemmas use, e.g., `(z - c)⁻¹ • f z` instead of `f z / (z - c)`.
## Main definitions
* `circle_map c R`: the exponential map $θ ↦ c + R e^{θi}$;
* `circle_integrable f c R`: a function `f : ℂ → E` is integrable on the circle with center `c` and
radius `R` if `f ∘ circle_map c R` is integrable on `[0, 2π]`;
* `circle_integral f c R`: the integral $\oint_{|z-c|=|R|} f(z)\,dz$, defined as
$\int_{0}^{2π}(c + Re^{θ i})' f(c+Re^{θ i})\,dθ$;
* `cauchy_power_series f c R`: the power series that is equal to
$\sum_{n=0}^{\infty} \oint_{|z-c|=R} \left(\frac{w-c}{z - c}\right)^n \frac{1}{z-c}f(z)\,dz$ at
`w - c`. The coefficients of this power series depend only on `f ∘ circle_map c R`, and the power
series converges to `f w` if `f` is differentiable on the closed ball `metric.closed_ball c R`
and `w` belongs to the corresponding open ball.
## Main statements
* `has_fpower_series_on_cauchy_integral`: for any circle integrable function `f`, the power series
`cauchy_power_series f c R`, `R > 0`, converges to the Cauchy integral
`(2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z` on the open disc `metric.ball c R`;
* `circle_integral.integral_sub_zpow_of_undef`, `circle_integral.integral_sub_zpow_of_ne`, and
`circle_integral.integral_sub_inv_of_mem_ball`: formulas for `∮ z in C(c, R), (z - w) ^ n`,
`n : ℤ`. These lemmas cover the following cases:
- `circle_integral.integral_sub_zpow_of_undef`, `n < 0` and `|w - c| = |R|`: in this case the
function is not integrable, so the integral is equal to its default value (zero);
- `circle_integral.integral_sub_zpow_of_ne`, `n ≠ -1`: in the cases not covered by the previous
lemma, we have `(z - w) ^ n = ((z - w) ^ (n + 1) / (n + 1))'`, thus the integral equals zero;
- `circle_integral.integral_sub_inv_of_mem_ball`, `n = -1`, `|w - c| < R`: in this case the
integral is equal to `2πi`.
The case `n = -1`, `|w -c| > R` is not covered by these lemmas. While it is possible to construct
an explicit primitive, it is easier to apply Cauchy theorem, so we postpone the proof till we have
this theorem (see #10000).
## Notation
- `∮ z in C(c, R), f z`: notation for the integral $\oint_{|z-c|=|R|} f(z)\,dz$, defined as
$\int_{0}^{2π}(c + Re^{θ i})' f(c+Re^{θ i})\,dθ$.
## Tags
integral, circle, Cauchy integral
-/
variables {E : Type*} [normed_group E]
noncomputable theory
open_locale real nnreal interval pointwise topological_space
open complex measure_theory topological_space metric function set filter asymptotics
/-!
### `circle_map`, a parametrization of a circle
-/
/-- The exponential map $θ ↦ c + R e^{θi}$. The range of this map is the circle in `ℂ` with center
`c` and radius `|R|`. -/
def circle_map (c : ℂ) (R : ℝ) : ℝ → ℂ := λ θ, c + R * exp (θ * I)
/-- `circle_map` is `2π`-periodic. -/
lemma periodic_circle_map (c : ℂ) (R : ℝ) : periodic (circle_map c R) (2 * π) :=
λ θ, by simp [circle_map, add_mul, exp_periodic _]
lemma set.countable.preimage_circle_map {s : set ℂ} (hs : s.countable) (c : ℂ)
{R : ℝ} (hR : R ≠ 0) : (circle_map c R ⁻¹' s).countable :=
show (coe ⁻¹' ((* I) ⁻¹' (exp ⁻¹' ((*) R ⁻¹' ((+) c ⁻¹' s))))).countable,
from (((hs.preimage (add_right_injective _)).preimage $ mul_right_injective₀ $ of_real_ne_zero.2
hR).preimage_cexp.preimage $ mul_left_injective₀ I_ne_zero).preimage of_real_injective
@[simp] lemma circle_map_sub_center (c : ℂ) (R : ℝ) (θ : ℝ) :
circle_map c R θ - c = circle_map 0 R θ :=
by simp [circle_map]
lemma circle_map_zero (R θ : ℝ) : circle_map 0 R θ = R * exp (θ * I) := zero_add _
@[simp] lemma abs_circle_map_zero (R : ℝ) (θ : ℝ) : abs (circle_map 0 R θ) = |R| :=
by simp [circle_map]
lemma circle_map_mem_sphere' (c : ℂ) (R : ℝ) (θ : ℝ) : circle_map c R θ ∈ sphere c (|R|) :=
by simp
lemma circle_map_mem_sphere (c : ℂ) {R : ℝ} (hR : 0 ≤ R) (θ : ℝ) : circle_map c R θ ∈ sphere c R :=
by simpa only [_root_.abs_of_nonneg hR] using circle_map_mem_sphere' c R θ
lemma circle_map_mem_closed_ball (c : ℂ) {R : ℝ} (hR : 0 ≤ R) (θ : ℝ) :
circle_map c R θ ∈ closed_ball c R :=
sphere_subset_closed_ball (circle_map_mem_sphere c hR θ)
/-- The range of `circle_map c R` is the circle with center `c` and radius `|R|`. -/
@[simp] lemma range_circle_map (c : ℂ) (R : ℝ) : range (circle_map c R) = sphere c (|R|) :=
calc range (circle_map c R) = c +ᵥ R • range (λ θ : ℝ, exp (θ * I)) :
by simp only [← image_vadd, ← image_smul, ← range_comp, vadd_eq_add, circle_map, (∘), real_smul]
... = sphere c (|R|) : by simp [smul_sphere R (0 : ℂ) zero_le_one, real.norm_eq_abs]
/-- The image of `(0, 2π]` under `circle_map c R` is the circle with center `c` and radius `|R|`. -/
@[simp] lemma image_circle_map_Ioc (c : ℂ) (R : ℝ) :
circle_map c R '' Ioc 0 (2 * π) = sphere c (|R|) :=
by rw [← range_circle_map, ← (periodic_circle_map c R).image_Ioc real.two_pi_pos 0, zero_add]
@[simp] lemma circle_map_eq_center_iff {c : ℂ} {R : ℝ} {θ : ℝ} : circle_map c R θ = c ↔ R = 0 :=
by simp [circle_map, exp_ne_zero]
@[simp] lemma circle_map_zero_radius (c : ℂ) : circle_map c 0 = const ℝ c :=
funext $ λ θ, circle_map_eq_center_iff.2 rfl
lemma circle_map_ne_center {c : ℂ} {R : ℝ} (hR : R ≠ 0) {θ : ℝ} : circle_map c R θ ≠ c :=
mt circle_map_eq_center_iff.1 hR
lemma has_deriv_at_circle_map (c : ℂ) (R : ℝ) (θ : ℝ) :
has_deriv_at (circle_map c R) (circle_map 0 R θ * I) θ :=
by simpa only [mul_assoc, one_mul, of_real_clm_apply, circle_map, of_real_one, zero_add]
using ((of_real_clm.has_deriv_at.mul_const I).cexp_real.const_mul (R : ℂ)).const_add c
/- TODO: prove `cont_diff ℝ (circle_map c R)`. This needs a version of `cont_diff.mul`
for multiplication in a normed algebra over the base field. -/
lemma differentiable_circle_map (c : ℂ) (R : ℝ) :
differentiable ℝ (circle_map c R) :=
λ θ, (has_deriv_at_circle_map c R θ).differentiable_at
@[continuity] lemma continuous_circle_map (c : ℂ) (R : ℝ) : continuous (circle_map c R) :=
(differentiable_circle_map c R).continuous
@[measurability] lemma measurable_circle_map (c : ℂ) (R : ℝ) : measurable (circle_map c R) :=
(continuous_circle_map c R).measurable
@[simp] lemma deriv_circle_map (c : ℂ) (R : ℝ) (θ : ℝ) :
deriv (circle_map c R) θ = circle_map 0 R θ * I :=
(has_deriv_at_circle_map _ _ _).deriv
lemma deriv_circle_map_eq_zero_iff {c : ℂ} {R : ℝ} {θ : ℝ} :
deriv (circle_map c R) θ = 0 ↔ R = 0 :=
by simp [I_ne_zero]
lemma deriv_circle_map_ne_zero {c : ℂ} {R : ℝ} {θ : ℝ} (hR : R ≠ 0) :
deriv (circle_map c R) θ ≠ 0 :=
mt deriv_circle_map_eq_zero_iff.1 hR
lemma lipschitz_with_circle_map (c : ℂ) (R : ℝ) :
lipschitz_with R.nnabs (circle_map c R) :=
lipschitz_with_of_nnnorm_deriv_le (differentiable_circle_map _ _) $ λ θ,
nnreal.coe_le_coe.1 $ by simp
/-!
### Integrability of a function on a circle
-/
/-- We say that a function `f : ℂ → E` is integrable on the circle with center `c` and radius `R` if
the function `f ∘ circle_map c R` is integrable on `[0, 2π]`.
Note that the actual function used in the definition of `circle_integral` is
`(deriv (circle_map c R) θ) • f (circle_map c R θ)`. Integrability of this function is equivalent
to integrability of `f ∘ circle_map c R` whenever `R ≠ 0`. -/
def circle_integrable (f : ℂ → E) (c : ℂ) (R : ℝ) : Prop :=
interval_integrable (λ θ : ℝ, f (circle_map c R θ)) volume 0 (2 * π)
@[simp] lemma circle_integrable_const (a : E) (c : ℂ) (R : ℝ) :
circle_integrable (λ _, a) c R :=
interval_integrable_const
namespace circle_integrable
variables {f g : ℂ → E} {c : ℂ} {R : ℝ}
lemma add (hf : circle_integrable f c R) (hg : circle_integrable g c R) :
circle_integrable (f + g) c R :=
hf.add hg
lemma neg (hf : circle_integrable f c R) : circle_integrable (-f) c R := hf.neg
/-- The function we actually integrate over `[0, 2π]` in the definition of `circle_integral` is
integrable. -/
lemma out [normed_space ℂ E] (hf : circle_integrable f c R) :
interval_integrable (λ θ : ℝ, deriv (circle_map c R) θ • f (circle_map c R θ)) volume 0 (2 * π) :=
begin
simp only [circle_integrable, deriv_circle_map, interval_integrable_iff] at *,
refine (hf.norm.const_mul (|R|)).mono' _ _,
{ exact ((continuous_circle_map _ _).ae_strongly_measurable.mul_const I).smul
hf.ae_strongly_measurable },
{ simp [norm_smul] }
end
end circle_integrable
@[simp] lemma circle_integrable_zero_radius {f : ℂ → E} {c : ℂ} : circle_integrable f c 0 :=
by simp [circle_integrable]
lemma circle_integrable_iff [normed_space ℂ E]
{f : ℂ → E} {c : ℂ} (R : ℝ) : circle_integrable f c R ↔
interval_integrable (λ θ : ℝ, deriv (circle_map c R) θ • f (circle_map c R θ)) volume 0 (2 * π) :=
begin
by_cases h₀ : R = 0,
{ simp [h₀], },
refine ⟨λ h, h.out, λ h, _⟩,
simp only [circle_integrable, interval_integrable_iff, deriv_circle_map] at h ⊢,
refine (h.norm.const_mul (|R|⁻¹)).mono' _ _,
{ have H : ∀ {θ}, circle_map 0 R θ * I ≠ 0 := λ θ, by simp [h₀, I_ne_zero],
simpa only [inv_smul_smul₀ H]
using (((continuous_circle_map 0 R).ae_strongly_measurable).mul_const I).ae_measurable
.inv.ae_strongly_measurable.smul h.ae_strongly_measurable },
{ simp [norm_smul, h₀] },
end
lemma continuous_on.circle_integrable' {f : ℂ → E} {c : ℂ} {R : ℝ}
(hf : continuous_on f (sphere c (|R|))) :
circle_integrable f c R :=
(hf.comp_continuous (continuous_circle_map _ _)
(circle_map_mem_sphere' _ _)).interval_integrable _ _
lemma continuous_on.circle_integrable {f : ℂ → E} {c : ℂ} {R : ℝ} (hR : 0 ≤ R)
(hf : continuous_on f (sphere c R)) :
circle_integrable f c R :=
continuous_on.circle_integrable' $ (_root_.abs_of_nonneg hR).symm ▸ hf
/-- The function `λ z, (z - w) ^ n`, `n : ℤ`, is circle integrable on the circle with center `c` and
radius `|R|` if and only if `R = 0` or `0 ≤ n`, or `w` does not belong to this circle. -/
@[simp] lemma circle_integrable_sub_zpow_iff {c w : ℂ} {R : ℝ} {n : ℤ} :
circle_integrable (λ z, (z - w) ^ n) c R ↔ R = 0 ∨ 0 ≤ n ∨ w ∉ sphere c (|R|) :=
begin
split,
{ intro h, contrapose! h, rcases h with ⟨hR, hn, hw⟩,
simp only [circle_integrable_iff R, deriv_circle_map],
rw ← image_circle_map_Ioc at hw, rcases hw with ⟨θ, hθ, rfl⟩,
replace hθ : θ ∈ [0, 2 * π], from Icc_subset_interval (Ioc_subset_Icc_self hθ),
refine not_interval_integrable_of_sub_inv_is_O_punctured _ real.two_pi_pos.ne hθ,
set f : ℝ → ℂ := λ θ', circle_map c R θ' - circle_map c R θ,
have : ∀ᶠ θ' in 𝓝[≠] θ, f θ' ∈ ball (0 : ℂ) 1 \ {0},
{ suffices : ∀ᶠ z in 𝓝[≠] (circle_map c R θ), z - circle_map c R θ ∈ ball (0 : ℂ) 1 \ {0},
from ((differentiable_circle_map c R θ).has_deriv_at.tendsto_punctured_nhds
(deriv_circle_map_ne_zero hR)).eventually this,
filter_upwards [self_mem_nhds_within,
mem_nhds_within_of_mem_nhds (ball_mem_nhds _ zero_lt_one)],
simp [dist_eq, sub_eq_zero] { contextual := tt } },
refine ((((has_deriv_at_circle_map c R θ).is_O_sub).mono inf_le_left).inv_rev
(this.mono (λ θ', and.right))).trans _,
refine is_O.of_bound (|R|)⁻¹ (this.mono $ λ θ' hθ', _),
set x := abs (f θ'),
suffices : x⁻¹ ≤ x ^ n, by simpa [inv_mul_cancel_left₀, mt _root_.abs_eq_zero.1 hR],
have : x ∈ Ioo (0 : ℝ) 1, by simpa [and.comm, x] using hθ',
rw ← zpow_neg_one,
refine (zpow_strict_anti this.1 this.2).le_iff_le.2 (int.lt_add_one_iff.1 _), exact hn },
{ rintro (rfl|H),
exacts [circle_integrable_zero_radius,
((continuous_on_id.sub continuous_on_const).zpow₀ _ $ λ z hz, H.symm.imp_left $
λ hw, sub_ne_zero.2 $ ne_of_mem_of_not_mem hz hw).circle_integrable'] },
end
@[simp] lemma circle_integrable_sub_inv_iff {c w : ℂ} {R : ℝ} :
circle_integrable (λ z, (z - w)⁻¹) c R ↔ R = 0 ∨ w ∉ sphere c (|R|) :=
by { simp only [← zpow_neg_one, circle_integrable_sub_zpow_iff], norm_num }
variables [normed_space ℂ E] [complete_space E]
/-- Definition for $\oint_{|z-c|=R} f(z)\,dz$. -/
def circle_integral (f : ℂ → E) (c : ℂ) (R : ℝ) : E :=
∫ (θ : ℝ) in 0..2 * π, deriv (circle_map c R) θ • f (circle_map c R θ)
notation `∮` binders ` in ` `C(` c `, ` R `)` `, ` r:(scoped:60 f, circle_integral f c R) := r
lemma circle_integral_def_Icc (f : ℂ → E) (c : ℂ) (R : ℝ) :
∮ z in C(c, R), f z = ∫ θ in Icc 0 (2 * π), deriv (circle_map c R) θ • f (circle_map c R θ) :=
by simp only [circle_integral, interval_integral.integral_of_le real.two_pi_pos.le,
measure.restrict_congr_set Ioc_ae_eq_Icc]
namespace circle_integral
@[simp] lemma integral_radius_zero (f : ℂ → E) (c : ℂ) : ∮ z in C(c, 0), f z = 0 :=
by simp [circle_integral]
lemma integral_congr {f g : ℂ → E} {c : ℂ} {R : ℝ} (hR : 0 ≤ R) (h : eq_on f g (sphere c R)) :
∮ z in C(c, R), f z = ∮ z in C(c, R), g z :=
interval_integral.integral_congr $ λ θ hθ, by simp only [h (circle_map_mem_sphere _ hR _)]
lemma integral_sub_inv_smul_sub_smul (f : ℂ → E) (c w : ℂ) (R : ℝ) :
∮ z in C(c, R), (z - w)⁻¹ • (z - w) • f z = ∮ z in C(c, R), f z :=
begin
rcases eq_or_ne R 0 with rfl|hR, { simp only [integral_radius_zero] },
have : countable (circle_map c R ⁻¹' {w}), from (countable_singleton _).preimage_circle_map c hR,
refine interval_integral.integral_congr_ae ((this.ae_not_mem _).mono $ λ θ hθ hθ', _),
change circle_map c R θ ≠ w at hθ,
simp only [inv_smul_smul₀ (sub_ne_zero.2 $ hθ)]
end
lemma integral_undef {f : ℂ → E} {c : ℂ} {R : ℝ} (hf : ¬circle_integrable f c R) :
∮ z in C(c, R), f z = 0 :=
interval_integral.integral_undef (mt (circle_integrable_iff R).mpr hf)
lemma integral_sub {f g : ℂ → E} {c : ℂ} {R : ℝ} (hf : circle_integrable f c R)
(hg : circle_integrable g c R) :
∮ z in C(c, R), f z - g z = (∮ z in C(c, R), f z) - ∮ z in C(c, R), g z :=
by simp only [circle_integral, smul_sub, interval_integral.integral_sub hf.out hg.out]
lemma norm_integral_le_of_norm_le_const' {f : ℂ → E} {c : ℂ} {R C : ℝ}
(hf : ∀ z ∈ sphere c (|R|), ∥f z∥ ≤ C) :
∥∮ z in C(c, R), f z∥ ≤ 2 * π * |R| * C :=
calc ∥∮ z in C(c, R), f z∥ ≤ |R| * C * |2 * π - 0| :
interval_integral.norm_integral_le_of_norm_le_const $ λ θ _,
(calc ∥deriv (circle_map c R) θ • f (circle_map c R θ)∥ = |R| * ∥f (circle_map c R θ)∥ :
by simp [norm_smul]
... ≤ |R| * C : mul_le_mul_of_nonneg_left (hf _ $ circle_map_mem_sphere' _ _ _)
(_root_.abs_nonneg _))
... = 2 * π * |R| * C :
by { rw [sub_zero, _root_.abs_of_pos real.two_pi_pos], ac_refl }
lemma norm_integral_le_of_norm_le_const {f : ℂ → E} {c : ℂ} {R C : ℝ} (hR : 0 ≤ R)
(hf : ∀ z ∈ sphere c R, ∥f z∥ ≤ C) :
∥∮ z in C(c, R), f z∥ ≤ 2 * π * R * C :=
have |R| = R, from _root_.abs_of_nonneg hR,
calc ∥∮ z in C(c, R), f z∥ ≤ 2 * π * |R| * C :
norm_integral_le_of_norm_le_const' $ by rwa this
... = 2 * π * R * C : by rw this
lemma norm_two_pi_I_inv_smul_integral_le_of_norm_le_const {f : ℂ → E} {c : ℂ} {R C : ℝ} (hR : 0 ≤ R)
(hf : ∀ z ∈ sphere c R, ∥f z∥ ≤ C) :
∥(2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), f z∥ ≤ R * C :=
begin
have : ∥(2 * π * I : ℂ)⁻¹∥ = (2 * π)⁻¹, by simp [real.pi_pos.le],
rw [norm_smul, this, ← div_eq_inv_mul, div_le_iff real.two_pi_pos, mul_comm (R * C), ← mul_assoc],
exact norm_integral_le_of_norm_le_const hR hf
end
/-- If `f` is continuous on the circle `|z - c| = R`, `R > 0`, the `∥f z∥` is less than or equal to
`C : ℝ` on this circle, and this norm is strictly less than `C` at some point `z` of the circle,
then `∥∮ z in C(c, R), f z∥ < 2 * π * R * C`. -/
lemma norm_integral_lt_of_norm_le_const_of_lt {f : ℂ → E} {c : ℂ} {R C : ℝ} (hR : 0 < R)
(hc : continuous_on f (sphere c R)) (hf : ∀ z ∈ sphere c R, ∥f z∥ ≤ C)
(hlt : ∃ z ∈ sphere c R, ∥f z∥ < C) :
∥∮ z in C(c, R), f z∥ < 2 * π * R * C :=
begin
rw [← _root_.abs_of_pos hR, ← image_circle_map_Ioc] at hlt,
rcases hlt with ⟨_, ⟨θ₀, hmem, rfl⟩, hlt⟩,
calc ∥∮ z in C(c, R), f z∥ ≤ ∫ θ in 0..2 * π, ∥deriv (circle_map c R) θ • f (circle_map c R θ)∥ :
interval_integral.norm_integral_le_integral_norm real.two_pi_pos.le
... < ∫ θ in 0..2 * π, R * C :
begin
simp only [norm_smul, deriv_circle_map, norm_eq_abs, complex.abs_mul, abs_I, mul_one,
abs_circle_map_zero, abs_of_pos hR],
refine interval_integral.integral_lt_integral_of_continuous_on_of_le_of_exists_lt
real.two_pi_pos _ continuous_on_const (λ θ hθ, _) ⟨θ₀, Ioc_subset_Icc_self hmem, _⟩,
{ exact continuous_on_const.mul (hc.comp (continuous_circle_map _ _).continuous_on
(λ θ hθ, circle_map_mem_sphere _ hR.le _)).norm },
{ exact mul_le_mul_of_nonneg_left (hf _ $ circle_map_mem_sphere _ hR.le _) hR.le },
{ exact (mul_lt_mul_left hR).2 hlt }
end
... = 2 * π * R * C : by simp [mul_assoc]
end
@[simp] lemma integral_smul {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] [smul_comm_class 𝕜 ℂ E]
(a : 𝕜) (f : ℂ → E) (c : ℂ) (R : ℝ) :
∮ z in C(c, R), a • f z = a • ∮ z in C(c, R), f z :=
by simp only [circle_integral, ← smul_comm a, interval_integral.integral_smul]
@[simp] lemma integral_smul_const (f : ℂ → ℂ) (a : E) (c : ℂ) (R : ℝ) :
∮ z in C(c, R), (f z • a) = (∮ z in C(c, R), f z) • a :=
by simp only [circle_integral, interval_integral.integral_smul_const, ← smul_assoc]
@[simp] lemma integral_const_mul (a : ℂ) (f : ℂ → ℂ) (c : ℂ) (R : ℝ) :
∮ z in C(c, R), a * f z = a * ∮ z in C(c, R), f z :=
integral_smul a f c R
@[simp] lemma integral_sub_center_inv (c : ℂ) {R : ℝ} (hR : R ≠ 0) :
∮ z in C(c, R), (z - c)⁻¹ = 2 * π * I :=
by simp [circle_integral, ← div_eq_mul_inv, mul_div_cancel_left _ (circle_map_ne_center hR)]
/-- If `f' : ℂ → E` is a derivative of a complex differentiable function on the circle
`metric.sphere c |R|`, then `∮ z in C(c, R), f' z = 0`. -/
lemma integral_eq_zero_of_has_deriv_within_at' {f f' : ℂ → E} {c : ℂ} {R : ℝ}
(h : ∀ z ∈ sphere c (|R|), has_deriv_within_at f (f' z) (sphere c (|R|)) z) :
∮ z in C(c, R), f' z = 0 :=
begin
by_cases hi : circle_integrable f' c R,
{ rw ← sub_eq_zero.2 ((periodic_circle_map c R).comp f).eq,
refine interval_integral.integral_eq_sub_of_has_deriv_at (λ θ hθ, _) hi.out,
exact (h _ (circle_map_mem_sphere' _ _ _)).scomp_has_deriv_at θ
(differentiable_circle_map _ _ _).has_deriv_at (circle_map_mem_sphere' _ _) },
{ exact integral_undef hi }
end
/-- If `f' : ℂ → E` is a derivative of a complex differentiable function on the circle
`metric.sphere c R`, then `∮ z in C(c, R), f' z = 0`. -/
lemma integral_eq_zero_of_has_deriv_within_at {f f' : ℂ → E} {c : ℂ} {R : ℝ} (hR : 0 ≤ R)
(h : ∀ z ∈ sphere c R, has_deriv_within_at f (f' z) (sphere c R) z) :
∮ z in C(c, R), f' z = 0 :=
integral_eq_zero_of_has_deriv_within_at' $ (_root_.abs_of_nonneg hR).symm.subst h
/-- If `n < 0` and `|w - c| = |R|`, then `(z - w) ^ n` is not circle integrable on the circle with
center `c` and radius `(|R|)`, so the integral `∮ z in C(c, R), (z - w) ^ n` is equal to zero. -/
lemma integral_sub_zpow_of_undef {n : ℤ} {c w : ℂ} {R : ℝ} (hn : n < 0) (hw : w ∈ sphere c (|R|)) :
∮ z in C(c, R), (z - w) ^ n = 0 :=
begin
rcases eq_or_ne R 0 with rfl|h0, { apply integral_radius_zero },
apply integral_undef,
simp [circle_integrable_sub_zpow_iff, *]
end
/-- If `n ≠ -1` is an integer number, then the integral of `(z - w) ^ n` over the circle equals
zero. -/
lemma integral_sub_zpow_of_ne {n : ℤ} (hn : n ≠ -1) (c w : ℂ) (R : ℝ) :
∮ z in C(c, R), (z - w) ^ n = 0 :=
begin
rcases em (w ∈ sphere c (|R|) ∧ n < -1) with ⟨hw, hn⟩|H,
{ exact integral_sub_zpow_of_undef (hn.trans dec_trivial) hw },
push_neg at H,
have hd : ∀ z, (z ≠ w ∨ -1 ≤ n) → has_deriv_at (λ z, (z - w) ^ (n + 1) / (n + 1)) ((z - w) ^ n) z,
{ intros z hne,
convert ((has_deriv_at_zpow (n + 1) _ (hne.imp _ _)).comp z
((has_deriv_at_id z).sub_const w)).div_const _ using 1,
{ have hn' : (n + 1 : ℂ) ≠ 0,
by rwa [ne, ← eq_neg_iff_add_eq_zero, ← int.cast_one, ← int.cast_neg, int.cast_inj],
simp [mul_assoc, mul_div_cancel_left _ hn'] },
exacts [sub_ne_zero.2, neg_le_iff_add_nonneg.1] },
refine integral_eq_zero_of_has_deriv_within_at' (λ z hz, (hd z _).has_deriv_within_at),
exact (ne_or_eq z w).imp_right (λ h, H $ h ▸ hz)
end
end circle_integral
/-- The power series that is equal to
$\sum_{n=0}^{\infty} \oint_{|z-c|=R} \left(\frac{w-c}{z - c}\right)^n \frac{1}{z-c}f(z)\,dz$ at
`w - c`. The coefficients of this power series depend only on `f ∘ circle_map c R`, and the power
series converges to `f w` if `f` is differentiable on the closed ball `metric.closed_ball c R` and
`w` belongs to the corresponding open ball. For any circle integrable function `f`, this power
series converges to the Cauchy integral for `f`. -/
def cauchy_power_series (f : ℂ → E) (c : ℂ) (R : ℝ) :
formal_multilinear_series ℂ ℂ E :=
λ n, continuous_multilinear_map.mk_pi_field ℂ _ $
(2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - c)⁻¹ ^ n • (z - c)⁻¹ • f z
lemma cauchy_power_series_apply (f : ℂ → E) (c : ℂ) (R : ℝ) (n : ℕ) (w : ℂ) :
cauchy_power_series f c R n (λ _, w) =
(2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (w / (z - c)) ^ n • (z - c)⁻¹ • f z :=
by simp only [cauchy_power_series, continuous_multilinear_map.mk_pi_field_apply, fin.prod_const,
div_eq_mul_inv, mul_pow, mul_smul, circle_integral.integral_smul, ← smul_comm (w ^ n)]
lemma norm_cauchy_power_series_le (f : ℂ → E) (c : ℂ) (R : ℝ) (n : ℕ) :
∥cauchy_power_series f c R n∥ ≤
(2 * π)⁻¹ * (∫ θ : ℝ in 0..2*π, ∥f (circle_map c R θ)∥) * (|R|⁻¹) ^ n :=
calc ∥cauchy_power_series f c R n∥
= (2 * π)⁻¹ * ∥∮ z in C(c, R), (z - c)⁻¹ ^ n • (z - c)⁻¹ • f z∥ :
by simp [cauchy_power_series, norm_smul, real.pi_pos.le]
... ≤ (2 * π)⁻¹ * ∫ θ in 0..2*π, ∥deriv (circle_map c R) θ • (circle_map c R θ - c)⁻¹ ^ n •
(circle_map c R θ - c)⁻¹ • f (circle_map c R θ)∥ :
mul_le_mul_of_nonneg_left (interval_integral.norm_integral_le_integral_norm real.two_pi_pos.le)
(by simp [real.pi_pos.le])
... = (2 * π)⁻¹ * (|R|⁻¹ ^ n * (|R| * (|R|⁻¹ * ∫ (x : ℝ) in 0..2 * π, ∥f (circle_map c R x)∥))) :
by simp [norm_smul, mul_left_comm (|R|)]
... ≤ (2 * π)⁻¹ * (∫ θ : ℝ in 0..2*π, ∥f (circle_map c R θ)∥) * |R|⁻¹ ^ n :
begin
rcases eq_or_ne R 0 with rfl|hR,
{ cases n; simp [-mul_inv_rev, real.two_pi_pos] },
{ rw [mul_inv_cancel_left₀, mul_assoc, mul_comm (|R|⁻¹ ^ n)],
rwa [ne.def, _root_.abs_eq_zero] }
end
lemma le_radius_cauchy_power_series (f : ℂ → E) (c : ℂ) (R : ℝ≥0) :
↑R ≤ (cauchy_power_series f c R).radius :=
begin
refine (cauchy_power_series f c R).le_radius_of_bound
((2 * π)⁻¹ * (∫ θ : ℝ in 0..2*π, ∥f (circle_map c R θ)∥)) (λ n, _),
refine (mul_le_mul_of_nonneg_right (norm_cauchy_power_series_le _ _ _ _)
(pow_nonneg R.coe_nonneg _)).trans _,
rw [_root_.abs_of_nonneg R.coe_nonneg],
cases eq_or_ne (R ^ n : ℝ) 0 with hR hR,
{ rw [hR, mul_zero],
exact mul_nonneg (inv_nonneg.2 real.two_pi_pos.le)
(interval_integral.integral_nonneg real.two_pi_pos.le (λ _ _, norm_nonneg _)) },
{ rw [inv_pow₀, inv_mul_cancel_right₀ hR] }
end
/-- For any circle integrable function `f`, the power series `cauchy_power_series f c R` multiplied
by `2πI` converges to the integral `∮ z in C(c, R), (z - w)⁻¹ • f z` on the open disc
`metric.ball c R`. -/
lemma has_sum_two_pi_I_cauchy_power_series_integral {f : ℂ → E} {c : ℂ} {R : ℝ} {w : ℂ}
(hf : circle_integrable f c R) (hw : abs w < R) :
has_sum (λ n : ℕ, ∮ z in C(c, R), (w / (z - c)) ^ n • (z - c)⁻¹ • f z)
(∮ z in C(c, R), (z - (c + w))⁻¹ • f z) :=
begin
have hR : 0 < R := (abs_nonneg w).trans_lt hw,
have hwR : abs w / R ∈ Ico (0 : ℝ) 1,
from ⟨div_nonneg (abs_nonneg w) hR.le, (div_lt_one hR).2 hw⟩,
refine interval_integral.has_sum_integral_of_dominated_convergence
(λ n θ, ∥f (circle_map c R θ)∥ * (abs w / R) ^ n) (λ n, _) (λ n, _) _ _ _,
{ simp only [deriv_circle_map],
apply_rules [ae_strongly_measurable.smul, hf.def.1];
{ apply measurable.ae_strongly_measurable, measurability } },
{ simp [norm_smul, abs_of_pos hR, mul_left_comm R, mul_inv_cancel_left₀ hR.ne', mul_comm (∥_∥)] },
{ exact eventually_of_forall (λ _ _, (summable_geometric_of_lt_1 hwR.1 hwR.2).mul_left _) },
{ simpa only [tsum_mul_left, tsum_geometric_of_lt_1 hwR.1 hwR.2]
using hf.norm.mul_continuous_on continuous_on_const },
{ refine eventually_of_forall (λ θ hθ, has_sum.const_smul _),
simp only [smul_smul],
refine has_sum.smul_const _,
have : ∥w / (circle_map c R θ - c)∥ < 1, by simpa [abs_of_pos hR] using hwR.2,
convert (has_sum_geometric_of_norm_lt_1 this).mul_right _,
simp [← sub_sub, ← mul_inv, sub_mul, div_mul_cancel _ (circle_map_ne_center hR.ne')] }
end
/-- For any circle integrable function `f`, the power series `cauchy_power_series f c R`, `R > 0`,
converges to the Cauchy integral `(2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z` on the open
disc `metric.ball c R`. -/
lemma has_sum_cauchy_power_series_integral {f : ℂ → E} {c : ℂ} {R : ℝ} {w : ℂ}
(hf : circle_integrable f c R) (hw : abs w < R) :
has_sum (λ n, cauchy_power_series f c R n (λ _, w))
((2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - (c + w))⁻¹ • f z) :=
begin
simp only [cauchy_power_series_apply],
exact (has_sum_two_pi_I_cauchy_power_series_integral hf hw).const_smul
end
/-- For any circle integrable function `f`, the power series `cauchy_power_series f c R`, `R > 0`,
converges to the Cauchy integral `(2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z` on the open
disc `metric.ball c R`. -/
lemma sum_cauchy_power_series_eq_integral {f : ℂ → E} {c : ℂ} {R : ℝ} {w : ℂ}
(hf : circle_integrable f c R) (hw : abs w < R) :
(cauchy_power_series f c R).sum w =
((2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - (c + w))⁻¹ • f z) :=
(has_sum_cauchy_power_series_integral hf hw).tsum_eq
/-- For any circle integrable function `f`, the power series `cauchy_power_series f c R`, `R > 0`,
converges to the Cauchy integral `(2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z` on the open
disc `metric.ball c R`. -/
lemma has_fpower_series_on_cauchy_integral {f : ℂ → E} {c : ℂ} {R : ℝ≥0}
(hf : circle_integrable f c R) (hR : 0 < R) :
has_fpower_series_on_ball
(λ w, (2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z)
(cauchy_power_series f c R) c R :=
{ r_le := le_radius_cauchy_power_series _ _ _,
r_pos := ennreal.coe_pos.2 hR,
has_sum := λ y hy,
begin
refine has_sum_cauchy_power_series_integral hf _,
rw [← norm_eq_abs, ← coe_nnnorm, nnreal.coe_lt_coe, ← ennreal.coe_lt_coe],
exact mem_emetric_ball_zero_iff.1 hy
end }
namespace circle_integral
/-- Integral $\oint_{|z-c|=R} \frac{dz}{z-w}=2πi$ whenever $|w-c|<R$. -/
lemma integral_sub_inv_of_mem_ball {c w : ℂ} {R : ℝ} (hw : w ∈ ball c R) :
∮ z in C(c, R), (z - w)⁻¹ = 2 * π * I :=
begin
have hR : 0 < R := dist_nonneg.trans_lt hw,
suffices H : has_sum (λ n : ℕ, ∮ z in C(c, R), ((w - c) / (z - c)) ^ n * (z - c)⁻¹) (2 * π * I),
{ have A : circle_integrable (λ _, (1 : ℂ)) c R, from continuous_on_const.circle_integrable',
refine (H.unique _).symm,
simpa only [smul_eq_mul, mul_one, add_sub_cancel'_right]
using has_sum_two_pi_I_cauchy_power_series_integral A hw },
have H : ∀ n : ℕ, n ≠ 0 → ∮ z in C(c, R), (z - c) ^ (-n - 1 : ℤ) = 0,
{ refine λ n hn, integral_sub_zpow_of_ne _ _ _ _, simpa },
have : ∮ z in C(c, R), ((w - c) / (z - c)) ^ 0 * (z - c)⁻¹ = 2 * π * I, by simp [hR.ne'],
refine this ▸ has_sum_single _ (λ n hn, _),
simp only [div_eq_mul_inv, mul_pow, integral_const_mul, mul_assoc],
rw [(integral_congr hR.le (λ z hz, _)).trans (H n hn), mul_zero],
rw [← pow_succ', ← zpow_coe_nat, inv_zpow₀, ← zpow_neg₀, int.coe_nat_succ, neg_add,
sub_eq_add_neg _ (1 : ℤ)]
end
end circle_integral
|
628821d7b88271e2a129a601e41370b583fd38f5 | c512f72c3704cbf8f34addab0d4482633dc46bbe | /src/pca.lean | 239f7e66d3b36fea49c2554b3f7abd93c3909d30 | [] | no_license | iehality/abstract-computability | 7479c2786ecac8e00f3d7be00cbd7cd4a4ae43fc | 19c1a32e748e733c65f3e9e6395e4e56e4330cca | refs/heads/main | 1,680,113,399,119 | 1,616,950,483,000 | 1,616,950,483,000 | 346,220,308 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,349 | lean | import data.option.basic
import tactic
universe variable u
variables {α : Type u}
class pmagma (α : Type u) :=
(mul : α → α → option α)
infixl ` ⬝ ` := pmagma.mul
infix ` ↓= `:50 := λ x y, x = some y
prefix `↓`:80 := some
abbreviation defined : option α → bool := option.is_some
abbreviation udefined : option α → bool := option.is_none
def pmagma.mmul [pmagma α] : option α → option α → option α
| ↓x ↓y := x ⬝ y
| _ _ := none
instance pm_mul [pmagma α] : has_mul (option α) := {mul := @pmagma.mmul α _}
@[simp] lemma pmagma.none_l [pmagma α] (p : option α) : none * p = none := option.cases_on p rfl (λ _, rfl)
@[simp] lemma pmagma.none_r [pmagma α] (p : option α) : p * none = none := option.cases_on p rfl (λ _, rfl)
lemma str_l [pmagma α] {p q : option α} : defined (p * q) → defined p :=
begin
contrapose,
assume (h0 : ¬ defined p),
have e : p = none, from option.not_is_some_iff_eq_none.mp h0,
rw e,
simp,
end
lemma str_r [pmagma α] {p q : option α} : defined (p * q) → defined q :=
begin
contrapose,
assume (h0 : ¬ defined q),
have e : q = none, from option.not_is_some_iff_eq_none.mp h0,
rw e,
simp,
end
def tot [pmagma α] (a : α) : Prop := ∀ x : α, defined (↓a * ↓x) = tt
def pmagma.equiv [pmagma α] (a b : option α) : Prop := ∀ x : α, a * ↓x = b * ↓x
infix ` ≃ `:50 := pmagma.equiv
@[refl] lemma pmagma.refl [pmagma α] (a : option α) : a ≃ a := λ x, rfl
@[trans] lemma pmagma.trans [pmagma α] (a b c : option α) (eab : a ≃ b) (ebc : b ≃ c) : a ≃ c :=
by { intros x, rw (eab x), exact ebc x, }
def total_in (A : set α) [pmagma α] : Prop := ∀ {x y}, x ∈ A → y ∈ A → defined (↓x * ↓y)
def extensional_in (A : set α) [pmagma α] : Prop :=
∀ {x y}, x ∈ A → y ∈ A → (∀ z, z ∈ A → ↓x * ↓z = ↓y * ↓z) → x = y
/- Partial Combinatory Algebra -/
class pca (α : Type u) extends pmagma α :=
(k : α)
(k_constant : ∀ x y : α, k ⬝ x * y = x)
(s : α)
(s_defined : ∀ x y : α, defined (s ⬝ x * y))
(s_substitution : ∀ x y z : α, s ⬝ x * y * z = (x ⬝ z) * (y ⬝ z))
namespace pca
variables [pca α]
lemma ktot : tot (k : α) :=
by { intros x, have h : defined (k ⬝ x * x) = tt, { rw k_constant x x, refl, }, exact str_l h, }
lemma stot : tot (s : α) := λ a, str_l (s_defined a a)
def const (x : α) : α := option.get (ktot x)
def subst (x y : α) : α := option.get (s_defined x y)
def subst' (x : α) : α := option.get (stot x)
notation `𝚔` := const
notation `𝚜` := subst
notation `𝚜'` := subst'
@[simp] lemma k_simp (a : α) : ↓k * ↓a = ↓(𝚔 a) := by { simp [const], }
@[simp] lemma s_simp (a b : α) : ↓s * ↓a * ↓b = ↓(𝚜 a b) := by { simp [subst], refl }
@[simp] lemma k_simp0 (a b : α) : ↓(𝚔 a) * ↓b = ↓a := by { rw ← k_simp, exact k_constant _ _, }
@[simp] lemma s_simp0 (a b c : α) : ↓(𝚜 a b) * ↓c = (↓a * ↓c) * (↓b * ↓c) := by { rw ← s_simp, exact s_substitution _ _ _, }
@[simp] lemma s'_simp (a b : α) : ↓(𝚜' a) * ↓b = ↓𝚜 a b := by { simp[subst'], }
def i : α := 𝚜 k k
@[simp] lemma i_simp (a : α) : ↓i * ↓a = ↓a := by { simp [i], }
lemma itot : tot (i : α) := by { intros x, simp, refl, }
class nontotal (α : Type u) [pmagma α] :=
(div0 div1 : α)
(nontot : div0 ⬝ div1 = none)
namespace nontotal
@[simp] lemma nontototal_simp [pmagma α] [nontotal α] : (↓div0 * ↓div1 : option α) = none := nontot
def divergent [nontotal α] : α := 𝚜 (𝚔 div0) (𝚔 div1)
theorem divergent_udefined [nontotal α] (a : α) : udefined (↓divergent * ↓a) = tt := by { simp[divergent], refl, }
theorem k_ne_s [nontotal α] : (k : α) ≠ s :=
begin
assume e : k = s,
have e0 : ↓(i : α) = ↓divergent,
{ calc
↓(i : α) = ↓k * (↓k * ↓i) * (↓k * ↓divergent) * ↓divergent : by simp
... = ↓s * (↓k * ↓i) * (↓k * ↓divergent) * ↓divergent : by rw e
... = ↓divergent : by simp, },
have c : defined (↓(i : α) * ↓k) = tt, { simp, refl, },
have c0 : defined (↓(i : α) * ↓k) = ff, { rw e0, simp[divergent], },
show false, from bool_iff_false.mpr c0 c,
end
instance [nontotal α] : nontrivial α := ⟨⟨k, s, k_ne_s⟩⟩
end nontotal
end pca
|
26543bc36ead60ee669942b9d02c97af78699798 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/measure_theory/probability_mass_function.lean | 8440980e4081b59ff48f685c1c02f41a1171eaa6 | [
"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 | 4,824 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Probability mass function -- discrete probability measures
-/
import topology.instances.nnreal topology.instances.ennreal topology.algebra.infinite_sum
noncomputable theory
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale classical
/-- Probability mass functions, i.e. discrete probability measures -/
def {u} pmf (α : Type u) : Type u := { f : α → nnreal // has_sum f 1 }
namespace pmf
instance : has_coe_to_fun (pmf α) := ⟨λp, α → nnreal, λp a, p.1 a⟩
@[ext] protected lemma ext : ∀{p q : pmf α}, (∀a, p a = q a) → p = q
| ⟨f, hf⟩ ⟨g, hg⟩ eq := subtype.eq $ funext eq
lemma has_sum_coe_one (p : pmf α) : has_sum p 1 := p.2
lemma summable_coe (p : pmf α) : summable p := (p.has_sum_coe_one).summable
@[simp] lemma tsum_coe (p : pmf α) : (∑a, p a) = 1 := tsum_eq_has_sum p.has_sum_coe_one
def support (p : pmf α) : set α := {a | p.1 a ≠ 0}
def pure (a : α) : pmf α := ⟨λa', if a' = a then 1 else 0, has_sum_ite_eq _ _⟩
@[simp] lemma pure_apply (a a' : α) : pure a a' = (if a' = a then 1 else 0) := rfl
instance [inhabited α] : inhabited (pmf α) := ⟨pure (default α)⟩
lemma coe_le_one (p : pmf α) (a : α) : p a ≤ 1 :=
has_sum_le (by intro b; split_ifs; simp [h]; exact le_refl _) (has_sum_ite_eq a (p a)) p.2
protected lemma bind.summable (p : pmf α) (f : α → pmf β) (b : β) : summable (λa:α, p a * f a b) :=
begin
refine nnreal.summable_of_le (assume a, _) p.summable_coe,
suffices : p a * f a b ≤ p a * 1, { simpa },
exact mul_le_mul_of_nonneg_left ((f a).coe_le_one _) (p a).2
end
def bind (p : pmf α) (f : α → pmf β) : pmf β :=
⟨λb, (∑a, p a * f a b),
begin
apply ennreal.has_sum_coe.1,
simp only [ennreal.coe_tsum (bind.summable p f _)],
rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm],
simp [ennreal.tsum_mul_left, (ennreal.coe_tsum (f _).summable_coe).symm,
(ennreal.coe_tsum p.summable_coe).symm]
end⟩
@[simp] lemma bind_apply (p : pmf α) (f : α → pmf β) (b : β) : p.bind f b = (∑a, p a * f a b) := rfl
lemma coe_bind_apply (p : pmf α) (f : α → pmf β) (b : β) :
(p.bind f b : ennreal) = (∑a, p a * f a b) :=
eq.trans (ennreal.coe_tsum $ bind.summable p f b) $ by simp
@[simp] lemma pure_bind (a : α) (f : α → pmf β) : (pure a).bind f = f a :=
have ∀b a', ite (a' = a) 1 0 * f a' b = ite (a' = a) (f a b) 0, from
assume b a', by split_ifs; simp; subst h; simp,
by ext b; simp [this]
@[simp] lemma bind_pure (p : pmf α) : p.bind pure = p :=
have ∀a a', (p a * ite (a' = a) 1 0) = ite (a = a') (p a') 0, from
assume a a', begin split_ifs; try { subst a }; try { subst a' }; simp * at * end,
by ext b; simp [this]
@[simp] lemma bind_bind (p : pmf α) (f : α → pmf β) (g : β → pmf γ) :
(p.bind f).bind g = p.bind (λa, (f a).bind g) :=
begin
ext b,
simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm,
ennreal.tsum_mul_right.symm],
rw [ennreal.tsum_comm],
simp [mul_assoc, mul_left_comm, mul_comm]
end
lemma bind_comm (p : pmf α) (q : pmf β) (f : α → β → pmf γ) :
p.bind (λa, q.bind (f a)) = q.bind (λb, p.bind (λa, f a b)) :=
begin
ext b,
simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm,
ennreal.tsum_mul_right.symm],
rw [ennreal.tsum_comm],
simp [mul_assoc, mul_left_comm, mul_comm]
end
def map (f : α → β) (p : pmf α) : pmf β := bind p (pure ∘ f)
lemma bind_pure_comp (f : α → β) (p : pmf α) : bind p (pure ∘ f) = map f p := rfl
lemma map_id (p : pmf α) : map id p = p := by simp [map]
lemma map_comp (p : pmf α) (f : α → β) (g : β → γ) : (p.map f).map g = p.map (g ∘ f) :=
by simp [map]
lemma pure_map (a : α) (f : α → β) : (pure a).map f = pure (f a) :=
by simp [map]
def seq (f : pmf (α → β)) (p : pmf α) : pmf β := f.bind (λm, p.bind $ λa, pure (m a))
def of_multiset (s : multiset α) (hs : s ≠ 0) : pmf α :=
⟨λa, s.count a / s.card,
have s.to_finset.sum (λa, (s.count a : ℝ) / s.card) = 1,
by simp [div_eq_inv_mul', finset.mul_sum.symm, (finset.sum_nat_cast _ _).symm, hs],
have s.to_finset.sum (λa, (s.count a : nnreal) / s.card) = 1,
by rw [← nnreal.eq_iff, nnreal.coe_one, ← this, nnreal.coe_sum]; simp,
begin
rw ← this,
apply has_sum_sum_of_ne_finset_zero,
simp {contextual := tt},
end⟩
def of_fintype [fintype α] (f : α → nnreal) (h : finset.univ.sum f = 1) : pmf α :=
⟨f, h ▸ has_sum_sum_of_ne_finset_zero (by simp)⟩
def bernoulli (p : nnreal) (h : p ≤ 1) : pmf bool :=
of_fintype (λb, cond b p (1 - p)) (nnreal.eq $ by simp [h])
end pmf
|
a477533f0fea277a0e6ab95b4d9b9c941c12d639 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/abelian/diagram_lemmas/four.lean | 5cd6428734fc1facf10c5a43c6036b8d8219c8c4 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 7,853 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import category_theory.abelian.pseudoelements
/-!
# The four and five lemmas
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Consider the following commutative diagram with exact rows in an abelian category:
```
A ---f--> B ---g--> C ---h--> D ---i--> E
| | | | |
α β γ δ ε
| | | | |
v v v v v
A' --f'-> B' --g'-> C' --h'-> D' --i'-> E'
```
We show:
- the "mono" version of the four lemma: if `α` is an epimorphism and `β` and `δ` are monomorphisms,
then `γ` is a monomorphism,
- the "epi" version of the four lemma: if `β` and `δ` are epimorphisms and `ε` is a monomorphism,
then `γ` is an epimorphism,
- the five lemma: if `α`, `β`, `δ` and `ε` are isomorphisms, then `γ` is an isomorphism.
## Implementation details
To show the mono version, we use pseudoelements. For the epi version, we use a completely different
arrow-theoretic proof. In theory, it should be sufficient to have one version and the other should
follow automatically by duality. In practice, mathlib's knowledge about duality isn't quite at the
point where this is doable easily.
However, one key duality statement about exactness is needed in the proof of the epi version of the
four lemma: we need to know that exactness of a pair `(f, g)`, which we defined via the map from
the image of `f` to the kernel of `g`, is the same as "co-exactness", defined via the map from the
cokernel of `f` to the coimage of `g` (more precisely, we only need the consequence that if `(f, g)`
is exact, then the factorization of `g` through the cokernel of `f` is monomorphic). Luckily, in the
case of abelian categories, we have the characterization that `(f, g)` is exact if and only if
`f ≫ g = 0` and `kernel.ι g ≫ cokernel.π f = 0`, and the latter condition is self dual, so the
equivalence of exactness and co-exactness follows easily.
## Tags
four lemma, five lemma, diagram lemma, diagram chase
-/
open category_theory (hiding comp_apply)
open category_theory.abelian.pseudoelement
open category_theory.limits
universes v u
variables {V : Type u} [category.{v} V] [abelian V]
local attribute [instance] preadditive.has_equalizers_of_has_kernels
open_locale pseudoelement
namespace category_theory.abelian
variables {A B C D A' B' C' D' : V}
variables {f : A ⟶ B} {g : B ⟶ C} {h : C ⟶ D}
variables {f' : A' ⟶ B'} {g' : B' ⟶ C'} {h' : C' ⟶ D'}
variables {α : A ⟶ A'} {β : B ⟶ B'} {γ : C ⟶ C'} {δ : D ⟶ D'}
variables (comm₁ : α ≫ f' = f ≫ β) (comm₂ : β ≫ g' = g ≫ γ) (comm₃ : γ ≫ h' = h ≫ δ)
include comm₁ comm₂ comm₃
section
variables (hfg : exact f g) (hgh : exact g h) (hf'g' : exact f' g')
/-- The four lemma, mono version. For names of objects and morphisms, refer to the following
diagram:
```
A ---f--> B ---g--> C ---h--> D
| | | |
α β γ δ
| | | |
v v v v
A' --f'-> B' --g'-> C' --h'-> D'
```
-/
lemma mono_of_epi_of_mono_of_mono (hα : epi α) (hβ : mono β) (hδ : mono δ) : mono γ :=
mono_of_zero_of_map_zero _ $ λ c hc,
have h c = 0, from
suffices δ (h c) = 0, from zero_of_map_zero _ (pseudo_injective_of_mono _) _ this,
calc δ (h c) = h' (γ c) : by rw [←comp_apply, ←comm₃, comp_apply]
... = h' 0 : by rw hc
... = 0 : apply_zero _,
exists.elim ((pseudo_exact_of_exact hgh).2 _ this) $ λ b hb,
have g' (β b) = 0, from
calc g' (β b) = γ (g b) : by rw [←comp_apply, comm₂, comp_apply]
... = γ c : by rw hb
... = 0 : hc,
exists.elim ((pseudo_exact_of_exact hf'g').2 _ this) $ λ a' ha',
exists.elim (pseudo_surjective_of_epi α a') $ λ a ha,
have f a = b, from
suffices β (f a) = β b, from pseudo_injective_of_mono _ this,
calc β (f a) = f' (α a) : by rw [←comp_apply, ←comm₁, comp_apply]
... = f' a' : by rw ha
... = β b : ha',
calc c = g b : hb.symm
... = g (f a) : by rw this
... = 0 : (pseudo_exact_of_exact hfg).1 _
end
section
variables (hgh : exact g h) (hf'g' : exact f' g') (hg'h' : exact g' h')
/-- The four lemma, epi version. For names of objects and morphisms, refer to the following
diagram:
```
A ---f--> B ---g--> C ---h--> D
| | | |
α β γ δ
| | | |
v v v v
A' --f'-> B' --g'-> C' --h'-> D'
```
-/
lemma epi_of_epi_of_epi_of_mono (hα : epi α) (hγ : epi γ) (hδ : mono δ) : epi β :=
preadditive.epi_of_cancel_zero _ $ λ R r hβr,
have hf'r : f' ≫ r = 0, from limits.zero_of_epi_comp α $
calc α ≫ f' ≫ r = f ≫ β ≫ r : by rw reassoc_of comm₁
... = f ≫ 0 : by rw hβr
... = 0 : has_zero_morphisms.comp_zero _ _,
let y : R ⟶ pushout r g' := pushout.inl, z : C' ⟶ pushout r g' := pushout.inr in
have mono y, from mono_inl_of_factor_thru_epi_mono_factorization r g' (cokernel.π f')
(cokernel.desc f' g' hf'g'.w) (by simp) (cokernel.desc f' r hf'r) (by simp) _
(colimit.is_colimit _),
have hz : g ≫ γ ≫ z = 0, from
calc g ≫ γ ≫ z = β ≫ g' ≫ z : by rw ←reassoc_of comm₂
... = β ≫ r ≫ y : by rw ←pushout.condition
... = 0 ≫ y : by rw reassoc_of hβr
... = 0 : has_zero_morphisms.zero_comp _ _,
let v : pushout r g' ⟶ pushout (γ ≫ z) (h ≫ δ) := pushout.inl,
w : D' ⟶ pushout (γ ≫ z) (h ≫ δ) := pushout.inr in
have mono v, from mono_inl_of_factor_thru_epi_mono_factorization _ _ (cokernel.π g)
(cokernel.desc g h hgh.w ≫ δ) (by simp) (cokernel.desc _ _ hz) (by simp) _
(colimit.is_colimit _),
have hzv : z ≫ v = h' ≫ w, from (cancel_epi γ).1 $
calc γ ≫ z ≫ v = h ≫ δ ≫ w : by rw [←category.assoc, pushout.condition, category.assoc]
... = γ ≫ h' ≫ w : by rw reassoc_of comm₃,
suffices (r ≫ y) ≫ v = 0, by exactI zero_of_comp_mono _ (zero_of_comp_mono _ this),
calc (r ≫ y) ≫ v = g' ≫ z ≫ v : by rw [pushout.condition, category.assoc]
... = g' ≫ h' ≫ w : by rw hzv
... = 0 ≫ w : hg'h'.w_assoc _
... = 0 : has_zero_morphisms.zero_comp _ _
end
section five
variables {E E' : V} {i : D ⟶ E} {i' : D' ⟶ E'} {ε : E ⟶ E'} (comm₄ : δ ≫ i' = i ≫ ε)
variables (hfg : exact f g) (hgh : exact g h) (hhi : exact h i)
variables (hf'g' : exact f' g') (hg'h' : exact g' h') (hh'i' : exact h' i')
variables [is_iso α] [is_iso β] [is_iso δ] [is_iso ε]
include comm₄ hfg hgh hhi hf'g' hg'h' hh'i'
/-- The five lemma. For names of objects and morphisms, refer to the following diagram:
```
A ---f--> B ---g--> C ---h--> D ---i--> E
| | | | |
α β γ δ ε
| | | | |
v v v v v
A' --f'-> B' --g'-> C' --h'-> D' --i'-> E'
```
-/
lemma is_iso_of_is_iso_of_is_iso_of_is_iso_of_is_iso : is_iso γ :=
have mono γ, by apply mono_of_epi_of_mono_of_mono comm₁ comm₂ comm₃ hfg hgh hf'g'; apply_instance,
have epi γ, by apply epi_of_epi_of_epi_of_mono comm₂ comm₃ comm₄ hhi hg'h' hh'i'; apply_instance,
by exactI is_iso_of_mono_of_epi _
end five
end category_theory.abelian
|
39c2a57a3bcb9d1160be2412ca5424a840c4f01f | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/topology/uniform_space/abstract_completion.lean | 75c54a385929ba0501ebe7ae107fcae6343cd743 | [
"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 | 11,271 | lean | /-
Copyright (c) 2019 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import topology.uniform_space.uniform_embedding
/-!
# Abstract theory of Hausdorff completions of uniform spaces
This file characterizes Hausdorff completions of a uniform space α as complete Hausdorff spaces
equipped with a map from α which has dense image and induce the original uniform structure on α.
Assuming these properties we "extend" uniformly continuous maps from α to complete Hausdorff spaces
to the completions of α. This is the universal property expected from a completion.
It is then used to extend uniformly continuous maps from α to α' to maps between
completions of α and α'.
This file does not construct any such completion, it only study consequences of their existence.
The first advantage is that formal properties are clearly highlighted without interference from
construction details. The second advantage is that this framework can then be used to compare
different completion constructions. See `topology/uniform_space/compare_reals` for an example.
Of course the comparison comes from the universal property as usual.
A general explicit construction of completions is done in `uniform_space/completion`, leading
to a functor from uniform spaces to complete Hausdorff uniform spaces that is left adjoint to the
inclusion, see `uniform_space/UniformSpace` for the category packaging.
## Implementation notes
A tiny technical advantage of using a characteristic predicate such as the properties listed in
`abstract_completion` instead of stating the universal property is that the universal property
derived from the predicate is more universe polymorphic.
## References
We don't know any traditional text discussing this. Real world mathematics simply silently
identify the results of any two constructions that lead to something one could reasonnably
call a completion.
## Tags
uniform spaces, completion, universal property
-/
noncomputable theory
local attribute [instance, priority 10] classical.prop_decidable
open filter set function
universes u
/-- A completion of `α` is the data of a complete separated uniform space (from the same universe)
and a map from `α` with dense range and inducing the original uniform structure on `α`. -/
structure abstract_completion (α : Type u) [uniform_space α] :=
(space : Type u)
(coe : α → space)
(uniform_struct : uniform_space space)
(complete : complete_space space)
(separation : separated_space space)
(uniform_inducing : uniform_inducing coe)
(dense : dense_range coe)
local attribute [instance]
abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation
namespace abstract_completion
variables {α : Type*} [uniform_space α] (pkg : abstract_completion α)
local notation `hatα` := pkg.space
local notation `ι` := pkg.coe
lemma closure_range : closure (range ι) = univ :=
pkg.dense.closure_range
lemma dense_inducing : dense_inducing ι :=
⟨pkg.uniform_inducing.inducing, pkg.dense⟩
lemma uniform_continuous_coe : uniform_continuous ι :=
uniform_inducing.uniform_continuous pkg.uniform_inducing
lemma continuous_coe : continuous ι :=
pkg.uniform_continuous_coe.continuous
@[elab_as_eliminator]
lemma induction_on {p : hatα → Prop}
(a : hatα) (hp : is_closed {a | p a}) (ih : ∀ a, p (ι a)) : p a :=
is_closed_property pkg.dense hp ih a
variables {β : Type*}
protected lemma funext [topological_space β] [t2_space β] {f g : hatα → β}
(hf : continuous f) (hg : continuous g)
(h : ∀ a, f (ι a) = g (ι a)) : f = g :=
funext $ assume a, pkg.induction_on a (is_closed_eq hf hg) h
variables [uniform_space β]
section extend
/-- Extension of maps to completions -/
protected def extend (f : α → β) : hatα → β :=
if uniform_continuous f then
pkg.dense_inducing.extend f
else
λ x, f (pkg.dense.some x)
variables {f : α → β}
lemma extend_def (hf : uniform_continuous f) : pkg.extend f = pkg.dense_inducing.extend f :=
if_pos hf
lemma extend_coe [t2_space β] (hf : uniform_continuous f) (a : α) :
(pkg.extend f) (ι a) = f a :=
begin
rw pkg.extend_def hf,
exact pkg.dense_inducing.extend_eq hf.continuous a
end
variables [complete_space β]
lemma uniform_continuous_extend : uniform_continuous (pkg.extend f) :=
begin
by_cases hf : uniform_continuous f,
{ rw pkg.extend_def hf,
exact uniform_continuous_uniformly_extend (pkg.uniform_inducing)
(pkg.dense) hf },
{ change uniform_continuous (ite _ _ _),
rw if_neg hf,
exact uniform_continuous_of_const (assume a b, by congr) }
end
lemma continuous_extend : continuous (pkg.extend f) :=
pkg.uniform_continuous_extend.continuous
variables [separated_space β]
lemma extend_unique (hf : uniform_continuous f) {g : hatα → β} (hg : uniform_continuous g)
(h : ∀ a : α, f a = g (ι a)) : pkg.extend f = g :=
begin
apply pkg.funext pkg.continuous_extend hg.continuous,
simpa only [pkg.extend_coe hf] using h
end
@[simp] lemma extend_comp_coe {f : hatα → β} (hf : uniform_continuous f) :
pkg.extend (f ∘ ι) = f :=
funext $ λ x, pkg.induction_on x (is_closed_eq pkg.continuous_extend hf.continuous)
(λ y, pkg.extend_coe (hf.comp $ pkg.uniform_continuous_coe) y)
end extend
section map_sec
variables (pkg' : abstract_completion β)
local notation `hatβ` := pkg'.space
local notation `ι'` := pkg'.coe
/-- Lifting maps to completions -/
protected def map (f : α → β) : hatα → hatβ := pkg.extend (ι' ∘ f)
local notation `map` := pkg.map pkg'
variables (f : α → β)
lemma uniform_continuous_map : uniform_continuous (map f) :=
pkg.uniform_continuous_extend
lemma continuous_map : continuous (map f) := pkg.continuous_extend
variables {f}
@[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : map f (ι a) = ι' (f a) :=
pkg.extend_coe (pkg'.uniform_continuous_coe.comp hf) a
lemma map_unique {f : α → β} {g : hatα → hatβ}
(hg : uniform_continuous g) (h : ∀ a, ι' (f a) = g (ι a)) : map f = g :=
pkg.funext (pkg.continuous_map _ _) hg.continuous $
begin
intro a,
change pkg.extend (ι' ∘ f) _ = _,
simp only [(∘), h],
rw [pkg.extend_coe (hg.comp pkg.uniform_continuous_coe)]
end
@[simp] lemma map_id : pkg.map pkg id = id :=
pkg.map_unique pkg uniform_continuous_id (assume a, rfl)
variables {γ : Type*} [uniform_space γ]
lemma extend_map [complete_space γ] [separated_space γ] {f : β → γ} {g : α → β}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
pkg'.extend f ∘ map g = pkg.extend (f ∘ g) :=
pkg.funext (pkg'.continuous_extend.comp (pkg.continuous_map pkg' _)) pkg.continuous_extend $ λ a,
by rw [pkg.extend_coe (hf.comp hg), comp_app, pkg.map_coe pkg' hg, pkg'.extend_coe hf]
variables (pkg'' : abstract_completion γ)
lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) :
(pkg'.map pkg'' g) ∘ (pkg.map pkg' f) = pkg.map pkg'' (g ∘ f) :=
pkg.extend_map pkg' (pkg''.uniform_continuous_coe.comp hg) hf
end map_sec
section compare
-- We can now compare two completion packages for the same uniform space
variables (pkg' : abstract_completion α)
/-- The comparison map between two completions of the same uniform space. -/
def compare : pkg.space → pkg'.space :=
pkg.extend pkg'.coe
lemma uniform_continuous_compare : uniform_continuous (pkg.compare pkg') :=
pkg.uniform_continuous_extend
lemma compare_coe (a : α) : pkg.compare pkg' (pkg.coe a) = pkg'.coe a :=
pkg.extend_coe pkg'.uniform_continuous_coe a
lemma inverse_compare : (pkg.compare pkg') ∘ (pkg'.compare pkg) = id :=
begin
have uc := pkg.uniform_continuous_compare pkg',
have uc' := pkg'.uniform_continuous_compare pkg,
apply pkg'.funext (uc.comp uc').continuous continuous_id,
intro a,
rw [comp_app, pkg'.compare_coe pkg, pkg.compare_coe pkg'],
refl
end
/-- The bijection between two completions of the same uniform space. -/
def compare_equiv : pkg.space ≃ pkg'.space :=
{ to_fun := pkg.compare pkg',
inv_fun := pkg'.compare pkg,
left_inv := congr_fun (pkg'.inverse_compare pkg),
right_inv := congr_fun (pkg.inverse_compare pkg') }
lemma uniform_continuous_compare_equiv : uniform_continuous (pkg.compare_equiv pkg') :=
pkg.uniform_continuous_compare pkg'
lemma uniform_continuous_compare_equiv_symm : uniform_continuous (pkg.compare_equiv pkg').symm :=
pkg'.uniform_continuous_compare pkg
end compare
section prod
variables (pkg' : abstract_completion β)
local notation `hatβ` := pkg'.space
local notation `ι'` := pkg'.coe
/-- Products of completions -/
protected def prod : abstract_completion (α × β) :=
{ space := hatα × hatβ,
coe := λ p, ⟨ι p.1, ι' p.2⟩,
uniform_struct := prod.uniform_space,
complete := by apply_instance,
separation := by apply_instance,
uniform_inducing := uniform_inducing.prod pkg.uniform_inducing pkg'.uniform_inducing,
dense := pkg.dense.prod_map pkg'.dense }
end prod
section extension₂
variables (pkg' : abstract_completion β)
local notation `hatβ` := pkg'.space
local notation `ι'` := pkg'.coe
variables {γ : Type*} [uniform_space γ]
open function
/-- Extend two variable map to completions. -/
protected def extend₂ (f : α → β → γ) : hatα → hatβ → γ :=
curry $ (pkg.prod pkg').extend (uncurry f)
section separated_space
variables [separated_space γ] {f : α → β → γ}
lemma extension₂_coe_coe (hf : uniform_continuous $ uncurry f) (a : α) (b : β) :
pkg.extend₂ pkg' f (ι a) (ι' b) = f a b :=
show (pkg.prod pkg').extend (uncurry f) ((pkg.prod pkg').coe (a, b)) = uncurry f (a, b),
from (pkg.prod pkg').extend_coe hf _
end separated_space
variables {f : α → β → γ}
variables [complete_space γ] (f)
lemma uniform_continuous_extension₂ : uniform_continuous₂ (pkg.extend₂ pkg' f) :=
begin
rw [uniform_continuous₂_def, abstract_completion.extend₂, uncurry_curry],
apply uniform_continuous_extend
end
end extension₂
section map₂
variables (pkg' : abstract_completion β)
local notation `hatβ` := pkg'.space
local notation `ι'` := pkg'.coe
variables {γ : Type*} [uniform_space γ] (pkg'' : abstract_completion γ)
local notation `hatγ` := pkg''.space
local notation `ι''` := pkg''.coe
local notation f ` ∘₂ ` g := bicompr f g
/-- Lift two variable maps to completions. -/
protected def map₂ (f : α → β → γ) : hatα → hatβ → hatγ :=
pkg.extend₂ pkg' (pkg''.coe ∘₂ f)
lemma uniform_continuous_map₂ (f : α → β → γ) : uniform_continuous₂ (pkg.map₂ pkg' pkg'' f) :=
pkg.uniform_continuous_extension₂ pkg' _
lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ}
{a : δ → hatα} {b : δ → hatβ} (ha : continuous a) (hb : continuous b) :
continuous (λd:δ, pkg.map₂ pkg' pkg'' f (a d) (b d)) :=
((pkg.uniform_continuous_map₂ pkg' pkg'' f).continuous.comp (continuous.prod_mk ha hb) : _)
lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous₂ f) :
pkg.map₂ pkg' pkg'' f (ι a) (ι' b) = ι'' (f a b) :=
pkg.extension₂_coe_coe pkg' (pkg''.uniform_continuous_coe.comp hf) a b
end map₂
end abstract_completion
|
65e179b019997cb3eb2d13b91a6475eeb70e34b2 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/category_theory/limits/cones.lean | 7c138a7a111336391df01a29ba9c09f1eb6a35f6 | [
"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 | 28,618 | 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.discrete_category
import category_theory.yoneda
import category_theory.reflects_isomorphisms
universes v u₁ u₂ -- morphism levels before object levels. See note [category_theory universes].
open category_theory
variables {J : Type v} [small_category J]
variables {K : Type v} [small_category K]
variables {C : Type u₁} [category.{v} C]
variables {D : Type u₂} [category.{v} D]
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`.
-/
@[simps]
def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ yoneda.obj F
/--
`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`.
-/
@[simps]
def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F)
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)
instance inhabited_cone (F : discrete punit ⥤ C) : inhabited (cone F) :=
⟨{ X := F.obj punit.star,
π := { app := λ ⟨⟩, 𝟙 _ } }⟩
@[simp, reassoc] 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 { rw ← c.π.naturality f, 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)
instance inhabited_cocone (F : discrete punit ⥤ C) : inhabited (cocone F) :=
⟨{ X := F.obj punit.star,
ι := { app := λ ⟨⟩, 𝟙 _ } }⟩
@[simp, reassoc] 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 { rw c.ι.naturality f, apply comp_id }
variables {F : J ⥤ C}
namespace cone
/-- The isomorphism between a cone on `F` and an element of the functor `F.cones`. -/
@[simps]
def equiv (F : J ⥤ C) : cone F ≅ Σ X, F.cones.obj X :=
{ hom := λ c, ⟨op c.X, c.π⟩,
inv := λ c, { X := c.1.unop, π := c.2 },
hom_inv_id' := by { ext1, cases x, refl },
inv_hom_id' := by { ext1, cases x, refl } }
/-- A map to the vertex of a cone naturally induces a cone by composition. -/
@[simps] 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. -/
@[simps] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F :=
{ X := X,
π := c.extensions.app (op X) f }
/-- Whisker a cone by precomposition of a functor. -/
@[simps] def whisker (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) :=
{ X := c.X,
π := whisker_left E c.π }
end cone
namespace cocone
/-- The isomorphism between a cocone on `F` and an element of the functor `F.cocones`. -/
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' := by { ext1, cases x, refl },
inv_hom_id' := by { ext1, cases x, refl } }
/-- A map from the vertex of a cocone naturally induces a cocone by composition. -/
@[simps] 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. -/
@[simps] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F :=
{ X := X,
ι := c.extensions.app X f }
/--
Whisker a cocone by precomposition of a functor. See `whiskering` for a functorial
version.
-/
@[simps] def whisker (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) :=
{ X := c.X,
ι := whisker_left E c.ι }
end cocone
/-- A cone morphism between two cones for the same diagram is a morphism of the cone points which
commutes with the cone legs. -/
@[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, reassoc] cone_morphism.w
instance inhabited_cone_morphism (A : cone F) : inhabited (cone_morphism A A) :=
⟨{ hom := 𝟙 _ }⟩
/-- The category of cones on a given diagram. -/
@[simps] instance cone.category : category (cone F) :=
{ hom := λ A B, cone_morphism A B,
comp := λ X Y Z f g, { hom := f.hom ≫ g.hom },
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) } }
/--
Given a cone morphism whose object part is an isomorphism, produce an
isomorphism of cones.
-/
lemma cone_iso_of_hom_iso {K : J ⥤ C} {c d : cone K} (f : c ⟶ d) [i : is_iso f.hom] :
is_iso f :=
⟨⟨{ hom := inv f.hom,
w' := λ j, (as_iso f.hom).inv_comp_eq.2 (f.w j).symm }, by tidy⟩⟩
/--
Functorially postcompose a cone for `F` by a natural transformation `F ⟶ G` to give a cone for `G`.
-/
@[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 } }
/-- Postcomposing a cone by the composite natural transformation `α ≫ β` is the same as
postcomposing by `α` and then by `β`. -/
@[simps]
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)
/-- Postcomposing by the identity does not change the cone up to isomorphism. -/
@[simps]
def postcompose_id : postcompose (𝟙 F) ≅ 𝟭 (cone F) :=
nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy)
/--
If `F` and `G` are naturally isomorphic functors, then they have equivalent categories of
cones.
-/
@[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 (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 (e : K ≌ J) :
cone F ≌ cone (e.functor ⋙ F) :=
{ functor := whiskering e.functor,
inverse := whiskering e.inverse ⋙ postcompose (e.inv_fun_id_assoc 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,
dsimp, -- See library note [dsimp, simp]
simpa [e.counit_app_functor] using s.w (e.unit_inv.app k),
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).
-/
@[simps functor inverse unit_iso counit_iso]
def equivalence_of_reindexing {G : K ⥤ C}
(e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cone F ≌ cone G :=
(whiskering_equivalence e).trans (postcompose_equivalence α)
section
variable (F)
/-- Forget the cone structure and obtain just the cone point. -/
@[simps]
def forget : cone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
variables (G : C ⥤ D)
/-- A functor `G : C ⥤ D` sends cones over `F` to cones over `F ⋙ G` functorially. -/
@[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' := λ j, by simp [-cone_morphism.w, ←f.w j] } }
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 } }
/--
If `e : C ≌ D` is an equivalence of categories, then `functoriality F e.functor` induces an
equivalence between cones over `F` and cones over `F ⋙ e.functor`.
-/
@[simps]
def functoriality_equivalence (e : C ≌ D) : cone F ≌ cone (F ⋙ e.functor) :=
let f : (F ⋙ e.functor) ⋙ e.inverse ≅ F :=
functor.associator _ _ _ ≪≫ iso_whisker_left _ (e.unit_iso).symm ≪≫ functor.right_unitor _ in
{ functor := functoriality F e.functor,
inverse := (functoriality (F ⋙ e.functor) e.inverse) ⋙
(postcompose_equivalence f).functor,
unit_iso := nat_iso.of_components (λ c, cones.ext (e.unit_iso.app _) (by tidy)) (by tidy),
counit_iso := nat_iso.of_components (λ c, cones.ext (e.counit_iso.app _) (by tidy)) (by tidy), }
/--
If `F` reflects isomorphisms, then `cones.functoriality F` reflects isomorphisms
as well.
-/
instance reflects_cone_isomorphism (F : C ⥤ D) [reflects_isomorphisms F] (K : J ⥤ C) :
reflects_isomorphisms (cones.functoriality K F) :=
begin
constructor,
introsI,
haveI : is_iso (F.map f.hom) :=
(cones.forget (K ⋙ F)).map_is_iso ((cones.functoriality K F).map f),
haveI := reflects_isomorphisms.reflects F f.hom,
apply cone_iso_of_hom_iso
end
end
end cones
/-- A cocone morphism between two cocones for the same diagram is a morphism of the cocone points
which commutes with the cocone legs. -/
@[ext] structure cocone_morphism (A B : cocone F) :=
(hom : A.X ⟶ B.X)
(w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously)
instance inhabited_cocone_morphism (A : cocone F) : inhabited (cocone_morphism A A) :=
⟨{ hom := 𝟙 _ }⟩
restate_axiom cocone_morphism.w'
attribute [simp, reassoc] cocone_morphism.w
@[simps] instance cocone.category : category (cocone F) :=
{ hom := λ A B, cocone_morphism A B,
comp := λ _ _ _ f g,
{ hom := f.hom ≫ g.hom },
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 } }
/--
Given a cocone morphism whose object part is an isomorphism, produce an
isomorphism of cocones.
-/
lemma cocone_iso_of_hom_iso {K : J ⥤ C} {c d : cocone K} (f : c ⟶ d) [i : is_iso f.hom] :
is_iso f :=
⟨⟨{ hom := inv f.hom,
w' := λ j, (as_iso f.hom).comp_inv_eq.2 (f.w j).symm }, by tidy⟩⟩
/-- Functorially precompose a cocone for `F` by a natural transformation `G ⟶ F` to give a cocone
for `G`. -/
@[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 } }
/-- Precomposing a cocone by the composite natural transformation `α ≫ β` is the same as
precomposing by `β` and then by `α`. -/
def precompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) :
precompose (α ≫ β) ≅ precompose β ⋙ precompose α :=
nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy)
/-- Precomposing by the identity does not change the cocone up to isomorphism. -/
def precompose_id : precompose (𝟙 F) ≅ 𝟭 (cocone F) :=
nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy)
/--
If `F` and `G` are naturally isomorphic functors, then they have equivalent categories of
cocones.
-/
@[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 (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 (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,
dsimp,
simpa [e.counit_inv_app_functor k] using s.w (e.unit.app k),
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).
-/
@[simps functor_obj]
def equivalence_of_reindexing {G : K ⥤ C}
(e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cocone F ≌ cocone G :=
(whiskering_equivalence e).trans (precompose_equivalence α.symm)
section
variable (F)
/-- Forget the cocone structure and obtain just the cocone point. -/
@[simps]
def forget : cocone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
variables (G : C ⥤ D)
/-- A functor `G : C ⥤ D` sends cocones over `F` to cocones over `F ⋙ G` functorially. -/
@[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 } }
/--
If `e : C ≌ D` is an equivalence of categories, then `functoriality F e.functor` induces an
equivalence between cocones over `F` and cocones over `F ⋙ e.functor`.
-/
@[simps]
def functoriality_equivalence (e : C ≌ D) : cocone F ≌ cocone (F ⋙ e.functor) :=
let f : (F ⋙ e.functor) ⋙ e.inverse ≅ F :=
functor.associator _ _ _ ≪≫ iso_whisker_left _ (e.unit_iso).symm ≪≫ functor.right_unitor _ in
{ functor := functoriality F e.functor,
inverse := (functoriality (F ⋙ e.functor) e.inverse) ⋙
(precompose_equivalence f.symm).functor,
unit_iso := nat_iso.of_components (λ c, cocones.ext (e.unit_iso.app _) (by tidy)) (by tidy),
counit_iso := nat_iso.of_components (λ c, cocones.ext (e.counit_iso.app _)
begin
-- Unfortunately this doesn't work by `tidy`.
-- In this configuration `simp` reaches a dead-end and needs help.
intros j,
dsimp,
simp only [←equivalence.counit_inv_app_functor, iso.inv_hom_id_app, map_comp,
equivalence.fun_inv_map, assoc, id_comp, iso.inv_hom_id_app_assoc],
dsimp, simp, -- See note [dsimp, simp].
end)
(λ c c' f, by { ext, dsimp, simp, dsimp, simp, }), }
/--
If `F` reflects isomorphisms, then `cocones.functoriality F` reflects isomorphisms
as well.
-/
instance reflects_cocone_isomorphism (F : C ⥤ D) [reflects_isomorphisms F] (K : J ⥤ C) :
reflects_isomorphisms (cocones.functoriality K F) :=
begin
constructor,
introsI,
haveI : is_iso (F.map f.hom) :=
(cocones.forget (K ⋙ F)).map_is_iso ((cocones.functoriality K F).map f),
haveI := reflects_isomorphisms.reflects F f.hom,
apply cocone_iso_of_hom_iso
end
end
end cocones
end limits
namespace functor
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. -/
@[simps]
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. -/
@[simps]
def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality F H).obj c
/-- Given a cone morphism `c ⟶ c'`, construct a cone morphism on the mapped cones functorially. -/
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
/-- Given a cocone morphism `c ⟶ c'`, construct a cocone morphism on the mapped cocones
functorially. -/
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
/-- If `H` is an equivalence, we invert `H.map_cone` and get a cone for `F` from a cone
for `F ⋙ H`.-/
def map_cone_inv [is_equivalence H]
(c : cone (F ⋙ H)) : cone F :=
(limits.cones.functoriality_equivalence F (as_equivalence H)).inverse.obj c
/-- `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 :=
(limits.cones.functoriality_equivalence F (as_equivalence H)).counit_iso.app c
/-- `map_cone` is the right inverse to `map_cone_inv`. -/
def map_cone_inv_map_cone {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cone F) :
map_cone_inv H (map_cone H c) ≅ c :=
(limits.cones.functoriality_equivalence F (as_equivalence H)).unit_iso.symm.app c
/-- If `H` is an equivalence, we invert `H.map_cone` and get a cone for `F` from a cone
for `F ⋙ H`.-/
def map_cocone_inv [is_equivalence H]
(c : cocone (F ⋙ H)) : cocone F :=
(limits.cocones.functoriality_equivalence F (as_equivalence H)).inverse.obj c
/-- `map_cocone` is the left inverse to `map_cocone_inv`. -/
def map_cocone_map_cocone_inv {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cocone (F ⋙ H)) :
map_cocone H (map_cocone_inv H c) ≅ c :=
(limits.cocones.functoriality_equivalence F (as_equivalence H)).counit_iso.app c
/-- `map_cocone` is the right inverse to `map_cocone_inv`. -/
def map_cocone_inv_map_cocone {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cocone F) :
map_cocone_inv H (map_cocone H c) ≅ c :=
(limits.cocones.functoriality_equivalence F (as_equivalence H)).unit_iso.symm.app c
/-- `functoriality F _ ⋙ postcompose (whisker_left F _)` simplifies to `functoriality F _`. -/
@[simps]
def functoriality_comp_postcompose {H H' : C ⥤ D} (α : H ≅ H') :
cones.functoriality F H ⋙ cones.postcompose (whisker_left F α.hom) ≅ cones.functoriality F H' :=
nat_iso.of_components (λ c, cones.ext (α.app _) (by tidy)) (by tidy)
/--
For `F : J ⥤ C`, given a cone `c : cone F`, and a natural isomorphism `α : H ≅ H'` for functors
`H H' : C ⥤ D`, the postcomposition of the cone `H.map_cone` using the isomorphism `α` is
isomorphic to the cone `H'.map_cone`.
-/
@[simps]
def postcompose_whisker_left_map_cone {H H' : C ⥤ D} (α : H ≅ H') (c : cone F) :
(cones.postcompose (whisker_left F α.hom : _)).obj (H.map_cone c) ≅ H'.map_cone c :=
(functoriality_comp_postcompose α).app c
/--
`map_cone` commutes with `postcompose`. In particular, for `F : J ⥤ C`, given a cone `c : cone F`, a
natural transformation `α : F ⟶ G` and a functor `H : C ⥤ D`, we have two obvious ways of producing
a cone over `G ⋙ H`, and they are both isomorphic.
-/
@[simps]
def map_cone_postcompose {α : F ⟶ G} {c} :
H.map_cone ((cones.postcompose α).obj c) ≅
(cones.postcompose (whisker_right α H : _)).obj (H.map_cone c) :=
cones.ext (iso.refl _) (by tidy)
/--
`map_cone` commutes with `postcompose_equivalence`
-/
@[simps]
def map_cone_postcompose_equivalence_functor {α : F ≅ G} {c} :
H.map_cone ((cones.postcompose_equivalence α).functor.obj c) ≅
(cones.postcompose_equivalence (iso_whisker_right α H : _)).functor.obj (H.map_cone c) :=
cones.ext (iso.refl _) (by tidy)
/-- `functoriality F _ ⋙ precompose (whisker_left F _)` simplifies to `functoriality F _`. -/
@[simps]
def functoriality_comp_precompose {H H' : C ⥤ D} (α : H ≅ H') :
cocones.functoriality F H ⋙ cocones.precompose (whisker_left F α.inv)
≅ cocones.functoriality F H' :=
nat_iso.of_components (λ c, cocones.ext (α.app _) (by tidy)) (by tidy)
/--
For `F : J ⥤ C`, given a cocone `c : cocone F`, and a natural isomorphism `α : H ≅ H'` for functors
`H H' : C ⥤ D`, the precomposition of the cocone `H.map_cocone` using the isomorphism `α` is
isomorphic to the cocone `H'.map_cocone`.
-/
@[simps]
def precompose_whisker_left_map_cocone {H H' : C ⥤ D} (α : H ≅ H') (c : cocone F) :
(cocones.precompose (whisker_left F α.inv : _)).obj (H.map_cocone c) ≅ H'.map_cocone c :=
(functoriality_comp_precompose α).app c
/--
`map_cocone` commutes with `precompose`. In particular, for `F : J ⥤ C`, given a cocone
`c : cocone F`, a natural transformation `α : F ⟶ G` and a functor `H : C ⥤ D`, we have two obvious
ways of producing a cocone over `G ⋙ H`, and they are both isomorphic.
-/
@[simps]
def map_cocone_precompose {α : F ⟶ G} {c} :
H.map_cocone ((cocones.precompose α).obj c) ≅
(cocones.precompose (whisker_right α H : _)).obj (H.map_cocone c) :=
cocones.ext (iso.refl _) (by tidy)
/--
`map_cocone` commutes with `precompose_equivalence`
-/
@[simps]
def map_cocone_precompose_equivalence_functor {α : F ≅ G} {c} :
H.map_cocone ((cocones.precompose_equivalence α).functor.obj c) ≅
(cocones.precompose_equivalence (iso_whisker_right α H : _)).functor.obj (H.map_cocone c) :=
cocones.ext (iso.refl _) (by tidy)
/--
`map_cone` commutes with `whisker`
-/
@[simps]
def map_cone_whisker {E : K ⥤ J} {c : cone F} :
H.map_cone (c.whisker E) ≅ (H.map_cone c).whisker E :=
cones.ext (iso.refl _) (by tidy)
/--
`map_cocone` commutes with `whisker`
-/
@[simps]
def map_cocone_whisker {E : K ⥤ J} {c : cocone F} :
H.map_cocone (c.whisker E) ≅ (H.map_cocone c).whisker E :=
cocones.ext (iso.refl _) (by tidy)
end functor
end category_theory
namespace category_theory.limits
section
variables {F : J ⥤ C}
/-- Change a `cocone F` into a `cone F.op`. -/
@[simps] def cocone.op (c : cocone F) : cone F.op :=
{ X := op c.X,
π :=
{ app := λ j, (c.ι.app (unop j)).op,
naturality' := λ j j' f, quiver.hom.unop_inj (by tidy) } }
/-- Change a `cone F` into a `cocone F.op`. -/
@[simps] def cone.op (c : cone F) : cocone F.op :=
{ X := op c.X,
ι :=
{ app := λ j, (c.π.app (unop j)).op,
naturality' := λ j j' f, quiver.hom.unop_inj (by tidy) } }
/-- Change a `cocone F.op` into a `cone F`. -/
@[simps] def cocone.unop (c : cocone F.op) : cone F :=
{ X := unop c.X,
π :=
{ app := λ j, (c.ι.app (op j)).unop,
naturality' := λ j j' f, quiver.hom.op_inj (c.ι.naturality f.op).symm } }
/-- Change a `cone F.op` into a `cocone F`. -/
@[simps] def cone.unop (c : cone F.op) : cocone F :=
{ X := unop c.X,
ι :=
{ app := λ j, (c.π.app (op j)).unop,
naturality' := λ j j' f, quiver.hom.op_inj (c.π.naturality f.op).symm } }
variables (F)
/--
The category of cocones on `F`
is equivalent to the opposite category of
the category of cones on the opposite of `F`.
-/
@[simps]
def cocone_equivalence_op_cone_op : cocone F ≌ (cone F.op)ᵒᵖ :=
{ functor :=
{ obj := λ c, op (cocone.op c),
map := λ X Y f, quiver.hom.op
{ hom := f.hom.op,
w' := λ j, by { apply quiver.hom.unop_inj, dsimp, simp, }, } },
inverse :=
{ obj := λ c, cone.unop (unop c),
map := λ X Y f,
{ hom := f.unop.hom.unop,
w' := λ j, by { apply quiver.hom.op_inj, dsimp, simp, }, } },
unit_iso := nat_iso.of_components (λ c, cocones.ext (iso.refl _) (by tidy)) (by tidy),
counit_iso := nat_iso.of_components (λ c,
by { induction c using opposite.rec,
dsimp, apply iso.op, exact cones.ext (iso.refl _) (by tidy), })
begin
intros,
have hX : X = op (unop X) := rfl,
revert hX,
generalize : unop X = X',
rintro rfl,
have hY : Y = op (unop Y) := rfl,
revert hY,
generalize : unop Y = Y',
rintro rfl,
apply quiver.hom.unop_inj,
apply cone_morphism.ext,
dsimp, simp,
end,
functor_unit_iso_comp' := λ c, begin apply quiver.hom.unop_inj, ext, dsimp, simp, end }
end
section
variables {F : J ⥤ Cᵒᵖ}
/-- Change a cocone on `F.left_op : Jᵒᵖ ⥤ C` to a cocone on `F : J ⥤ Cᵒᵖ`. -/
-- Here and below we only automatically generate the `@[simp]` lemma for the `X` field,
-- as we can write a simpler `rfl` lemma for the components of the natural transformation by hand.
@[simps {rhs_md := semireducible, simp_rhs := tt}]
def cone_of_cocone_left_op (c : cocone F.left_op) : cone F :=
{ X := op c.X,
π := nat_trans.remove_left_op (c.ι ≫ (const.op_obj_unop (op c.X)).hom) }
/-- Change a cone on `F : J ⥤ Cᵒᵖ` to a cocone on `F.left_op : Jᵒᵖ ⥤ C`. -/
@[simps {rhs_md := semireducible, simp_rhs := tt}]
def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) :=
{ X := unop c.X,
ι := nat_trans.left_op c.π }
/-- Change a cone on `F.left_op : Jᵒᵖ ⥤ C` to a cocone on `F : J ⥤ Cᵒᵖ`. -/
/- When trying use `@[simps]` to generate the `ι_app` field of this definition, `@[simps]` tries to
reduce the RHS using `expr.dsimp` and `expr.simp`, but for some reason the expression is not
being simplified properly. -/
@[simps X]
def cocone_of_cone_left_op (c : cone F.left_op) : cocone F :=
{ X := op c.X,
ι := nat_trans.remove_left_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 }
/-- Change a cocone on `F : J ⥤ Cᵒᵖ` to a cone on `F.left_op : Jᵒᵖ ⥤ C`. -/
@[simps {rhs_md := semireducible, simp_rhs := tt}]
def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) :=
{ X := unop c.X,
π := nat_trans.left_op c.ι }
end
end category_theory.limits
namespace category_theory.functor
open category_theory.limits
variables {F : J ⥤ C}
section
variables (G : C ⥤ D)
/-- The opposite cocone of the image of a cone is the image of the opposite cocone. -/
@[simps {rhs_md := semireducible}]
def map_cone_op (t : cone F) : (G.map_cone t).op ≅ (G.op.map_cocone t.op) :=
cocones.ext (iso.refl _) (by tidy)
/-- The opposite cone of the image of a cocone is the image of the opposite cone. -/
@[simps {rhs_md := semireducible}]
def map_cocone_op {t : cocone F} : (G.map_cocone t).op ≅ (G.op.map_cone t.op) :=
cones.ext (iso.refl _) (by tidy)
end
end category_theory.functor
|
ae658afd2f5e06ec59024f84b5a3a90de248cf5f | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/analysis/calculus/tangent_cone.lean | 1d67b4f994f5251beb273011abe90dca278d5026 | [
"Apache-2.0"
] | permissive | hjvromen/lewis | 40b035973df7c77ebf927afab7878c76d05ff758 | 105b675f73630f028ad5d890897a51b3c1146fb0 | refs/heads/master | 1,677,944,636,343 | 1,676,555,301,000 | 1,676,555,301,000 | 327,553,599 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,696 | 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.basic
import analysis.normed_space.bounded_linear_maps
import 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 `fderiv.lean`. Hence, derivatives are not defined yet. The
property of uniqueness of the derivative is therefore proved in `fderiv.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]
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 in at_top, x + d n ∈ s) ∧
(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 `fderiv.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 :=
dense ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E) ∧ 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
`fderiv.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_one_lt 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_inv_at_top_zero.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 in l, ∥c n∥⁻¹ * ∥c n • d n∥ = ∥d n∥,
{ apply (eventually_ne_of_tendsto_norm_at_top hc 0).mono (λn hn, _),
rw [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
lemma tangent_cone_mono_nhds (h : 𝓝[s] x ≤ 𝓝[t] x) :
tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x :=
begin
rintros y ⟨c, d, ds, ctop, clim⟩,
refine ⟨c, d, _, ctop, clim⟩,
suffices : tendsto (λ n, x + d n) at_top (𝓝[t] x),
from tendsto_principal.1 (tendsto_inf.1 this).2,
refine (tendsto_inf.2 ⟨_, tendsto_principal.2 ds⟩).mono_right h,
simpa only [add_zero] using tendsto_const_nhds.add (tangent_cone_at.lim_zero at_top ctop clim)
end
/-- Tangent cone of `s` at `x` depends only on `𝓝[s] x`. -/
lemma tangent_cone_congr (h : 𝓝[s] x = 𝓝[t] x) :
tangent_cone_at 𝕜 s x = tangent_cone_at 𝕜 t x :=
subset.antisymm
(tangent_cone_mono_nhds $ le_of_eq h)
(tangent_cone_mono_nhds $ le_of_eq h.symm)
/-- 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 :=
tangent_cone_congr (nhds_within_restrict' _ ht).symm
/-- 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) :
linear_map.inl 𝕜 E F '' (tangent_cone_at 𝕜 s x) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) :=
begin
rintros _ ⟨v, ⟨c, d, hd, hc, hy⟩, rfl⟩,
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.2 c_pos) (pow_pos _ _),
norm_num } },
choose d' hd' using this,
refine ⟨c, λn, (d n, d' n), _, hc, _⟩,
show ∀ᶠ n in at_top, (x, y) + (d n, d' n) ∈ set.prod s t,
{ apply filter.mem_sets_of_superset hd,
assume n hn,
simp at hn,
simp [hn, (hd' n).1] },
{ apply hy.prod_mk_nhds,
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) :
linear_map.inr 𝕜 E F '' (tangent_cone_at 𝕜 t y) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) :=
begin
rintros _ ⟨w, ⟨c, d, hd, hc, hy⟩, rfl⟩,
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.2 c_pos) (pow_pos _ _),
norm_num } },
choose d' hd' using this,
refine ⟨c, λn, (d' n, d n), _, hc, _⟩,
show ∀ᶠ n in at_top, (x, y) + (d' n, d n) ∈ set.prod s t,
{ 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 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,
{ rw segment_eq_image,
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, sub_smul, smul_sub, one_smul], 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_one_lt (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
/-!
### Properties of `unique_diff_within_at` and `unique_diff_on`
This section is devoted to properties of the predicates `unique_diff_within_at` and `unique_diff_on`. -/
lemma unique_diff_on.unique_diff_within_at {s : set E} {x} (hs : unique_diff_on 𝕜 s) (h : x ∈ s) :
unique_diff_within_at 𝕜 s x :=
hs x h
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_on_empty : unique_diff_on 𝕜 (∅ : set E) :=
λ x hx, hx.elim
lemma unique_diff_within_at.mono_nhds (h : unique_diff_within_at 𝕜 s x)
(st : 𝓝[s] x ≤ 𝓝[t] x) :
unique_diff_within_at 𝕜 t x :=
begin
unfold unique_diff_within_at at *,
rw [mem_closure_iff_nhds_within_ne_bot] at h ⊢,
exact ⟨h.1.mono $ submodule.span_mono $ tangent_cone_mono_nhds st,
h.2.mono st⟩
end
lemma unique_diff_within_at.mono (h : unique_diff_within_at 𝕜 s x) (st : s ⊆ t) :
unique_diff_within_at 𝕜 t x :=
h.mono_nhds $ nhds_within_mono _ st
lemma unique_diff_within_at_congr (st : 𝓝[s] x = 𝓝[t] x) :
unique_diff_within_at 𝕜 s x ↔ unique_diff_within_at 𝕜 t x :=
⟨λ h, h.mono_nhds $ le_of_eq st, λ h, h.mono_nhds $ le_of_eq st.symm⟩
lemma unique_diff_within_at_inter (ht : t ∈ 𝓝 x) :
unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x :=
unique_diff_within_at_congr $ (nhds_within_restrict' _ ht).symm
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 ∈ 𝓝[s] x) :
unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x :=
unique_diff_within_at_congr $ (nhds_within_restrict'' _ ht).symm
lemma unique_diff_within_at.inter' (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝[s] x) :
unique_diff_within_at 𝕜 (s ∩ t) x :=
(unique_diff_within_at_inter' ht).2 hs
lemma unique_diff_within_at_of_mem_nhds (h : s ∈ 𝓝 x) : unique_diff_within_at 𝕜 s x :=
by simpa only [univ_inter] using unique_diff_within_at_univ.inter h
lemma is_open.unique_diff_within_at (hs : is_open s) (xs : x ∈ s) : unique_diff_within_at 𝕜 s x :=
unique_diff_within_at_of_mem_nhds (mem_nhds_sets hs xs)
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] at ⊢ hs ht,
rw [closure_prod_eq],
refine ⟨_, hs.2, ht.2⟩,
have : _ ≤ submodule.span 𝕜 (tangent_cone_at 𝕜 (s.prod t) (x, y)) :=
submodule.span_mono (union_subset (subset_tangent_cone_prod_left ht.2)
(subset_tangent_cone_prod_right hs.2)),
rw [linear_map.span_inl_union_inr, submodule.le_def, submodule.prod_coe] at this,
exact (hs.1.prod ht.1).mono this
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).nonempty) :
unique_diff_on ℝ s :=
begin
assume x xs,
rcases hs with ⟨y, hy⟩,
suffices : y - x ∈ interior (tangent_cone_at ℝ s x),
{ refine ⟨dense.of_closure _, subset_closure xs⟩,
simp [(submodule.span ℝ (tangent_cone_at ℝ s x)).eq_top_of_nonempty_interior'
⟨y - x, interior_mono submodule.subset_span this⟩] },
rw [mem_interior_iff_mem_nhds] at hy ⊢,
apply mem_sets_of_superset ((is_open_map_sub_right x).image_mem_nhds hy),
rintros _ ⟨z, zs, rfl⟩,
exact mem_tangent_cone_of_segment_subset (conv.segment_subset xs zs)
end
lemma unique_diff_on_Ici (a : ℝ) : unique_diff_on ℝ (Ici a) :=
unique_diff_on_convex (convex_Ici a) $ by simp only [interior_Ici, nonempty_Ioi]
lemma unique_diff_on_Iic (a : ℝ) : unique_diff_on ℝ (Iic a) :=
unique_diff_on_convex (convex_Iic a) $ by simp only [interior_Iic, nonempty_Iio]
lemma unique_diff_on_Ioi (a : ℝ) : unique_diff_on ℝ (Ioi a) :=
is_open_Ioi.unique_diff_on
lemma unique_diff_on_Iio (a : ℝ) : unique_diff_on ℝ (Iio a) :=
is_open_Iio.unique_diff_on
lemma unique_diff_on_Icc {a b : ℝ} (hab : a < b) : unique_diff_on ℝ (Icc a b) :=
unique_diff_on_convex (convex_Icc a b) $ by simp only [interior_Icc, nonempty_Ioo, hab]
lemma unique_diff_on_Ico (a b : ℝ) : unique_diff_on ℝ (Ico a b) :=
if hab : a < b
then unique_diff_on_convex (convex_Ico a b) $ by simp only [interior_Ico, nonempty_Ioo, hab]
else by simp only [Ico_eq_empty (le_of_not_lt hab), unique_diff_on_empty]
lemma unique_diff_on_Ioc (a b : ℝ) : unique_diff_on ℝ (Ioc a b) :=
if hab : a < b
then unique_diff_on_convex (convex_Ioc a b) $ by simp only [interior_Ioc, nonempty_Ioo, hab]
else by simp only [Ioc_eq_empty (le_of_not_lt hab), unique_diff_on_empty]
lemma unique_diff_on_Ioo (a b : ℝ) : unique_diff_on ℝ (Ioo a b) :=
is_open_Ioo.unique_diff_on
/-- The real interval `[0, 1]` is a set of unique differentiability. -/
lemma unique_diff_on_Icc_zero_one : unique_diff_on ℝ (Icc (0:ℝ) 1) :=
unique_diff_on_Icc zero_lt_one
end unique_diff
|
ca1ad38beeabaa8489e1f342e80808e6b3af8308 | 618003631150032a5676f229d13a079ac875ff77 | /src/category_theory/adjunction/basic.lean | 98631f30a4cca9a93226fc42d86235da31f7a7e7 | [
"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 | 14,652 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Johan Commelin, Bhavik Mehta
-/
import category_theory.equivalence
import data.equiv.basic
namespace category_theory
open category
universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation
local attribute [elab_simple] whisker_left whisker_right
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
/--
`F ⊣ G` represents the data of an adjunction between two functors
`F : C ⥤ D` and `G : D ⥤ C`. `F` is the left adjoint and `G` is the right adjoint.
-/
structure adjunction (F : C ⥤ D) (G : D ⥤ C) :=
(hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y))
(unit : 𝟭 C ⟶ F.comp G)
(counit : G.comp F ⟶ 𝟭 D)
(hom_equiv_unit' : Π {X Y f}, (hom_equiv X Y) f = (unit : _ ⟶ _).app X ≫ G.map f . obviously)
(hom_equiv_counit' : Π {X Y g}, (hom_equiv X Y).symm g = F.map g ≫ counit.app Y . obviously)
infix ` ⊣ `:15 := adjunction
class is_left_adjoint (left : C ⥤ D) :=
(right : D ⥤ C)
(adj : left ⊣ right)
class is_right_adjoint (right : D ⥤ C) :=
(left : C ⥤ D)
(adj : left ⊣ right)
def left_adjoint (R : D ⥤ C) [is_right_adjoint R] : C ⥤ D :=
is_right_adjoint.left R
def right_adjoint (L : C ⥤ D) [is_left_adjoint L] : D ⥤ C :=
is_left_adjoint.right L
namespace adjunction
restate_axiom hom_equiv_unit'
restate_axiom hom_equiv_counit'
attribute [simp, priority 10] hom_equiv_unit hom_equiv_counit
section
variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X' X : C} {Y Y' : D}
@[simp, priority 10] lemma hom_equiv_naturality_left_symm (f : X' ⟶ X) (g : X ⟶ G.obj Y) :
(adj.hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (adj.hom_equiv X Y).symm g :=
by rw [hom_equiv_counit, F.map_comp, assoc, adj.hom_equiv_counit.symm]
@[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) :
(adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g :=
by rw [← equiv.eq_symm_apply]; simp [-hom_equiv_unit]
@[simp, priority 10] lemma hom_equiv_naturality_right (f : F.obj X ⟶ Y) (g : Y ⟶ Y') :
(adj.hom_equiv X Y') (f ≫ g) = (adj.hom_equiv X Y) f ≫ G.map g :=
by rw [hom_equiv_unit, G.map_comp, ← assoc, ←hom_equiv_unit]
@[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') :
(adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g :=
by rw [equiv.symm_apply_eq]; simp [-hom_equiv_counit]
@[simp] lemma left_triangle :
(whisker_right adj.unit F) ≫ (whisker_left F adj.counit) = nat_trans.id _ :=
begin
ext, dsimp,
erw [← adj.hom_equiv_counit, equiv.symm_apply_eq, adj.hom_equiv_unit],
simp
end
@[simp] lemma right_triangle :
(whisker_left G adj.unit) ≫ (whisker_right adj.counit G) = nat_trans.id _ :=
begin
ext, dsimp,
erw [← adj.hom_equiv_unit, ← equiv.eq_symm_apply, adj.hom_equiv_counit],
simp
end
@[simp, reassoc] lemma left_triangle_components :
F.map (adj.unit.app X) ≫ adj.counit.app (F.obj X) = 𝟙 (F.obj X) :=
congr_arg (λ (t : nat_trans _ (𝟭 C ⋙ F)), t.app X) adj.left_triangle
@[simp, reassoc] lemma right_triangle_components {Y : D} :
adj.unit.app (G.obj Y) ≫ G.map (adj.counit.app Y) = 𝟙 (G.obj Y) :=
congr_arg (λ (t : nat_trans _ (G ⋙ 𝟭 C)), t.app Y) adj.right_triangle
@[simp, reassoc] lemma counit_naturality {X Y : D} (f : X ⟶ Y) :
F.map (G.map f) ≫ (adj.counit).app Y = (adj.counit).app X ≫ f :=
adj.counit.naturality f
@[simp, reassoc] lemma unit_naturality {X Y : C} (f : X ⟶ Y) :
(adj.unit).app X ≫ G.map (F.map f) = f ≫ (adj.unit).app Y :=
(adj.unit.naturality f).symm
lemma hom_equiv_apply_eq {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) :
adj.hom_equiv A B f = g ↔ f = (adj.hom_equiv A B).symm g :=
⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩
lemma eq_hom_equiv_apply {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) :
g = adj.hom_equiv A B f ↔ (adj.hom_equiv A B).symm g = f :=
⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩
end
end adjunction
namespace adjunction
structure core_hom_equiv (F : C ⥤ D) (G : D ⥤ C) :=
(hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y))
(hom_equiv_naturality_left_symm' : Π {X' X Y} (f : X' ⟶ X) (g : X ⟶ G.obj Y),
(hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (hom_equiv X Y).symm g . obviously)
(hom_equiv_naturality_right' : Π {X Y Y'} (f : F.obj X ⟶ Y) (g : Y ⟶ Y'),
(hom_equiv X Y') (f ≫ g) = (hom_equiv X Y) f ≫ G.map g . obviously)
namespace core_hom_equiv
restate_axiom hom_equiv_naturality_left_symm'
restate_axiom hom_equiv_naturality_right'
attribute [simp, priority 10] hom_equiv_naturality_left_symm hom_equiv_naturality_right
variables {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D}
@[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) :
(adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g :=
by rw [← equiv.eq_symm_apply]; simp
@[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') :
(adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g :=
by rw [equiv.symm_apply_eq]; simp
end core_hom_equiv
structure core_unit_counit (F : C ⥤ D) (G : D ⥤ C) :=
(unit : 𝟭 C ⟶ F.comp G)
(counit : G.comp F ⟶ 𝟭 D)
(left_triangle' : whisker_right unit F ≫ (functor.associator F G F).hom ≫ whisker_left F counit = nat_trans.id (𝟭 C ⋙ F) . obviously)
(right_triangle' : whisker_left G unit ≫ (functor.associator G F G).inv ≫ whisker_right counit G = nat_trans.id (G ⋙ 𝟭 C) . obviously)
namespace core_unit_counit
restate_axiom left_triangle'
restate_axiom right_triangle'
attribute [simp] left_triangle right_triangle
end core_unit_counit
variables {F : C ⥤ D} {G : D ⥤ C}
def mk_of_hom_equiv (adj : core_hom_equiv F G) : F ⊣ G :=
{ unit :=
{ app := λ X, (adj.hom_equiv X (F.obj X)) (𝟙 (F.obj X)),
naturality' :=
begin
intros,
erw [← adj.hom_equiv_naturality_left, ← adj.hom_equiv_naturality_right],
dsimp, simp
end },
counit :=
{ app := λ Y, (adj.hom_equiv _ _).inv_fun (𝟙 (G.obj Y)),
naturality' :=
begin
intros,
erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm],
dsimp, simp
end },
hom_equiv_unit' := λ X Y f, by erw [← adj.hom_equiv_naturality_right]; simp,
hom_equiv_counit' := λ X Y f, by erw [← adj.hom_equiv_naturality_left_symm]; simp,
.. adj }
def mk_of_unit_counit (adj : core_unit_counit F G) : F ⊣ G :=
{ hom_equiv := λ X Y,
{ to_fun := λ f, adj.unit.app X ≫ G.map f,
inv_fun := λ g, F.map g ≫ adj.counit.app Y,
left_inv := λ f, begin
change F.map (_ ≫ _) ≫ _ = _,
rw [F.map_comp, assoc, ←functor.comp_map, adj.counit.naturality, ←assoc],
convert id_comp f,
have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.left_triangle,
dsimp at t,
simp only [id_comp] at t,
exact t,
end,
right_inv := λ g, begin
change _ ≫ G.map (_ ≫ _) = _,
rw [G.map_comp, ←assoc, ←functor.comp_map, ←adj.unit.naturality, assoc],
convert comp_id g,
have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.right_triangle,
dsimp at t,
simp only [id_comp] at t,
exact t,
end },
.. adj }
def id : 𝟭 C ⊣ 𝟭 C :=
{ hom_equiv := λ X Y, equiv.refl _,
unit := 𝟙 _,
counit := 𝟙 _ }
/-- If F and G are naturally isomorphic functors, establish an equivalence of hom-sets. -/
def equiv_homset_left_of_nat_iso
{F F' : C ⥤ D} (iso : F ≅ F') {X : C} {Y : D} :
(F.obj X ⟶ Y) ≃ (F'.obj X ⟶ Y) :=
{ to_fun := λ f, iso.inv.app _ ≫ f,
inv_fun := λ g, iso.hom.app _ ≫ g,
left_inv := λ f, by simp,
right_inv := λ g, by simp }
@[simp]
lemma equiv_homset_left_of_nat_iso_apply {F F' : C ⥤ D} (iso : F ≅ F') {X : C} {Y : D} (f : F.obj X ⟶ Y) :
(equiv_homset_left_of_nat_iso iso) f = iso.inv.app _ ≫ f := rfl
@[simp]
lemma equiv_homset_left_of_nat_iso_symm_apply {F F' : C ⥤ D} (iso : F ≅ F') {X : C} {Y : D} (g : F'.obj X ⟶ Y) :
(equiv_homset_left_of_nat_iso iso).symm g = iso.hom.app _ ≫ g := rfl
/-- If G and H are naturally isomorphic functors, establish an equivalence of hom-sets. -/
def equiv_homset_right_of_nat_iso
{G G' : D ⥤ C} (iso : G ≅ G') {X : C} {Y : D} :
(X ⟶ G.obj Y) ≃ (X ⟶ G'.obj Y) :=
{ to_fun := λ f, f ≫ iso.hom.app _,
inv_fun := λ g, g ≫ iso.inv.app _,
left_inv := λ f, by simp,
right_inv := λ g, by simp }
@[simp]
lemma equiv_homset_right_of_nat_iso_apply {G G' : D ⥤ C} (iso : G ≅ G') {X : C} {Y : D} (f : X ⟶ G.obj Y) :
(equiv_homset_right_of_nat_iso iso) f = f ≫ iso.hom.app _ := rfl
@[simp]
lemma equiv_homset_right_of_nat_iso_symm_apply {G G' : D ⥤ C} (iso : G ≅ G') {X : C} {Y : D} (g : X ⟶ G'.obj Y) :
(equiv_homset_right_of_nat_iso iso).symm g = g ≫ iso.inv.app _ := rfl
/-- Transport an adjunction along an natural isomorphism on the left. -/
def of_nat_iso_left
{F G : C ⥤ D} {H : D ⥤ C} (adj : F ⊣ H) (iso : F ≅ G) :
G ⊣ H :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y, (equiv_homset_left_of_nat_iso iso.symm).trans (adj.hom_equiv X Y) }
/-- Transport an adjunction along an natural isomorphism on the right. -/
def of_nat_iso_right
{F : C ⥤ D} {G H : D ⥤ C} (adj : F ⊣ G) (iso : G ≅ H) :
F ⊣ H :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y, (adj.hom_equiv X Y).trans (equiv_homset_right_of_nat_iso iso) }
/-- Transport being a right adjoint along a natural isomorphism. -/
def right_adjoint_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [r : is_right_adjoint F] : is_right_adjoint G :=
{ left := r.left,
adj := of_nat_iso_right r.adj h }
/-- Transport being a left adjoint along a natural isomorphism. -/
def left_adjoint_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [r : is_left_adjoint F] : is_left_adjoint G :=
{ right := r.right,
adj := of_nat_iso_left r.adj h }
section
variables {E : Type u₃} [ℰ : category.{v₃} E] (H : D ⥤ E) (I : E ⥤ D)
/-- Show that adjunctions can be composed. -/
def comp (adj₁ : F ⊣ G) (adj₂ : H ⊣ I) : F ⋙ H ⊣ I ⋙ G :=
{ hom_equiv := λ X Z, equiv.trans (adj₂.hom_equiv _ _) (adj₁.hom_equiv _ _),
unit := adj₁.unit ≫
(whisker_left F $ whisker_right adj₂.unit G) ≫ (functor.associator _ _ _).inv,
counit := (functor.associator _ _ _).hom ≫
(whisker_left I $ whisker_right adj₁.counit H) ≫ adj₂.counit }
/-- If `F` and `G` are left adjoints then `F ⋙ G` is a left adjoint too. -/
instance left_adjoint_of_comp {E : Type u₃} [ℰ : category.{v₃} E] (F : C ⥤ D) (G : D ⥤ E)
[Fl : is_left_adjoint F] [Gl : is_left_adjoint G] : is_left_adjoint (F ⋙ G) :=
{ right := Gl.right ⋙ Fl.right,
adj := comp _ _ Fl.adj Gl.adj }
/-- If `F` and `G` are right adjoints then `F ⋙ G` is a right adjoint too. -/
instance right_adjoint_of_comp {E : Type u₃} [ℰ : category.{v₃} E] {F : C ⥤ D} {G : D ⥤ E}
[Fr : is_right_adjoint F] [Gr : is_right_adjoint G] : is_right_adjoint (F ⋙ G) :=
{ left := Gr.left ⋙ Fr.left,
adj := comp _ _ Gr.adj Fr.adj }
end
section construct_left
-- Construction of a left adjoint. In order to construct a left
-- adjoint to a functor G : D → C, it suffices to give the object part
-- of a functor F : C → D together with isomorphisms Hom(FX, Y) ≃
-- Hom(X, GY) natural in Y. The action of F on morphisms can be
-- constructed from this data.
variables {F_obj : C → D} {G}
variables (e : Π X Y, (F_obj X ⟶ Y) ≃ (X ⟶ G.obj Y))
variables (he : Π X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g)
include he
private lemma he' {X Y Y'} (f g) : (e X Y').symm (f ≫ G.map g) = (e X Y).symm f ≫ g :=
by intros; rw [equiv.symm_apply_eq, he]; simp
def left_adjoint_of_equiv : C ⥤ D :=
{ obj := F_obj,
map := λ X X' f, (e X (F_obj X')).symm (f ≫ e X' (F_obj X') (𝟙 _)),
map_comp' := λ X X' X'' f f', begin
rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply],
conv { to_rhs, rw [assoc, ←he, id_comp, equiv.apply_symm_apply] },
simp
end }
def adjunction_of_equiv_left : left_adjoint_of_equiv e he ⊣ G :=
mk_of_hom_equiv
{ hom_equiv := e,
hom_equiv_naturality_left_symm' :=
begin
intros,
erw [← he' e he, ← equiv.apply_eq_iff_eq],
simp [(he _ _ _ _ _).symm]
end }
end construct_left
section construct_right
-- Construction of a right adjoint, analogous to the above.
variables {F} {G_obj : D → C}
variables (e : Π X Y, (F.obj X ⟶ Y) ≃ (X ⟶ G_obj Y))
variables (he : Π X' X Y f g, e X' Y (F.map f ≫ g) = f ≫ e X Y g)
include he
private lemma he' {X' X Y} (f g) : F.map f ≫ (e X Y).symm g = (e X' Y).symm (f ≫ g) :=
by intros; rw [equiv.eq_symm_apply, he]; simp
def right_adjoint_of_equiv : D ⥤ C :=
{ obj := G_obj,
map := λ Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (𝟙 _) ≫ g),
map_comp' := λ Y Y' Y'' g g', begin
rw [← equiv.eq_symm_apply, ← he' e he, equiv.symm_apply_apply],
conv { to_rhs, rw [← assoc, he' e he, comp_id, equiv.symm_apply_apply] },
simp
end }
def adjunction_of_equiv_right : F ⊣ right_adjoint_of_equiv e he :=
mk_of_hom_equiv
{ hom_equiv := e,
hom_equiv_naturality_left_symm' := by intros; rw [equiv.symm_apply_eq, he]; simp,
hom_equiv_naturality_right' :=
begin
intros X Y Y' g h,
erw [←he, equiv.apply_eq_iff_eq, ←assoc, he' e he, comp_id, equiv.symm_apply_apply]
end }
end construct_right
end adjunction
open adjunction
namespace equivalence
def to_adjunction (e : C ≌ D) : e.functor ⊣ e.inverse :=
mk_of_unit_counit ⟨e.unit, e.counit,
by { ext, dsimp, simp only [id_comp], exact e.functor_unit_comp _, },
by { ext, dsimp, simp only [id_comp], exact e.unit_inverse_comp _, }⟩
end equivalence
namespace functor
/-- An equivalence `E` is left adjoint to its inverse. -/
def adjunction (E : C ⥤ D) [is_equivalence E] : E ⊣ E.inv :=
(E.as_equivalence).to_adjunction
/-- If `F` is an equivalence, it's a left adjoint. -/
@[priority 10]
instance left_adjoint_of_equivalence {F : C ⥤ D} [is_equivalence F] : is_left_adjoint F :=
{ right := _,
adj := functor.adjunction F }
/-- If `F` is an equivalence, it's a right adjoint. -/
@[priority 10]
instance right_adjoint_of_equivalence {F : C ⥤ D} [is_equivalence F] : is_right_adjoint F :=
{ left := _,
adj := functor.adjunction F.inv }
end functor
end category_theory
|
7d54afc34ec5f529f612ad5b99bb6d410b6b81ee | b7f22e51856f4989b970961f794f1c435f9b8f78 | /library/data/nat/sqrt.lean | 63e62ef26234900eb0193073d6fa1fe3d14dbd8e | [
"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 | 6,901 | 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
Very simple (sqrt n) function that returns s s.t.
s*s ≤ n ≤ s*s + s + s
-/
import data.nat.order data.nat.sub
namespace nat
open decidable
-- This is the simplest possible function that just performs a linear search
definition sqrt_aux : nat → nat → nat
| 0 n := 0
| (succ s) n := if (succ s)*(succ s) ≤ n then succ s else sqrt_aux s n
theorem sqrt_aux_succ_of_pos {s n} : (succ s)*(succ s) ≤ n → sqrt_aux (succ s) n = (succ s) :=
assume h, if_pos h
theorem sqrt_aux_succ_of_neg {s n} : ¬ (succ s)*(succ s) ≤ n → sqrt_aux (succ s) n = sqrt_aux s n :=
assume h, if_neg h
theorem sqrt_aux_of_le : ∀ {s n : nat}, s * s ≤ n → sqrt_aux s n = s
| 0 n h := rfl
| (succ s) n h := by rewrite [sqrt_aux_succ_of_pos h]
theorem sqrt_aux_le : ∀ (s n), sqrt_aux s n ≤ s
| 0 n := !zero_le
| (succ s) n := or.elim (em ((succ s)*(succ s) ≤ n))
(λ h, begin unfold sqrt_aux, rewrite [if_pos h] end)
(λ h,
have sqrt_aux s n ≤ succ s, from le.step (sqrt_aux_le s n),
begin unfold sqrt_aux, rewrite [if_neg h], assumption end)
definition sqrt (n : nat) : nat :=
sqrt_aux n n
theorem sqrt_aux_lower : ∀ {s n : nat}, s ≤ n → sqrt_aux s n * sqrt_aux s n ≤ n
| 0 n h := h
| (succ s) n h := by_cases
(λ h₁ : (succ s)*(succ s) ≤ n, by rewrite [sqrt_aux_succ_of_pos h₁]; exact h₁)
(λ h₂ : ¬ (succ s)*(succ s) ≤ n,
have aux : s ≤ n, from le_of_succ_le h,
by rewrite [sqrt_aux_succ_of_neg h₂]; exact (sqrt_aux_lower aux))
theorem sqrt_lower (n : nat) : sqrt n * sqrt n ≤ n :=
sqrt_aux_lower (le.refl n)
theorem sqrt_aux_upper : ∀ {s n : nat}, n ≤ s*s + s + s → n ≤ sqrt_aux s n * sqrt_aux s n + sqrt_aux s n + sqrt_aux s n
| 0 n h := h
| (succ s) n h := by_cases
(λ h₁ : (succ s)*(succ s) ≤ n,
by rewrite [sqrt_aux_succ_of_pos h₁]; exact h)
(λ h₂ : ¬ (succ s)*(succ s) ≤ n,
have h₃ : n < (succ s) * (succ s), from lt_of_not_ge h₂,
have h₄ : n ≤ s * s + s + s, by rewrite [succ_mul_succ_eq at h₃]; exact le_of_lt_succ h₃,
by rewrite [sqrt_aux_succ_of_neg h₂]; exact (sqrt_aux_upper h₄))
theorem sqrt_upper (n : nat) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n :=
have aux : n ≤ n*n + n + n, from le_add_of_le_right (le_add_of_le_left (le.refl n)),
sqrt_aux_upper aux
private theorem le_squared : ∀ (n : nat), n ≤ n*n
| 0 := !le.refl
| (succ n) :=
have aux₁ : 1 ≤ succ n, from succ_le_succ !zero_le,
have aux₂ : 1 * succ n ≤ succ n * succ n, from nat.mul_le_mul aux₁ !le.refl,
by rewrite [one_mul at aux₂]; exact aux₂
private theorem lt_squared : ∀ {n : nat}, n > 1 → n < n * n
| 0 h := absurd h dec_trivial
| 1 h := absurd h dec_trivial
| (succ (succ n)) h :=
have 1 < succ (succ n), from dec_trivial,
have succ (succ n) * 1 < succ (succ n) * succ (succ n), from mul_lt_mul_of_pos_left this dec_trivial,
by rewrite [mul_one at this]; exact this
theorem sqrt_le (n : nat) : sqrt n ≤ n :=
calc sqrt n ≤ sqrt n * sqrt n : le_squared
... ≤ n : sqrt_lower
theorem eq_zero_of_sqrt_eq_zero {n : nat} : sqrt n = 0 → n = 0 :=
suppose sqrt n = 0,
have n ≤ sqrt n * sqrt n + sqrt n + sqrt n, from !sqrt_upper,
have n ≤ 0, by rewrite [*`sqrt n = 0` at this]; exact this,
eq_zero_of_le_zero this
theorem le_three_of_sqrt_eq_one {n : nat} : sqrt n = 1 → n ≤ 3 :=
suppose sqrt n = 1,
have n ≤ sqrt n * sqrt n + sqrt n + sqrt n, from !sqrt_upper,
show n ≤ 3, by rewrite [*`sqrt n = 1` at this]; exact this
theorem sqrt_lt : ∀ {n : nat}, n > 1 → sqrt n < n
| 0 h := absurd h dec_trivial
| 1 h := absurd h dec_trivial
| 2 h := dec_trivial
| 3 h := dec_trivial
| (n+4) h :=
have sqrt (n+4) > 1, from by_contradiction
(suppose ¬ sqrt (n+4) > 1,
have sqrt (n+4) ≤ 1, from le_of_not_gt this,
or.elim (eq_or_lt_of_le this)
(suppose sqrt (n+4) = 1,
have n+4 ≤ 3, from le_three_of_sqrt_eq_one this,
absurd this dec_trivial)
(suppose sqrt (n+4) < 1,
have sqrt (n+4) = 0, from eq_zero_of_le_zero (le_of_lt_succ this),
have n + 4 = 0, from eq_zero_of_sqrt_eq_zero this,
absurd this dec_trivial)),
calc sqrt (n+4) < sqrt (n+4) * sqrt (n+4) : lt_squared this
... ≤ n+4 : sqrt_lower
theorem sqrt_pos_of_pos {n : nat} : n > 0 → sqrt n > 0 :=
suppose n > 0,
have sqrt n ≠ 0, from
suppose sqrt n = 0,
have n = 0, from eq_zero_of_sqrt_eq_zero this,
by subst n; exact absurd `0 > 0` !lt.irrefl,
pos_of_ne_zero this
theorem sqrt_aux_offset_eq {n k : nat} (h₁ : k ≤ n + n) : ∀ {s}, s ≥ n → sqrt_aux s (n*n + k) = n
| 0 h₂ :=
have neqz : n = 0, from eq_zero_of_le_zero h₂,
by rewrite neqz
| (succ s) h₂ := by_cases
(λ hl : (succ s)*(succ s) ≤ n*n + k,
have l₁ : n*n + k ≤ n*n + n + n, from by rewrite [add.assoc]; exact (add_le_add_left h₁ (n*n)),
have l₂ : n*n + k < n*n + n + n + 1, from lt_succ_of_le l₁,
have l₃ : n*n + k < (succ n)*(succ n), by rewrite [-succ_mul_succ_eq at l₂]; exact l₂,
have l₄ : (succ s)*(succ s) < (succ n)*(succ n), from lt_of_le_of_lt hl l₃,
have ng : ¬ succ s > (succ n), from
assume g : succ s > succ n,
have g₁ : (succ s)*(succ s) > (succ n)*(succ n), from mul_lt_mul_of_le_of_le g g,
absurd (lt.trans g₁ l₄) !lt.irrefl,
have sslesn : succ s ≤ succ n, from le_of_not_gt ng,
have ssnesn : succ s ≠ succ n, from
assume sseqsn : succ s = succ n,
by rewrite [sseqsn at l₄]; exact (absurd l₄ !lt.irrefl),
have sslen : s < n, from lt_of_succ_lt_succ (lt_of_le_of_ne sslesn ssnesn),
have sseqn : succ s = n, from le.antisymm sslen h₂,
by rewrite [sqrt_aux_succ_of_pos hl]; exact sseqn)
(λ hg : ¬ (succ s)*(succ s) ≤ n*n + k,
or.elim (eq_or_lt_of_le h₂)
(λ neqss : n = succ s,
have p : n*n ≤ n*n + k, from !le_add_right,
have n : ¬ n*n ≤ n*n + k, by rewrite [-neqss at hg]; exact hg,
absurd p n)
(λ sgen : succ s > n,
by rewrite [sqrt_aux_succ_of_neg hg]; exact (sqrt_aux_offset_eq (le_of_lt_succ sgen))))
theorem sqrt_offset_eq {n k : nat} : k ≤ n + n → sqrt (n*n + k) = n :=
assume h,
have h₁ : n ≤ n*n + k, from le.trans !le_squared !le_add_right,
sqrt_aux_offset_eq h h₁
theorem sqrt_eq (n : nat) : sqrt (n*n) = n :=
sqrt_offset_eq !zero_le
theorem mul_square_cancel {a b : nat} : a*a = b*b → a = b :=
assume h,
have aux : sqrt (a*a) = sqrt (b*b), by rewrite h,
by rewrite [*sqrt_eq at aux]; exact aux
end nat
|
9af40ddbabe419d3ba2dc992fd4dd8f76d941be1 | fcf3ffa92a3847189ca669cb18b34ef6b2ec2859 | /src/world6/level1.lean | 08aeda0f6e6ef313031bd77fb4d4ef53dc1a97f4 | [
"Apache-2.0"
] | permissive | nomoid/lean-proofs | 4a80a97888699dee42b092b7b959b22d9aa0c066 | b9f03a24623d1a1d111d6c2bbf53c617e2596d6a | refs/heads/master | 1,674,955,317,080 | 1,607,475,706,000 | 1,607,475,706,000 | 314,104,281 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 75 | lean | example (P Q : Prop) (p : P) (h : P → Q) : Q :=
begin
exact h(p),
end |
cf9d8d5bb5a96cbbcf6b01fe034ef5bd4a8cfb9b | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /tests/lean/run/rw_set1.lean | 4d69c86119b7b0d5821d7cb6958a96dfc4f9bfdb | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 238 | lean | import data.nat
namespace foo
attribute nat.add.assoc [simp]
print nat.add.assoc
end foo
print nat.add.assoc
namespace foo
print nat.add.assoc
attribute nat.add.comm [simp]
open nat
print "---------"
print [simp]
end foo
|
228c58ca26106e0e2c186b932708e230a56e5d47 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/classical_auto.lean | 2a95bda6e898a9c7ea6efcd407fadc3c4949002d | [] | 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 | 4,238 | 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, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.data.subtype.basic
import Mathlib.Lean3Lib.init.funext
universes u v
namespace Mathlib
namespace classical
/- the axiom -/
axiom choice {α : Sort u} : Nonempty α → α
theorem indefinite_description {α : Sort u} (p : α → Prop) (h : ∃ (x : α), p x) :
Subtype fun (x : α) => p x :=
sorry
def some {α : Sort u} {p : α → Prop} (h : ∃ (x : α), p x) : α :=
subtype.val (indefinite_description p h)
theorem some_spec {α : Sort u} {p : α → Prop} (h : ∃ (x : α), p x) : p (some h) :=
subtype.property (indefinite_description p h)
/- Diaconescu's theorem: using function extensionality and propositional extensionality,
we can get excluded middle from this. -/
/- TODO(Leo): check why the code generator is not ignoring (some exU)
when we mark u as def. -/
theorem em (p : Prop) : p ∨ ¬p :=
or.elim (not_uv_or_p p) (fun (hne : u p ≠ v p) => Or.inr (mt (p_implies_uv p) hne)) Or.inl
theorem exists_true_of_nonempty {α : Sort u} : Nonempty α → ∃ (x : α), True :=
fun (ᾰ : Nonempty α) =>
nonempty.dcases_on ᾰ fun (ᾰ : α) => idRhs (∃ (x : α), True) (Exists.intro ᾰ trivial)
def inhabited_of_nonempty {α : Sort u} (h : Nonempty α) : Inhabited α :=
{ default := Classical.choice h }
def inhabited_of_exists {α : Sort u} {p : α → Prop} (h : ∃ (x : α), p x) : Inhabited α :=
inhabited_of_nonempty sorry
/- all propositions are decidable -/
def prop_decidable (a : Prop) : Decidable a := Classical.choice sorry
def decidable_inhabited (a : Prop) : Inhabited (Decidable a) := { default := prop_decidable a }
def type_decidable_eq (α : Sort u) : DecidableEq α := fun (x y : α) => prop_decidable (x = y)
def type_decidable (α : Sort u) : psum α (α → False) := sorry
theorem strong_indefinite_description {α : Sort u} (p : α → Prop) (h : Nonempty α) :
Subtype fun (x : α) => (∃ (y : α), p y) → p x :=
sorry
/- the Hilbert epsilon function -/
def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α :=
subtype.val (strong_indefinite_description p h)
theorem epsilon_spec_aux {α : Sort u} (h : Nonempty α) (p : α → Prop) :
(∃ (y : α), p y) → p (epsilon p) :=
subtype.property (strong_indefinite_description p h)
theorem epsilon_spec {α : Sort u} {p : α → Prop} (hex : ∃ (y : α), p y) : p (epsilon p) :=
epsilon_spec_aux (nonempty_of_exists hex) p hex
theorem epsilon_singleton {α : Sort u} (x : α) : (epsilon fun (y : α) => y = x) = x :=
epsilon_spec (Exists.intro x rfl)
/- the axiom of choice -/
theorem axiom_of_choice {α : Sort u} {β : α → Sort v} {r : (x : α) → β x → Prop}
(h : ∀ (x : α), ∃ (y : β x), r x y) : ∃ (f : (x : α) → β x), ∀ (x : α), r x (f x) :=
Exists.intro (fun (x : α) => some (h x)) fun (x : α) => some_spec (h x)
theorem skolem {α : Sort u} {b : α → Sort v} {p : (x : α) → b x → Prop} :
(∀ (x : α), ∃ (y : b x), p x y) ↔ ∃ (f : (x : α) → b x), ∀ (x : α), p x (f x) :=
sorry
theorem prop_complete (a : Prop) : a = True ∨ a = False :=
or.elim (em a) (fun (t : a) => Or.inl (eq_true_intro t)) fun (f : ¬a) => Or.inr (eq_false_intro f)
def eq_true_or_eq_false (a : Prop) : a = True ∨ a = False := prop_complete
theorem cases_true_false (p : Prop → Prop) (h1 : p True) (h2 : p False) (a : Prop) : p a :=
or.elim (prop_complete a) (fun (ht : a = True) => Eq.symm ht ▸ h1)
fun (hf : a = False) => Eq.symm hf ▸ h2
theorem cases_on (a : Prop) {p : Prop → Prop} (h1 : p True) (h2 : p False) : p a :=
cases_true_false p h1 h2 a
-- this supercedes by_cases in decidable
def by_cases {p : Prop} {q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q := decidable.by_cases hpq hnpq
-- this supercedes by_contradiction in decidable
theorem by_contradiction {p : Prop} (h : ¬p → False) : p := decidable.by_contradiction h
theorem eq_false_or_eq_true (a : Prop) : a = False ∨ a = True := or.symm (prop_complete a)
end Mathlib |
eff78b4afd335c884bdf06a0349c17031af18d2f | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/algebra/infinite_sum.lean | 473837ee9cf79a178852b5125881648c90c1cf10 | [
"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 | 59,313 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import algebra.big_operators.intervals
import algebra.big_operators.nat_antidiagonal
import data.equiv.encodable.lattice
import topology.algebra.mul_action
import topology.algebra.ordered.monotone_convergence
import topology.instances.real
/-!
# Infinite sum over a topological monoid
This sum is known as unconditionally convergent, as it sums to the same value under all possible
permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute
convergence.
Note: There are summable sequences which are not unconditionally convergent! The other way holds
generally, see `has_sum.tendsto_sum_nat`.
## References
* Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups)
-/
noncomputable theory
open finset filter function classical
open_locale topological_space classical big_operators nnreal
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
section has_sum
variables [add_comm_monoid α] [topological_space α]
/-- Infinite sum on a topological monoid
The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum
up bigger and bigger sets. This sum operation is invariant under reordering. In particular,
the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a
sum for this definition, but a series which is absolutely convergent will have the correct sum.
This is based on Mario Carneiro's
[infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html).
For the definition or many statements, `α` does not need to be a topological monoid. We only add
this assumption later, for the lemmas where it is relevant.
-/
def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a)
/-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/
def summable (f : β → α) : Prop := ∃a, has_sum f a
/-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/
@[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0
-- see Note [operator precedence of big operators]
notation `∑'` binders `, ` r:(scoped:67 f, tsum f) := r
variables {f g : β → α} {a b : α} {s : finset β}
lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) :=
by simp [ha, tsum]; exact some_spec ha
lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩
/-- Constant zero function has sum `0` -/
lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 :=
by simp [has_sum, tendsto_const_nhds]
lemma has_sum_empty [is_empty β] : has_sum f 0 :=
by convert has_sum_zero
lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable
lemma summable_empty [is_empty β] : summable f := has_sum_empty.summable
lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : ∑'b, f b = 0 :=
by simp [tsum, h]
lemma summable_congr (hfg : ∀b, f b = g b) :
summable f ↔ summable g :=
iff_of_eq (congr_arg summable $ funext hfg)
lemma summable.congr (hf : summable f) (hfg : ∀b, f b = g b) :
summable g :=
(summable_congr hfg).mp hf
lemma has_sum.has_sum_of_sum_eq {g : γ → α}
(h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b)
(hf : has_sum g a) :
has_sum f a :=
le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf
lemma has_sum_iff_has_sum {g : γ → α}
(h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b)
(h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) :
has_sum f a ↔ has_sum g a :=
⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩
lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g)
(hf : ∀ x ∉ set.range g, f x = 0) :
has_sum (f ∘ g) a ↔ has_sum f a :=
by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf]
lemma function.injective.summable_iff {g : γ → β} (hg : injective g)
(hf : ∀ x ∉ set.range g, f x = 0) :
summable (f ∘ g) ↔ summable f :=
exists_congr $ λ _, hg.has_sum_iff hf
lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) :
has_sum (f ∘ coe : s → α) a ↔ has_sum f a :=
subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf
lemma has_sum_subtype_iff_indicator {s : set β} :
has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a :=
by rw [← set.indicator_range_comp, subtype.range_coe,
has_sum_subtype_iff_of_support_subset set.support_indicator_subset]
@[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a :=
has_sum_subtype_iff_of_support_subset $ set.subset.refl _
lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) :=
order_top.tendsto_at_top_nhds _
protected lemma finset.has_sum (s : finset β) (f : β → α) :
has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) :=
by { rw ← sum_attach, exact has_sum_fintype _ }
protected lemma finset.summable (s : finset β) (f : β → α) :
summable (f ∘ coe : (↑s : set β) → α) :=
(s.has_sum f).summable
protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) :
summable (f ∘ coe : s → α) :=
by convert hs.to_finset.summable f; simp only [hs.coe_to_finset]
/-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/
lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) :=
(has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f
lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f :=
(has_sum_sum_of_ne_finset_zero hf).summable
lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) :
has_sum f (f b) :=
suffices has_sum f (∑ b' in {b}, f b'),
by simpa using this,
has_sum_sum_of_ne_finset_zero $ by simpa [hf]
lemma has_sum_ite_eq (b : β) [decidable_pred (= b)] (a : α) :
has_sum (λb', if b' = b then a else 0) a :=
begin
convert has_sum_single b _,
{ exact (if_pos rfl).symm },
assume b' hb',
exact if_neg hb'
end
lemma equiv.has_sum_iff (e : γ ≃ β) :
has_sum (f ∘ e) a ↔ has_sum f a :=
e.injective.has_sum_iff $ by simp
lemma function.injective.has_sum_range_iff {g : γ → β} (hg : injective g) :
has_sum (λ x : set.range g, f x) a ↔ has_sum (f ∘ g) a :=
(equiv.of_injective g hg).has_sum_iff.symm
lemma equiv.summable_iff (e : γ ≃ β) :
summable (f ∘ e) ↔ summable f :=
exists_congr $ λ a, e.has_sum_iff
lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) :=
(equiv.prod_comm γ β).summable_iff.2 hf
lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g)
(he : ∀ x : support f, g (e x) = f x) :
has_sum f a ↔ has_sum g a :=
have (g ∘ coe) ∘ e = f ∘ coe, from funext he,
by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support]
lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β)
(hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y)
(hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) :
has_sum f a ↔ has_sum g a :=
iff.symm $ equiv.has_sum_iff_of_support
(equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩)
⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h,
λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩)
hfg
lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g)
(he : ∀ x : support f, g (e x) = f x) :
summable f ↔ summable g :=
exists_congr $ λ _, e.has_sum_iff_of_support he
protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a)
(g : α →+ γ) (hg : continuous g) :
has_sum (g ∘ f) (g a) :=
have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)),
from funext $ g.map_sum _,
show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)),
from this ▸ (hg.tendsto a).comp hf
protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f)
(g : α →+ γ) (hg : continuous g) :
summable (g ∘ f) :=
(hf.has_sum.map g hg).summable
/-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/
lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) :
tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) :=
h.comp tendsto_finset_range
lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ :=
tendsto_nhds_unique
lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) :
has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) :=
begin
refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩,
rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat,
exact hf.has_sum
end
lemma equiv.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α']
[topological_space α'] (e : α' ≃ α) {f : β → α} {g : γ → α'}
(he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) :
summable f ↔ summable g :=
⟨λ ⟨a, ha⟩, ⟨e.symm a, he.1 $ by rwa [e.apply_symm_apply]⟩, λ ⟨a, ha⟩, ⟨e a, he.2 ha⟩⟩
variable [has_continuous_add α]
lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) :=
by simp only [has_sum, sum_add_distrib]; exact hf.add hg
lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) :=
(hf.has_sum.add hg.has_sum).summable
lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} :
(∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) :=
finset.induction_on s (by simp only [has_sum_zero, sum_empty, forall_true_iff])
(by simp only [has_sum.add, sum_insert, mem_insert, forall_eq_or_imp,
forall_2_true_iff, not_false_iff, forall_true_iff] {contextual := tt})
lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) :
summable (λb, ∑ i in s, f i b) :=
(has_sum_sum $ assume i hi, (hf i hi).has_sum).summable
lemma has_sum.add_disjoint {s t : set β} (hs : disjoint s t)
(ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) :
has_sum (f ∘ coe : s ∪ t → α) (a + b) :=
begin
rw has_sum_subtype_iff_indicator at *,
rw set.indicator_union_of_disjoint hs,
exact ha.add hb
end
lemma has_sum.add_is_compl {s t : set β} (hs : is_compl s t)
(ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) :
has_sum f (a + b) :=
by simpa [← hs.compl_eq]
using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb)
lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a)
(hb : has_sum (f ∘ coe : sᶜ → α) b) :
has_sum f (a + b) :=
ha.add_is_compl is_compl_compl hb
lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α))
(hsc : summable (f ∘ coe : sᶜ → α)) :
summable f :=
(hs.has_sum.add_compl hsc.has_sum).summable
lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a)
(hb : has_sum (f ∘ coe : s → α) b) :
has_sum f (a + b) :=
ha.add_is_compl is_compl_compl.symm hb
lemma has_sum.even_add_odd {f : ℕ → α} (he : has_sum (λ k, f (2 * k)) a)
(ho : has_sum (λ k, f (2 * k + 1)) b) :
has_sum f (a + b) :=
begin
have := mul_right_injective₀ (@two_ne_zero ℕ _ _),
replace he := this.has_sum_range_iff.2 he,
replace ho := ((add_left_injective 1).comp this).has_sum_range_iff.2 ho,
refine he.add_is_compl _ ho,
simpa [(∘)] using nat.is_compl_even_odd
end
lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α))
(hsc : summable (f ∘ coe : s → α)) :
summable f :=
(hs.has_sum.compl_add hsc.has_sum).summable
lemma summable.even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k)))
(ho : summable (λ k, f (2 * k + 1))) :
summable f :=
(he.has_sum.even_add_odd ho.has_sum).summable
lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α}
(ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a :=
begin
refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _,
rintros s ⟨hs, hsc⟩,
rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩,
use [u.image sigma.fst, trivial],
intros bs hbs,
simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu,
have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p)
at_top (𝓝 $ ∑ b in bs, g b),
{ simp only [← sigma_preimage_mk, sum_sigma],
refine tendsto_finset_sum _ (λ b hb, _),
change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)),
exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) },
refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩),
exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩
end
/-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ`
has sum `g b`, then the series `g` has sum `a`. -/
lemma has_sum.prod_fiberwise [regular_space α] {f : β × γ → α} {g : β → α} {a : α}
(ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) :
has_sum g a :=
has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf
lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) :
summable (λb, ∑'c, f ⟨b, c⟩) :=
(ha.has_sum.sigma (assume b, (hf b).has_sum)).summable
lemma has_sum.sigma_of_has_sum [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α}
{a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) :
has_sum f a :=
by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum
end has_sum
section tsum
variables [add_comm_monoid α] [topological_space α] [t2_space α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma has_sum.tsum_eq (ha : has_sum f a) : ∑'b, f b = a :=
(summable.has_sum ⟨a, ha⟩).unique ha
lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ ∑'b, f b = a :=
iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum)
@[simp] lemma tsum_zero : ∑'b:β, (0:α) = 0 := has_sum_zero.tsum_eq
@[simp] lemma tsum_empty [is_empty β] : ∑'b, f b = 0 := has_sum_empty.tsum_eq
lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) :
∑' b, f b = ∑ b in s, f b :=
(has_sum_sum_of_ne_finset_zero hf).tsum_eq
lemma tsum_congr {α β : Type*} [add_comm_monoid α] [topological_space α]
{f g : β → α} (hfg : ∀ b, f b = g b) : ∑' b, f b = ∑' b, g b :=
congr_arg tsum (funext hfg)
lemma tsum_fintype [fintype β] (f : β → α) : ∑'b, f b = ∑ b, f b :=
(has_sum_fintype f).tsum_eq
lemma tsum_bool (f : bool → α) : ∑' i : bool, f i = f false + f true :=
by { rw [tsum_fintype, finset.sum_eq_add]; simp }
@[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) :
∑' x : {x // x ∈ s}, f x = ∑ x in s, f x :=
(s.has_sum f).tsum_eq
@[simp] lemma finset.tsum_subtype' (s : finset β) (f : β → α) :
∑' x : (s : set β), f x = ∑ x in s, f x :=
s.tsum_subtype f
lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) :
∑'b, f b = f b :=
(has_sum_single b hf).tsum_eq
@[simp] lemma tsum_ite_eq (b : β) [decidable_pred (= b)] (a : α) :
∑' b', (if b' = b then a else 0) = a :=
(has_sum_ite_eq b a).tsum_eq
lemma tsum_dite_right (P : Prop) [decidable P] (x : β → ¬ P → α) :
∑' (b : β), (if h : P then (0 : α) else x b h) = if h : P then (0 : α) else ∑' (b : β), x b h :=
by by_cases hP : P; simp [hP]
lemma tsum_dite_left (P : Prop) [decidable P] (x : β → P → α) :
∑' (b : β), (if h : P then x b h else 0) = if h : P then (∑' (b : β), x b h) else 0 :=
by by_cases hP : P; simp [hP]
lemma equiv.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α']
[topological_space α'] (e : α' ≃ α) (h0 : e 0 = 0) {f : β → α} {g : γ → α'}
(h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) :
∑' b, f b = e (∑' c, g c) :=
by_cases
(assume : summable g, (h.mpr this.has_sum).tsum_eq)
(assume hg : ¬ summable g,
have hf : ¬ summable f, from mt (e.summable_iff_of_has_sum_iff @h).1 hg,
by simp [tsum, hf, hg, h0])
lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α}
(h : ∀{a}, has_sum f a ↔ has_sum g a) :
∑'b, f b = ∑'c, g c :=
(equiv.refl α).tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h
lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : ∑'c, f (j c) = ∑'b, f b :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff
lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g)
(he : ∀ x, g (e x) = f x) :
(∑' x, f x) = ∑' y, g y :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he
lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β)
(hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y)
(hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) :
∑' x, f x = ∑' y, g y :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg
lemma tsum_subtype (s : set β) (f : β → α) :
∑' x:s, f x = ∑' x, s.indicator f x :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator
section has_continuous_add
variable [has_continuous_add α]
lemma tsum_add (hf : summable f) (hg : summable g) : ∑'b, (f b + g b) = (∑'b, f b) + (∑'b, g b) :=
(hf.has_sum.add hg.has_sum).tsum_eq
lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) :
∑'b, ∑ i in s, f i b = ∑ i in s, ∑'b, f i b :=
(has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq
lemma tsum_sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ :=
(h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm
lemma tsum_prod' [regular_space α] {f : β × γ → α} (h : summable f)
(h₁ : ∀b, summable (λc, f (b, c))) :
∑'p, f p = ∑'b c, f (b, c) :=
(h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm
lemma tsum_comm' [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f))
(h₁ : ∀b, summable (f b)) (h₂ : ∀ c, summable (λ b, f b c)) :
∑' c b, f b c = ∑' b c, f b c :=
begin
erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm β γ).tsum_eq],
refl,
assumption
end
end has_continuous_add
section encodable
open encodable
variable [encodable γ]
/-- You can compute a sum over an encodably type by summing over the natural numbers and
taking a supremum. This is useful for outer measures. -/
theorem tsum_supr_decode₂ [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(s : γ → β) : ∑' i : ℕ, m (⨆ b ∈ decode₂ γ i, s b) = ∑' b : γ, m (s b) :=
begin
have H : ∀ n, m (⨆ b ∈ decode₂ γ n, s b) ≠ 0 → (decode₂ γ n).is_some,
{ intros n h,
cases decode₂ γ n with b,
{ refine (h $ by simp [m0]).elim },
{ exact rfl } },
symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _,
{ rintros ⟨m, hm⟩ ⟨n, hn⟩ e,
have := mem_decode₂.1 (option.get_mem (H n hn)),
rwa [← e, mem_decode₂.1 (option.get_mem (H m hm))] at this },
{ intros b h,
refine ⟨⟨encode b, _⟩, _⟩,
{ simp only [mem_support, encodek₂] at h ⊢, convert h, simp [set.ext_iff, encodek₂] },
{ exact option.get_of_mem _ (encodek₂ _) } },
{ rintros ⟨n, h⟩, dsimp only [subtype.coe_mk],
transitivity, swap,
rw [show decode₂ γ n = _, from option.get_mem (H n h)],
congr, simp [ext_iff, -option.some_get] }
end
/-- `tsum_supr_decode₂` specialized to the complete lattice of sets. -/
theorem tsum_Union_decode₂ (m : set β → α) (m0 : m ∅ = 0)
(s : γ → set β) : ∑' i, m (⋃ b ∈ decode₂ γ i, s b) = ∑' b, m (s b) :=
tsum_supr_decode₂ m m0 s
/-! Some properties about measure-like functions.
These could also be functions defined on complete sublattices of sets, with the property
that they are countably sub-additive.
`R` will probably be instantiated with `(≤)` in all applications.
-/
/-- If a function is countably sub-additive then it is sub-additive on encodable types -/
theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) ∑' i, m (s i))
(s : γ → β) : R (m (⨆ b : γ, s b)) ∑' b : γ, m (s b) :=
by { rw [← supr_decode₂, ← tsum_supr_decode₂ _ m0 s], exact m_supr _ }
/-- If a function is countably sub-additive then it is sub-additive on finite sets -/
theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i)))
(s : δ → β) (t : finset δ) :
R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) :=
by { cases t.nonempty_encodable, rw [supr_subtype'], convert rel_supr_tsum m m0 R m_supr _,
rw [← finset.tsum_subtype], assumption }
/-- If a function is countably sub-additive then it is binary sub-additive -/
theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i)))
(s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) :=
begin
convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂),
{ simp only [supr_bool_eq, cond] },
{ rw [tsum_fintype, fintype.sum_bool, cond, cond] }
end
end encodable
variables [has_continuous_add α]
lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α))
(hsc : summable (f ∘ coe : sᶜ → α)) :
(∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x :=
(hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm
lemma tsum_union_disjoint {s t : set β} (hd : disjoint s t)
(hs : summable (f ∘ coe : s → α)) (ht : summable (f ∘ coe : t → α)) :
(∑' x : s ∪ t, f x) = (∑' x : s, f x) + (∑' x : t, f x) :=
(hs.has_sum.add_disjoint hd ht.has_sum).tsum_eq
lemma tsum_even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k)))
(ho : summable (λ k, f (2 * k + 1))) :
(∑' k, f (2 * k)) + (∑' k, f (2 * k + 1)) = ∑' k, f k :=
(he.has_sum.even_add_odd ho.has_sum).tsum_eq.symm
end tsum
section prod
variables [add_comm_monoid α] [topological_space α] [add_comm_monoid γ] [topological_space γ]
lemma has_sum.prod_mk {f : β → α} {g : β → γ} {a : α} {b : γ}
(hf : has_sum f a) (hg : has_sum g b) :
has_sum (λ x, (⟨f x, g x⟩ : α × γ)) ⟨a, b⟩ :=
by simp [has_sum, ← prod_mk_sum, filter.tendsto.prod_mk_nhds hf hg]
end prod
section pi
variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)]
lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} :
has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) :=
by simp only [has_sum, tendsto_pi, sum_apply]
lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) :=
by simp only [summable, pi.has_sum, skolem]
lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) :
(∑' i, f i) x = ∑' i, f i x :=
(pi.has_sum.mp hf.has_sum x).tsum_eq.symm
end pi
section topological_group
variables [add_comm_group α] [topological_space α] [topological_add_group α]
variables {f g : β → α} {a a₁ a₂ : α}
-- `by simpa using` speeds up elaboration. Why?
lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) :=
by simpa only using h.map (-add_monoid_hom.id α) continuous_neg
lemma summable.neg (hf : summable f) : summable (λb, - f b) :=
hf.has_sum.neg.summable
lemma summable.of_neg (hf : summable (λb, - f b)) : summable f :=
by simpa only [neg_neg] using hf.neg
lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f :=
⟨summable.of_neg, summable.neg⟩
lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) :=
by { simp only [sub_eq_add_neg], exact hf.add hg.neg }
lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) :=
(hf.has_sum.sub hg.has_sum).summable
lemma summable.trans_sub (hg : summable g) (hfg : summable (λb, f b - g b)) :
summable f :=
by simpa only [sub_add_cancel] using hfg.add hg
lemma summable_iff_of_summable_sub (hfg : summable (λb, f b - g b)) :
summable f ↔ summable g :=
⟨λ hf, hf.trans_sub $ by simpa only [neg_sub] using hfg.neg, λ hg, hg.trans_sub hfg⟩
lemma has_sum.update (hf : has_sum f a₁) (b : β) [decidable_eq β] (a : α) :
has_sum (update f b a) (a - f b + a₁) :=
begin
convert ((has_sum_ite_eq b _).add hf),
ext b',
by_cases h : b' = b,
{ rw [h, update_same],
simp only [eq_self_iff_true, if_true, sub_add_cancel] },
simp only [h, update_noteq, if_false, ne.def, zero_add, not_false_iff],
end
lemma summable.update (hf : summable f) (b : β) [decidable_eq β] (a : α) :
summable (update f b a) :=
(hf.has_sum.update b a).summable
lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) :
has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) :=
begin
refine ⟨λ h, hf.add_compl h, λ h, _⟩,
rw [has_sum_subtype_iff_indicator] at hf ⊢,
rw [set.indicator_compl],
simpa only [add_sub_cancel'] using h.sub hf
end
lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) :
has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) :=
iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right]
lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) :
summable (f ∘ coe : sᶜ → α) ↔ summable f :=
⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable,
λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩
protected lemma finset.has_sum_compl_iff (s : finset β) :
has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) :=
(s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm]
protected lemma finset.has_sum_iff_compl (s : finset β) :
has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) :=
(s.has_sum f).has_sum_iff_compl
protected lemma finset.summable_compl_iff (s : finset β) :
summable (λ x : {x // x ∉ s}, f x) ↔ summable f :=
(s.summable f).summable_compl_iff
lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) :
summable (f ∘ coe : sᶜ → α) ↔ summable f :=
(hs.summable f).summable_compl_iff
lemma has_sum_ite_eq_extract [decidable_eq β] (hf : has_sum f a) (b : β) :
has_sum (λ n, ite (n = b) 0 (f n)) (a - f b) :=
begin
convert hf.update b 0 using 1,
{ ext n, rw function.update_apply, },
{ rw [sub_add_eq_add_sub, zero_add], },
end
section tsum
variables [t2_space α]
lemma tsum_neg (hf : summable f) : ∑'b, - f b = - ∑'b, f b :=
hf.has_sum.neg.tsum_eq
lemma tsum_sub (hf : summable f) (hg : summable g) : ∑'b, (f b - g b) = ∑'b, f b - ∑'b, g b :=
(hf.has_sum.sub hg.has_sum).tsum_eq
lemma sum_add_tsum_compl {s : finset β} (hf : summable f) :
(∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x :=
((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm
/-- Let `f : β → α` be a sequence with summable series and let `b ∈ β` be an index.
Lemma `tsum_ite_eq_extract` writes `Σ f n` as the sum of `f b` plus the series of the
remaining terms. -/
lemma tsum_ite_eq_extract [decidable_eq β] (hf : summable f) (b : β) :
∑' n, f n = f b + ∑' n, ite (n = b) 0 (f n) :=
begin
rw (has_sum_ite_eq_extract hf.has_sum b).tsum_eq,
exact (add_sub_cancel'_right _ _).symm,
end
end tsum
/-!
### Sums on subtypes
If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype
`univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the
formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`.
-/
section subtype
lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} :
has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) :=
begin
refine iff.trans _ ((range k).has_sum_compl_iff),
rw [← (not_mem_range_equiv k).symm.has_sum_iff],
refl
end
lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f :=
iff.symm $ (equiv.add_right (∑ i in range k, f i)).summable_iff_of_has_sum_iff $
λ a, (has_sum_nat_add_iff k).symm
lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} :
has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a :=
by simp [has_sum_nat_add_iff]
lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) :
(∑ i in range k, f i) + (∑' i, f (i + k)) = ∑' i, f i :=
by simpa only [add_comm] using
((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum
lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) :
∑'b, f b = f 0 + ∑'b, f (b + 1) :=
by simpa only [sum_range_one] using (sum_add_tsum_nat_add 1 hf).symm
/-- For `f : ℕ → α`, then `∑' k, f (k + i)` tends to zero. This does not require a summability
assumption on `f`, as otherwise all sums are zero. -/
lemma tendsto_sum_nat_add [t2_space α] (f : ℕ → α) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) :=
begin
by_cases hf : summable f,
{ have h₀ : (λ i, (∑' i, f i) - ∑ j in range i, f j) = λ i, ∑' (k : ℕ), f (k + i),
{ ext1 i,
rw [sub_eq_iff_eq_add, add_comm, sum_add_tsum_nat_add i hf] },
have h₁ : tendsto (λ i : ℕ, ∑' i, f i) at_top (𝓝 (∑' i, f i)) := tendsto_const_nhds,
simpa only [h₀, sub_self] using tendsto.sub h₁ hf.has_sum.tendsto_sum_nat },
{ convert tendsto_const_nhds,
ext1 i,
rw ← summable_nat_add_iff i at hf,
{ exact tsum_eq_zero_of_not_summable hf },
{ apply_instance } }
end
end subtype
end topological_group
section topological_ring
variables [semiring α] [topological_space α] [topological_ring α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma has_sum.mul_left (a₂) (h : has_sum f a₁) : has_sum (λb, a₂ * f b) (a₂ * a₁) :=
by simpa only using h.map (add_monoid_hom.mul_left a₂) (continuous_const.mul continuous_id)
lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) :=
by simpa only using hf.map (add_monoid_hom.mul_right a₂) (continuous_id.mul continuous_const)
lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) :=
(hf.has_sum.mul_left _).summable
lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) :=
(hf.has_sum.mul_right _).summable
section tsum
variables [t2_space α]
lemma summable.tsum_mul_left (a) (hf : summable f) : ∑'b, a * f b = a * ∑'b, f b :=
(hf.has_sum.mul_left _).tsum_eq
lemma summable.tsum_mul_right (a) (hf : summable f) : (∑'b, f b * a) = (∑'b, f b) * a :=
(hf.has_sum.mul_right _).tsum_eq
end tsum
end topological_ring
section has_continuous_smul
variables {R : Type*}
[monoid R] [topological_space R]
[topological_space α] [add_comm_monoid α]
[distrib_mul_action R α] [has_continuous_smul R α]
{f : β → α}
lemma has_sum.smul {a : α} {r : R} (hf : has_sum f a) : has_sum (λ z, r • f z) (r • a) :=
hf.map (distrib_mul_action.to_add_monoid_hom α r) (continuous_const.smul continuous_id)
lemma summable.smul {r : R} (hf : summable f) : summable (λ z, r • f z) :=
hf.has_sum.smul.summable
lemma tsum_smul [t2_space α] {r : R} (hf : summable f) : ∑' z, r • f z = r • ∑' z, f z :=
hf.has_sum.smul.tsum_eq
end has_continuous_smul
section division_ring
variables [division_ring α] [topological_space α] [topological_ring α]
{f g : β → α} {a a₁ a₂ : α}
lemma has_sum.div_const (h : has_sum f a) (b : α) : has_sum (λ x, f x / b) (a / b) :=
by simp only [div_eq_mul_inv, h.mul_right b⁻¹]
lemma summable.div_const (h : summable f) (b : α) : summable (λ x, f x / b) :=
(h.has_sum.div_const b).summable
lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) :=
⟨has_sum.mul_left _, λ H, by simpa only [inv_mul_cancel_left₀ h] using H.mul_left a₂⁻¹⟩
lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) :=
⟨has_sum.mul_right _, λ H, by simpa only [mul_inv_cancel_right₀ h] using H.mul_right a₂⁻¹⟩
lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) :=
⟨λ H, H.mul_left _, λ H, by simpa only [inv_mul_cancel_left₀ h] using H.mul_left a⁻¹⟩
lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) :=
⟨λ H, H.mul_right _, λ H, by simpa only [mul_inv_cancel_right₀ h] using H.mul_right a⁻¹⟩
lemma tsum_mul_left [t2_space α] : (∑' x, a * f x) = a * ∑' x, f x :=
if hf : summable f then hf.tsum_mul_left a
else if ha : a = 0 then by simp [ha]
else by rw [tsum_eq_zero_of_not_summable hf,
tsum_eq_zero_of_not_summable (mt (summable_mul_left_iff ha).2 hf), mul_zero]
lemma tsum_mul_right [t2_space α] : (∑' x, f x * a) = (∑' x, f x) * a :=
if hf : summable f then hf.tsum_mul_right a
else if ha : a = 0 then by simp [ha]
else by rw [tsum_eq_zero_of_not_summable hf,
tsum_eq_zero_of_not_summable (mt (summable_mul_right_iff ha).2 hf), zero_mul]
end division_ring
section order_topology
variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ :=
le_of_tendsto_of_tendsto' hf hg $ assume s, sum_le_sum $ assume b _, h b
@[mono] lemma has_sum_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f ≤ g) : a₁ ≤ a₂ :=
has_sum_le h hf hg
lemma has_sum_le_of_sum_le (hf : has_sum f a) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) :
a ≤ a₂ :=
le_of_tendsto' hf h
lemma le_has_sum_of_le_sum (hf : has_sum f a) (h : ∀ s : finset β, a₂ ≤ ∑ b in s, f b) :
a₂ ≤ a :=
ge_of_tendsto' hf h
lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c)
(h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ :=
have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁,
begin
refine (has_sum_iff_has_sum_of_ne_zero_bij (i ∘ coe) _ _ _).2 hf,
{ exact assume c₁ c₂ eq, hi eq },
{ intros c hc,
rw [mem_support] at hc,
cases eq : partial_inv i c with b; rw eq at hc,
{ contradiction },
{ rw [partial_inv_of_injective hi] at eq,
exact ⟨⟨b, hc⟩, eq⟩ } },
{ assume c, simp [partial_inv_left hi, option.cases_on'] }
end,
begin
refine has_sum_le (assume c, _) this hg,
by_cases c ∈ set.range i,
{ rcases h with ⟨b, rfl⟩,
rw [partial_inv_left hi, option.cases_on'],
exact h _ },
{ have : partial_inv i c = none := dif_neg h,
rw [this, option.cases_on'],
exact hs _ h }
end
lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c)
(h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g :=
has_sum_le_inj i hi hs h hf.has_sum hg.has_sum
lemma sum_le_has_sum (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) :
∑ b in s, f b ≤ a :=
ge_of_tendsto hf (eventually_at_top.2 ⟨s, λ t hst,
sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩)
lemma is_lub_has_sum (h : ∀ b, 0 ≤ f b) (hf : has_sum f a) :
is_lub (set.range (λ s : finset β, ∑ b in s, f b)) a :=
is_lub_of_tendsto (finset.sum_mono_set_of_nonneg h) hf
lemma le_has_sum (hf : has_sum f a) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ a :=
calc f b = ∑ b in {b}, f b : finset.sum_singleton.symm
... ≤ a : sum_le_has_sum _ (by { convert hb, simp }) hf
lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) :
∑ b in s, f b ≤ ∑' b, f b :=
sum_le_has_sum s hs hf.has_sum
lemma le_tsum (hf : summable f) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ ∑' b, f b :=
le_has_sum (summable.has_sum hf) b hb
lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : ∑'b, f b ≤ ∑'b, g b :=
has_sum_le h hf.has_sum hg.has_sum
@[mono] lemma tsum_mono (hf : summable f) (hg : summable g) (h : f ≤ g) :
∑' n, f n ≤ ∑' n, g n :=
tsum_le_tsum h hf hg
lemma tsum_le_of_sum_le (hf : summable f) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) :
∑' b, f b ≤ a₂ :=
has_sum_le_of_sum_le hf.has_sum h
lemma tsum_le_of_sum_le' (ha₂ : 0 ≤ a₂) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) :
∑' b, f b ≤ a₂ :=
begin
by_cases hf : summable f,
{ exact tsum_le_of_sum_le hf h },
{ rw tsum_eq_zero_of_not_summable hf,
exact ha₂ }
end
lemma has_sum.nonneg (h : ∀ b, 0 ≤ g b) (ha : has_sum g a) : 0 ≤ a :=
has_sum_le h has_sum_zero ha
lemma has_sum.nonpos (h : ∀ b, g b ≤ 0) (ha : has_sum g a) : a ≤ 0 :=
has_sum_le h ha has_sum_zero
lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ ∑'b, g b :=
begin
by_cases hg : summable g,
{ exact hg.has_sum.nonneg h },
{ simp [tsum_eq_zero_of_not_summable hg] }
end
lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : ∑'b, f b ≤ 0 :=
begin
by_cases hf : summable f,
{ exact hf.has_sum.nonpos h },
{ simp [tsum_eq_zero_of_not_summable hf] }
end
end order_topology
section ordered_topological_group
variables [ordered_add_comm_group α] [topological_space α] [topological_add_group α]
[order_closed_topology α] {f g : β → α} {a₁ a₂ : α}
lemma has_sum_lt {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i)
(hf : has_sum f a₁) (hg : has_sum g a₂) :
a₁ < a₂ :=
have update f i 0 ≤ update g i 0 := update_le_update_iff.mpr ⟨rfl.le, λ i _, h i⟩,
have 0 - f i + a₁ ≤ 0 - g i + a₂ := has_sum_le this (hf.update i 0) (hg.update i 0),
by simpa only [zero_sub, add_neg_cancel_left] using add_lt_add_of_lt_of_le hi this
@[mono] lemma has_sum_strict_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f < g) : a₁ < a₂ :=
let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg
lemma tsum_lt_tsum {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i)
(hf : summable f) (hg : summable g) :
∑' n, f n < ∑' n, g n :=
has_sum_lt h hi hf.has_sum hg.has_sum
@[mono] lemma tsum_strict_mono (hf : summable f) (hg : summable g) (h : f < g) :
∑' n, f n < ∑' n, g n :=
let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hf hg
lemma tsum_pos (hsum : summable g) (hg : ∀ b, 0 ≤ g b) (i : β) (hi : 0 < g i) :
0 < ∑' b, g b :=
by { rw ← tsum_zero, exact tsum_lt_tsum hg hi summable_zero hsum }
end ordered_topological_group
section canonically_ordered
variables [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α]
variables {f : β → α} {a : α}
lemma le_has_sum' (hf : has_sum f a) (b : β) : f b ≤ a :=
le_has_sum hf b $ λ _ _, zero_le _
lemma le_tsum' (hf : summable f) (b : β) : f b ≤ ∑' b, f b :=
le_tsum hf b $ λ _ _, zero_le _
lemma has_sum_zero_iff : has_sum f 0 ↔ ∀ x, f x = 0 :=
begin
refine ⟨_, λ h, _⟩,
{ contrapose!,
exact λ ⟨x, hx⟩ h, irrefl _ (lt_of_lt_of_le (pos_iff_ne_zero.2 hx) (le_has_sum' h x)) },
{ convert has_sum_zero,
exact funext h }
end
lemma tsum_eq_zero_iff (hf : summable f) : ∑' i, f i = 0 ↔ ∀ x, f x = 0 :=
by rw [←has_sum_zero_iff, hf.has_sum_iff]
lemma tsum_ne_zero_iff (hf : summable f) : ∑' i, f i ≠ 0 ↔ ∃ x, f x ≠ 0 :=
by rw [ne.def, tsum_eq_zero_iff hf, not_forall]
lemma is_lub_has_sum' (hf : has_sum f a) : is_lub (set.range (λ s : finset β, ∑ b in s, f b)) a :=
is_lub_of_tendsto (finset.sum_mono_set f) hf
end canonically_ordered
section uniform_group
variables [add_comm_group α] [uniform_space α]
lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} :
summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) :=
cauchy_map_iff_exists_tendsto.symm
variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α}
lemma cauchy_seq_finset_iff_vanishing :
cauchy_seq (λ (s : finset β), ∑ b in s, f b)
↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) :=
begin
simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot,
prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)],
rw [tendsto_at_top'],
split,
{ assume h e he,
rcases h e he with ⟨⟨s₁, s₂⟩, h⟩,
use [s₁ ∪ s₂],
assume t ht,
specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_of_le_left le_sup_right⟩,
simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h },
{ assume h e he,
rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩,
rcases h d hd with ⟨s, h⟩,
use [(s, s)],
rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩,
have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b,
{ simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm,
add_sub_add_right_eq_sub] },
simp only [this],
exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) }
end
local attribute [instance] topological_add_group.regular_space
/-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole
space. This does not need a summability assumption, as otherwise all sums are zero. -/
lemma tendsto_tsum_compl_at_top_zero [t1_space α] (f : β → α) :
tendsto (λ (s : finset β), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) :=
begin
by_cases H : summable f,
{ assume e he,
rcases nhds_is_closed he with ⟨o, ho, oe, o_closed⟩,
simp only [le_eq_subset, set.mem_preimage, mem_at_top_sets, filter.mem_map, ge_iff_le],
obtain ⟨s, hs⟩ : ∃ (s : finset β), ∀ (t : finset β), disjoint t s → ∑ (b : β) in t, f b ∈ o :=
cauchy_seq_finset_iff_vanishing.1 (tendsto.cauchy_seq H.has_sum) o ho,
refine ⟨s, λ a sa, oe _⟩,
have A : summable (λ b : {x // x ∉ a}, f b) := a.summable_compl_iff.2 H,
apply is_closed.mem_of_tendsto o_closed A.has_sum (eventually_of_forall (λ b, _)),
have : disjoint (finset.image (λ (i : {x // x ∉ a}), (i : β)) b) s,
{ apply disjoint_left.2 (λ i hi his, _),
rcases mem_image.1 hi with ⟨i', hi', rfl⟩,
exact i'.2 (sa his), },
convert hs _ this using 1,
rw sum_image,
assume i hi j hj hij,
exact subtype.ext hij },
{ convert tendsto_const_nhds,
ext s,
apply tsum_eq_zero_of_not_summable,
rwa finset.summable_compl_iff }
end
variable [complete_space α]
lemma summable_iff_vanishing :
summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) :=
by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing]
/- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/
lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) :
summable g :=
summable_iff_vanishing.2 $
assume e he,
let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in
⟨s, assume t ht,
have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b :=
calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b :
finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm)
... = ∑ b in t, g b :
begin
refine finset.sum_subset (finset.filter_subset _ _) _,
assume b hbt hb,
simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb,
exact (h b).resolve_right hb
end,
eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩
protected lemma summable.indicator (hf : summable f) (s : set β) :
summable (s.indicator f) :=
hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _
lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) :
summable (f ∘ i) :=
begin
simpa only [set.indicator_range_comp]
using (hi.summable_iff _).2 (hf.indicator (set.range i)),
exact λ x hx, set.indicator_of_not_mem hx _
end
lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) :=
hf.comp_injective subtype.coe_injective
lemma summable_subtype_and_compl {s : set β} :
summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f :=
⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩
lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) :=
ha.comp_injective sigma_mk_injective
lemma summable.sigma [t1_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) :=
ha.sigma' (λ b, ha.sigma_factor b)
lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) :
summable (λ c, f (b, c)) :=
h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2
lemma tsum_sigma [t1_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ :=
tsum_sigma' (λ b, ha.sigma_factor b) ha
lemma tsum_prod [t1_space α] {f : β × γ → α} (h : summable f) :
∑'p, f p = ∑'b c, f ⟨b, c⟩ :=
tsum_prod' h h.prod_factor
lemma tsum_comm [t1_space α] {f : β → γ → α} (h : summable (function.uncurry f)) :
∑' c b, f b c = ∑' b c, f b c :=
tsum_comm' h h.prod_factor h.prod_symm.prod_factor
end uniform_group
section topological_group
variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G]
{f : α → G}
lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) :
∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e :=
begin
letI : uniform_space G := topological_add_group.to_uniform_space G,
letI : uniform_add_group G := topological_add_group_is_uniform,
rcases hf with ⟨y, hy⟩,
exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he
end
/-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along
`cofinite`. -/
lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) :=
begin
intros e he,
rw [filter.mem_map],
rcases hf.vanishing he with ⟨s, hs⟩,
refine s.eventually_cofinite_nmem.mono (λ x hx, _),
by simpa using hs {x} (disjoint_singleton_left.2 hx)
end
lemma summable.tendsto_at_top_zero {f : ℕ → G} (hf : summable f) : tendsto f at_top (𝓝 0) :=
by { rw ←nat.cofinite_eq_at_top, exact hf.tendsto_cofinite_zero }
lemma summable.tendsto_top_of_pos {α : Type*}
[linear_ordered_field α] [topological_space α] [order_topology α] {f : ℕ → α}
(hf : summable f⁻¹) (hf' : ∀ n, 0 < f n) : tendsto f at_top at_top :=
begin
rw [show f = f⁻¹⁻¹, by { ext, simp }],
apply filter.tendsto.inv_tendsto_zero,
apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _
(summable.tendsto_at_top_zero hf),
rw eventually_iff_exists_mem,
refine ⟨set.Ioi 0, Ioi_mem_at_top _, λ _ _, _⟩,
rw [set.mem_Ioi, inv_eq_one_div, one_div, pi.inv_apply, _root_.inv_pos],
exact hf' _,
end
end topological_group
section linear_order
/-! For infinite sums taking values in a linearly ordered monoid, the existence of a least upper
bound for the finite sums is a criterion for summability.
This criterion is useful when applied in a linearly ordered monoid which is also a complete or
conditionally complete linear order, such as `ℝ`, `ℝ≥0`, `ℝ≥0∞`, because it is then easy to check
the existence of a least upper bound.
-/
lemma has_sum_of_is_lub_of_nonneg [linear_ordered_add_comm_monoid β] [topological_space β]
[order_topology β] {f : α → β} (b : β) (h : ∀ b, 0 ≤ f b)
(hf : is_lub (set.range (λ s, ∑ a in s, f a)) b) :
has_sum f b :=
tendsto_at_top_is_lub (finset.sum_mono_set_of_nonneg h) hf
lemma has_sum_of_is_lub [canonically_linear_ordered_add_monoid β] [topological_space β]
[order_topology β] {f : α → β} (b : β) (hf : is_lub (set.range (λ s, ∑ a in s, f a)) b) :
has_sum f b :=
tendsto_at_top_is_lub (finset.sum_mono_set f) hf
lemma summable_abs_iff [linear_ordered_add_comm_group β] [uniform_space β]
[uniform_add_group β] [complete_space β] {f : α → β} :
summable (λ x, |f x|) ↔ summable f :=
have h1 : ∀ x : {x | 0 ≤ f x}, |f x| = f x := λ x, abs_of_nonneg x.2,
have h2 : ∀ x : {x | 0 ≤ f x}ᶜ, |f x| = -f x := λ x, abs_of_neg (not_le.1 x.2),
calc summable (λ x, |f x|) ↔
summable (λ x : {x | 0 ≤ f x}, |f x|) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, |f x|) :
summable_subtype_and_compl.symm
... ↔ summable (λ x : {x | 0 ≤ f x}, f x) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, -f x) :
by simp only [h1, h2]
... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl]
alias summable_abs_iff ↔ summable.of_abs summable.abs
end linear_order
section cauchy_seq
open filter
/-- If the extended distance between consecutive points of a sequence is estimated
by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/
lemma cauchy_seq_of_edist_le_of_summable [pseudo_emetric_space α] {f : ℕ → α} (d : ℕ → ℝ≥0)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f :=
begin
refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _),
-- Actually we need partial sums of `d` to be a Cauchy sequence
replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) :=
let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq,
-- Now we take the same `N` as in one of the definitions of a Cauchy sequence
refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _),
have hsum := hN n hn,
-- We simplify the known inequality
rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, add_tsub_cancel_left] at hsum,
norm_cast at hsum,
replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum,
rw edist_comm,
-- Then use `hf` to simplify the goal to the same form
apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)),
assumption_mod_cast
end
/-- If the distance between consecutive points of a sequence is estimated by a summable series,
then the original sequence is a Cauchy sequence. -/
lemma cauchy_seq_of_dist_le_of_summable [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ)
(hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f :=
begin
refine metric.cauchy_seq_iff'.2 (λε εpos, _),
replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) :=
let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq,
refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _),
have hsum := hN n hn,
rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum,
calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _
... ≤ ∑ x in Ico N n, d x : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k)
... ≤ |∑ x in Ico N n, d x| : le_abs_self _
... < ε : hsum
end
lemma cauchy_seq_of_summable_dist [pseudo_metric_space α] {f : ℕ → α}
(h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ (λ _, le_refl _) h
lemma dist_le_tsum_of_dist_le_of_tendsto [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ)
(hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a))
(n : ℕ) :
dist (f n) a ≤ ∑' m, d (n + m) :=
begin
refine le_of_tendsto (tendsto_const_nhds.dist ha)
(eventually_at_top.2 ⟨n, λ m hnm, _⟩),
refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _,
rw [sum_Ico_eq_sum_range],
refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _,
exact hd.comp_injective (add_right_injective n)
end
lemma dist_le_tsum_of_dist_le_of_tendsto₀ [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ)
(hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ tsum d :=
by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0
lemma dist_le_tsum_dist_of_tendsto [pseudo_metric_space α] {f : ℕ → α}
(h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) :
dist (f n) a ≤ ∑' m, dist (f (n+m)) (f (n+m).succ) :=
show dist (f n) a ≤ ∑' m, (λx, dist (f x) (f x.succ)) (n + m), from
dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_refl _) h ha n
lemma dist_le_tsum_dist_of_tendsto₀ [pseudo_metric_space α] {f : ℕ → α}
(h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) :=
by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0
end cauchy_seq
/-! ## Multipliying two infinite sums
In this section, we prove various results about `(∑' x : β, f x) * (∑' y : γ, g y)`. Note that we
always assume that the family `λ x : β × γ, f x.1 * g x.2` is summable, since there is no way to
deduce this from the summmabilities of `f` and `g` in general, but if you are working in a normed
space, you may want to use the analogous lemmas in `analysis/normed_space/basic`
(e.g `tsum_mul_tsum_of_summable_norm`).
We first establish results about arbitrary index types, `β` and `γ`, and then we specialize to
`β = γ = ℕ` to prove the Cauchy product formula (see `tsum_mul_tsum_eq_tsum_sum_antidiagonal`).
### Arbitrary index types
-/
section tsum_mul_tsum
variables [topological_space α] [regular_space α] [semiring α] [topological_ring α]
{f : β → α} {g : γ → α} {s t u : α}
lemma has_sum.mul_eq (hf : has_sum f s) (hg : has_sum g t)
(hfg : has_sum (λ (x : β × γ), f x.1 * g x.2) u) :
s * t = u :=
have key₁ : has_sum (λ b, f b * t) (s * t),
from hf.mul_right t,
have this : ∀ b : β, has_sum (λ c : γ, f b * g c) (f b * t),
from λ b, hg.mul_left (f b),
have key₂ : has_sum (λ b, f b * t) u,
from has_sum.prod_fiberwise hfg this,
key₁.unique key₂
lemma has_sum.mul (hf : has_sum f s) (hg : has_sum g t)
(hfg : summable (λ (x : β × γ), f x.1 * g x.2)) :
has_sum (λ (x : β × γ), f x.1 * g x.2) (s * t) :=
let ⟨u, hu⟩ := hfg in
(hf.mul_eq hg hu).symm ▸ hu
/-- Product of two infinites sums indexed by arbitrary types.
See also `tsum_mul_tsum_of_summable_norm` if `f` and `g` are abolutely summable. -/
lemma tsum_mul_tsum (hf : summable f) (hg : summable g)
(hfg : summable (λ (x : β × γ), f x.1 * g x.2)) :
(∑' x, f x) * (∑' y, g y) = (∑' z : β × γ, f z.1 * g z.2) :=
hf.has_sum.mul_eq hg.has_sum hfg.has_sum
end tsum_mul_tsum
section cauchy_product
/-! ### `ℕ`-indexed families (Cauchy product)
We prove two versions of the Cauchy product formula. The first one is
`tsum_mul_tsum_eq_tsum_sum_range`, where the `n`-th term is a sum over `finset.range (n+1)`
involving `nat` substraction.
In order to avoid `nat` substraction, we also provide `tsum_mul_tsum_eq_tsum_sum_antidiagonal`,
where the `n`-th term is a sum over all pairs `(k, l)` such that `k+l=n`, which corresponds to the
`finset` `finset.nat.antidiagonal n` -/
variables {f : ℕ → α} {g : ℕ → α}
open finset
variables [topological_space α] [semiring α]
/- The family `(k, l) : ℕ × ℕ ↦ f k * g l` is summable if and only if the family
`(n, k, l) : Σ (n : ℕ), nat.antidiagonal n ↦ f k * g l` is summable. -/
lemma summable_mul_prod_iff_summable_mul_sigma_antidiagonal {f g : ℕ → α} :
summable (λ x : ℕ × ℕ, f x.1 * g x.2) ↔
summable (λ x : (Σ (n : ℕ), nat.antidiagonal n), f (x.2 : ℕ × ℕ).1 * g (x.2 : ℕ × ℕ).2) :=
nat.sigma_antidiagonal_equiv_prod.summable_iff.symm
variables [regular_space α] [topological_ring α]
lemma summable_sum_mul_antidiagonal_of_summable_mul {f g : ℕ → α}
(h : summable (λ x : ℕ × ℕ, f x.1 * g x.2)) :
summable (λ n, ∑ kl in nat.antidiagonal n, f kl.1 * g kl.2) :=
begin
rw summable_mul_prod_iff_summable_mul_sigma_antidiagonal at h,
conv {congr, funext, rw [← finset.sum_finset_coe, ← tsum_fintype]},
exact h.sigma' (λ n, (has_sum_fintype _).summable),
end
/-- The Cauchy product formula for the product of two infinites sums indexed by `ℕ`,
expressed by summing on `finset.nat.antidiagonal`.
See also `tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm`
if `f` and `g` are absolutely summable. -/
lemma tsum_mul_tsum_eq_tsum_sum_antidiagonal (hf : summable f) (hg : summable g)
(hfg : summable (λ (x : ℕ × ℕ), f x.1 * g x.2)) :
(∑' n, f n) * (∑' n, g n) = (∑' n, ∑ kl in nat.antidiagonal n, f kl.1 * g kl.2) :=
begin
conv_rhs {congr, funext, rw [← finset.sum_finset_coe, ← tsum_fintype]},
rw [tsum_mul_tsum hf hg hfg, ← nat.sigma_antidiagonal_equiv_prod.tsum_eq (_ : ℕ × ℕ → α)],
exact tsum_sigma' (λ n, (has_sum_fintype _).summable)
(summable_mul_prod_iff_summable_mul_sigma_antidiagonal.mp hfg)
end
lemma summable_sum_mul_range_of_summable_mul {f g : ℕ → α}
(h : summable (λ x : ℕ × ℕ, f x.1 * g x.2)) :
summable (λ n, ∑ k in range (n+1), f k * g (n - k)) :=
begin
simp_rw ← nat.sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l),
exact summable_sum_mul_antidiagonal_of_summable_mul h
end
/-- The Cauchy product formula for the product of two infinites sums indexed by `ℕ`,
expressed by summing on `finset.range`.
See also `tsum_mul_tsum_eq_tsum_sum_range_of_summable_norm`
if `f` and `g` are absolutely summable. -/
lemma tsum_mul_tsum_eq_tsum_sum_range (hf : summable f) (hg : summable g)
(hfg : summable (λ (x : ℕ × ℕ), f x.1 * g x.2)) :
(∑' n, f n) * (∑' n, g n) = (∑' n, ∑ k in range (n+1), f k * g (n - k)) :=
begin
simp_rw ← nat.sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l),
exact tsum_mul_tsum_eq_tsum_sum_antidiagonal hf hg hfg
end
end cauchy_product
|
f7415534ef7d7902e22da28840ec3fb1da68530e | c777c32c8e484e195053731103c5e52af26a25d1 | /src/topology/homeomorph.lean | 1b72dea1ee01ba505496f2fd552503b0bc3347b7 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 23,887 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton
-/
import logic.equiv.fin
import topology.dense_embedding
import topology.support
/-!
# Homeomorphisms
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines homeomorphisms between two topological spaces. They are bijections with both
directions continuous. We denote homeomorphisms with the notation `≃ₜ`.
# Main definitions
* `homeomorph α β`: The type of homeomorphisms from `α` to `β`.
This type can be denoted using the following notation: `α ≃ₜ β`.
# Main results
* Pretty much every topological property is preserved under homeomorphisms.
* `homeomorph.homeomorph_of_continuous_open`: A continuous bijection that is
an open map is a homeomorphism.
-/
open set filter
open_locale topology
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- Homeomorphism between `α` and `β`, also called topological isomorphism -/
@[nolint has_nonempty_instance] -- not all spaces are homeomorphic to each other
structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends α ≃ β :=
(continuous_to_fun : continuous to_fun . tactic.interactive.continuity')
(continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity')
infix ` ≃ₜ `:25 := homeomorph
namespace homeomorph
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
instance : has_coe_to_fun (α ≃ₜ β) (λ _, α → β) := ⟨λe, e.to_equiv⟩
@[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) :
((homeomorph.mk a b c) : α → β) = a :=
rfl
/-- Inverse of a homeomorphism. -/
protected def symm (h : α ≃ₜ β) : β ≃ₜ α :=
{ continuous_to_fun := h.continuous_inv_fun,
continuous_inv_fun := h.continuous_to_fun,
to_equiv := h.to_equiv.symm }
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : α ≃ₜ β) : α → β := h
/-- See Note [custom simps projection] -/
def simps.symm_apply (h : α ≃ₜ β) : β → α := h.symm
initialize_simps_projections homeomorph
(to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv)
@[simp] lemma coe_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv = h := rfl
@[simp] lemma coe_symm_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv.symm = h.symm := rfl
lemma to_equiv_injective : function.injective (to_equiv : α ≃ₜ β → α ≃ β)
| ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl
@[ext] lemma ext {h h' : α ≃ₜ β} (H : ∀ x, h x = h' x) : h = h' :=
to_equiv_injective $ equiv.ext H
@[simp] lemma symm_symm (h : α ≃ₜ β) : h.symm.symm = h := ext $ λ _, rfl
/-- Identity map as a homeomorphism. -/
@[simps apply {fully_applied := ff}]
protected def refl (α : Type*) [topological_space α] : α ≃ₜ α :=
{ continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id,
to_equiv := equiv.refl α }
/-- Composition of two homeomorphisms. -/
protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ :=
{ continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun,
continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun,
to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv }
@[simp] lemma trans_apply (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) (a : α) : h₁.trans h₂ a = h₂ (h₁ a) := rfl
@[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) :
((homeomorph.mk a b c).symm : β → α) = a.symm :=
rfl
@[simp] lemma refl_symm : (homeomorph.refl α).symm = homeomorph.refl α := rfl
@[continuity]
protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun
@[continuity] -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm`
protected lemma continuous_symm (h : α ≃ₜ β) : continuous (h.symm) := h.continuous_inv_fun
@[simp] lemma apply_symm_apply (h : α ≃ₜ β) (x : β) : h (h.symm x) = x :=
h.to_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (h : α ≃ₜ β) (x : α) : h.symm (h x) = x :=
h.to_equiv.symm_apply_apply x
@[simp] lemma self_trans_symm (h : α ≃ₜ β) : h.trans h.symm = homeomorph.refl α :=
by { ext, apply symm_apply_apply }
@[simp] lemma symm_trans_self (h : α ≃ₜ β) : h.symm.trans h = homeomorph.refl β :=
by { ext, apply apply_symm_apply }
protected lemma bijective (h : α ≃ₜ β) : function.bijective h := h.to_equiv.bijective
protected lemma injective (h : α ≃ₜ β) : function.injective h := h.to_equiv.injective
protected lemma surjective (h : α ≃ₜ β) : function.surjective h := h.to_equiv.surjective
/-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/
def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β :=
have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm
... = f.symm x : by rw hg x),
{ to_fun := f,
inv_fun := g,
left_inv := by convert f.left_inv,
right_inv := by convert f.right_inv,
continuous_to_fun := f.continuous,
continuous_inv_fun := by convert f.symm.continuous }
@[simp] lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id :=
funext h.symm_apply_apply
@[simp] lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id :=
funext h.apply_symm_apply
@[simp] lemma range_coe (h : α ≃ₜ β) : range h = univ :=
h.surjective.range_eq
lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h :=
funext h.symm.to_equiv.image_eq_preimage
lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h :=
(funext h.to_equiv.image_eq_preimage).symm
@[simp] lemma image_preimage (h : α ≃ₜ β) (s : set β) : h '' (h ⁻¹' s) = s :=
h.to_equiv.image_preimage s
@[simp] lemma preimage_image (h : α ≃ₜ β) (s : set α) : h ⁻¹' (h '' s) = s :=
h.to_equiv.preimage_image s
protected lemma inducing (h : α ≃ₜ β) : inducing h :=
inducing_of_inducing_compose h.continuous h.symm.continuous $
by simp only [symm_comp_self, inducing_id]
lemma induced_eq (h : α ≃ₜ β) : topological_space.induced h ‹_› = ‹_› := h.inducing.1.symm
protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h :=
quotient_map.of_quotient_map_compose h.symm.continuous h.continuous $
by simp only [self_comp_symm, quotient_map.id]
lemma coinduced_eq (h : α ≃ₜ β) : topological_space.coinduced h ‹_› = ‹_› :=
h.quotient_map.2.symm
protected lemma embedding (h : α ≃ₜ β) : embedding h :=
⟨h.inducing, h.injective⟩
/-- Homeomorphism given an embedding. -/
noncomputable def of_embedding (f : α → β) (hf : embedding f) : α ≃ₜ (set.range f) :=
{ continuous_to_fun := hf.continuous.subtype_mk _,
continuous_inv_fun := by simp [hf.continuous_iff, continuous_subtype_coe],
to_equiv := equiv.of_injective f hf.inj }
protected lemma second_countable_topology [topological_space.second_countable_topology β]
(h : α ≃ₜ β) :
topological_space.second_countable_topology α :=
h.inducing.second_countable_topology
lemma is_compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s :=
h.embedding.is_compact_iff_is_compact_image.symm
lemma is_compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s :=
by rw ← image_symm; exact h.symm.is_compact_image
@[simp] lemma comap_cocompact (h : α ≃ₜ β) : comap h (cocompact β) = cocompact α :=
(comap_cocompact_le h.continuous).antisymm $
(has_basis_cocompact.le_basis_iff (has_basis_cocompact.comap h)).2 $ λ K hK,
⟨h ⁻¹' K, h.is_compact_preimage.2 hK, subset.rfl⟩
@[simp] lemma map_cocompact (h : α ≃ₜ β) : map h (cocompact α) = cocompact β :=
by rw [← h.comap_cocompact, map_comap_of_surjective h.surjective]
protected lemma compact_space [compact_space α] (h : α ≃ₜ β) : compact_space β :=
{ is_compact_univ := by { rw [← image_univ_of_surjective h.surjective, h.is_compact_image],
apply compact_space.is_compact_univ } }
protected lemma t0_space [t0_space α] (h : α ≃ₜ β) : t0_space β :=
h.symm.embedding.t0_space
protected lemma t1_space [t1_space α] (h : α ≃ₜ β) : t1_space β :=
h.symm.embedding.t1_space
protected lemma t2_space [t2_space α] (h : α ≃ₜ β) : t2_space β :=
h.symm.embedding.t2_space
protected lemma t3_space [t3_space α] (h : α ≃ₜ β) : t3_space β :=
h.symm.embedding.t3_space
protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h :=
{ dense := h.surjective.dense_range,
.. h.embedding }
@[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s :=
h.quotient_map.is_open_preimage
@[simp] lemma is_open_image (h : α ≃ₜ β) {s : set α} : is_open (h '' s) ↔ is_open s :=
by rw [← preimage_symm, is_open_preimage]
protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := λ s, h.is_open_image.2
@[simp] lemma is_closed_preimage (h : α ≃ₜ β) {s : set β} : is_closed (h ⁻¹' s) ↔ is_closed s :=
by simp only [← is_open_compl_iff, ← preimage_compl, is_open_preimage]
@[simp] lemma is_closed_image (h : α ≃ₜ β) {s : set α} : is_closed (h '' s) ↔ is_closed s :=
by rw [← preimage_symm, is_closed_preimage]
protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := λ s, h.is_closed_image.2
protected lemma open_embedding (h : α ≃ₜ β) : open_embedding h :=
open_embedding_of_embedding_open h.embedding h.is_open_map
protected lemma closed_embedding (h : α ≃ₜ β) : closed_embedding h :=
closed_embedding_of_embedding_closed h.embedding h.is_closed_map
protected lemma normal_space [normal_space α] (h : α ≃ₜ β) : normal_space β :=
h.symm.closed_embedding.normal_space
lemma preimage_closure (h : α ≃ₜ β) (s : set β) : h ⁻¹' (closure s) = closure (h ⁻¹' s) :=
h.is_open_map.preimage_closure_eq_closure_preimage h.continuous _
lemma image_closure (h : α ≃ₜ β) (s : set α) : h '' (closure s) = closure (h '' s) :=
by rw [← preimage_symm, preimage_closure]
lemma preimage_interior (h : α ≃ₜ β) (s : set β) : h⁻¹' (interior s) = interior (h ⁻¹' s) :=
h.is_open_map.preimage_interior_eq_interior_preimage h.continuous _
lemma image_interior (h : α ≃ₜ β) (s : set α) : h '' (interior s) = interior (h '' s) :=
by rw [← preimage_symm, preimage_interior]
lemma preimage_frontier (h : α ≃ₜ β) (s : set β) : h ⁻¹' (frontier s) = frontier (h ⁻¹' s) :=
h.is_open_map.preimage_frontier_eq_frontier_preimage h.continuous _
lemma image_frontier (h : α ≃ₜ β) (s : set α) : h '' frontier s = frontier (h '' s) :=
by rw [←preimage_symm, preimage_frontier]
@[to_additive]
lemma _root_.has_compact_mul_support.comp_homeomorph {M} [has_one M] {f : β → M}
(hf : has_compact_mul_support f) (φ : α ≃ₜ β) : has_compact_mul_support (f ∘ φ) :=
hf.comp_closed_embedding φ.closed_embedding
@[simp] lemma map_nhds_eq (h : α ≃ₜ β) (x : α) : map h (𝓝 x) = 𝓝 (h x) :=
h.embedding.map_nhds_of_mem _ (by simp)
lemma symm_map_nhds_eq (h : α ≃ₜ β) (x : α) : map h.symm (𝓝 (h x)) = 𝓝 x :=
by rw [h.symm.map_nhds_eq, h.symm_apply_apply]
lemma nhds_eq_comap (h : α ≃ₜ β) (x : α) : 𝓝 x = comap h (𝓝 (h x)) :=
h.embedding.to_inducing.nhds_eq_comap x
@[simp] lemma comap_nhds_eq (h : α ≃ₜ β) (y : β) : comap h (𝓝 y) = 𝓝 (h.symm y) :=
by rw [h.nhds_eq_comap, h.apply_symm_apply]
/-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/
def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) :
α ≃ₜ β :=
{ continuous_to_fun := h₁,
continuous_inv_fun := begin
rw continuous_def,
intros s hs,
convert ← h₂ s hs using 1,
apply e.image_eq_preimage
end,
to_equiv := e }
@[simp] lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) :
continuous_on (h ∘ f) s ↔ continuous_on f s :=
h.inducing.continuous_on_iff.symm
@[simp] lemma comp_continuous_iff (h : α ≃ₜ β) {f : γ → α} :
continuous (h ∘ f) ↔ continuous f :=
h.inducing.continuous_iff.symm
@[simp] lemma comp_continuous_iff' (h : α ≃ₜ β) {f : β → γ} :
continuous (f ∘ h) ↔ continuous f :=
h.quotient_map.continuous_iff.symm
lemma comp_continuous_at_iff (h : α ≃ₜ β) (f : γ → α) (x : γ) :
continuous_at (h ∘ f) x ↔ continuous_at f x :=
h.inducing.continuous_at_iff.symm
lemma comp_continuous_at_iff' (h : α ≃ₜ β) (f : β → γ) (x : α) :
continuous_at (f ∘ h) x ↔ continuous_at f (h x) :=
h.inducing.continuous_at_iff' (by simp)
lemma comp_continuous_within_at_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) (x : γ) :
continuous_within_at f s x ↔ continuous_within_at (h ∘ f) s x :=
h.inducing.continuous_within_at_iff
@[simp] lemma comp_is_open_map_iff (h : α ≃ₜ β) {f : γ → α} :
is_open_map (h ∘ f) ↔ is_open_map f :=
begin
refine ⟨_, λ hf, h.is_open_map.comp hf⟩,
intros hf,
rw [← function.comp.left_id f, ← h.symm_comp_self, function.comp.assoc],
exact h.symm.is_open_map.comp hf,
end
@[simp] lemma comp_is_open_map_iff' (h : α ≃ₜ β) {f : β → γ} :
is_open_map (f ∘ h) ↔ is_open_map f :=
begin
refine ⟨_, λ hf, hf.comp h.is_open_map⟩,
intros hf,
rw [← function.comp.right_id f, ← h.self_comp_symm, ← function.comp.assoc],
exact hf.comp h.symm.is_open_map,
end
/-- If two sets are equal, then they are homeomorphic. -/
def set_congr {s t : set α} (h : s = t) : s ≃ₜ t :=
{ continuous_to_fun := continuous_inclusion h.subset,
continuous_inv_fun := continuous_inclusion h.symm.subset,
to_equiv := equiv.set_congr h }
/-- Sum of two homeomorphisms. -/
def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ :=
{ continuous_to_fun := h₁.continuous.sum_map h₂.continuous,
continuous_inv_fun := h₁.symm.continuous.sum_map h₂.symm.continuous,
to_equiv := h₁.to_equiv.sum_congr h₂.to_equiv }
/-- Product of two homeomorphisms. -/
def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ :=
{ continuous_to_fun := (h₁.continuous.comp continuous_fst).prod_mk
(h₂.continuous.comp continuous_snd),
continuous_inv_fun := (h₁.symm.continuous.comp continuous_fst).prod_mk
(h₂.symm.continuous.comp continuous_snd),
to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv }
@[simp] lemma prod_congr_symm (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
(h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl
@[simp] lemma coe_prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl
section
variables (α β γ)
/-- `α × β` is homeomorphic to `β × α`. -/
def prod_comm : α × β ≃ₜ β × α :=
{ continuous_to_fun := continuous_snd.prod_mk continuous_fst,
continuous_inv_fun := continuous_snd.prod_mk continuous_fst,
to_equiv := equiv.prod_comm α β }
@[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl
@[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl
/-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/
def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) :=
{ continuous_to_fun := (continuous_fst.comp continuous_fst).prod_mk
((continuous_snd.comp continuous_fst).prod_mk continuous_snd),
continuous_inv_fun := (continuous_fst.prod_mk (continuous_fst.comp continuous_snd)).prod_mk
(continuous_snd.comp continuous_snd),
to_equiv := equiv.prod_assoc α β γ }
/-- `α × {*}` is homeomorphic to `α`. -/
@[simps apply {fully_applied := ff}]
def prod_punit : α × punit ≃ₜ α :=
{ to_equiv := equiv.prod_punit α,
continuous_to_fun := continuous_fst,
continuous_inv_fun := continuous_id.prod_mk continuous_const }
/-- `{*} × α` is homeomorphic to `α`. -/
def punit_prod : punit × α ≃ₜ α :=
(prod_comm _ _).trans (prod_punit _)
@[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl
/-- If both `α` and `β` have a unique element, then `α ≃ₜ β`. -/
@[simps] def _root_.homeomorph.homeomorph_of_unique [unique α] [unique β] : α ≃ₜ β :=
{ continuous_to_fun := @continuous_const α β _ _ default,
continuous_inv_fun := @continuous_const β α _ _ default,
.. equiv.equiv_of_unique α β }
end
/-- If each `β₁ i` is homeomorphic to `β₂ i`, then `Π i, β₁ i` is homeomorphic to `Π i, β₂ i`. -/
@[simps apply to_equiv] def Pi_congr_right {ι : Type*} {β₁ β₂ : ι → Type*}
[Π i, topological_space (β₁ i)] [Π i, topological_space (β₂ i)] (F : Π i, β₁ i ≃ₜ β₂ i) :
(Π i, β₁ i) ≃ₜ (Π i, β₂ i) :=
{ continuous_to_fun := continuous_pi (λ i, (F i).continuous.comp $ continuous_apply i),
continuous_inv_fun := continuous_pi (λ i, (F i).symm.continuous.comp $ continuous_apply i),
to_equiv := equiv.Pi_congr_right (λ i, (F i).to_equiv) }
@[simp] lemma Pi_congr_right_symm {ι : Type*} {β₁ β₂ : ι → Type*} [Π i, topological_space (β₁ i)]
[Π i, topological_space (β₂ i)] (F : Π i, β₁ i ≃ₜ β₂ i) :
(Pi_congr_right F).symm = Pi_congr_right (λ i, (F i).symm) := rfl
/-- `ulift α` is homeomorphic to `α`. -/
def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α :=
{ continuous_to_fun := continuous_ulift_down,
continuous_inv_fun := continuous_ulift_up,
to_equiv := equiv.ulift }
section distrib
/-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/
def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ :=
homeomorph.symm $ homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm
((continuous_inl.prod_map continuous_id).sum_elim (continuous_inr.prod_map continuous_id)) $
(is_open_map_inl.prod is_open_map.id).sum_elim (is_open_map_inr.prod is_open_map.id)
/-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/
def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ :=
(prod_comm _ _).trans $
sum_prod_distrib.trans $
sum_congr (prod_comm _ _) (prod_comm _ _)
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
/-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/
def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) :=
homeomorph.symm $ homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm
(continuous_sigma $ λ i, continuous_sigma_mk.fst'.prod_mk continuous_snd)
(is_open_map_sigma.2 $ λ i, is_open_map_sigma_mk.prod is_open_map.id)
end distrib
/-- If `ι` has a unique element, then `ι → α` is homeomorphic to `α`. -/
@[simps { fully_applied := ff }]
def fun_unique (ι α : Type*) [unique ι] [topological_space α] : (ι → α) ≃ₜ α :=
{ to_equiv := equiv.fun_unique ι α,
continuous_to_fun := continuous_apply _,
continuous_inv_fun := continuous_pi (λ _, continuous_id) }
/-- Homeomorphism between dependent functions `Π i : fin 2, α i` and `α 0 × α 1`. -/
@[simps { fully_applied := ff }]
def {u} pi_fin_two (α : fin 2 → Type u) [Π i, topological_space (α i)] : (Π i, α i) ≃ₜ α 0 × α 1 :=
{ to_equiv := pi_fin_two_equiv α,
continuous_to_fun := (continuous_apply 0).prod_mk (continuous_apply 1),
continuous_inv_fun := continuous_pi $ fin.forall_fin_two.2 ⟨continuous_fst, continuous_snd⟩ }
/-- Homeomorphism between `α² = fin 2 → α` and `α × α`. -/
@[simps { fully_applied := ff }] def fin_two_arrow : (fin 2 → α) ≃ₜ α × α :=
{ to_equiv := fin_two_arrow_equiv α, .. pi_fin_two (λ _, α) }
/--
A subset of a topological space is homeomorphic to its image under a homeomorphism.
-/
@[simps] def image (e : α ≃ₜ β) (s : set α) : s ≃ₜ e '' s :=
{ continuous_to_fun := by continuity!,
continuous_inv_fun := by continuity!,
to_equiv := e.to_equiv.image s, }
/-- `set.univ α` is homeomorphic to `α`. -/
@[simps { fully_applied := ff }]
def set.univ (α : Type*) [topological_space α] : (univ : set α) ≃ₜ α :=
{ to_equiv := equiv.set.univ α,
continuous_to_fun := continuous_subtype_coe,
continuous_inv_fun := continuous_id.subtype_mk _ }
/-- `s ×ˢ t` is homeomorphic to `s × t`. -/
@[simps] def set.prod (s : set α) (t : set β) : ↥(s ×ˢ t) ≃ₜ s × t :=
{ to_equiv := equiv.set.prod s t,
continuous_to_fun := (continuous_subtype_coe.fst.subtype_mk _).prod_mk
(continuous_subtype_coe.snd.subtype_mk _),
continuous_inv_fun := (continuous_subtype_coe.fst'.prod_mk
continuous_subtype_coe.snd').subtype_mk _ }
section
variable {ι : Type*}
/-- The topological space `Π i, β i` can be split as a product by separating the indices in ι
depending on whether they satisfy a predicate p or not.-/
@[simps] def pi_equiv_pi_subtype_prod (p : ι → Prop) (β : ι → Type*) [Π i, topological_space (β i)]
[decidable_pred p] : (Π i, β i) ≃ₜ (Π i : {x // p x}, β i) × Π i : {x // ¬p x}, β i :=
{ to_equiv := equiv.pi_equiv_pi_subtype_prod p β,
continuous_to_fun := by apply continuous.prod_mk; exact continuous_pi (λ j, continuous_apply j),
continuous_inv_fun := continuous_pi $ λ j, begin
dsimp only [equiv.pi_equiv_pi_subtype_prod], split_ifs,
exacts [(continuous_apply _).comp continuous_fst, (continuous_apply _).comp continuous_snd],
end }
variables [decidable_eq ι] (i : ι)
/-- A product of topological spaces can be split as the binary product of one of the spaces and
the product of all the remaining spaces. -/
@[simps] def pi_split_at (β : ι → Type*) [Π j, topological_space (β j)] :
(Π j, β j) ≃ₜ β i × Π j : {j // j ≠ i}, β j :=
{ to_equiv := equiv.pi_split_at i β,
continuous_to_fun := (continuous_apply i).prod_mk (continuous_pi $ λ j, continuous_apply j),
continuous_inv_fun := continuous_pi $ λ j, by { dsimp only [equiv.pi_split_at],
split_ifs, subst h, exacts [continuous_fst, (continuous_apply _).comp continuous_snd] } }
/-- A product of copies of a topological space can be split as the binary product of one copy and
the product of all the remaining copies. -/
@[simps] def fun_split_at : (ι → β) ≃ₜ β × ({j // j ≠ i} → β) := pi_split_at i _
end
end homeomorph
/-- An inducing equiv between topological spaces is a homeomorphism. -/
@[simps] def equiv.to_homeomorph_of_inducing [topological_space α] [topological_space β] (f : α ≃ β)
(hf : inducing f) :
α ≃ₜ β :=
{ continuous_to_fun := hf.continuous,
continuous_inv_fun := hf.continuous_iff.2 $ by simpa using continuous_id,
.. f }
namespace continuous
variables [topological_space α] [topological_space β]
lemma continuous_symm_of_equiv_compact_to_t2 [compact_space α] [t2_space β]
{f : α ≃ β} (hf : continuous f) : continuous f.symm :=
begin
rw continuous_iff_is_closed,
intros C hC,
have hC' : is_closed (f '' C) := (hC.is_compact.image hf).is_closed,
rwa equiv.image_eq_preimage at hC',
end
/-- Continuous equivalences from a compact space to a T2 space are homeomorphisms.
This is not true when T2 is weakened to T1
(see `continuous.homeo_of_equiv_compact_to_t2.t1_counterexample`). -/
@[simps]
def homeo_of_equiv_compact_to_t2 [compact_space α] [t2_space β]
{f : α ≃ β} (hf : continuous f) : α ≃ₜ β :=
{ continuous_to_fun := hf,
continuous_inv_fun := hf.continuous_symm_of_equiv_compact_to_t2,
..f }
end continuous
|
6ef7ef2b49a829c1208dea948be39ac646534ac6 | 9a2260f3b7b64ae9c50bf326fdb0387f5ac64683 | /src/NITRO/Default.lean | a49e07f73760f4ccc3d1ffc8364d1cff21d8e6f8 | [
"LicenseRef-scancode-mit-taylor-variant",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | o89/nitro | e8e1c7f3e7baeb7a659f899c605d37b1d3e553a6 | c62a67398a89d6e6a2e9da62350adaf5f17cfda9 | refs/heads/master | 1,670,068,174,264 | 1,669,086,407,000 | 1,669,086,407,000 | 204,147,098 | 3 | 5 | null | null | null | null | UTF-8 | Lean | false | false | 83 | lean | import NITRO.Tags
import NITRO.Elements
import NITRO.JavaScript
import NITRO.Proto
|
7653a53ae7bd502e083ef003518a41d95de27c46 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /hott/init/types/empty.hlean | f9f221b519d1f713ee17c533b997888a0fc8de27 | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 523 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: init.types.empty
Author: Jeremy Avigad, Floris van Doorn, Jakob von Raumer
-/
prelude
import ..datatypes ..logic
-- Empty type
-- ----------
namespace empty
protected theorem elim (A : Type) (H : empty) : A :=
empty.rec (λe, A) H
end empty
protected definition empty.has_decidable_eq [instance] : decidable_eq empty :=
take (a b : empty), decidable.inl (!empty.elim a)
|
a1ab5e789c5e7d406b828dea64a87940ef5eab29 | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/sets_functions_and_relations/unnamed_80.lean | e2b2939d5490f9a1dc6b2fac78813f0a2a03a167 | [] | no_license | jamescheuk91/mathematics_in_lean | 09f1f87d2b0dce53464ff0cbe592c568ff59cf5e | 4452499264e2975bca2f42565c0925506ba5dda3 | refs/heads/master | 1,679,716,410,967 | 1,613,957,947,000 | 1,613,957,947,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 410 | lean | import tactic
variable {α : Type*}
variables (s t u : set α)
open set
example (h : s ⊆ t) : s ∩ u ⊆ t ∩ u :=
begin
rw [subset_def, inter_def, inter_def],
rw subset_def at h,
dsimp,
rintros x ⟨xs, xu⟩,
exact ⟨h _ xs, xu⟩,
end
example (h : s ⊆ t) : s ∩ u ⊆ t ∩ u :=
begin
simp only [subset_def, mem_inter_eq] at *,
rintros x ⟨xs, xu⟩,
exact ⟨h _ xs, xu⟩,
end |
c413c99c985a537cb32c203ccff6b9e2d53fa4b7 | 874a8d2247ab9a4516052498f80da2e32d0e3a48 | /pigeonhole.lean | 7c7da7be7a79d74b6e0676d4fe411bf027594c08 | [] | no_license | AlexKontorovich/Spring2020Math492 | 378b36c643ee029f5ab91c1677889baa591f5e85 | 659108c5d864ff5c75b9b3b13b847aa5cff4348a | refs/heads/master | 1,610,780,595,457 | 1,588,174,859,000 | 1,588,174,859,000 | 243,017,788 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 4,268 | lean | import tactic
def injective {X Y} (f : X → Y) := ∀ x₁ x₂, f x₁ = f x₂ → x₁ = x₂
def range {X Y} (f : X → Y) := { y | ∃ x, f x = y }
theorem comp_inj_is_inj
{X Y Z} (f : X → Y) (g : Y → Z)
(p1 : injective f)
(p2 : injective g)
: injective (g ∘ f)
:= begin
introv x p3,
change g (f x) = g (f x₂) at p3,
apply p1,
apply p2,
apply p3,
end
lemma succ_greater_than_nat (n : ℕ) : nat.succ n > n
:=
begin
rw nat.succ_eq_add_one,
linarith
end
lemma pred_exists (n : ℕ) (p: n > 0) : exists k, nat.succ k = n
:=
begin
induction n with d hd,
{linarith,},
{
existsi d,
refl
}
end
-- forgot library function, lifted from square root prime code
-- credit to github user dm1237
lemma succ_eq_add_one (n : ℕ) : nat.succ n = n + 1 :=
begin
exact rfl,
end
-- forgot library function
lemma my_le_trans
(j k m : ℕ)
(p1: k < m)
(p2: j < k)
: j < m - 1
:=
begin
sorry
end
-- I'm not gonna waste time proving this
lemma inequality_fact
(j m : ℕ)
(p: j < m)
: j - 1 < m - 1
:= begin
sorry
end
/--
Type of pairs (k,p) where k
is a natural number and p is a witness to the proof that k < n.
-/
def finite_subset (n : ℕ) := Σ' k, k < n
/--
Every pair that lives in finite_subest m lives in finite_subset n
where m < n
-/
def lift_finite (m n : ℕ) (p : m < n) : finite_subset m → finite_subset n
:= λ k, ⟨k.1, lt.trans k.2 p⟩
/--
Application of lift_finite from m to m + 1
-/
def lift_one
(m : ℕ)
: finite_subset m → finite_subset (m + 1)
:= (lift_finite m (m+1) (succ_greater_than_nat m))
/--
The lifting function is injective
-/
theorem lift_finite_injective (m n : ℕ) (p : m < n) : injective (lift_finite m n p)
:= begin
/- pf sketch
-- suppose f x1 = f x2 = < k, pf: k < n >
-- we know x1 = < l , pf: k < m > and x2 = < j , pf: j < m >
-- note that (f x1).1 = (f x2).1 = k
-- furthermore, k < m < n
-- then x1 = < k, pf: k < m > = x2
-- done
-/
introv x p2,
cases x,
cases x₂,
cases p2,
refl,
end
/--
The lifting from m to m + 1 injective
-/
lemma lift_one_injective (m : ℕ)
: injective (lift_one m)
:= begin
apply lift_finite_injective m (m + 1) (succ_greater_than_nat m),
end
-- warning, sort of janky
-- ie, don't use if we don't miss k in the codomain
-- it's not injective by itself
-- but relabel k ∘ f ∘ lift IS injective
-- because f ∘ lift misses k
def relabel
(m k : ℕ)
(p: k < m)
: finite_subset m → finite_subset (m - 1)
:= λ j, if H : j.1 < k then ⟨j.1, my_le_trans j.1 k m p H ⟩ else ⟨j.1 - 1, inequality_fact j.1 m j.2⟩
/-
This formalizes the notion that when f is injective and misses k
in the codomain then when we relabel to bring m to m - 1,
composition is injective
-/
lemma relabel_with_inj_f_misses_k_is_inj
(m k : ℕ)
(p: k < m)
(f: finite_subset m → finite_subset m)
(inj: injective f)
: injective ((relabel m k p) ∘ f)
:=
begin
sorry
end
/--
Pigeonhole principle, induction on n
-/
theorem pigeonhole_principle
(n m : ℕ)
(f : finite_subset n → finite_subset m)
: (n > m) → ¬(injective f)
:= begin
intros n_gt_m f_injective,
induction n with d hd,
{ linarith, /- case d = 0 -/ },
let g := f ∘ (lift_one d),
let hd' := hd g,
rcases lt_or_eq_of_le (nat.lt_succ_iff.1 n_gt_m) with h | rfl,
{ /- case where d > m -/
/- prove injective g -/
apply hd' h,
let g_injective := comp_inj_is_inj (lift_one d) f (lift_one_injective d) f_injective,
exact g_injective,
},
{ /- case where d = m -/
/- prove f : finite_subset (nat.succ m) → finite_subset m is not injective -/
induction m with l hl,
{sorry,}, -- need to recall the proof we gave before
let k := f ⟨l + 1, succ_greater_than_nat (l + 1)⟩, -- let k = f(l + 1)
let violator := f ∘ (lift_one (l + 1)),
let restriction := (relabel (l + 1) k.1 k.2) ∘ violator,
let violator_is_inj := comp_inj_is_inj (lift_one (l + 1)) f (lift_one_injective (l + 1)) f_injective,
let res_is_inj := relabel_with_inj_f_misses_k_is_inj (l + 1) k.1 k.2 violator violator_is_inj,
/- contradiction, since restriction: [m] → [m - 1] is injective,
but this can't be true IH
-/
sorry
}
end
#print pigeonhole_principle |
490c1f3e46c6b04f95d0801cff391117ec3966a8 | 618003631150032a5676f229d13a079ac875ff77 | /src/tactic/ext.lean | c6c67cbf8fe38a6820dd5ad2bf37099c8bf1b0e3 | [
"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 | 13,829 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import tactic.rcases
import data.sum
universes u₁ u₂
open interactive interactive.types
open lean.parser nat tactic
/--
`derive_struct_ext_lemma n` generates two extensionality lemmas based on
the equality of all non-propositional projections.
On the following:
```lean
@[ext]
structure foo (α : Type*) :=
(x y : ℕ)
(z : {z // z < x})
(k : α)
(h : x < y)
```
`derive_struct_lemma` generates:
```lean
lemma foo.ext : ∀ {α : Type u_1} (x y : foo α),
x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y
lemma foo.ext_iff : ∀ {α : Type u_1} (x y : foo α),
x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k
```
-/
meta def derive_struct_ext_lemma (n : name) : tactic name :=
do e ← get_env,
fs ← e.structure_fields n,
d ← get_decl n,
n ← resolve_constant n,
let r := @expr.const tt n $ d.univ_params.map level.param,
(args,_) ← infer_type r >>= mk_local_pis,
let args := args.map expr.to_implicit_local_const,
let t := r.mk_app args,
x ← mk_local_def `x t,
y ← mk_local_def `y t,
let args_x := args ++ [x],
let args_y := args ++ [y],
bs ← fs.mmap $ λ f,
do { d ← get_decl (n ++ f),
let a := @expr.const tt (n ++ f) $ d.univ_params.map level.param,
t ← infer_type a,
s ← infer_type t,
if s ≠ `(Prop)
then do
let x := a.mk_app args_x,
let y := a.mk_app args_y,
t ← infer_type x,
t' ← infer_type y,
some <$> if t = t'
then mk_app `eq [x,y] >>= mk_local_def `h
else mk_mapp `heq [none,x,none,y] >>= mk_local_def `h
else pure none },
let bs := bs.filter_map id,
eq_t ← mk_app `eq [x,y],
t ← pis (args ++ [x,y] ++ bs) eq_t,
pr ← run_async $
do { (_,pr) ← solve_aux t (do
{ args ← intron args.length,
x ← intro1, y ← intro1,
cases x, cases y,
bs.mmap' (λ _,
do e ← intro1,
cases e),
reflexivity }),
instantiate_mvars pr },
let decl_n := n <.> "ext",
add_decl (declaration.thm decl_n d.univ_params t pr),
bs ← bs.mmap infer_type,
let rhs := expr.mk_and_lst bs,
iff_t ← mk_app `iff [eq_t,rhs],
t ← pis (args ++ [x,y]) iff_t,
pr ← run_async $
do { (_,pr) ← solve_aux t $ do
{ args ← intron args.length,
x ← intro1, y ← intro1,
cases x, cases y,
split,
solve1 $ do
{ h ← intro1, hs ← injection h, subst_vars,
repeat (refine ``( and.intro _ _ ) >> reflexivity ),
done <|> reflexivity },
solve1 $ do
{ repeat (do refine ``(and_imp.mpr _),
h ← intro1, cases h, skip ),
h ← intro1, cases h,
reflexivity } },
instantiate_mvars pr },
add_decl (declaration.thm (n <.> "ext_iff") d.univ_params t pr),
pure decl_n
meta def get_ext_subject : expr → tactic name
| (expr.pi n bi d b) :=
do v ← mk_local' n bi d,
b' ← whnf $ b.instantiate_var v,
get_ext_subject b'
| (expr.app _ e) :=
do t ← infer_type e >>= instantiate_mvars >>= head_beta,
if t.get_app_fn.is_constant then
pure $ t.get_app_fn.const_name
else if t.is_pi then
pure $ name.mk_numeral 0 name.anonymous
else if t.is_sort then
pure $ name.mk_numeral 1 name.anonymous
else do
t ← pp t,
fail format!"only constants and Pi types are supported: {t}"
| e := fail format!"Only expressions of the form `_ → _ → ... → R ... e are supported: {e}"
open native
@[reducible] def ext_param_type := option name ⊕ option name
meta def opt_minus : lean.parser (option name → ext_param_type) :=
sum.inl <$ tk "-" <|> pure sum.inr
meta def ext_param :=
opt_minus <*> ( name.mk_numeral 0 name.anonymous <$ brackets "(" ")" (tk "→" <|> tk "->") <|>
none <$ tk "*" <|>
some <$> ident )
meta def saturate_fun : name → tactic expr
| (name.mk_numeral 0 name.anonymous) :=
do v₀ ← mk_mvar,
v₁ ← mk_mvar,
return $ v₀.imp v₁
| (name.mk_numeral 1 name.anonymous) :=
do u ← mk_meta_univ,
pure $ expr.sort u
| n :=
do e ← resolve_constant n >>= mk_const,
a ← get_arity e,
e.mk_app <$> (list.iota a).mmap (λ _, mk_mvar)
meta def equiv_type_constr (n n' : name) : tactic unit :=
do e ← saturate_fun n,
e' ← saturate_fun n',
unify e e' <|> fail format!"{n} and {n'} are not definitionally equal types"
section performance_hack
/--
For performance reasons, it is inadvisable to use `user_attribute.get_param`.
The parameter is stored as a reflected expression. When calling `get_param`,
the stored parameter is evaluated using `eval_expr`, which first compiles the
expression into VM bytecode. The unevaluated expression is available using
`user_attribute.get_param_untyped`.
In particular, `user_attribute.get_param` MUST NEVER BE USED in the
implementation of an attribute cache. This is because calling `eval_expr`
disables the attribute cache.
There are several possible workarounds:
1. Set a different attribute depending on the parameter.
2. Use your own evaluation function instead of `eval_expr`, such as e.g. `expr.to_nat`.
3. Write your own `has_reflect Param` instance (using a more efficient serialization format).
The `user_attribute` code unfortunately checks whether the expression has the correct type,
but you can use `` `(id %%e : Param) `` to pretend that your expression `e` has type `Param`.
-/
library_note "user attribute parameters"
/-!
For performance reasons, the parameters of the `@[ext]` attribute are stored
in two auxiliary attributes:
```lean
attribute [ext [thunk]] funext
-- is turned into
attribute [_ext_core (@id name @funext)] thunk
attribute [_ext_lemma_core] funext
```
see Note [user attribute parameters]
-/
local attribute [semireducible] reflected
local attribute [instance, priority 9000]
private meta def hacky_name_reflect : has_reflect name :=
λ n, `(id %%(expr.const n []) : name)
@[user_attribute]
private meta def ext_attr_core : user_attribute (name_map name) name :=
{ name := `_ext_core,
descr := "(internal attribute used by ext)",
cache_cfg := {
dependencies := [],
mk_cache := λ ns, do
attrs ← ns.mmap (λ n, do
ext_l ← ext_attr_core.get_param_untyped n,
pure (n, ext_l.app_arg.const_name)),
pure $ rb_map.of_list attrs },
parser := failure }
end performance_hack
/-- Private attribute used to tag extensionality lemmas. -/
@[user_attribute]
private meta def ext_lemma_attr_core : user_attribute :=
{ name := `_ext_lemma_core,
descr := "(internal attribute used by ext)",
parser := failure }
/--
Returns the extensionality lemmas in the environment, as a map from structure
name to lemma name.
-/
meta def get_ext_lemmas : tactic (name_map name) :=
ext_attr_core.get_cache
/--
Returns the extensionality lemmas in the environment, as a list of lemma names.
-/
meta def get_ext_lemma_names : tactic (list name) :=
attribute.get_instances ext_lemma_attr_core.name
/--
Tag lemmas of the form:
```lean
@[ext]
lemma my_collection.ext (a b : my_collection)
(h : ∀ x, a.lookup x = b.lookup y) :
a = b := ...
```
The attribute indexes extensionality lemma using the type of the
objects (i.e. `my_collection`) which it gets from the statement of
the lemma. In some cases, the same lemma can be used to state the
extensionality of multiple types that are definitionally equivalent.
```lean
attribute [ext [(→),thunk,stream]] funext
```
Those parameters are cumulative. The following are equivalent:
```lean
attribute [ext [(→),thunk]] funext
attribute [ext [stream]] funext
```
and
```lean
attribute [ext [(→),thunk,stream]] funext
```
One removes type names from the list for one lemma with:
```lean
attribute [ext [-stream,-thunk]] funext
```
Also, the following:
```lean
@[ext]
lemma my_collection.ext (a b : my_collection)
(h : ∀ x, a.lookup x = b.lookup y) :
a = b := ...
```
is equivalent to
```lean
@[ext *]
lemma my_collection.ext (a b : my_collection)
(h : ∀ x, a.lookup x = b.lookup y) :
a = b := ...
```
This allows us specify type synonyms along with the type
that is referred to in the lemma statement.
```lean
@[ext [*,my_type_synonym]]
lemma my_collection.ext (a b : my_collection)
(h : ∀ x, a.lookup x = b.lookup y) :
a = b := ...
```
The `ext` attribute can be applied to a structure to generate its extensionality lemmas:
```lean
@[ext]
structure foo (α : Type*) :=
(x y : ℕ)
(z : {z // z < x})
(k : α)
(h : x < y)
```
will generate:
```lean
@[ext] lemma foo.ext : ∀ {α : Type u_1} (x y : foo α),
x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y
lemma foo.ext_iff : ∀ {α : Type u_1} (x y : foo α),
x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k
```
-/
@[user_attribute]
meta def extensional_attribute : user_attribute unit (list ext_param_type) :=
{ name := `ext,
descr := "lemmas usable by `ext` tactic",
parser := pure <$> ext_param <|> list_of ext_param <|> pure [],
after_set := some $ λ n prio b,
do ls ← extensional_attribute.get_param n,
e ← get_env,
n ← if (e.structure_fields n).is_some
then derive_struct_ext_lemma n
else pure n,
s ← mk_const n >>= infer_type >>= get_ext_subject,
let (rs,ls'') := if ls.empty
then ([],[s])
else ls.partition_map (sum.map (flip option.get_or_else s)
(flip option.get_or_else s)),
ls''.mmap' (equiv_type_constr s),
ls' ← get_ext_lemmas,
let l := ls'' ∪ (ls'.to_list.filter $ λ l, prod.snd l = n).map prod.fst \ rs,
l.mmap' $ λ l, do
ext_attr_core.set l n b prio,
ext_lemma_attr_core.set n () b prio }
add_tactic_doc
{ name := "ext",
category := doc_category.attr,
decl_names := [`extensional_attribute],
tags := ["rewrite", "logic"] }
-- We mark some existing extensionality lemmas.
attribute [ext] array.ext propext
attribute [ext [(→),thunk]] _root_.funext
-- We create some extensionality lemmas for existing structures.
attribute [ext] ulift
namespace plift
-- This is stronger than the one generated automatically.
@[ext] lemma ext {P : Prop} (a b : plift P) : a = b :=
begin
cases a, cases b, refl
end
end plift
-- Conservatively, we'll only add extensionality lemmas for `has_*` structures
-- as they become useful.
attribute [ext] has_zero
namespace tactic
meta def try_intros : ext_patt → tactic ext_patt
| [] := try intros $> []
| (x::xs) :=
do tgt ← target >>= whnf,
if tgt.is_pi
then rintro [x] >> try_intros xs
else pure (x :: xs)
meta def ext1 (xs : ext_patt) (cfg : apply_cfg := {}) : tactic ext_patt :=
do subject ← target >>= get_ext_subject,
m ← get_ext_lemmas,
do { rule ← m.find subject,
applyc rule cfg } <|>
do { ls ← get_ext_lemma_names,
ls.any_of (λ n, applyc n cfg) } <|>
fail format!"no applicable extensionality rule found for {subject}",
try_intros xs
meta def ext : ext_patt → option ℕ → tactic unit
| _ (some 0) := skip
| xs n := focus1 $ do
ys ← ext1 xs, try (ext ys (nat.pred <$> n))
local postfix `?`:9001 := optional
local postfix *:9001 := many
/--
`ext1 id` selects and apply one extensionality lemma (with attribute
`ext`), using `id`, if provided, to name a local constant
introduced by the lemma. If `id` is omitted, the local constant is
named automatically, as per `intro`.
-/
meta def interactive.ext1 (xs : parse ext_parse) : tactic unit :=
ext1 xs $> ()
/--
- `ext` applies as many extensionality lemmas as possible;
- `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them
until it runs out of identifiers in `ids` to name the local constants.
When trying to prove:
```lean
α β : Type,
f g : α → set β
⊢ f = g
```
applying `ext x y` yields:
```lean
α β : Type,
f g : α → set β,
x : α,
y : β
⊢ y ∈ f x ↔ y ∈ f x
```
by applying functional extensionality and set extensionality.
A maximum depth can be provided with `ext x y z : 3`.
-/
meta def interactive.ext : parse ext_parse → parse (tk ":" *> small_nat)? → tactic unit
| [] (some n) := iterate_range 1 n (ext1 [] $> ())
| [] none := repeat1 (ext1 [] $> ())
| xs n := tactic.ext xs n
/--
* `ext1 id` selects and apply one extensionality lemma (with
attribute `ext`), using `id`, if provided, to name a
local constant introduced by the lemma. If `id` is omitted, the
local constant is named automatically, as per `intro`.
* `ext` applies as many extensionality lemmas as possible;
* `ext ids`, with `ids` a list of identifiers, finds extensionality lemmas
and applies them until it runs out of identifiers in `ids` to name
the local constants.
When trying to prove:
```lean
α β : Type,
f g : α → set β
⊢ f = g
```
applying `ext x y` yields:
```lean
α β : Type,
f g : α → set β,
x : α,
y : β
⊢ y ∈ f x ↔ y ∈ g x
```
by applying functional extensionality and set extensionality.
A maximum depth can be provided with `ext x y z : 3`.
-/
add_tactic_doc
{ name := "ext1 / ext",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ext1, `tactic.interactive.ext],
tags := ["rewriting", "logic"] }
end tactic
|
54d14f9f907cdf6f07d950118548e7bd755a369f | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/measure_theory/measure_space.lean | bb94d74ad22c482d02e3d32ef21756b9de24f4ec | [
"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 | 54,617 | 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
-/
import measure_theory.outer_measure
import order.filter.countable_Inter
/-!
# Measure spaces
Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the
extended nonnegative reals that satisfies the following conditions:
1. `μ ∅ = 0`;
2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint
sets is equal to the measure of the individual sets.
Every measure can be canonically extended to an outer measure, so that it assigns values to
all subsets, not just the measurable subsets. On the other hand, a measure that is countably
additive on measurable sets can be restricted to measurable sets to obtain a measure.
In this file a measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure.
In the first part of the file we define operations on arbitrary functions defined on measurable
sets.
Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ennreal`.
Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding
outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the
measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0`
on the null sets.
## Main statements
* `completion` is the completion of a measure to all null measurable sets.
* `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure.
## Implementation notes
Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`.
This conveniently allows us to apply the measure to sets without proving that they are measurable.
We get countable subadditivity for all sets, but only countable additivity for measurable sets.
You often don't want to define a measure via its constructor.
Two ways that are sometimes more convenient:
* `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets
and proving the properties (1) and (2) mentioned above.
* `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that
all measurable sets in the measurable space are Carathéodory measurable.
A `measure_space` is a class that is a measurable space with a canonical measure.
The measure is denoted `volume`.
## References
* <https://en.wikipedia.org/wiki/Measure_(mathematics)>
* <https://en.wikipedia.org/wiki/Complete_measure>
* <https://en.wikipedia.org/wiki/Almost_everywhere>
## Tags
measure, almost everywhere, measure space, completion, null set, null measurable set
-/
noncomputable theory
open classical set filter finset function
open_locale classical topological_space big_operators filter
universes u v w x
namespace measure_theory
/- We first consider operations on arbitrary functions defined on measurable sets. -/
section of_measurable
parameters {α : Type*} [measurable_space α]
parameters (m : Π (s : set α), is_measurable s → ennreal)
parameters (m0 : m ∅ is_measurable.empty = 0)
include m0
/-- We can trivially extend a function defined on measurable sets to all sets by defining it to be
`∞` on the non-measurable sets.
`measure'` is mainly used to derive the outer measure, for the main `measure` projection. -/
def measure' (s : set α) : ennreal := ⨅ h : is_measurable s, m s h
lemma measure'_eq {s} (h : is_measurable s) : measure' s = m s h :=
by simp [measure', h]
lemma measure'_empty : measure' ∅ = 0 :=
(measure'_eq is_measurable.empty).trans m0
lemma measure'_Union_nat
{f : ℕ → set α}
(hm : ∀i, is_measurable (f i))
(mU : m (⋃i, f i) (is_measurable.Union hm) = (∑'i, m (f i) (hm i))) :
measure' (⋃i, f i) = (∑'i, measure' (f i)) :=
(measure'_eq _).trans $ mU.trans $
by congr; funext i; rw measure'_eq
/-- Given an arbitrary function on measurable sets, we can define the outer measure corresponding to
it (this is the unique maximal outer measure that is at most `m` on measurable sets). -/
def outer_measure' : outer_measure α :=
outer_measure.of_function measure' measure'_empty
lemma measure'_Union_le_tsum_nat'
(mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
m (⋃i, f i) (is_measurable.Union hm) ≤ (∑'i, m (f i) (hm i)))
(s : ℕ → set α) :
measure' (⋃i, s i) ≤ (∑'i, measure' (s i)) :=
begin
by_cases h : ∀i, is_measurable (s i),
{ rw [measure'_eq _ _ (is_measurable.Union h),
congr_arg tsum _], {apply mU h},
funext i, apply measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) }
end
parameter (mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union hm) = (∑'i, m (f i) (hm i)))
include mU
lemma measure'_Union
{β} [encodable β] {f : β → set α}
(hd : pairwise (disjoint on f)) (hm : ∀i, is_measurable (f i)) :
measure' (⋃i, f i) = (∑'i, measure' (f i)) :=
begin
rw [← encodable.Union_decode2, ← tsum_Union_decode2],
{ exact measure'_Union_nat _ _
(λ n, encodable.Union_decode2_cases is_measurable.empty hm)
(mU _ (encodable.Union_decode2_disjoint_on hd)) },
{ apply measure'_empty },
end
lemma measure'_union {s₁ s₂ : set α}
(hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
measure' (s₁ ∪ s₂) = measure' s₁ + measure' s₂ :=
begin
rw [union_eq_Union, measure'_Union _ _ @mU
(pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩),
tsum_fintype],
change _+_ = _, simp
end
lemma measure'_mono {s₁ s₂ : set α} (h₁ : is_measurable s₁) (hs : s₁ ⊆ s₂) :
measure' s₁ ≤ measure' s₂ :=
le_infi $ λ h₂, begin
have := measure'_union _ _ @mU disjoint_diff h₁ (h₂.diff h₁),
rw union_diff_cancel hs at this,
rw ← measure'_eq m m0 _,
exact le_iff_exists_add.2 ⟨_, this⟩
end
lemma measure'_Union_le_tsum_nat : ∀ (s : ℕ → set α),
measure' (⋃i, s i) ≤ (∑'i, measure' (s i)) :=
measure'_Union_le_tsum_nat' $ λ f h, begin
simp [Union_disjointed.symm] {single_pass := tt},
rw [mU (is_measurable.disjointed h) disjoint_disjointed],
refine ennreal.tsum_le_tsum (λ i, _),
rw [← measure'_eq m m0, ← measure'_eq m m0],
exact measure'_mono _ _ @mU (is_measurable.disjointed h _) (inter_subset_left _ _)
end
lemma outer_measure'_eq {s : set α} (hs : is_measurable s) :
outer_measure' s = m s hs :=
by rw ← measure'_eq m m0 hs; exact
(le_antisymm (outer_measure.of_function_le _ _ _) $
le_infi $ λ f, le_infi $ λ hf,
le_trans (measure'_mono _ _ @mU hs hf) $
measure'_Union_le_tsum_nat _ _ @mU _)
lemma outer_measure'_eq_measure' {s : set α} (hs : is_measurable s) :
outer_measure' s = measure' s :=
by rw [measure'_eq m m0 hs, outer_measure'_eq m m0 @mU hs]
end of_measurable
namespace outer_measure
variables {α : Type*} [measurable_space α] (m : outer_measure α)
/-- Given an outer measure `m` we can forget its value on non-measurable sets, and then consider
`m.trim`, the unique maximal outer measure less than that function. -/
def trim : outer_measure α :=
outer_measure' (λ s _, m s) m.empty
theorem trim_ge : m ≤ m.trim :=
λ s, le_infi $ λ f, le_infi $ λ hs,
le_trans (m.mono hs) $ le_trans (m.Union_nat f) $
ennreal.tsum_le_tsum $ λ i, le_infi $ λ hf, le_refl _
theorem trim_eq {s : set α} (hs : is_measurable s) : m.trim s = m s :=
le_antisymm (le_trans (of_function_le _ _ _) (infi_le _ hs)) (trim_ge _ _)
theorem trim_congr {m₁ m₂ : outer_measure α}
(H : ∀ {s : set α}, is_measurable s → m₁ s = m₂ s) :
m₁.trim = m₂.trim :=
by unfold trim; congr; funext s hs; exact H hs
theorem trim_le_trim {m₁ m₂ : outer_measure α} (H : m₁ ≤ m₂) : m₁.trim ≤ m₂.trim :=
λ s, infi_le_infi $ λ f, infi_le_infi $ λ hs,
ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _
theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔
∀ s, is_measurable s → m₁ s ≤ m₂ s :=
le_of_function.trans $ forall_congr $ λ s, le_infi_iff
theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), m t :=
begin
refine le_antisymm
(le_infi $ λ t, le_infi $ λ st, le_infi $ λ ht, _)
(le_infi $ λ f, le_infi $ λ hf, _),
{ rw ← trim_eq m ht, exact (trim m).mono st },
{ by_cases h : ∀i, is_measurable (f i),
{ refine infi_le_of_le _ (infi_le_of_le hf $
infi_le_of_le (is_measurable.Union h) _),
rw congr_arg tsum _, {exact m.Union_nat _},
funext i, exact measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } }
end
theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ is_measurable t}, m t :=
by simp [infi_subtype, infi_and, trim_eq_infi]
theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim :=
le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (trim_ge _)
@[simp] theorem trim_zero : (0 : outer_measure α).trim = 0 :=
ext $ λ s, le_antisymm
(le_trans ((trim 0).mono (subset_univ s)) $
le_of_eq $ trim_eq _ is_measurable.univ)
(zero_le _)
theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim :=
ext $ λ s, begin
simp only [trim_eq_infi', add_apply],
rw ennreal.infi_add_infi,
rintro ⟨t₁, st₁, ht₁⟩ ⟨t₂, st₂, ht₂⟩,
exact ⟨⟨_, subset_inter_iff.2 ⟨st₁, st₂⟩, ht₁.inter ht₂⟩,
add_le_add
(m₁.mono' (inter_subset_left _ _))
(m₂.mono' (inter_subset_right _ _))⟩,
end
theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim :=
λ s, by simp [trim_eq_infi]; exact
λ t st ht, ennreal.tsum_le_tsum (λ i,
infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht)
lemma exists_is_measurable_superset_of_trim_eq_zero
{m : outer_measure α} {s : set α} (h : m.trim s = 0) :
∃t, s ⊆ t ∧ is_measurable t ∧ m t = 0 :=
begin
erw [trim_eq_infi, infi_eq_bot] at h,
choose t ht using show ∀n:ℕ, ∃t, s ⊆ t ∧ is_measurable t ∧ m t < n⁻¹,
{ assume n,
have : (0 : ennreal) < n⁻¹ := (ennreal.inv_pos.2 $ ennreal.nat_ne_top _),
rcases h _ this with ⟨t, ht⟩,
use [t],
simpa only [infi_lt_iff, exists_prop] using ht },
refine ⟨⋂n, t n, subset_Inter (λn, (ht n).1), is_measurable.Inter (λn, (ht n).2.1), _⟩,
refine le_antisymm _ (zero_le _),
refine le_of_tendsto_of_tendsto tendsto_const_nhds
ennreal.tendsto_inv_nat_nhds_zero (eventually_of_forall $ assume n, _),
exact le_trans (m.mono' $ Inter_subset _ _) (le_of_lt (ht n).2.2)
end
theorem trim_smul (c : ennreal) (m : outer_measure α) :
(c • m).trim = c • m.trim :=
begin
ext1 s,
simp only [trim_eq_infi', smul_apply],
haveI : nonempty {t // s ⊆ t ∧ is_measurable t} := ⟨⟨univ, subset_univ _, is_measurable.univ⟩⟩,
refine ennreal.infi_mul_left (assume hc hs, _),
rw ← trim_eq_infi' at hs,
simpa [and_assoc] using exists_is_measurable_superset_of_trim_eq_zero hs
end
end outer_measure
/-- A measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure. -/
structure measure (α : Type*) [measurable_space α] extends outer_measure α :=
(m_Union {f : ℕ → set α} :
(∀i, is_measurable (f i)) → pairwise (disjoint on f) →
measure_of (⋃i, f i) = (∑'i, measure_of (f i)))
(trimmed : to_outer_measure.trim = to_outer_measure)
/-- Measure projections for a measure space.
For measurable sets this returns the measure assigned by the `measure_of` field in `measure`.
But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and
subadditivity for all sets.
-/
instance measure.has_coe_to_fun {α} [measurable_space α] : has_coe_to_fun (measure α) :=
⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩
namespace measure
/-- Obtain a measure by giving a countably additive function that sends `∅` to `0`. -/
def of_measurable {α} [measurable_space α]
(m : Π (s : set α), is_measurable s → ennreal)
(m0 : m ∅ is_measurable.empty = 0)
(mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))) :
measure α :=
{ m_Union := λ f hf hd,
show outer_measure' m m0 (Union f) =
∑' i, outer_measure' m m0 (f i), begin
rw [outer_measure'_eq m m0 @mU, mU hf hd],
congr, funext n, rw outer_measure'_eq m m0 @mU
end,
trimmed :=
show (outer_measure' m m0).trim = outer_measure' m m0, begin
unfold outer_measure.trim,
congr, funext s hs,
exact outer_measure'_eq m m0 @mU hs
end,
..outer_measure' m m0 }
lemma of_measurable_apply {α} [measurable_space α]
{m : Π (s : set α), is_measurable s → ennreal}
{m0 : m ∅ is_measurable.empty = 0}
{mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))}
(s : set α) (hs : is_measurable s) :
of_measurable m m0 @mU s = m s hs :=
outer_measure'_eq m m0 @mU hs
lemma to_outer_measure_injective {α} [measurable_space α] :
injective (to_outer_measure : measure α → outer_measure α) :=
λ ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h, by { congr, exact h }
@[ext] lemma ext {α} [measurable_space α] {μ₁ μ₂ : measure α}
(h : ∀s, is_measurable s → μ₁ s = μ₂ s) :
μ₁ = μ₂ :=
to_outer_measure_injective $ by rw [← trimmed, outer_measure.trim_congr h, trimmed]
end measure
section
variables {α : Type*} {β : Type*} {ι : Type*} [measurable_space α] {μ μ₁ μ₂ : measure α}
{s s₁ s₂ : set α}
@[simp] lemma coe_to_outer_measure : ⇑μ.to_outer_measure = μ := rfl
lemma to_outer_measure_apply (s) : μ.to_outer_measure s = μ s := rfl
lemma measure_eq_trim (s) : μ s = μ.to_outer_measure.trim s :=
by rw μ.trimmed; refl
lemma measure_eq_infi (s) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t :=
by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl
lemma measure_eq_outer_measure' :
μ s = outer_measure' (λ s _, μ s) μ.empty s :=
measure_eq_trim _
lemma to_outer_measure_eq_outer_measure' :
μ.to_outer_measure = outer_measure' (λ s _, μ s) μ.empty :=
μ.trimmed.symm
lemma measure_eq_measure' (hs : is_measurable s) :
μ s = measure' (λ s _, μ s) μ.empty s :=
by rw [measure_eq_outer_measure',
outer_measure'_eq_measure' (λ s _, μ s) _ μ.m_Union hs]
@[simp] lemma measure_empty : μ ∅ = 0 := μ.empty
lemma nonempty_of_measure_ne_zero (h : μ s ≠ 0) : s.nonempty :=
ne_empty_iff_nonempty.1 $ λ h', h $ h'.symm ▸ measure_empty
lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h
lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 :=
by rw [← le_zero_iff_eq, ← h₂]; exact measure_mono h
lemma exists_is_measurable_superset_of_measure_eq_zero {s : set α} (h : μ s = 0) :
∃t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 :=
outer_measure.exists_is_measurable_superset_of_trim_eq_zero (by rw [← measure_eq_trim, h])
lemma exists_is_measurable_superset_iff_measure_eq_zero {s : set α} :
(∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = 0) ↔ μ s = 0 :=
⟨λ ⟨t, hst, _, ht⟩, measure_mono_null hst ht, exists_is_measurable_superset_of_measure_eq_zero⟩
theorem measure_Union_le {β} [encodable β] (s : β → set α) : μ (⋃i, s i) ≤ (∑'i, μ (s i)) :=
μ.to_outer_measure.Union _
lemma measure_bUnion_le {s : set β} (hs : countable s) (f : β → set α) :
μ (⋃b∈s, f b) ≤ ∑'p:s, μ (f p) :=
begin
haveI := hs.to_encodable,
rw [bUnion_eq_Union],
apply measure_Union_le
end
lemma measure_bUnion_finset_le (s : finset β) (f : β → set α) :
μ (⋃b∈s, f b) ≤ ∑ p in s, μ (f p) :=
begin
rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype],
exact measure_bUnion_le s.countable_to_set f
end
lemma measure_Union_null {β} [encodable β] {s : β → set α} :
(∀ i, μ (s i) = 0) → μ (⋃i, s i) = 0 :=
μ.to_outer_measure.Union_null
theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ :=
μ.to_outer_measure.union _ _
lemma measure_union_null {s₁ s₂ : set α} : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 :=
μ.to_outer_measure.union_null
lemma measure_Union {β} [encodable β] {f : β → set α}
(hn : pairwise (disjoint on f)) (h : ∀i, is_measurable (f i)) :
μ (⋃i, f i) = (∑'i, μ (f i)) :=
by rw [measure_eq_measure' (is_measurable.Union h),
measure'_Union (λ s _, μ s) _ μ.m_Union hn h];
simp [measure_eq_measure', h]
lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
μ (s₁ ∪ s₂) = μ s₁ + μ s₂ :=
by rw [measure_eq_measure' (h₁.union h₂),
measure'_union (λ s _, μ s) _ μ.m_Union hd h₁ h₂];
simp [measure_eq_measure', h₁, h₂]
lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s)
(hd : pairwise_on s (disjoint on f)) (h : ∀b∈s, is_measurable (f b)) :
μ (⋃b∈s, f b) = ∑'p:s, μ (f p) :=
begin
haveI := hs.to_encodable,
rw [← measure_Union, bUnion_eq_Union],
{ rintro ⟨i, hi⟩ ⟨j, hj⟩ ij x ⟨h₁, h₂⟩,
exact hd i hi j hj (mt subtype.ext_val ij:_) ⟨h₁, h₂⟩ },
{ simpa }
end
lemma measure_sUnion {S : set (set α)} (hs : countable S)
(hd : pairwise_on S disjoint) (h : ∀s∈S, is_measurable s) :
μ (⋃₀ S) = ∑' s:S, μ s :=
by rw [sUnion_eq_bUnion, measure_bUnion hs hd h]
lemma measure_bUnion_finset {s : finset ι} {f : ι → set α} (hd : pairwise_on ↑s (disjoint on f))
(hm : ∀b∈s, is_measurable (f b)) :
μ (⋃b∈s, f b) = ∑ p in s, μ (f p) :=
begin
rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype],
exact measure_bUnion s.countable_to_set hd hm
end
/-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma tsum_measure_preimage_singleton {s : set β} (hs : countable s) {f : α → β}
(hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) :
(∑' b : s, μ (f ⁻¹' {↑b})) = μ (f ⁻¹' s) :=
by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_on_disjoint_fiber _ _) hf]
/-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma sum_measure_preimage_singleton (s : finset β) {f : α → β}
(hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) :
∑ b in s, μ (f ⁻¹' {b}) = μ (f ⁻¹' ↑s) :=
by simp only [← measure_bUnion_finset (pairwise_on_disjoint_fiber _ _) hf,
finset.bUnion_preimage_singleton]
lemma measure_diff {s₁ s₂ : set α} (h : s₂ ⊆ s₁)
(h₁ : is_measurable s₁) (h₂ : is_measurable s₂)
(h_fin : μ s₂ < ⊤) : μ (s₁ \ s₂) = μ s₁ - μ s₂ :=
begin
refine (ennreal.add_sub_self' h_fin).symm.trans _,
rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h]
end
lemma sum_measure_le_measure_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i))
(H : pairwise_on ↑s (disjoint on t)) :
∑ i in s, μ (t i) ≤ μ (univ : set α) :=
by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) }
lemma tsum_measure_le_measure_univ {s : ι → set α} (hs : ∀ i, is_measurable (s i))
(H : pairwise (disjoint on s)) :
(∑' i, μ (s i)) ≤ μ (univ : set α) :=
begin
rw [ennreal.tsum_eq_supr_sum],
exact supr_le (λ s, sum_measure_le_measure_univ (λ i hi, hs i) (λ i hi j hj hij, H i j hij))
end
/-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then
one of the intersections `s i ∩ s j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure (μ : measure α) {s : ι → set α}
(hs : ∀ i, is_measurable (s i)) (H : μ (univ : set α) < ∑' i, μ (s i)) :
∃ i j (h : i ≠ j), (s i ∩ s j).nonempty :=
begin
contrapose! H,
apply tsum_measure_le_measure_univ hs,
exact λ i j hij x hx, H i j hij ⟨x, hx⟩
end
/-- Pigeonhole principle for measure spaces: if `s` is a `finset` and
`∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure (μ : measure α) {s : finset ι}
{t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : μ (univ : set α) < ∑ i in s, μ (t i)) :
∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty :=
begin
contrapose! H,
apply sum_measure_le_measure_univ h,
exact λ i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩
end
lemma measure_Union_eq_supr_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) (hs : monotone s) :
μ (⋃i, s i) = (⨆i, μ (s i)) :=
begin
have : ∀ t : finset ℕ, ∃ n, t ⊆ finset.range (n + 1),
from λ t, (finset.exists_nat_subset_range t).imp (λ n hn, finset.subset.trans hn $
finset.range_mono $ (le_add_iff_nonneg_right _).2 (zero_le 1)),
rw [← Union_disjointed, measure_Union disjoint_disjointed (is_measurable.disjointed h),
ennreal.tsum_eq_supr_sum' _ this],
congr' 1, ext1 n,
rw [← measure_bUnion_finset (disjoint_disjointed.pairwise_on _)
(λ n _, is_measurable.disjointed h n)],
convert congr_arg μ (Union_disjointed_of_mono hs n),
ext, simp
end
lemma measure_Inter_eq_infi_nat {s : ℕ → set α}
(h : ∀i, is_measurable (s i)) (hs : ∀i j, i ≤ j → s j ⊆ s i)
(hfin : ∃i, μ (s i) < ⊤) :
μ (⋂i, s i) = (⨅i, μ (s i)) :=
begin
rcases hfin with ⟨k, hk⟩,
rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k),
ennreal.sub_infi,
← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)),
← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h)
(lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk),
diff_Inter, measure_Union_eq_supr_nat],
{ congr, funext i,
cases le_total k i with ik ik,
{ exact measure_diff (hs _ _ ik) (h k) (h i)
(lt_of_le_of_lt (measure_mono (hs _ _ ik)) hk) },
{ rw [diff_eq_empty.2 (hs _ _ ik), measure_empty,
ennreal.sub_eq_zero_of_le (measure_mono (hs _ _ ik))] } },
{ exact λ i, (h k).diff (h i) },
{ exact λ i j ij, diff_subset_diff_right (hs _ _ ij) }
end
lemma measure_eq_inter_diff {μ : measure α} {s t : set α}
(hs : is_measurable s) (ht : is_measurable t) :
μ s = μ (s ∩ t) + μ (s \ t) :=
have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs ,
by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t]
lemma tendsto_measure_Union {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : monotone s) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋃n, s n))) :=
begin
rw measure_Union_eq_supr_nat hs hm,
exact tendsto_at_top_supr_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm $ hnm)
end
lemma tendsto_measure_Inter {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : ∀n m, n ≤ m → s m ⊆ s n) (hf : ∃i, μ (s i) < ⊤) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋂n, s n))) :=
begin
rw measure_Inter_eq_infi_nat hs hm hf,
exact tendsto_at_top_infi_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm _ _ $ hnm),
end
end
/-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are
Carathéodory measurable. -/
def outer_measure.to_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
measure α :=
measure.of_measurable (λ s _, m s) m.empty
(λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd)
lemma le_to_outer_measure_caratheodory {α} [ms : measurable_space α]
(μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory :=
begin
assume s hs,
rw to_outer_measure_eq_outer_measure',
refine outer_measure.caratheodory_is_measurable (λ t, le_infi $ λ ht, _),
rw [← measure_eq_measure' (ht.inter hs),
← measure_eq_measure' (ht.diff hs),
← measure_union _ (ht.inter hs) (ht.diff hs),
inter_union_diff],
exact le_refl _,
exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁
end
@[simp] lemma to_measure_to_outer_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
(m.to_measure h).to_outer_measure = m.trim := rfl
@[simp] lemma to_measure_apply {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory)
{s : set α} (hs : is_measurable s) :
m.to_measure h s = m s := m.trim_eq hs
lemma le_to_measure_apply {α} (m : outer_measure α) [ms : measurable_space α]
(h : ms ≤ m.caratheodory) (s : set α) :
m s ≤ m.to_measure h s :=
m.trim_ge s
@[simp] lemma to_outer_measure_to_measure {α : Type*} [ms : measurable_space α] {μ : measure α} :
μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ :=
measure.ext $ λ s, μ.to_outer_measure.trim_eq
namespace measure
variables {α : Type*} {β : Type*} {γ : Type*}
[measurable_space α] [measurable_space β] [measurable_space γ]
instance : has_zero (measure α) :=
⟨{ to_outer_measure := 0,
m_Union := λ f hf hd, tsum_zero.symm,
trimmed := outer_measure.trim_zero }⟩
@[simp] theorem zero_to_outer_measure : (0 : measure α).to_outer_measure = 0 := rfl
@[simp, norm_cast] theorem coe_zero : ⇑(0 : measure α) = 0 := rfl
lemma eq_zero_of_not_nonempty (h : ¬nonempty α) (μ : measure α) : μ = 0 :=
ext $ λ s hs, by simp only [eq_empty_of_not_nonempty h s, measure_empty]
instance : inhabited (measure α) := ⟨0⟩
instance : has_add (measure α) :=
⟨λμ₁ μ₂, {
to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure,
m_Union := λs hs hd,
show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑' i, μ₁ (s i) + μ₂ (s i),
by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs],
trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩
@[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) :
(μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl
@[simp, norm_cast] theorem coe_add (μ₁ μ₂ : measure α) : ⇑(μ₁ + μ₂) = μ₁ + μ₂ := rfl
theorem add_apply (μ₁ μ₂ : measure α) (s) : (μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl
instance add_comm_monoid : add_comm_monoid (measure α) :=
to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure
add_to_outer_measure
instance : has_scalar ennreal (measure α) :=
⟨λ c μ,
{ to_outer_measure := c • μ.to_outer_measure,
m_Union := λ s hs hd, by simp [measure_Union, *, ennreal.tsum_mul_left],
trimmed := by rw [outer_measure.trim_smul, μ.trimmed] }⟩
@[simp] theorem smul_to_outer_measure (c : ennreal) (μ : measure α) :
(c • μ).to_outer_measure = c • μ.to_outer_measure :=
rfl
@[simp, norm_cast] theorem coe_smul (c : ennreal) (μ : measure α) :
⇑(c • μ) = c • μ :=
rfl
instance : semimodule ennreal (measure α) :=
injective.semimodule ennreal ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩
to_outer_measure_injective smul_to_outer_measure
instance : partial_order (measure α) :=
{ le := λm₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s,
le_refl := assume m s hs, le_refl _,
le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs),
le_antisymm := assume m₁ m₂ h₁ h₂, ext $
assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) }
theorem le_iff {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl
theorem to_outer_measure_le {μ₁ μ₂ : measure α} :
μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ :=
by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl
theorem le_iff' {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s :=
to_outer_measure_le.symm
theorem lt_iff {μ ν : measure α} : μ < ν ↔ μ ≤ ν ∧ ∃ s, is_measurable s ∧ μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop]
theorem lt_iff' {μ ν : measure α} : μ < ν ↔ μ ≤ ν ∧ ∃ s, μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le]
section
variables {m : set (measure α)} {μ : measure α}
lemma Inf_caratheodory (s : set α) (hs : is_measurable s) :
(Inf (measure.to_outer_measure '' m)).caratheodory.is_measurable s :=
begin
rw [outer_measure.Inf_eq_of_function_Inf_gen],
refine outer_measure.caratheodory_is_measurable (assume t, _),
cases t.eq_empty_or_nonempty with ht ht, by simp [ht],
simp only [outer_measure.Inf_gen_nonempty1 _ _ ht, le_infi_iff, ball_image_iff,
coe_to_outer_measure, measure_eq_infi t],
assume μ hμ u htu hu,
have hm : ∀{s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t,
{ assume s t hst,
rw [outer_measure.Inf_gen_nonempty2 _ _ (mem_image_of_mem _ hμ)],
refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _),
rw [to_outer_measure_apply],
refine measure_mono hst },
rw [measure_eq_inter_diff hu hs],
refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu)
end
instance : has_Inf (measure α) :=
⟨λm, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩
lemma Inf_apply {m : set (measure α)} {s : set α} (hs : is_measurable s) :
Inf m s = Inf (to_outer_measure '' m) s :=
to_measure_apply _ _ hs
private lemma Inf_le (h : μ ∈ m) : Inf m ≤ μ :=
have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h),
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
private lemma le_Inf (h : ∀μ' ∈ m, μ ≤ μ') : μ ≤ Inf m :=
have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) :=
le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ,
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
instance : complete_lattice (measure α) :=
{ bot := 0,
bot_le := assume a s hs, by exact bot_le,
/- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now
top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top),
le_top := assume a s hs,
by cases s.eq_empty_or_nonempty with h h;
simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply],
-/
.. complete_lattice_of_Inf (measure α) (λ ms, ⟨λ _, Inf_le, λ _, le_Inf⟩) }
-- TODO: add typeclasses for `∀ c, monotone ((*) c)` and `∀ c, monotone ((+) c)`
protected lemma add_le_add_left {μ₁ μ₂ : measure α} (ν : measure α) (hμ : μ₁ ≤ μ₂) :
ν + μ₁ ≤ ν + μ₂ :=
λ s hs, add_le_add_left (hμ s hs) _
protected lemma add_le_add_right {μ₁ μ₂ : measure α} (hμ : μ₁ ≤ μ₂) (ν : measure α) :
μ₁ + ν ≤ μ₂ + ν :=
λ s hs, add_le_add_right (hμ s hs) _
protected lemma add_le_add {μ₁ μ₂ : measure α} (hμ : μ₁ ≤ μ₂) {ν₁ ν₂ : measure α} (hν : ν₁ ≤ ν₂) :
μ₁ + ν₁ ≤ μ₂ + ν₂ :=
λ s hs, add_le_add (hμ s hs) (hν s hs)
protected lemma zero_le (μ : measure α) : 0 ≤ μ := bot_le
protected lemma le_add_left {ν ν' : measure α} (h : μ ≤ ν) : μ ≤ ν' + ν :=
λ s hs, le_add_left (h s hs)
protected lemma le_add_right {ν ν' : measure α} (h : μ ≤ ν) : μ ≤ ν + ν' :=
λ s hs, le_add_right (h s hs)
end
/-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable
set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/
def lift_linear (f : outer_measure α →ₗ[ennreal] outer_measure β)
(hf : ∀ μ : measure α, ‹_› ≤ (f μ.to_outer_measure).caratheodory) :
measure α →ₗ[ennreal] measure β :=
{ to_fun := λ μ, (f μ.to_outer_measure).to_measure (hf μ),
map_add' := λ μ₁ μ₂, ext $ λ s hs, by simp [hs],
map_smul' := λ c μ, ext $ λ s hs, by simp [hs] }
@[simp] lemma lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf)
{μ : measure α} {s : set β} (hs : is_measurable s) :
lift_linear f hf μ s = f μ.to_outer_measure s :=
to_measure_apply _ _ hs
lemma le_lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf)
{μ : measure α} (s : set β) :
f μ.to_outer_measure s ≤ lift_linear f hf μ s :=
le_to_measure_apply _ _ s
/-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/
def map (f : α → β) : measure α →ₗ[ennreal] measure β :=
if hf : measurable f then
lift_linear (outer_measure.map f) $ λ μ s hs t,
le_to_outer_measure_caratheodory μ _ (hf hs) (f ⁻¹' t)
else 0
variables {μ ν : measure α}
@[simp] theorem map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) :
map f μ s = μ (f ⁻¹' s) :=
by simp [map, dif_pos hf, hs]
@[simp] lemma map_id : map id μ = μ :=
ext $ λ s, map_apply measurable_id
lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) :
map g (map f μ) = map (g ∘ f) μ :=
ext $ λ s hs,
by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp]
/-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each
measurable set `s` we have `comap f μ s = μ (f '' s)`. -/
def comap (f : α → β) : measure β →ₗ[ennreal] measure α :=
if hf : injective f ∧ ∀ s, is_measurable s → is_measurable (f '' s) then
lift_linear (outer_measure.comap f) $ λ μ s hs t,
begin
simp only [coe_to_outer_measure, outer_measure.comap_apply, ← image_inter hf.1, image_diff hf.1],
apply le_to_outer_measure_caratheodory,
exact hf.2 s hs
end
else 0
lemma comap_apply (f : α → β) (hfi : injective f)
(hf : ∀ s, is_measurable s → is_measurable (f '' s)) (μ : measure β)
{s : set α} (hs : is_measurable s) :
comap f μ s = μ (f '' s) :=
begin
rw [comap, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure],
exact ⟨hfi, hf⟩
end
/-- Restrict a measure `μ` to a set `s` as an `ennreal`-linear map. -/
def restrictₗ (s : set α) : measure α →ₗ[ennreal] measure α :=
lift_linear (outer_measure.restrict s) $ λ μ s' hs' t,
begin
suffices : μ (s ∩ t) = μ (s ∩ t ∩ s') + μ (s ∩ t \ s'),
{ simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] },
exact le_to_outer_measure_caratheodory _ _ hs' _,
end
/-- Restrict a measure `μ` to a set `s`. -/
def restrict (μ : measure α) (s : set α) : measure α := restrictₗ s μ
@[simp] lemma restrictₗ_apply (s : set α) (μ : measure α) :
restrictₗ s μ = μ.restrict s :=
rfl
@[simp] lemma restrict_apply {s t : set α} (ht : is_measurable t) :
μ.restrict s t = μ (t ∩ s) :=
by simp [← restrictₗ_apply, restrictₗ, ht]
lemma le_restrict_apply (s t : set α) :
μ (t ∩ s) ≤ μ.restrict s t :=
by { rw [restrict, restrictₗ], convert le_lift_linear_apply _ t, simp }
@[simp] lemma restrict_add (μ ν : measure α) (s : set α) :
(μ + ν).restrict s = μ.restrict s + ν.restrict s :=
(restrictₗ s).map_add μ ν
@[simp] lemma restrict_zero (s : set α) : (0 : measure α).restrict s = 0 :=
(restrictₗ s).map_zero
@[simp] lemma restrict_smul (c : ennreal) (μ : measure α) (s : set α) :
(c • μ).restrict s = c • μ.restrict s :=
(restrictₗ s).map_smul c μ
lemma restrict_apply_eq_zero {s t : set α} (ht : is_measurable t) :
μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
by rw [restrict_apply ht]
lemma restrict_apply_eq_zero' {s t : set α} (hs : is_measurable s) :
μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
begin
refine ⟨λ h, le_zero_iff_eq.1 (h ▸ le_restrict_apply _ _), λ h, _⟩,
rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t', htt', ht', ht'0⟩,
apply measure_mono_null ((inter_subset _ _ _).1 htt'),
rw [restrict_apply (hs.compl.union ht'), union_inter_distrib_right, compl_inter_self,
set.empty_union],
exact measure_mono_null (inter_subset_left _ _) ht'0
end
@[simp] lemma restrict_empty : μ.restrict ∅ = 0 := ext $ λ s hs, by simp [hs]
@[simp] lemma restrict_univ : μ.restrict univ = μ := ext $ λ s hs, by simp [hs]
lemma restrict_union_apply {s s' t : set α} (h : disjoint (t ∩ s) (t ∩ s')) (hs : is_measurable s)
(hs' : is_measurable s') (ht : is_measurable t) :
μ.restrict (s ∪ s') t = μ.restrict s t + μ.restrict s' t :=
begin
simp only [restrict_apply, ht, set.inter_union_distrib_left],
exact measure_union h (ht.inter hs) (ht.inter hs'),
end
lemma restrict_union {s t : set α} (h : disjoint s t) (hs : is_measurable s)
(ht : is_measurable t) :
μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t :=
ext $ λ t' ht', restrict_union_apply (h.mono inf_le_right inf_le_right) hs ht ht'
lemma restrict_union_le (s s' : set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' :=
begin
intros t ht,
suffices : μ (t ∩ s ∪ t ∩ s') ≤ μ (t ∩ s) + μ (t ∩ s'),
by simpa [ht, inter_union_distrib_left],
apply measure_union_le
end
lemma restrict_Union_apply {ι} [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, is_measurable (s i)) {t : set α} (ht : is_measurable t) :
μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t :=
begin
simp only [restrict_apply, ht, inter_Union],
exact measure_Union (λ i j hij, (hd i j hij).mono inf_le_right inf_le_right)
(λ i, ht.inter (hm i))
end
lemma map_comap_subtype_coe {s : set α} (hs : is_measurable s) :
(map (coe : s → α)).comp (comap coe) = restrictₗ s :=
linear_map.ext $ λ μ, ext $ λ t ht,
by rw [restrictₗ_apply, restrict_apply ht, linear_map.comp_apply,
map_apply measurable_subtype_coe ht,
comap_apply (coe : s → α) subtype.val_injective (λ _, hs.subtype_image) _
(measurable_subtype_coe ht), subtype.image_preimage_coe]
/-- Restriction of a measure to a subset is monotone
both in set and in measure. -/
@[mono] lemma restrict_mono ⦃s s' : set α⦄ (hs : s ⊆ s') ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) :
μ.restrict s ≤ ν.restrict s' :=
assume t ht,
calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht
... ≤ μ (t ∩ s') : measure_mono $ inter_subset_inter_right _ hs
... ≤ ν (t ∩ s') : le_iff'.1 hμν (t ∩ s')
... = ν.restrict s' t : (restrict_apply ht).symm
/-- The dirac measure. -/
def dirac (a : α) : measure α :=
(outer_measure.dirac a).to_measure (by simp)
lemma dirac_apply' (a : α) {s : set α} (hs : is_measurable s) :
dirac a s = ⨆ h : a ∈ s, 1 :=
to_measure_apply _ _ hs
@[simp] lemma dirac_apply (a : α) {s : set α} (hs : is_measurable s) :
dirac a s = s.indicator 1 a :=
(dirac_apply' a hs).trans $ by { by_cases h : a ∈ s; simp [h] }
lemma dirac_apply_of_mem {a : α} {s : set α} (h : a ∈ s) :
dirac a s = 1 :=
begin
rw [measure_eq_infi, infi_subtype', infi_subtype'],
convert infi_const,
{ ext1 ⟨⟨t, hst⟩, ht⟩,
dsimp only [subtype.coe_mk] at *,
simp only [dirac_apply _ ht, indicator_of_mem (hst h), pi.one_apply] },
{ exact ⟨⟨⟨set.univ, subset_univ _⟩, is_measurable.univ⟩⟩ }
end
/-- Sum of an indexed family of measures. -/
def sum {ι : Type*} (f : ι → measure α) : measure α :=
(outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $
le_trans
(by exact le_infi (λ i, le_to_outer_measure_caratheodory _))
(outer_measure.le_sum_caratheodory _)
@[simp] lemma sum_apply {ι : Type*} (f : ι → measure α) {s : set α} (hs : is_measurable s) :
sum f s = ∑' i, f i s :=
to_measure_apply _ _ hs
lemma restrict_Union {ι} [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, is_measurable (s i)) :
μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) :=
ext $ λ t ht, by simp only [sum_apply _ ht, restrict_Union_apply hd hm ht]
lemma restrict_Union_le {ι} [encodable ι] {s : ι → set α} :
μ.restrict (⋃ i, s i) ≤ sum (λ i, μ.restrict (s i)) :=
begin
intros t ht,
suffices : μ (⋃ i, t ∩ s i) ≤ ∑' i, μ (t ∩ s i), by simpa [ht, inter_Union],
apply measure_Union_le
end
@[simp] lemma sum_bool (f : bool → measure α) : sum f = f tt + f ff :=
ext $ λ s hs, by simp [hs, tsum_fintype]
@[simp] lemma restrict_sum {ι : Type*} (μ : ι → measure α) {s : set α} (hs : is_measurable s) :
(sum μ).restrict s = sum (λ i, (μ i).restrict s) :=
ext $ λ t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs]
/-- Counting measure on any measurable space. -/
def count : measure α := sum dirac
lemma count_apply {s : set α} (hs : is_measurable s) :
count s = ∑' i : s, 1 :=
by simp only [count, sum_apply, hs, dirac_apply, ← tsum_subtype s 1, pi.one_apply]
@[simp] lemma count_apply_finset [measurable_singleton_class α] (s : finset α) :
count (↑s : set α) = s.card :=
calc count (↑s : set α) = ∑' i : (↑s : set α), (1 : α → ennreal) i : count_apply s.is_measurable
... = ∑ i in s, 1 : s.tsum_subtype 1
... = s.card : by simp
/-- A measure is complete if every null set is also measurable.
A null set is a subset of a measurable set with measure `0`.
Since every measure is defined as a special case of an outer measure, we can more simply state
that a set `s` is null if `μ s = 0`. -/
@[class] def is_complete {α} {_:measurable_space α} (μ : measure α) : Prop :=
∀ s, μ s = 0 → is_measurable s
/-- The "almost everywhere" filter of co-null sets. -/
def ae (μ : measure α) : filter α :=
{ sets := {s | μ sᶜ = 0},
univ_sets := by simp,
inter_sets := λ s t hs ht, by simp only [compl_inter, mem_set_of_eq];
exact measure_union_null hs ht,
sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs }
/-- The filter of sets `s` such that `sᶜ` has finite measure. -/
def cofinite (μ : measure α) : filter α :=
{ sets := {s | μ sᶜ < ⊤},
univ_sets := by simp,
inter_sets := λ s t hs ht, by { simp only [compl_inter, mem_set_of_eq],
calc μ (sᶜ ∪ tᶜ) ≤ μ sᶜ + μ tᶜ : measure_union_le _ _
... < ⊤ : ennreal.add_lt_top.2 ⟨hs, ht⟩ },
sets_of_superset := λ s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs }
lemma mem_cofinite {s : set α} : s ∈ μ.cofinite ↔ μ sᶜ < ⊤ := iff.rfl
lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in μ.cofinite, p x) ↔ μ {x | ¬p x} < ⊤ := iff.rfl
end measure
variables {α : Type*} {β : Type*} [measurable_space α] {μ : measure α}
notation `∀ᵐ` binders `∂` μ `, ` r:(scoped P, filter.eventually P (measure.ae μ)) := r
notation f ` =ᵐ[`:50 μ:50 `] `:0 g:50 := f =ᶠ[measure.ae μ] g
notation f ` ≤ᵐ[`:50 μ:50 `] `:0 g:50 := f ≤ᶠ[measure.ae μ] g
lemma mem_ae_iff {s : set α} : s ∈ μ.ae ↔ μ sᶜ = 0 := iff.rfl
lemma ae_iff {p : α → Prop} : (∀ᵐ a ∂ μ, p a) ↔ μ { a | ¬ p a } = 0 := iff.rfl
lemma measure_zero_iff_ae_nmem {s : set α} : μ s = 0 ↔ ∀ᵐ a ∂ μ, a ∉ s :=
by simp only [ae_iff, not_not, set_of_mem_eq]
lemma ae_of_all {p : α → Prop} (μ : measure α) : (∀a, p a) → ∀ᵐ a ∂ μ, p a :=
eventually_of_forall
instance : countable_Inter_filter μ.ae :=
⟨begin
intros S hSc hS,
simp only [mem_ae_iff, compl_sInter, sUnion_image, bUnion_eq_Union] at hS ⊢,
haveI := hSc.to_encodable,
exact measure_Union_null (subtype.forall.2 hS)
end⟩
lemma ae_all_iff {ι : Type*} [encodable ι] {p : α → ι → Prop} :
(∀ᵐ a ∂ μ, ∀i, p a i) ↔ (∀i, ∀ᵐ a ∂ μ, p a i) :=
eventually_countable_forall
lemma ae_ball_iff {ι} {S : set ι} (hS : countable S) {p : Π (x : α) (i ∈ S), Prop} :
(∀ᵐ x ∂ μ, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᵐ x ∂ μ, p x i ‹_› :=
eventually_countable_ball hS
lemma ae_eq_refl (f : α → β) : f =ᵐ[μ] f := eventually_eq.refl _ _
lemma ae_eq_symm {f g : α → β} (h : f =ᵐ[μ] g) : g =ᵐ[μ] f :=
h.symm
lemma ae_eq_trans {f g h: α → β} (h₁ : f =ᵐ[μ] g) (h₂ : g =ᵐ[μ] h) :
f =ᵐ[μ] h :=
h₁.trans h₂
lemma mem_ae_map_iff [measurable_space β] {f : α → β} (hf : measurable f)
{s : set β} (hs : is_measurable s) :
s ∈ (measure.map f μ).ae ↔ (f ⁻¹' s) ∈ μ.ae :=
by simp only [mem_ae_iff, measure.map_apply hf hs.compl, preimage_compl]
lemma ae_map_iff [measurable_space β] {f : α → β} (hf : measurable f)
{p : β → Prop} (hp : is_measurable {x | p x}) :
(∀ᵐ y ∂ (measure.map f μ), p y) ↔ ∀ᵐ x ∂ μ, p (f x) :=
mem_ae_map_iff hf hp
@[simp] lemma ae_restrict_eq {s : set α} (hs : is_measurable s):
(μ.restrict s).ae = μ.ae ⊓ 𝓟 s :=
begin
ext t,
simp only [mem_inf_principal, mem_ae_iff, measure.restrict_apply_eq_zero' hs, compl_set_of,
not_imp, and_comm (_ ∈ s)],
refl
end
lemma mem_dirac_ae_iff {a : α} {s : set α} (hs : is_measurable s) :
s ∈ (measure.dirac a).ae ↔ a ∈ s :=
by by_cases a ∈ s; simp [mem_ae_iff, measure.dirac_apply, hs.compl, indicator_apply, *]
lemma eventually_dirac {a : α} {p : α → Prop} (hp : is_measurable {x | p x}) :
(∀ᵐ x ∂(measure.dirac a), p x) ↔ p a :=
mem_dirac_ae_iff hp
lemma eventually_eq_dirac [measurable_space β] [measurable_singleton_class β] {a : α} {f : α → β}
(hf : measurable f) :
f =ᵐ[measure.dirac a] const α (f a) :=
(eventually_dirac $ show is_measurable (f ⁻¹' {f a}), from hf $ is_measurable_singleton _).2 rfl
lemma dirac_ae_eq [measurable_singleton_class α] (a : α) : (measure.dirac a).ae = pure a :=
begin
ext s,
simp only [mem_ae_iff, mem_pure_sets],
by_cases ha : a ∈ s,
{ simp only [ha, iff_true],
rw [← set.singleton_subset_iff, ← compl_subset_compl] at ha,
refine measure_mono_null ha _,
simp [measure.dirac_apply a (is_measurable_singleton a).compl] },
{ simp only [ha, iff_false, measure.dirac_apply_of_mem (mem_compl ha)],
exact one_ne_zero }
end
lemma eventually_eq_dirac' [measurable_singleton_class α] {a : α} (f : α → β) :
f =ᵐ[measure.dirac a] const α (f a) :=
by { rw [dirac_ae_eq], show f a = f a, refl }
lemma measure_diff_of_ae_imp {s t : set α} (H : ∀ᵐ x ∂μ, x ∈ s → x ∈ t) :
μ (s \ t) = 0 :=
flip measure_mono_null H $ λ x hx H, hx.2 (H hx.1)
/-- If `s ⊆ t` modulo a set of measure `0`, then `μ s ≤ μ t`. -/
lemma measure_le_of_ae_imp {s t : set α} (H : ∀ᵐ x ∂μ, x ∈ s → x ∈ t) :
μ s ≤ μ t :=
calc μ s ≤ μ (s ∪ t) : measure_mono $ subset_union_left s t
... = μ (t ∪ s \ t) : by rw [union_diff_self, set.union_comm]
... ≤ μ t + μ (s \ t) : measure_union_le _ _
... = μ t : by rw [measure_diff_of_ae_imp H, add_zero]
/-- If two sets are equal modulo a set of measure zero, then `μ s = μ t`. -/
lemma measure_congr {s t : set α} (H : ∀ᵐ x ∂μ, x ∈ s ↔ x ∈ t) : μ s = μ t :=
le_antisymm (measure_le_of_ae_imp $ H.mono $ λ x, iff.mp)
(measure_le_of_ae_imp $ H.mono $ λ x, iff.mpr)
end measure_theory
section is_complete
open measure_theory
variables {α : Type*} [measurable_space α] (μ : measure α)
/-- A set is null measurable if it is the union of a null set and a measurable set. -/
def is_null_measurable (s : set α) : Prop :=
∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0
theorem is_null_measurable_iff {μ : measure α} {s : set α} :
is_null_measurable μ s ↔
∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 :=
begin
split,
{ rintro ⟨t, z, rfl, ht, hz⟩,
refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩,
simp [union_diff_left, diff_subset] },
{ rintro ⟨t, st, ht, hz⟩,
exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ }
end
theorem is_null_measurable_measure_eq {μ : measure α} {s t : set α}
(st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t :=
begin
refine le_antisymm _ (measure_mono st),
have := measure_union_le t (s \ t),
rw [union_diff_cancel st, hz] at this, simpa
end
theorem is_measurable.is_null_measurable
{s : set α} (hs : is_measurable s) : is_null_measurable μ s :=
⟨s, ∅, by simp, hs, μ.empty⟩
theorem is_null_measurable_of_complete [c : μ.is_complete]
{s : set α} : is_null_measurable μ s ↔ is_measurable s :=
⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact
is_measurable.union ht (c _ hz),
λ h, h.is_null_measurable _⟩
variables {μ}
theorem is_null_measurable.union_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s ∪ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, le_zero_iff_eq.1
(le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩
end
theorem null_is_null_measurable {z : set α}
(hz : μ z = 0) : is_null_measurable μ z :=
by simpa using (is_measurable.empty.is_null_measurable _).union_null hz
theorem is_null_measurable.Union_nat {s : ℕ → set α}
(hs : ∀ i, is_null_measurable μ (s i)) :
is_null_measurable μ (Union s) :=
begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht,
rcases ht with ⟨st, ht, hz⟩,
refine is_null_measurable_iff.2
⟨Union t, Union_subset_Union st, is_measurable.Union ht,
measure_mono_null _ (measure_Union_null hz)⟩,
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff)
end
theorem is_measurable.diff_null {s z : set α}
(hs : is_measurable s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rw measure_eq_infi at hz,
choose f hf using show ∀ q : {q:ℚ//q>0}, ∃ t:set α,
z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal),
{ rintro ⟨ε, ε0⟩,
have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 },
rw ← hz at this, simpa [infi_lt_iff] },
refine is_null_measurable_iff.2 ⟨s \ Inter f,
diff_subset_diff_right (subset_Inter (λ i, (hf i).1)),
hs.diff (is_measurable.Inter (λ i, (hf i).2.1)),
measure_mono_null _ (le_zero_iff_eq.1 $ le_of_not_lt $ λ h, _)⟩,
{ exact Inter f },
{ rw [diff_subset_iff, diff_union_self],
exact subset.trans (diff_subset _ _) (subset_union_left _ _) },
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩,
simp at ε0,
apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h),
exact measure_mono (Inter_subset _ _)
end
theorem is_null_measurable.diff_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
rw [set.union_diff_distrib],
exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz')
end
theorem is_null_measurable.compl {s : set α}
(hs : is_null_measurable μ s) :
is_null_measurable μ sᶜ :=
begin
rcases hs with ⟨t, z, rfl, ht, hz⟩,
rw compl_union,
exact ht.compl.diff_null hz
end
/-- The measurable space of all null measurable sets. -/
def null_measurable {α : Type u} [measurable_space α]
(μ : measure α) : measurable_space α :=
{ is_measurable := is_null_measurable μ,
is_measurable_empty := is_measurable.empty.is_null_measurable _,
is_measurable_compl := λ s hs, hs.compl,
is_measurable_Union := λ f, is_null_measurable.Union_nat }
/-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/
def completion {α : Type u} [measurable_space α] (μ : measure α) :
@measure_theory.measure α (null_measurable μ) :=
{ to_outer_measure := μ.to_outer_measure,
m_Union := λ s hs hd, show μ (Union s) = ∑' i, μ (s i), begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩,
rw is_null_measurable_measure_eq (Union_subset_Union st),
{ rw measure_Union _ ht,
{ congr, funext i,
exact (is_null_measurable_measure_eq (st i) (hz i)).symm },
{ rintro i j ij x ⟨h₁, h₂⟩,
exact hd i j ij ⟨st i h₁, st j h₂⟩ } },
{ refine measure_mono_null _ (measure_Union_null hz),
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff) }
end,
trimmed := begin
letI := null_measurable μ,
refine le_antisymm (λ s, _) (outer_measure.trim_ge _),
rw outer_measure.trim_eq_infi,
dsimp,
clear _inst,
resetI,
rw measure_eq_infi s,
exact infi_le_infi (λ t, infi_le_infi $ λ st,
infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩)
end }
instance completion.is_complete {α : Type u} [measurable_space α] (μ : measure α) :
(completion μ).is_complete :=
λ z hz, null_is_null_measurable hz
end is_complete
namespace measure_theory
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A measure space is a measurable space equipped with a
measure, referred to as `volume`. -/
class measure_space (α : Type*) extends measurable_space α :=
(volume : measure α)
end prio
export measure_space (volume)
/-- `volume` is the canonical measure on `α`. -/
add_decl_doc volume
section measure_space
variables {α : Type*} {ι : Type*} [measure_space α] {s₁ s₂ : set α}
notation `∀ᵐ` binders `, ` r:(scoped P, filter.eventually P (measure.ae volume)) := r
/-- The tactic `exact volume`, to be used in optional (`auto_param`) arguments. -/
meta def volume_tac : tactic unit := `[exact measure_theory.measure_space.volume]
end measure_space
end measure_theory
|
039638594cb83c3baf07826552fbf40b7fa6a110 | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /algebra/ordered_field.lean | eb1655c7b9fc430f59b4f5248713b97058e1ad62 | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 8,224 | 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.ordered_ring algebra.field
section linear_ordered_field
variables {α : Type*} [linear_ordered_field α] {a b c d : α}
def div_pos := @div_pos_of_pos_of_pos
lemma inv_pos {a : α} : 0 < a → 0 < a⁻¹ :=
by rw [inv_eq_one_div]; exact div_pos zero_lt_one
lemma inv_lt_zero {a : α} : a < 0 → a⁻¹ < 0 :=
by rw [inv_eq_one_div]; exact div_neg_of_pos_of_neg zero_lt_one
lemma one_le_div_iff_le (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a :=
⟨le_of_one_le_div a hb, one_le_div_of_le a hb⟩
lemma one_lt_div_iff_lt (hb : 0 < b) : 1 < a / b ↔ b < a :=
⟨lt_of_one_lt_div a hb, one_lt_div_of_lt a hb⟩
lemma div_le_one_iff_le (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (one_lt_div_iff_lt hb)
lemma div_lt_one_iff_lt (hb : 0 < b) : a / b < 1 ↔ a < b :=
le_iff_le_iff_lt_iff_lt.1 (one_le_div_iff_le hb)
lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b :=
⟨mul_le_of_le_div hc, le_div_of_mul_le hc⟩
lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b :=
by rw [mul_comm, le_div_iff hc]
lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b :=
⟨le_mul_of_div_le hb, by rw [mul_comm]; exact div_le_of_le_mul hb⟩
lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c :=
by rw [mul_comm, div_le_iff hb]
lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b :=
⟨mul_lt_of_lt_div hc, lt_div_of_mul_lt hc⟩
lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b :=
by rw [mul_comm, lt_div_iff hc]
lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b :=
⟨mul_le_of_div_le_of_neg hc, div_le_of_mul_le_of_neg hc⟩
lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c :=
le_iff_le_iff_lt_iff_lt.1 (le_div_iff hc)
lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a :=
by rw [mul_comm, div_lt_iff hc]
lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b :=
⟨mul_lt_of_gt_div_of_neg hc, div_lt_of_mul_gt_of_neg hc⟩
lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
by rw [inv_eq_one_div, div_le_iff ha,
← div_eq_inv_mul, one_le_div_iff_le hb]
lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a :=
by rw [← inv_le_inv hb (inv_pos ha), division_ring.inv_inv (ne_of_gt ha)]
lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ :=
by rw [← inv_le_inv (inv_pos hb) ha, division_ring.inv_inv (ne_of_gt hb)]
lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a :=
by simpa [one_div_eq_inv] using inv_le_inv ha hb
lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a :=
le_iff_le_iff_lt_iff_lt.1 (inv_le_inv hb ha)
lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a :=
le_iff_le_iff_lt_iff_lt.1 (le_inv hb ha)
lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ :=
le_iff_le_iff_lt_iff_lt.1 (inv_le hb ha)
lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a :=
le_iff_le_iff_lt_iff_lt.1 (one_div_le_one_div hb ha)
def div_nonneg := @div_nonneg_of_nonneg_of_pos
lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b :=
⟨le_imp_le_iff_lt_imp_lt.1 (λ h, div_le_div_of_le_of_pos h hc),
λ h, div_lt_div_of_lt_of_pos h hc⟩
lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right hc)
lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a :=
⟨le_imp_le_iff_lt_imp_lt.1 (λ h, div_le_div_of_le_of_neg h hc),
λ h, div_lt_div_of_lt_of_neg h hc⟩
lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right_of_neg hc)
lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b :=
(mul_lt_mul_left ha).trans (inv_lt_inv hb hc)
lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb)
lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) :
a / b < c / d ↔ a * d < c * b :=
by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0]
lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) :
a / b < c / d :=
(div_lt_div_iff (lt_of_lt_of_le d0 hbd) d0).2 (mul_lt_mul hac hbd d0 c0)
lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) :
a / b < c / d :=
(div_lt_div_iff (lt_trans d0 hbd) d0).2 (mul_lt_mul' hac hbd (le_of_lt d0) c0)
lemma half_pos {a : α} (h : 0 < a) : 0 < a / 2 := div_pos h two_pos
lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one
def half_lt_self := @div_two_lt_of_pos
lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one
lemma ivl_translate : (λx, x + c) '' {r:α | a ≤ r ∧ r ≤ b } = {r:α | a + c ≤ r ∧ r ≤ b + c} :=
calc (λx, x + c) '' {r | a ≤ r ∧ r ≤ b } = (λx, x - c) ⁻¹' {r | a ≤ r ∧ r ≤ b } :
congr_fun (set.image_eq_preimage_of_inverse
(assume a, add_sub_cancel a c) (assume b, sub_add_cancel b c)) _
... = {r | a + c ≤ r ∧ r ≤ b + c} :
set.ext $ by simp [-sub_eq_add_neg, le_sub_iff_add_le, sub_le_iff_le_add]
lemma ivl_stretch (hc : 0 < c) : (λx, x * c) '' {r | a ≤ r ∧ r ≤ b } = {r | a * c ≤ r ∧ r ≤ b * c} :=
calc (λx, x * c) '' {r | a ≤ r ∧ r ≤ b } = (λx, x / c) ⁻¹' {r | a ≤ r ∧ r ≤ b } :
congr_fun (set.image_eq_preimage_of_inverse
(assume a, mul_div_cancel _ $ ne_of_gt hc) (assume b, div_mul_cancel _ $ ne_of_gt hc)) _
... = {r | a * c ≤ r ∧ r ≤ b * c} :
set.ext $ by simp [le_div_iff, div_le_iff, hc]
instance linear_ordered_field.to_densely_ordered [linear_ordered_field α] : densely_ordered α :=
{ dense := assume a₁ a₂ h, ⟨(a₁ + a₂) / 2,
calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm
... < (a₁ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_left h _) two_pos,
calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_right h _) two_pos
... = a₂ : add_self_div_two a₂⟩ }
instance linear_ordered_field.to_no_top_order [linear_ordered_field α] : no_top_order α :=
{ no_top := assume a, ⟨a + 1, lt_add_of_le_of_pos (le_refl a) zero_lt_one ⟩ }
instance linear_ordered_field.to_no_bot_order [linear_ordered_field α] : no_bot_order α :=
{ no_bot := assume a, ⟨a + -1,
add_lt_of_le_of_neg (le_refl _) (neg_lt_of_neg_lt $ by simp [zero_lt_one]) ⟩ }
lemma inv_lt_one {a : α} (ha : 1 < a) : a⁻¹ < 1 :=
by rw [inv_eq_one_div]; exact div_lt_of_mul_lt_of_pos (lt_trans zero_lt_one ha) (by simp *)
lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ :=
by rw [inv_eq_one_div, lt_div_iff h₁]; simp [h₂]
lemma mul_self_inj_of_nonneg {a b : α} (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b :=
(mul_self_eq_mul_self_iff a b).trans $ or_iff_left_of_imp $
λ h, by subst a; rw [le_antisymm (neg_nonneg.1 a0) b0, neg_zero]
end linear_ordered_field
section
variables {α : Type*} [discrete_linear_ordered_field α] (a b c : α)
lemma inv_pos' {a : α} : 0 < a⁻¹ ↔ 0 < a :=
⟨by rw [inv_eq_one_div]; exact pos_of_one_div_pos, inv_pos⟩
lemma inv_neg' {a : α} : a⁻¹ < 0 ↔ a < 0 :=
⟨by rw [inv_eq_one_div]; exact neg_of_one_div_neg, inv_lt_zero⟩
lemma inv_nonneg {a : α} : 0 ≤ a⁻¹ ↔ 0 ≤ a :=
le_iff_le_iff_lt_iff_lt.2 inv_neg'
lemma inv_nonpos {a : α} : a⁻¹ ≤ 0 ↔ a ≤ 0 :=
le_iff_le_iff_lt_iff_lt.2 inv_pos'
lemma abs_inv : abs a⁻¹ = (abs a)⁻¹ :=
have h : abs (1 / a) = 1 / abs a,
begin rw [abs_div, abs_of_nonneg], exact zero_le_one end,
by simp [*] at *
lemma inv_neg : (-a)⁻¹ = -(a⁻¹) :=
if h : a = 0
then by simp [h, inv_zero]
else by rwa [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div]
lemma inv_le_inv_of_le {a b : α} (hb : 0 < b) (h : b ≤ a) : a⁻¹ ≤ b⁻¹ :=
begin
rw [inv_eq_one_div, inv_eq_one_div],
exact one_div_le_one_div_of_le hb h
end
lemma div_nonneg' {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b :=
(lt_or_eq_of_le hb).elim (div_nonneg ha) (λ h, by simp [h.symm])
end
|
039d6cb42f99e2478d16273cad2adcd119b8017f | 5719a16e23dfc08cdea7a5bf035b81690f307965 | /src/Init/Lean/Elab/StructInst.lean | 2aed9e89a750e62e864ec5e9232bb791bcbf63c6 | [
"Apache-2.0"
] | permissive | postmasters/lean4 | 488b03969a371e1507e1e8a4df9ebf63c7cbe7ac | f3976fc53a883ac7606fc59357d43f4b51016ca7 | refs/heads/master | 1,655,582,707,480 | 1,588,682,595,000 | 1,588,682,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 34,243 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Util.FindExpr
import Init.Lean.Elab.App
import Init.Lean.Elab.Binders
import Init.Lean.Elab.Quotation
namespace Lean
namespace Elab
namespace Term
namespace StructInst
/- parser! symbol "{" appPrec >> optional (try (ident >> " . ")) >> sepBy (structInstField <|> structInstSource) ", " true >> "}" -/
namespace ExpandNonAtomicExplicitSource
structure State :=
(found : Bool := false)
(source? : Option Syntax := none)
/- Auxiliary function for `expandNonAtomicExplicitSource` -/
def main (stx : Syntax) : StateT State TermElabM (Option Syntax) := do
let args := (stx.getArg 2).getArgs;
args ← args.mapM $ fun arg =>
if arg.getKind == `Lean.Parser.Term.structInstSource then do
-- parser! ".." >> optional termParser
s ← get;
if s.found then
liftM $ throwError arg "source has already been specified"
else
let optSource := arg.getArg 1;
if optSource.isNone then do
modify $ fun s => { found := true, .. s };
pure arg
else do
let source := optSource.getArg 0;
fvar? ← liftM $ isLocalTermId? source;
match fvar? with
| some _ => do
-- it is already a local variable
modify $ fun s => { found := true, .. s };
pure arg
| none => do
src ← `(src);
modify $ fun s => { found := true, source? := source, .. s };
let optSource := optSource.setArg 0 src;
let arg := arg.setArg 1 optSource;
pure arg
else
pure arg;
s ← get;
match s.source? with
| none => pure none
| some source => do
let newStx := stx.setArg 2 (mkNullNode args);
`(let src := $source; $newStx)
end ExpandNonAtomicExplicitSource
/-
If `stx` is of the form `{ ... .. s }` and `s` is not a local variable, expand into `let src := s; { ... .. src}`.
-/
private def expandNonAtomicExplicitSource (stx : Syntax) : TermElabM (Option Syntax) :=
withFreshMacroScope $ (ExpandNonAtomicExplicitSource.main stx).run' {}
inductive Source
| none -- structure instance source has not been provieded
| implicit (stx : Syntax) -- `..`
| explicit (stx : Syntax) (src : Expr) -- `.. term`
instance Source.inhabited : Inhabited Source := ⟨Source.none⟩
def Source.isNone : Source → Bool
| Source.none => true
| _ => false
instance Source.hasFormat : HasFormat Source :=
⟨fun src => match src with
| Source.none => ""
| Source.implicit _ => " .."
| Source.explicit _ src => " .. " ++ format src⟩
def Source.addSyntax : Source → Array Syntax → Array Syntax
| Source.none, acc => acc
| Source.implicit stx, acc => acc.push stx
| Source.explicit stx _, acc => acc.push stx
private def getStructSource (stx : Syntax) : TermElabM Source :=
let args := (stx.getArg 2).getArgs;
args.foldSepByM
(fun arg r =>
if arg.getKind == `Lean.Parser.Term.structInstSource then
-- parser! ".." >> optional termParser
if !r.isNone then throwError arg "source has already been specified"
else
let optTerm := arg.getArg 1;
if optTerm.isNone then pure $ Source.implicit arg
else do
fvar? ← isLocalTermId? (optTerm.getArg 0);
match fvar? with
| none => unreachable! -- expandNonAtomicExplicitSource must have been used when we get here
| some fvar => pure $ Source.explicit arg fvar
else
pure r)
Source.none
/-
We say a `{ ... }` notation is a `modifyOp` if it contains only one
```
def structInstArrayRef := parser! "[" >> termParser >>"]"
``` -/
private def isModifyOp? (stx : Syntax) : TermElabM (Option Syntax) := do
let args := (stx.getArg 2).getArgs;
s? ← args.foldSepByM
(fun arg s? =>
let k := arg.getKind;
if k == `Lean.Parser.Term.structInstSource then pure s?
else if k == `Lean.Parser.Term.structInstField then
/- Remark: the syntax for `structInstField` is
```
def structInstLVal := (ident <|> numLit <|> structInstArrayRef) >> many (group ("." >> (ident <|> numLit)) <|> structInstArrayRef)
def structInstField := parser! structInstLVal >> " := " >> termParser
``` -/
let lval := arg.getArg 0;
let k := lval.getKind;
if k == `Lean.Parser.Term.structInstArrayRef then
match s? with
| none => pure (some arg)
| some s =>
if s.getKind == `Lean.Parser.Term.structInstArrayRef then
throwError arg "invalid {...} notation, at most one `[..]` at a given level"
else
throwError arg "invalid {...} notation, can't mix field and `[..]` at a given level"
else
match s? with
| none => pure (some arg)
| some s =>
if s.getKind == `Lean.Parser.Term.structInstArrayRef then
throwError arg "invalid {...} notation, can't mix field and `[..]` at a given level"
else
pure s?
else
throwError arg "unexpected {...} notation")
none;
match s? with
| none => pure none
| some s => if (s.getArg 0).getKind == `Lean.Parser.Term.structInstArrayRef then pure s? else pure none
private def elabModifyOp (stx modifyOp source : Syntax) (expectedType? : Option Expr) : TermElabM Expr :=
let continue (val : Syntax) : TermElabM Expr := do {
let lval := modifyOp.getArg 0;
let idx := lval.getArg 1;
let self := (source.getArg 1).getArg 0;
stxNew ← `($(self).modifyOp (idx := $idx) (fun s => $val));
withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
};
let rest := modifyOp.getArg 1;
if rest.isNone then do
continue (modifyOp.getArg 3)
else do
s ← `(s);
let valFirst := rest.getArg 0;
let valFirst := if valFirst.getKind == `Lean.Parser.Term.structInstArrayRef then valFirst else valFirst.getArg 1;
let restArgs := rest.getArgs;
let valRest := mkNullNode (restArgs.extract 1 restArgs.size);
let valField := modifyOp.setArg 0 valFirst;
let valField := valField.setArg 1 valRest;
let valSource := source.modifyArg 1 $ fun stx => stx.modifyArg 0 $ fun _ => s;
let val := stx.setArg 1 mkNullNode;
let val := val.setArg 2 $ mkNullNode #[valField, mkAtomFrom stx ", ", valSource];
continue val
/- Get structure name and elaborate explicit source (if avialable) -/
private def getStructName (stx : Syntax) (expectedType? : Option Expr) (sourceView : Source) : TermElabM Name :=
let arg := stx.getArg 1;
if !arg.isNone then do
r : List (Name × List String) ← resolveGlobalName (arg.getIdAt 0);
env ← getEnv;
let r := r.filter $ fun p => p.2.isEmpty && isStructureLike env p.1;
let candidates := r.map $ fun p => p.1;
match candidates with
| [c] => pure c
| [] => throwError arg "invalid {...} notation, structure expected"
| _ => throwError arg ("invalid {...} notation, ambiguous " ++ toString candidates)
else do
let ref := stx;
tryPostponeIfNoneOrMVar expectedType?;
let useSource : Unit → TermElabM Name := fun _ =>
match sourceView with
| Source.explicit _ src => do
srcType ← inferType stx src;
srcType ← whnf stx srcType;
tryPostponeIfMVar srcType;
match srcType.getAppFn with
| Expr.const constName _ _ => pure constName
| _ => throwError stx ("invalid {...} notation, source type is not of the form (C ...)" ++ indentExpr srcType)
| _ => throwError ref ("invalid {...} notation, expected type is not of the form (C ...)" ++ indentExpr expectedType?.get!);
match expectedType? with
| none => useSource ()
| some expectedType => do
expectedType ← whnf ref expectedType;
match expectedType.getAppFn with
| Expr.const constName _ _ => pure constName
| _ => useSource ()
inductive FieldLHS
| fieldName (ref : Syntax) (name : Name)
| fieldIndex (ref : Syntax) (idx : Nat)
| modifyOp (ref : Syntax) (index : Syntax)
instance FieldLHS.inhabited : Inhabited FieldLHS := ⟨FieldLHS.fieldName (arbitrary _) (arbitrary _)⟩
instance FieldLHS.hasFormat : HasFormat FieldLHS :=
⟨fun lhs => match lhs with
| FieldLHS.fieldName _ n => fmt n
| FieldLHS.fieldIndex _ i => fmt i
| FieldLHS.modifyOp _ i => "[" ++ i.prettyPrint ++ "]"⟩
inductive FieldVal (σ : Type)
| term {} (stx : Syntax) : FieldVal
| nested (s : σ) : FieldVal
| default {} : FieldVal -- mark that field must be synthesized using default value
structure Field (σ : Type) :=
mk {} :: (ref : Syntax) (lhs : List FieldLHS) (val : FieldVal σ) (expr? : Option Expr := none)
instance Field.inhabited {σ} : Inhabited (Field σ) := ⟨⟨arbitrary _, [], FieldVal.term (arbitrary _), arbitrary _⟩⟩
def Field.isSimple {σ} : Field σ → Bool
| { lhs := [_], .. } => true
| _ => false
inductive Struct
| mk (ref : Syntax) (structName : Name) (fields : List (Field Struct)) (source : Source)
instance Struct.inhabited : Inhabited Struct := ⟨⟨arbitrary _, arbitrary _, [], arbitrary _⟩⟩
abbrev Fields := List (Field Struct)
def Struct.ref : Struct → Syntax
| ⟨ref, _, _, _⟩ => ref
def Struct.structName : Struct → Name
| ⟨_, structName, _, _⟩ => structName
def Struct.fields : Struct → Fields
| ⟨_, _, fields, _⟩ => fields
def Struct.source : Struct → Source
| ⟨_, _, _, s⟩ => s
def formatField (formatStruct : Struct → Format) (field : Field Struct) : Format :=
Format.joinSep field.lhs " . " ++ " := " ++
match field.val with
| FieldVal.term v => v.prettyPrint
| FieldVal.nested s => formatStruct s
| FieldVal.default => "<default>"
partial def formatStruct : Struct → Format
| ⟨_, structName, fields, source⟩ =>
"{" ++ fmt structName ++ " . " ++ Format.joinSep (fields.map (formatField formatStruct)) ", " ++ fmt source ++ "}"
instance Struct.hasFormat : HasFormat Struct := ⟨formatStruct⟩
instance Struct.hasToString : HasToString Struct := ⟨toString ∘ format⟩
instance Field.hasFormat : HasFormat (Field Struct) := ⟨formatField formatStruct⟩
instance Field.hasToString : HasToString (Field Struct) := ⟨toString ∘ format⟩
/-
Recall that `structInstField` elements have the form
```
def structInstField := parser! structInstLVal >> " := " >> termParser
def structInstLVal := (ident <|> numLit <|> structInstArrayRef) >> many (("." >> (ident <|> numLit)) <|> structInstArrayRef)
def structInstArrayRef := parser! "[" >> termParser >>"]"
-/
-- Remark: this code relies on the fact that `expandStruct` only transforms `fieldLHS.fieldName`
def FieldLHS.toSyntax (first : Bool) : FieldLHS → Syntax
| FieldLHS.modifyOp stx _ => stx
| FieldLHS.fieldName stx name => if first then mkIdentFrom stx name else mkNullNode #[mkAtomFrom stx ".", mkIdentFrom stx name]
| FieldLHS.fieldIndex stx _ => if first then stx else mkNullNode #[mkAtomFrom stx ".", stx]
def FieldVal.toSyntax : FieldVal Struct → Syntax
| FieldVal.term stx => stx
| _ => unreachable!
def Field.toSyntax : Field Struct → Syntax
| field =>
let stx := field.ref;
let stx := stx.setArg 3 field.val.toSyntax;
match field.lhs with
| first::rest =>
let stx := stx.setArg 0 $ first.toSyntax true;
let stx := stx.setArg 1 $ mkNullNode $ rest.toArray.map (FieldLHS.toSyntax false);
stx
| _ => unreachable!
private def toFieldLHS (stx : Syntax) : Except String FieldLHS :=
if stx.getKind == `Lean.Parser.Term.structInstArrayRef then
pure $ FieldLHS.modifyOp stx (stx.getArg 1)
else
-- Note that the representation of the first field is different.
let stx := if stx.getKind == nullKind then stx.getArg 1 else stx;
if stx.isIdent then pure $ FieldLHS.fieldName stx stx.getId
else match stx.isFieldIdx? with
| some idx => pure $ FieldLHS.fieldIndex stx idx
| none => throw "unexpected structure syntax"
private def mkStructView (stx : Syntax) (structName : Name) (source : Source) : Except String Struct := do
let args := (stx.getArg 2).getArgs;
let fieldsStx := args.filter $ fun arg => arg.getKind == `Lean.Parser.Term.structInstField;
fields ← fieldsStx.toList.mapM $ fun fieldStx => do {
let val := fieldStx.getArg 3;
first ← toFieldLHS (fieldStx.getArg 0);
rest ← (fieldStx.getArg 1).getArgs.toList.mapM toFieldLHS;
pure $ ({ref := fieldStx, lhs := first :: rest, val := FieldVal.term val } : Field Struct)
};
pure ⟨stx, structName, fields, source⟩
def Struct.modifyFieldsM {m : Type → Type} [Monad m] (s : Struct) (f : Fields → m Fields) : m Struct :=
match s with
| ⟨ref, structName, fields, source⟩ => do fields ← f fields; pure ⟨ref, structName, fields, source⟩
@[inline] def Struct.modifyFields (s : Struct) (f : Fields → Fields) : Struct :=
Id.run $ s.modifyFieldsM f
def Struct.setFields (s : Struct) (fields : Fields) : Struct :=
s.modifyFields $ fun _ => fields
private def expandCompositeFields (s : Struct) : Struct :=
s.modifyFields $ fun fields => fields.map $ fun field => match field with
| { lhs := FieldLHS.fieldName ref (Name.str Name.anonymous _ _) :: rest, .. } => field
| { lhs := FieldLHS.fieldName ref n@(Name.str _ _ _) :: rest, .. } =>
let newEntries := n.components.map $ FieldLHS.fieldName ref;
{ lhs := newEntries ++ rest, .. field }
| _ => field
private def expandNumLitFields (s : Struct) : TermElabM Struct :=
s.modifyFieldsM $ fun fields => do
env ← getEnv;
let fieldNames := getStructureFields env s.structName;
fields.mapM $ fun field => match field with
| { lhs := FieldLHS.fieldIndex ref idx :: rest, .. } =>
if idx == 0 then throwError ref "invalid field index, index must be greater than 0"
else if idx > fieldNames.size then throwError ref ("invalid field index, structure has only #" ++ toString fieldNames.size ++ " fields")
else pure { lhs := FieldLHS.fieldName ref (fieldNames.get! $ idx - 1) :: rest, .. field }
| _ => pure field
/- For example, consider the following structures:
```
structure A := (x : Nat)
structure B extends A := (y : Nat)
structure C extends B := (z : Bool)
```
This method expands parent structure fields using the path to the parent structure.
For example,
```
{ C . x := 0, y := 0, z := true }
```
is expanded into
```
{ C . toB.toA.x := 0, toB.y := 0, z := true }
``` -/
private def expandParentFields (s : Struct) : TermElabM Struct := do
env ← getEnv;
s.modifyFieldsM $ fun fields => fields.mapM $ fun field => match field with
| { lhs := FieldLHS.fieldName ref fieldName :: rest, .. } =>
match findField? env s.structName fieldName with
| none => throwError ref ("'" ++ fieldName ++ "' is not a field of structure '" ++ s.structName ++ "'")
| some baseStructName =>
if baseStructName == s.structName then pure field
else match getPathToBaseStructure? env baseStructName s.structName with
| some path => do
let path := path.map $ fun funName => match funName with
| Name.str _ s _ => FieldLHS.fieldName ref (mkNameSimple s)
| _ => unreachable!;
pure { lhs := path ++ field.lhs, .. field }
| _ => throwError ref ("failed to access field '" ++ fieldName ++ "' in parent structure")
| _ => pure field
private abbrev FieldMap := HashMap Name Fields
private def mkFieldMap (fields : Fields) : TermElabM FieldMap :=
fields.foldlM
(fun fieldMap field =>
match field.lhs with
| FieldLHS.fieldName _ fieldName :: rest =>
match fieldMap.find? fieldName with
| some (prevField::restFields) =>
if field.isSimple || prevField.isSimple then
throwError field.ref ("field '" ++ fieldName ++ "' has already beed specified")
else
pure $ fieldMap.insert fieldName (field::prevField::restFields)
| _ => pure $ fieldMap.insert fieldName [field]
| _ => unreachable!)
{}
private def isSimpleField? : Fields → Option (Field Struct)
| [field] => if field.isSimple then some field else none
| _ => none
private def getFieldIdx (ref : Syntax) (structName : Name) (fieldNames : Array Name) (fieldName : Name) : TermElabM Nat := do
match fieldNames.findIdx? $ fun n => n == fieldName with
| some idx => pure idx
| none => throwError ref ("field '" ++ fieldName ++ "' is not a valid field of '" ++ structName ++ "'")
private def mkProjStx (s : Syntax) (fieldName : Name) : Syntax :=
Syntax.node `Lean.Parser.Term.proj #[s, mkAtomFrom s ".", mkIdentFrom s fieldName]
private def mkSubstructSource (ref : Syntax) (structName : Name) (fieldNames : Array Name) (fieldName : Name) (src : Source) : TermElabM Source :=
match src with
| Source.explicit stx src => do
idx ← getFieldIdx ref structName fieldNames fieldName;
let stx := stx.modifyArg 1 $ fun stx => stx.modifyArg 0 $ fun stx => mkProjStx stx fieldName;
pure $ Source.explicit stx (mkProj structName idx src)
| s => pure s
@[specialize] private def groupFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do
env ← getEnv;
let fieldNames := getStructureFields env s.structName;
s.modifyFieldsM $ fun fields => do
fieldMap ← mkFieldMap fields;
fieldMap.toList.mapM $ fun ⟨fieldName, fields⟩ =>
match isSimpleField? fields with
| some field => pure field
| none => do
let substructFields := fields.map $ fun field => { lhs := field.lhs.tail!, .. field };
substructSource ← mkSubstructSource s.ref s.structName fieldNames fieldName s.source;
let field := fields.head!;
match Lean.isSubobjectField? env s.structName fieldName with
| some substructName => do
let substruct := Struct.mk s.ref substructName substructFields substructSource;
substruct ← expandStruct substruct;
pure { lhs := [field.lhs.head!], val := FieldVal.nested substruct, .. field }
| none => do
-- It is not a substructure field. Thus, we wrap fields using `Syntax`, and use `elabTerm` to process them.
let valStx := s.ref; -- construct substructure syntax using s.ref as template
let valStx := valStx.setArg 1 mkNullNode; -- erase optional struct name
let args := substructFields.toArray.map $ Field.toSyntax;
let args := substructSource.addSyntax args;
let valStx := valStx.setArg 2 (mkSepStx args (mkAtomFrom s.ref ","));
pure { lhs := [field.lhs.head!], val := FieldVal.term valStx, .. field }
def findField? (fields : Fields) (fieldName : Name) : Option (Field Struct) :=
fields.find? $ fun field =>
match field.lhs with
| [FieldLHS.fieldName _ n] => n == fieldName
| _ => false
@[specialize] private def addMissingFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do
env ← getEnv;
let fieldNames := getStructureFields env s.structName;
let ref := s.ref;
fields ← fieldNames.foldlM
(fun fields fieldName => do
match findField? s.fields fieldName with
| some field => pure $ field::fields
| none =>
let addField (val : FieldVal Struct) : TermElabM Fields := do {
pure $ { ref := s.ref, lhs := [FieldLHS.fieldName s.ref fieldName], val := val } :: fields
};
match Lean.isSubobjectField? env s.structName fieldName with
| some substructName => do
substructSource ← mkSubstructSource s.ref s.structName fieldNames fieldName s.source;
let substruct := Struct.mk s.ref substructName [] substructSource;
substruct ← expandStruct substruct;
addField (FieldVal.nested substruct)
| none =>
match s.source with
| Source.none => addField FieldVal.default
| Source.implicit _ => addField (FieldVal.term (mkHole s.ref))
| Source.explicit stx _ =>
-- stx is of the form `".." >> optional termParser`
let src := (stx.getArg 1).getArg 0;
let val := mkProjStx src fieldName;
addField (FieldVal.term val))
[];
pure $ s.setFields fields.reverse
private partial def expandStruct : Struct → TermElabM Struct
| s => do
let s := expandCompositeFields s;
s ← expandNumLitFields s;
s ← expandParentFields s;
s ← groupFields expandStruct s;
addMissingFields expandStruct s
structure CtorHeaderResult :=
(ctorFn : Expr)
(ctorFnType : Expr)
(instMVars : Array MVarId := #[])
private def mkCtorHeaderAux (ref : Syntax) : Nat → Expr → Expr → Array MVarId → TermElabM CtorHeaderResult
| 0, type, ctorFn, instMVars => pure { ctorFn := ctorFn, ctorFnType := type, instMVars := instMVars }
| n+1, type, ctorFn, instMVars => do
type ← whnfForall ref type;
match type with
| Expr.forallE _ d b c =>
match c.binderInfo with
| BinderInfo.instImplicit => do
a ← mkFreshExprMVar ref d MetavarKind.synthetic;
mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) (instMVars.push a.mvarId!)
| _ => do
a ← mkFreshExprMVar ref d;
mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) instMVars
| _ => throwError ref "unexpected constructor type"
private partial def getForallBody : Nat → Expr → Option Expr
| i+1, Expr.forallE _ _ b _ => getForallBody i b
| i+1, _ => none
| 0, type => type
private def propagateExpectedType (ref : Syntax) (type : Expr) (numFields : Nat) (expectedType? : Option Expr) : TermElabM Unit :=
match expectedType? with
| none => pure ()
| some expectedType =>
match getForallBody numFields type with
| none => pure ()
| some typeBody =>
unless typeBody.hasLooseBVars $ do
_ ← isDefEq ref expectedType typeBody;
pure ()
private def mkCtorHeader (ref : Syntax) (ctorVal : ConstructorVal) (expectedType? : Option Expr) : TermElabM CtorHeaderResult := do
lvls ← ctorVal.lparams.mapM $ fun _ => mkFreshLevelMVar ref;
let val := Lean.mkConst ctorVal.name lvls;
let type := (ConstantInfo.ctorInfo ctorVal).instantiateTypeLevelParams lvls;
r ← mkCtorHeaderAux ref ctorVal.nparams type val #[];
propagateExpectedType ref r.ctorFnType ctorVal.nfields expectedType?;
synthesizeAppInstMVars ref r.instMVars;
pure r
def markDefaultMissing (e : Expr) : Expr :=
mkAnnotation `structInstDefault e
def isDefaultMissing? (e : Expr) : Option Expr :=
isAnnotation? `structInstDefault e
def throwFailedToElabField {α} (ref : Syntax) (fieldName : Name) (structName : Name) (msgData : MessageData) : TermElabM α :=
throwError ref ("failed to elaborate field '" ++ fieldName ++ "' of '" ++ structName ++ ", " ++ msgData)
private partial def elabStruct : Struct → Option Expr → TermElabM (Expr × Struct)
| s, expectedType? => do
env ← getEnv;
let ctorVal := getStructureCtor env s.structName;
{ ctorFn := ctorFn, ctorFnType := ctorFnType, .. } ← mkCtorHeader s.ref ctorVal expectedType?;
(e, _, fields) ← s.fields.foldlM
(fun (acc : Expr × Expr × Fields) field =>
let (e, type, fields) := acc;
match field.lhs with
| [FieldLHS.fieldName ref fieldName] => do
type ← whnfForall field.ref type;
match type with
| Expr.forallE _ d b c =>
let continue (val : Expr) (field : Field Struct) : TermElabM (Expr × Expr × Fields) := do {
let e := mkApp e val;
let type := b.instantiate1 val;
let field := { expr? := some val, .. field };
pure (e, type, field::fields)
};
match field.val with
| FieldVal.term stx => do val ← elabTerm stx (some d); val ← ensureHasType stx d val; continue val field
| FieldVal.nested s => do (val, sNew) ← elabStruct s (some d); val ← ensureHasType s.ref d val; continue val { val := FieldVal.nested sNew, .. field }
| FieldVal.default => do val ← mkFreshExprMVar field.ref (some d); continue (markDefaultMissing val) field
| _ => throwFailedToElabField field.ref fieldName s.structName ("unexpected constructor type" ++ indentExpr type)
| _ => throwError field.ref "unexpected unexpanded structure field")
(ctorFn, ctorFnType, []);
pure (e, s.setFields fields.reverse)
namespace DefaultFields
structure Context :=
-- We must search for default values overriden in derived structures
(structs : Array Struct := #[])
(allStructNames : Array Name := #[])
/-
Consider the following example:
```
structure A :=
(x : Nat := 1)
structure B extends A :=
(y : Nat := x + 1) (x := y + 1)
structure C extends B :=
(z : Nat := 2*y) (x := z + 3)
```
And we are trying to elaborate a structure instance for `C`. There are default values for `x` at `A`, `B`, and `C`.
We say the default value at `C` has distance 0, the one at `B` distance 1, and the one at `A` distance 2.
The field `maxDistance` specifies the maximum distance considered in a round of Default field computation.
Remark: since `C` does not set a default value of `y`, the default value at `B` is at distance 0.
The fixpoint for setting default values works in the following way.
- Keep computing default values using `maxDistance == 0`.
- We increase `maxDistance` whenever we failed to compute a new default value in a round.
- If `maxDistance > 0`, then we interrupt a round as soon as we compute some default value.
We use depth-first search.
- We sign an error if no progress is made when `maxDistance` == structure hierarchy depth (2 in the example above).
-/
(maxDistance : Nat := 0)
structure State :=
(progress : Bool := false)
partial def collectStructNames : Struct → Array Name → Array Name
| struct, names =>
let names := names.push struct.structName;
struct.fields.foldl
(fun names field =>
match field.val with
| FieldVal.nested struct => collectStructNames struct names
| _ => names)
names
partial def getHierarchyDepth : Struct → Nat
| struct =>
struct.fields.foldl
(fun max field =>
match field.val with
| FieldVal.nested struct => Nat.max max (getHierarchyDepth struct + 1)
| _ => max)
0
partial def findDefaultMissing? (mctx : MetavarContext) : Struct → Option (Field Struct)
| struct =>
struct.fields.findSome? $ fun field =>
match field.val with
| FieldVal.nested struct => findDefaultMissing? struct
| _ => match field.expr? with
| none => unreachable!
| some expr => match isDefaultMissing? expr with
| some (Expr.mvar mvarId _) => if mctx.isExprAssigned mvarId then none else some field
| _ => none
def getFieldName (field : Field Struct) : Name :=
match field.lhs with
| [FieldLHS.fieldName _ fieldName] => fieldName
| _ => unreachable!
abbrev M := ReaderT Context (StateT State TermElabM)
def isRoundDone : M Bool := do
ctx ← read;
s ← get;
pure (s.progress && ctx.maxDistance > 0)
def getFieldValue? (struct : Struct) (fieldName : Name) : Option Expr :=
struct.fields.findSome? $ fun field =>
if getFieldName field == fieldName then
field.expr?
else
none
partial def mkDefaultValueAux? (struct : Struct) : Expr → TermElabM (Option Expr)
| Expr.lam n d b c =>
let ref := struct.ref;
if c.binderInfo.isExplicit then
let fieldName := n;
match getFieldValue? struct fieldName with
| none => pure none
| some val => do
valType ← inferType ref val;
condM (isDefEq ref valType d)
(mkDefaultValueAux? (b.instantiate1 val))
(pure none)
else do
arg ← mkFreshExprMVar ref d;
mkDefaultValueAux? (b.instantiate1 arg)
| e =>
if e.isAppOfArity `id 2 then
pure (some e.appArg!)
else
pure (some e)
def mkDefaultValue? (struct : Struct) (cinfo : ConstantInfo) : TermElabM (Option Expr) := do
let ref := struct.ref;
us ← cinfo.lparams.mapM $ fun _ => mkFreshLevelMVar ref;
mkDefaultValueAux? struct (cinfo.instantiateValueLevelParams us)
/-- If `e` is a projection function of one of the given structures, then reduce it -/
def reduceProjOf? (structNames : Array Name) (e : Expr) : MetaM (Option Expr) := do
if !e.isApp then pure none
else match e.getAppFn with
| Expr.const name _ _ => do
env ← Meta.getEnv;
if env.isProjectionFn name then
match name with
| Name.str structName fieldName _ => do
if structNames.contains structName then
Meta.unfoldDefinition? e
else
pure none
| _ => pure none
else
pure none
| _ => pure none
/-- Reduce default value. It performs beta reduction and projections of the given structures. -/
partial def reduce (structNames : Array Name) : Expr → MetaM Expr
| e@(Expr.lam _ _ _ _) => Meta.lambdaTelescope e $ fun xs b => do b ← reduce b; Meta.mkLambda xs b
| e@(Expr.forallE _ _ _ _) => Meta.forallTelescope e $ fun xs b => do b ← reduce b; Meta.mkForall xs b
| e@(Expr.letE _ _ _ _ _) => Meta.lambdaTelescope e $ fun xs b => do b ← reduce b; Meta.mkLambda xs b
| e@(Expr.proj _ i b _) => do
r? ← Meta.reduceProj? b i;
match r? with
| some r => reduce r
| none => do b ← reduce b; pure $ e.updateProj! b
| e@(Expr.app f _ _) => do
r? ← reduceProjOf? structNames e;
match r? with
| some r => reduce r
| none => do
let f := f.getAppFn;
f' ← reduce f;
if f'.isLambda then
let revArgs := e.getAppRevArgs;
reduce $ f'.betaRev revArgs
else do
args ← e.getAppArgs.mapM reduce;
pure (mkAppN f' args)
| e@(Expr.mdata _ b _) => do
b ← reduce b;
if (isDefaultMissing? e).isSome && !b.isMVar then
pure b
else
pure $ e.updateMData! b
| e@(Expr.mvar mvarId _) => do
val? ← Meta.getExprMVarAssignment? mvarId;
match val? with
| some val => if val.isMVar then reduce val else pure val
| none => pure e
| e => pure e
partial def tryToSynthesizeDefaultAux (ref : Syntax) (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat)
(fieldName : Name) (mvarId : MVarId) : Nat → Nat → TermElabM Bool
| i, dist =>
if dist > maxDistance then pure false
else if h : i < structs.size then do
let struct := structs.get ⟨i, h⟩;
let defaultName := struct.structName ++ fieldName ++ `_default;
env ← getEnv;
match env.find? defaultName with
| some cinfo@(ConstantInfo.defnInfo defVal) => do
mctx ← getMCtx;
val? ← mkDefaultValue? struct cinfo;
match val? with
| none => do setMCtx mctx; tryToSynthesizeDefaultAux (i+1) (dist+1)
| some val => do
val ← liftMetaM struct.ref $ reduce allStructNames val;
match val.find? $ fun e => (isDefaultMissing? e).isSome with
| some _ => do setMCtx mctx; tryToSynthesizeDefaultAux (i+1) (dist+1)
| none => do
mvarDecl ← getMVarDecl mvarId;
val ← ensureHasType ref mvarDecl.type val;
assignExprMVar mvarId val;
pure true
| _ => tryToSynthesizeDefaultAux (i+1) dist
else
pure false
def tryToSynthesizeDefault (ref : Syntax) (structs : Array Struct) (allStructNames : Array Name)
(maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : TermElabM Bool :=
tryToSynthesizeDefaultAux ref structs allStructNames maxDistance fieldName mvarId 0 0
partial def step : Struct → M Unit
| struct => unlessM isRoundDone $ adaptReader (fun (ctx : Context) => { structs := ctx.structs.push struct, .. ctx }) $ do
struct.fields.forM $ fun field =>
match field.val with
| FieldVal.nested struct => step struct
| _ => match field.expr? with
| none => unreachable!
| some expr => match isDefaultMissing? expr with
| some (Expr.mvar mvarId _) =>
unlessM (liftM $ isExprMVarAssigned mvarId) $ do
ctx ← read;
whenM (liftM $ tryToSynthesizeDefault field.ref ctx.structs ctx.allStructNames ctx.maxDistance (getFieldName field) mvarId) $ do
modify $ fun s => { progress := true, .. s }
| _ => pure ()
partial def propagateLoop (hierarchyDepth : Nat) : Nat → Struct → M Unit
| d, struct => do
mctx ← liftM $ getMCtx;
match findDefaultMissing? mctx struct with
| none => pure () -- Done
| some field =>
if d > hierarchyDepth then
liftM $ throwError field.ref ("field '" ++ getFieldName field ++ "' is missing")
else adaptReader (fun (ctx : Context) => { maxDistance := d, .. ctx }) $ do
modify $ fun (s : State) => { progress := false, .. s};
step struct;
s ← get;
if s.progress then do
propagateLoop 0 struct
else
propagateLoop (d+1) struct
def propagate (struct : Struct) : TermElabM Unit :=
let hierarchyDepth := getHierarchyDepth struct;
let structNames := collectStructNames struct #[];
(propagateLoop hierarchyDepth 0 struct { allStructNames := structNames }).run' {}
end DefaultFields
private def elabStructInstAux (stx : Syntax) (expectedType? : Option Expr) (source : Source) : TermElabM Expr := do
structName ← getStructName stx expectedType? source;
env ← getEnv;
unless (isStructureLike env structName) $
throwError stx ("invalid {...} notation, '" ++ structName ++ "' is not a structure");
match mkStructView stx structName source with
| Except.error ex => throwError stx ex
| Except.ok struct => do
struct ← expandStruct struct;
trace `Elab.struct stx $ fun _ => toString struct;
(r, struct) ← elabStruct struct expectedType?;
DefaultFields.propagate struct;
pure r
@[builtinTermElab structInst] def elabStructInst : TermElab :=
fun stx expectedType? => do
stxNew? ← expandNonAtomicExplicitSource stx;
match stxNew? with
| some stxNew => withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
| none => do
sourceView ← getStructSource stx;
modifyOp? ← isModifyOp? stx;
match modifyOp?, sourceView with
| some modifyOp, Source.explicit source _ => elabModifyOp stx modifyOp source expectedType?
| some _, _ => throwError stx ("invalid {...} notation, explicit source is required when using '[<index>] := <value>'")
| _, _ => elabStructInstAux stx expectedType? sourceView
end StructInst
end Term
end Elab
end Lean
|
fd44741cd5d0c016b92828c773b2665faa6714aa | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/andCasesOnBug.lean | cd7f6ab7fcd866cfd6e169decb761781b1967093 | [
"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 | 773 | lean | inductive FinInt: Nat → Type :=
| nil: FinInt 0
| next: Bool → FinInt n → FinInt (n+1)
deriving DecidableEq
def zero (sz: Nat): FinInt sz :=
match sz with
| 0 => .nil
| sz+1 => .next false (zero sz)
inductive Pair :=
| mk (sz: Nat) (lhs rhs: FinInt sz)
def makePair?: (n m: (sz: Nat) × FinInt sz) → Option Pair
| ⟨sz, lhs⟩, ⟨sz', rhs⟩ =>
if EQ: true /\ sz = sz' then
have rhs' : FinInt sz := by {
cases EQ;
case intro left right =>
simp [right];
exact rhs;
};
some (Pair.mk sz lhs rhs')
else none
def usePair: Pair → Bool := fun ⟨sz, lhs, rhs⟩ => lhs = rhs
#eval (makePair? ⟨8, zero 8⟩ ⟨8, zero 8⟩).map usePair
|
e9bbfa6cce1f8b026ff3b3dc09aa28d33fad04f5 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/group_theory/sylow.lean | b7a94608224d110129e604cc864207416071d7f6 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,054 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import group_theory.p_group
/-!
# Sylow theorems
The Sylow theorems are the following results for every finite group `G` and every prime number `p`.
* There exists a Sylow `p`-subgroup of `G`.
* All Sylow `p`-subgroups of `G` are conjugate to each other.
* Let `nₚ` be the number of Sylow `p`-subgroups of `G`, then `nₚ` divides the index of the Sylow
`p`-subgroup, `nₚ ≡ 1 [MOD p]`, and `nₚ` is equal to the index of the normalizer of the Sylow
`p`-subgroup in `G`.
In this file, currently only the first of these results is proven.
## Main statements
* `exists_subgroup_card_pow_prime`: A generalisation of the first of the Sylow theorems: For every
prime power `pⁿ` dividing `G`, there exists a subgroup of `G` of order `pⁿ`.
## TODO
* Prove the second and third of the Sylow theorems.
* Sylow theorems for infinite groups
-/
open equiv fintype finset mul_action function
open equiv.perm subgroup list quotient_group
open_locale big_operators
universes u v w
variables {G : Type u} {α : Type v} {β : Type w} [group G]
local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable
lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G)
(t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) =
fintype.card s * fintype.card t :=
by rw [← fintype.card_prod, fintype.card_congr
(preimage_mk_equiv_subgroup_times_set _ _)]
namespace sylow
open subgroup submonoid mul_action
lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G}
[fintype ((H : set G) : Type u)] {x : G} :
(x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H :=
⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x,
from λ _, ((mem_fixed_points' _).1 hx _),
(inv_mem_iff _).1 (@mem_normalizer_fintype _ _ _ _inst_2 _ (λ n (hn : n ∈ H),
have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)),
show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv}
)),
λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H),
(mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2
(let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in
have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂,
(inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (H.inv_mem hb₁)).1
$ by rw hx at hb₂;
simpa [mul_inv_rev, mul_assoc] using hb₂)⟩
def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [fintype (H : set G)] :
mul_action.fixed_points H (quotient H) ≃
quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) :=
@subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _)
(λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ _inst_2 _).symm)
(by intros; refl)
/-- If `H` is a `p`-subgroup of `G`, then the index of `H` inside its normalizer is congruent
mod `p` to the index of `H`. -/
lemma card_quotient_normalizer_modeq_card_quotient [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
{H : subgroup G} (hH : fintype.card H = p ^ n) :
card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H))
≡ card (quotient H) [MOD p] :=
begin
rw [← fintype.card_congr (fixed_points_mul_left_cosets_equiv_quotient H)],
exact (card_modeq_card_fixed_points _ (is_p_group.of_card hH)).symm
end
/-- If `H` is a subgroup of `G` of cardinality `p ^ n`, then the cardinality of the
normalizer of `H` is congruent mod `p ^ (n + 1)` to the cardinality of `G`. -/
lemma card_normalizer_modeq_card [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
{H : subgroup G} (hH : fintype.card H = p ^ n) :
card (normalizer H) ≡ card G [MOD p ^ (n + 1)] :=
have subgroup.comap ((normalizer H).subtype : normalizer H →* G) H ≃ H,
from set.bij_on.equiv (normalizer H).subtype
⟨λ _, id, λ _ _ _ _ h, subtype.val_injective h,
λ x hx, ⟨⟨x, le_normalizer hx⟩, hx, rfl⟩⟩,
begin
rw [card_eq_card_quotient_mul_card_subgroup H,
card_eq_card_quotient_mul_card_subgroup
(subgroup.comap ((normalizer H).subtype : normalizer H →* G) H),
fintype.card_congr this, hH, pow_succ],
exact (card_quotient_normalizer_modeq_card_quotient hH).mul_right' _
end
/-- If `H` is a `p`-subgroup but not a Sylow `p`-subgroup, then `p` divides the
index of `H` inside its normalizer. -/
lemma prime_dvd_card_quotient_normalizer [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
(hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) :
p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) :=
let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in
have hcard : card (quotient H) = s * p :=
(nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2
⟨⟨1, H.one_mem⟩⟩)).1
(by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH, hs,
pow_succ', mul_assoc, mul_comm p]),
have hm : s * p % p =
card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p :=
hcard ▸ (card_quotient_normalizer_modeq_card_quotient hH).symm,
nat.dvd_of_mod_eq_zero
(by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm)
/-- If `H` is a `p`-subgroup but not a Sylow `p`-subgroup of cardinality `p ^ n`,
then `p ^ (n + 1)` divides the cardinality of the normalizer of `H`. -/
lemma prime_pow_dvd_card_normalizer [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
(hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) :
p ^ (n + 1) ∣ card (normalizer H) :=
nat.modeq_zero_iff_dvd.1 ((card_normalizer_modeq_card hH).trans
hdvd.modeq_zero_nat)
/-- If `H` is a subgroup of `G` of cardinality `p ^ n`,
then `H` is contained in a subgroup of cardinality `p ^ (n + 1)`
if `p ^ (n + 1)` divides the cardinality of `G` -/
theorem exists_subgroup_card_pow_succ [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
(hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) :
∃ K : subgroup G, fintype.card K = p ^ (n + 1) ∧ H ≤ K :=
let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in
have hcard : card (quotient H) = s * p :=
(nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2
⟨⟨1, H.one_mem⟩⟩)).1
(by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH, hs,
pow_succ', mul_assoc, mul_comm p]),
have hm : s * p % p =
card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p :=
card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸
@card_modeq_card_fixed_points p _ _ _ _ _ _ (is_p_group.of_card hH) hp,
have hm' : p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) :=
nat.dvd_of_mod_eq_zero
(by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm),
let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.quotient.group _) _ _ hp hm' in
have hequiv : H ≃ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) :=
⟨λ a, ⟨⟨a.1, le_normalizer a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩,
λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩,
⟨subgroup.map ((normalizer H).subtype) (subgroup.comap
(quotient_group.mk' (comap H.normalizer.subtype H)) (gpowers x)),
begin
show card ↥(map H.normalizer.subtype
(comap (mk' (comap H.normalizer.subtype H)) (subgroup.gpowers x))) = p ^ (n + 1),
suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (comap H.normalizer.subtype H))
(gpowers x)) : set (↥(H.normalizer)))) = p^(n+1),
{ convert this using 2 },
rw [set.card_image_of_injective
(subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x) : set (H.normalizer))
subtype.val_injective,
pow_succ', ← hH, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers,
← fintype.card_prod],
exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _)
end,
begin
assume y hy,
simp only [exists_prop, subgroup.coe_subtype, mk'_apply, subgroup.mem_map, subgroup.mem_comap],
refine ⟨⟨y, le_normalizer hy⟩, ⟨0, _⟩, rfl⟩,
rw [gpow_zero, eq_comm, quotient_group.eq_one_iff],
simpa using hy
end⟩
/-- If `H` is a subgroup of `G` of cardinality `p ^ n`,
then `H` is contained in a subgroup of cardinality `p ^ m`
if `n ≤ m` and `p ^ m` divides the cardinality of `G` -/
theorem exists_subgroup_card_pow_prime_le [fintype G] (p : ℕ) : ∀ {n m : ℕ} [hp : fact p.prime]
(hdvd : p ^ m ∣ card G) (H : subgroup G) (hH : card H = p ^ n) (hnm : n ≤ m),
∃ K : subgroup G, card K = p ^ m ∧ H ≤ K
| n m := λ hp hdvd H hH hnm,
(lt_or_eq_of_le hnm).elim
(λ hnm : n < m,
have h0m : 0 < m, from (lt_of_le_of_lt n.zero_le hnm),
have wf : m - 1 < m, from nat.sub_lt h0m zero_lt_one,
have hnm1 : n ≤ m - 1, from nat.le_sub_right_of_add_le hnm,
let ⟨K, hK⟩ := @exists_subgroup_card_pow_prime_le n (m - 1) hp
(nat.pow_dvd_of_le_of_pow_dvd (nat.sub_le_self _ _) hdvd) H hH hnm1 in
have hdvd' : p ^ ((m - 1) + 1) ∣ card G, by rwa [nat.sub_add_cancel h0m],
let ⟨K', hK'⟩ := @exists_subgroup_card_pow_succ _ _ _ _ _ hp hdvd' K hK.1 in
⟨K', by rw [hK'.1, nat.sub_add_cancel h0m], le_trans hK.2 hK'.2⟩)
(λ hnm : n = m, ⟨H, by simp [hH, hnm]⟩)
/-- A generalisation of **Sylow's first theorem**. If `p ^ n` divides
the cardinality of `G`, then there is a subgroup of cardinality `p ^ n` -/
theorem exists_subgroup_card_pow_prime [fintype G] (p : ℕ) {n : ℕ} [fact p.prime]
(hdvd : p ^ n ∣ card G) : ∃ K : subgroup G, fintype.card K = p ^ n :=
let ⟨K, hK⟩ := exists_subgroup_card_pow_prime_le p hdvd ⊥ (by simp) n.zero_le in
⟨K, hK.1⟩
end sylow
|
55126d4562d1c96de901a154bf61d85cf39ed161 | 5c7fe6c4a9d4079b5457ffa5f061797d42a1cd65 | /src/exercises/src_35_algebraic_axioms.lean | 492011e6cbeef81a653863dfc72c2217b9d568cd | [] | no_license | gihanmarasingha/mth1001_tutorial | 8e0817feeb96e7c1bb3bac49b63e3c9a3a329061 | bb277eebd5013766e1418365b91416b406275130 | refs/heads/master | 1,675,008,746,310 | 1,607,993,443,000 | 1,607,993,443,000 | 321,511,270 | 3 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,692 | lean | import ..library.src_field
import tactic
namespace mth1001
namespace myreal
section grouplaws
variables {R : Type} [comm_group R]
lemma add_comm (x y : R) : x + y = y + x := comm_group.add_comm x y
lemma add_assoc (x y z : R) : (x + y) + z = x + (y + z) := comm_group.add_assoc x y z
lemma add_zero (x : R) : x + 0 = x := comm_group.add_zero x
lemma zero_add (x : R) : 0 + x = x := by {rw [add_comm, add_zero]}
lemma add_neg (x : R) : x + (-x) = 0 := comm_group.add_inv x
lemma neg_add (x : R) : (-x) + x = 0 := by {rw [add_comm, add_neg]}
def add_identity (u : R) := ∀ x : R, (x + u = x) ∧ (u + x = x)
example : add_identity (0 : R) :=
begin
intro x,
exact and.intro (add_zero x) (zero_add x),
end
lemma has_add_inverse : ∀ a : R, ∃ b : R, (a + b = 0) ∧ (b + a = 0) :=
begin
intro a,
use (-a),
exact and.intro (add_neg a) (neg_add a)
end
theorem add_identity_unique {a b : R} (h₁ : add_identity a) (h₂ : add_identity b)
: a = b :=
begin
specialize h₁ b, -- `h₁ : (b + a = b) ∧ (a + b = b)`
specialize h₂ a, -- `h₂ : (a + b = a) ∧ (b + a = a)`
calc a = a + b : h₂.left.symm -- If `h : x = y`, then `h.symm : y = x`.
... = b : h₁.right
end
def add_inverse (y x : R) := (x + y = 0) ∧ (y + x = 0)
theorem add_inverse_unique {a b x : R} (h₁ : add_inverse a x) (h₂ : add_inverse b x)
: a = b :=
calc a = a + 0 : (add_zero a).symm
... = a + (x + b) : by rw h₂.left
... = (a + x) + b : by rw add_assoc
... = 0 + b : by rw h₁.right
... = b : zero_add b
-- Exercise 146:
lemma add_left_eq_self_mp {x a : R} : x + a = a → x = 0 :=
begin
sorry
end
-- Exercise 147:
lemma add_left_eq_self_mpr {x a : R} : x = 0 → x + a = a :=
begin
sorry
end
-- Exercise 148:
-- You can prove the following in one line using the above two results.
theorem add_left_eq_self (x a : R) : x + a = a ↔ x = 0:=
sorry
-- Exercise 149:
theorem add_left_inj (x a b : R) : a + x = b + x ↔ a = b :=
begin
sorry
end
lemma sub_eq_add_neg (x y : R) : x - y = x + (-y) := rfl
-- Exercise 150:
-- You can do the following with two rewrites. Use `add_zero` and `neg_add`
lemma neg_zero : -(0 : R) = 0 :=
sorry
-- Exercise 151:
lemma sub_zero (a : R) : a - 0 = a :=
sorry
-- Exercise 152:
-- The following can be proved in one line as a sequences of rewrites.
theorem sub_eq_zero_iff_eq (x y : R) : x - y = 0 ↔ x = y :=
sorry
-- Exercise 153:
-- The following can be proved in one line as a sequences of rewrites.
theorem neg_neg (x : R) : - - x = x :=
sorry
-- Exercise 154:
-- Do the following using proof by calculation.
lemma neg_add_eq_neg_add_neg (x y : R) : -(x + y) = -y + - x :=
sorry
end grouplaws
section fieldlaws
variables {R : Type} [myfield R]
lemma mul_comm (x y : R) : x * y = y * x := myfield.mul_comm x y
lemma mul_assoc (x y z : R) : (x * y) * z = x * (y * z) := myfield.mul_assoc x y z
lemma mul_one (x : R) : x * 1 = x := myfield.mul_one x
lemma one_mul (x : R) : 1 * x = x := by { rw [mul_comm, mul_one] }
lemma mul_inv (x : R) : x ≠ 0 → x * x⁻¹ = 1 := myfield.mul_inv x
lemma inv_mul (x : R) : x ≠ 0 → x⁻¹ * x = 1 := by {intro h, rw [mul_comm, mul_inv x h], }
lemma mul_add (x y z : R) : x * (y + z) = x * y + x * z := myfield.mul_add x y z
lemma zero_ne_one : (0 : R) ≠ (1 : R) := myfield.zero_ne_one
def mul_identity (u : R) := ∀ x : R, (x * u = x) ∧ (u * x = x)
-- Exercise 155:
-- Use `add_mul` and `add_comm` to prove the following.
theorem add_mul (x y z : R) : (x + y) * z = x * z + y * z :=
begin
sorry
end
-- Exercise 156:
theorem mul_identity_unique {a b : R} (h₁ : mul_identity a) (h₂ : mul_identity b)
: a = b :=
begin
sorry
end
def mul_inverse (y x : R) := (x * y = 1) ∧ (y * x = 1)
-- Exercise 157:
theorem mul_inverse_unique {a b x : R} (h₁ : mul_inverse a x) (h₂ : mul_inverse b x)
: a = b :=
sorry
-- Exercise 158:
-- This exercise is somewhat challenging.
theorem mul_zero {x : R} : x * (0 : R) = (0 : R) :=
begin
have h₁ : x * 0 = x * 0 + x * 0,
calc x * 0
= x * (0 + 0) : by rw add_zero (0 : R)
... = x * 0 + x * 0 : by rw mul_add,
sorry
end
-- Exercise 159:
-- Whereas the next result is a simple consequence of the previous result.
theorem zero_mul {x : R} : (0 : R) * x = (0 : R) :=
begin
sorry
end
-- Exercise 160:
theorem neg_one_mul (x : R) : (-1) * x = -x :=
begin
sorry
end
-- Exercise 161:
-- Use the result above to prove this lemma.
lemma neg_one_mul_neg_one : (-(1 : R)) * (-1) = 1 :=
sorry
-- Exercise 162:
lemma neg_mul_eq_mul_neg (x y : R) : -(x * y) = x * (-y) :=
sorry
lemma neg_mul_neg_self (x : R) : (-x)*(-x) = x * x :=
by rw [←neg_one_mul, mul_assoc, mul_comm x _, ←mul_assoc, ←mul_assoc, neg_one_mul_neg_one, one_mul]
-- Exercise 163:
lemma neg_mul_neg (x y : R) : (-x) * (-y) = x * y :=
begin
sorry
end
-- Exercise 164:
lemma one_inv : (1 : R)⁻¹ = (1 : R) :=
sorry
-- Exercise 165:
theorem mul_sub (x y z : R) : x * (y - z) = x * y - x * z :=
begin
sorry
end
-- Exercise 166:
theorem mul_left_inj' (x a b : R) (h₁ : x ≠ 0): a * x = b * x ↔ a = b :=
begin
sorry
end
open_locale classical
-- Exercise 167:
-- This is a challenging exercise.
-- Hint 1. Do a `by_cases` proof, depending on whether `x = 0` or not.
-- Hint 2. Use the fact that a non-zero real number has a multiplicative inverse.
lemma eq_zero_of_not_eq_zero_of_mul_not_eq_zero (x b : R) (h₁ : b ≠ 0) (h₂ : x * b = 0) : x = 0 :=
begin
sorry
end
-- Exercise 168:
-- The following is a corollary of the result above.
lemma eq_zero_or_eq_zero_of_mul_eq_zero (x y : R) (h : x * y = 0) : x = 0 ∨ y = 0 :=
begin
sorry
end
-- Exercise 169:
lemma mul_inv' (x y : R) (h₁ : x ≠ 0) (h₂ : y ≠ 0) : (x * y)⁻¹ = y⁻¹ * x⁻¹ :=
begin
have h : x * y ≠ 0,
{ sorry, },
rw ←(mul_left_inj' _ _ _ h₁),
sorry
end
-- Exercise 170:
theorem inv_ne_zero {a : R} : a ≠ 0 → a⁻¹ ≠ 0 :=
begin
sorry
end
-- Exercise 171:
theorem inv_inv' (a : R) (h : a ≠ 0 ) : (a⁻¹)⁻¹ = a :=
begin
sorry end
end fieldlaws
section powers
variables {R : Type} [myfield R]
def pow1 : R → ℕ → R
| x 0 := (1 : R)
| x (nat.succ n) := (pow1 x n) * x -- `nat.succ` is the Lean version of our function `S`
-- Exercise 172:
example (x : R) : pow1 x 2 = x * x :=
begin
sorry end
-- Exercise 173:
-- Prove the following by induction on `n`.
theorem pow_ne_zero (x : R) (n : ℕ) (h : x ≠ 0) : pow1 x n ≠ 0 :=
begin
sorry
end
-- Exercise 174:
-- Use induction. Make use of `nat.add_zero`.
theorem pow1_add (x : R) (m n : ℕ) : pow1 x (m + n) = (pow1 x m) * (pow1 x n) :=
begin
sorry
end
-- Exercise 175:
-- Use induction. Make use of `nat.mul_zero`, `nat.succ_eq_add_one`, and `nat.mul_one`.begin
-- You'll need `left_distrib`, a synonym of `mul_add` for `ℕ`.
theorem pow1_mul (x : R) (m n : ℕ) : pow1 x (m*n) = pow1 (pow1 x m) n :=
begin
sorry
end
lemma sub_succ_eq_pred_sub_of_le (b k : ℕ) : nat.succ k ≤ b → (b-(nat.succ k)) = (b - 1) - k :=
begin
induction k with m hm,
{ rw nat.sub_zero, intro h, refl, },
{ intro h,
exact (nat.pred_sub b (nat.succ m)).symm, },
end
-- Exercise 176:
-- The exercise below is very hard. Use the result above together with any other appropriate
-- results concerning the natural numbers from mathlib.
theorem pow1_sub (x : R) (h₁ : x ≠ 0) (n : ℕ) :
∀ m : ℕ, n ≤ m → pow1 x (m - n) = (pow1 x m) * (pow1 x n)⁻¹ :=
begin
sorry
end
def pow2 (x : R) (m : ℤ) := ite (m ≥ 0) (pow1 x (int.to_nat m)) (pow1 x (int.to_nat (-m)))
end powers
end myreal
end mth1001
|
50902e82e75798c3368455e3f59545115f591b1b | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/category_theory/instances/rel.lean | 63db8961fc97b08dec23273486d741b3eccfc8db | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 354 | lean | import category_theory.category
namespace category_theory
universe u
-- We must work in `Type u` rather than `Sort u`, because
-- `X → Y → Prop` is in `Sort (max u 1)`.
def rel : large_category (Type u) :=
{ hom := λ X Y, X → Y → Prop,
id := λ X, λ x y, x = y,
comp := λ X Y Z f g x z, ∃ y, f x y ∧ g y z }
end category_theory
|
b81a11b28eb23d878dcc09511bc7ef2f10ae9827 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/calculus/extend_deriv.lean | a80b6895a99a205f23ecfd622833fda54f825c61 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 11,600 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.calculus.mean_value
/-!
# Extending differentiability to the boundary
We investigate how differentiable functions inside a set extend to differentiable functions
on the boundary. For this, it suffices that the function and its derivative admit limits there.
A general version of this statement is given in `has_fderiv_at_boundary_of_tendsto_fderiv`.
One-dimensional versions, in which one wants to obtain differentiability at the left endpoint or
the right endpoint of an interval, are given in
`has_deriv_at_interval_left_endpoint_of_tendsto_deriv` and
`has_deriv_at_interval_right_endpoint_of_tendsto_deriv`. These versions are formulated in terms
of the one-dimensional derivative `deriv ℝ f`.
-/
variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E]
{F : Type*} [normed_add_comm_group F] [normed_space ℝ F]
open filter set metric continuous_linear_map
open_locale topology
local attribute [mono] prod_mono
/-- If a function `f` is differentiable in a convex open set and continuous on its closure, and its
derivative converges to a limit `f'` at a point on the boundary, then `f` is differentiable there
with derivative `f'`. -/
theorem has_fderiv_at_boundary_of_tendsto_fderiv {f : E → F} {s : set E} {x : E} {f' : E →L[ℝ] F}
(f_diff : differentiable_on ℝ f s) (s_conv : convex ℝ s) (s_open : is_open s)
(f_cont : ∀y ∈ closure s, continuous_within_at f s y)
(h : tendsto (λy, fderiv ℝ f y) (𝓝[s] x) (𝓝 f')) :
has_fderiv_within_at f f' (closure s) x :=
begin
classical,
-- one can assume without loss of generality that `x` belongs to the closure of `s`, as the
-- statement is empty otherwise
by_cases hx : x ∉ closure s,
{ rw ← closure_closure at hx, exact has_fderiv_within_at_of_not_mem_closure hx },
push_neg at hx,
rw [has_fderiv_within_at, has_fderiv_at_filter, asymptotics.is_o_iff],
/- One needs to show that `‖f y - f x - f' (y - x)‖ ≤ ε ‖y - x‖` for `y` close to `x` in `closure
s`, where `ε` is an arbitrary positive constant. By continuity of the functions, it suffices to
prove this for nearby points inside `s`. In a neighborhood of `x`, the derivative of `f` is
arbitrarily close to `f'` by assumption. The mean value inequality completes the proof. -/
assume ε ε_pos,
obtain ⟨δ, δ_pos, hδ⟩ : ∃ δ > 0, ∀ y ∈ s, dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε,
by simpa [dist_zero_right] using tendsto_nhds_within_nhds.1 h ε ε_pos,
set B := ball x δ,
suffices : ∀ y ∈ B ∩ (closure s), ‖f y - f x - (f' y - f' x)‖ ≤ ε * ‖y - x‖,
from mem_nhds_within_iff.2 ⟨δ, δ_pos, λy hy, by simpa using this y hy⟩,
suffices : ∀ p : E × E, p ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) → ‖f p.2 - f p.1 - (f' p.2 - f' p.1)‖
≤ ε * ‖p.2 - p.1‖,
{ rw closure_prod_eq at this,
intros y y_in,
apply this ⟨x, y⟩,
have : B ∩ closure s ⊆ closure (B ∩ s), from is_open_ball.inter_closure,
exact ⟨this ⟨mem_ball_self δ_pos, hx⟩, this y_in⟩ },
have key : ∀ p : E × E, p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.2 - f p.1 - (f' p.2 - f' p.1)‖
≤ ε * ‖p.2 - p.1‖,
{ rintros ⟨u, v⟩ ⟨u_in, v_in⟩,
have conv : convex ℝ (B ∩ s) := (convex_ball _ _).inter s_conv,
have diff : differentiable_on ℝ f (B ∩ s) := f_diff.mono (inter_subset_right _ _),
have bound : ∀ z ∈ (B ∩ s), ‖fderiv_within ℝ f (B ∩ s) z - f'‖ ≤ ε,
{ intros z z_in,
convert le_of_lt (hδ _ z_in.2 z_in.1),
have op : is_open (B ∩ s) := is_open_ball.inter s_open,
rw differentiable_at.fderiv_within _ (op.unique_diff_on z z_in),
exact (diff z z_in).differentiable_at (is_open.mem_nhds op z_in) },
simpa using conv.norm_image_sub_le_of_norm_fderiv_within_le' diff bound u_in v_in },
rintros ⟨u, v⟩ uv_in,
refine continuous_within_at.closure_le uv_in _ _ key,
have f_cont' : ∀y ∈ closure s, continuous_within_at (f - f') s y,
{ intros y y_in,
exact tendsto.sub (f_cont y y_in) (f'.cont.continuous_within_at) },
all_goals { -- common start for both continuity proofs
have : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s, by mono ; exact inter_subset_right _ _,
obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s,
by simpa [closure_prod_eq] using closure_mono this uv_in,
apply continuous_within_at.mono _ this,
simp only [continuous_within_at] },
rw nhds_within_prod_eq,
{ have : ∀ u v, f v - f u - (f' v - f' u) = f v - f' v - (f u - f' u) := by { intros, abel },
simp only [this],
exact tendsto.comp continuous_norm.continuous_at
((tendsto.comp (f_cont' v v_in) tendsto_snd).sub $
tendsto.comp (f_cont' u u_in) tendsto_fst) },
{ apply tendsto_nhds_within_of_tendsto_nhds,
rw nhds_prod_eq,
exact tendsto_const_nhds.mul
(tendsto.comp continuous_norm.continuous_at $ tendsto_snd.sub tendsto_fst) },
end
/-- If a function is differentiable on the right of a point `a : ℝ`, continuous at `a`, and
its derivative also converges at `a`, then `f` is differentiable on the right at `a`. -/
lemma has_deriv_at_interval_left_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E}
(f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a)
(hs : s ∈ 𝓝[>] a)
(f_lim' : tendsto (λx, deriv f x) (𝓝[>] a) (𝓝 e)) :
has_deriv_within_at f e (Ici a) a :=
begin
/- This is a specialization of `has_fderiv_at_boundary_of_tendsto_fderiv`. To be in the setting of
this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we
call `t = (a, b)`. Then, we check all the assumptions of this theorem and we apply it. -/
obtain ⟨b, ab : a < b, sab : Ioc a b ⊆ s⟩ :=
mem_nhds_within_Ioi_iff_exists_Ioc_subset.1 hs,
let t := Ioo a b,
have ts : t ⊆ s := subset.trans Ioo_subset_Ioc_self sab,
have t_diff : differentiable_on ℝ f t := f_diff.mono ts,
have t_conv : convex ℝ t := convex_Ioo a b,
have t_open : is_open t := is_open_Ioo,
have t_closure : closure t = Icc a b := closure_Ioo ab.ne,
have t_cont : ∀y ∈ closure t, continuous_within_at f t y,
{ rw t_closure,
assume y hy,
by_cases h : y = a,
{ rw h, exact f_lim.mono ts },
{ have : y ∈ s := sab ⟨lt_of_le_of_ne hy.1 (ne.symm h), hy.2⟩,
exact (f_diff.continuous_on y this).mono ts } },
have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)),
{ simp only [deriv_fderiv.symm],
exact tendsto.comp
(is_bounded_bilinear_map_smul_right : is_bounded_bilinear_map ℝ _)
.continuous_right.continuous_at
(tendsto_nhds_within_mono_left Ioo_subset_Ioi_self f_lim'), },
-- now we can apply `has_fderiv_at_boundary_of_differentiable`
have : has_deriv_within_at f e (Icc a b) a,
{ rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure],
exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' },
exact this.nhds_within (Icc_mem_nhds_within_Ici $ left_mem_Ico.2 ab)
end
/-- If a function is differentiable on the left of a point `a : ℝ`, continuous at `a`, and
its derivative also converges at `a`, then `f` is differentiable on the left at `a`. -/
lemma has_deriv_at_interval_right_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E}
(f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a)
(hs : s ∈ 𝓝[<] a)
(f_lim' : tendsto (λx, deriv f x) (𝓝[<] a) (𝓝 e)) :
has_deriv_within_at f e (Iic a) a :=
begin
/- This is a specialization of `has_fderiv_at_boundary_of_differentiable`. To be in the setting of
this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we
call `t = (b, a)`. Then, we check all the assumptions of this theorem and we apply it. -/
obtain ⟨b, ba, sab⟩ : ∃ b ∈ Iio a, Ico b a ⊆ s :=
mem_nhds_within_Iio_iff_exists_Ico_subset.1 hs,
let t := Ioo b a,
have ts : t ⊆ s := subset.trans Ioo_subset_Ico_self sab,
have t_diff : differentiable_on ℝ f t := f_diff.mono ts,
have t_conv : convex ℝ t := convex_Ioo b a,
have t_open : is_open t := is_open_Ioo,
have t_closure : closure t = Icc b a := closure_Ioo (ne_of_lt ba),
have t_cont : ∀y ∈ closure t, continuous_within_at f t y,
{ rw t_closure,
assume y hy,
by_cases h : y = a,
{ rw h, exact f_lim.mono ts },
{ have : y ∈ s := sab ⟨hy.1, lt_of_le_of_ne hy.2 h⟩,
exact (f_diff.continuous_on y this).mono ts } },
have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)),
{ simp only [deriv_fderiv.symm],
exact tendsto.comp
(is_bounded_bilinear_map_smul_right : is_bounded_bilinear_map ℝ _)
.continuous_right.continuous_at
(tendsto_nhds_within_mono_left Ioo_subset_Iio_self f_lim'), },
-- now we can apply `has_fderiv_at_boundary_of_differentiable`
have : has_deriv_within_at f e (Icc b a) a,
{ rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure],
exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' },
exact this.nhds_within (Icc_mem_nhds_within_Iic $ right_mem_Ioc.2 ba)
end
/-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are
continuous at this point, then `g` is also the derivative of `f` at this point. -/
lemma has_deriv_at_of_has_deriv_at_of_ne {f g : ℝ → E} {x : ℝ}
(f_diff : ∀ y ≠ x, has_deriv_at f (g y) y)
(hf : continuous_at f x) (hg : continuous_at g x) :
has_deriv_at f (g x) x :=
begin
have A : has_deriv_within_at f (g x) (Ici x) x,
{ have diff : differentiable_on ℝ f (Ioi x) :=
λy hy, (f_diff y (ne_of_gt hy)).differentiable_at.differentiable_within_at,
-- next line is the nontrivial bit of this proof, appealing to differentiability
-- extension results.
apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff hf.continuous_within_at
self_mem_nhds_within,
have : tendsto g (𝓝[>] x) (𝓝 (g x)) := tendsto_inf_left hg,
apply this.congr' _,
apply mem_of_superset self_mem_nhds_within (λy hy, _),
exact (f_diff y (ne_of_gt hy)).deriv.symm },
have B : has_deriv_within_at f (g x) (Iic x) x,
{ have diff : differentiable_on ℝ f (Iio x) :=
λy hy, (f_diff y (ne_of_lt hy)).differentiable_at.differentiable_within_at,
-- next line is the nontrivial bit of this proof, appealing to differentiability
-- extension results.
apply has_deriv_at_interval_right_endpoint_of_tendsto_deriv diff hf.continuous_within_at
self_mem_nhds_within,
have : tendsto g (𝓝[<] x) (𝓝 (g x)) := tendsto_inf_left hg,
apply this.congr' _,
apply mem_of_superset self_mem_nhds_within (λy hy, _),
exact (f_diff y (ne_of_lt hy)).deriv.symm },
simpa using B.union A
end
/-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are
continuous at this point, then `g` is the derivative of `f` everywhere. -/
lemma has_deriv_at_of_has_deriv_at_of_ne' {f g : ℝ → E} {x : ℝ}
(f_diff : ∀ y ≠ x, has_deriv_at f (g y) y)
(hf : continuous_at f x) (hg : continuous_at g x) (y : ℝ) :
has_deriv_at f (g y) y :=
begin
rcases eq_or_ne y x with rfl|hne,
{ exact has_deriv_at_of_has_deriv_at_of_ne f_diff hf hg },
{ exact f_diff y hne }
end
|
0226525d3a07a06735278b194a6845349f834933 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/category_theory/limits/shapes/equalizers.lean | 310be9929914facb18f4d7b5f4ac56f5e2b44ad5 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 29,823 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Markus Himmel
-/
import category_theory.epi_mono
import category_theory.limits.limits
/-!
# Equalizers and coequalizers
This file defines (co)equalizers as special cases of (co)limits.
An equalizer is the categorical generalization of the subobject {a ∈ A | f(a) = g(a)} known
from abelian groups or modules. It is a limit cone over the diagram formed by `f` and `g`.
A coequalizer is the dual concept.
## Main definitions
* `walking_parallel_pair` is the indexing category used for (co)equalizer_diagrams
* `parallel_pair` is a functor from `walking_parallel_pair` to our category `C`.
* a `fork` is a cone over a parallel pair.
* there is really only one interesting morphism in a fork: the arrow from the vertex of the fork
to the domain of f and g. It is called `fork.ι`.
* an `equalizer` is now just a `limit (parallel_pair f g)`
Each of these has a dual.
## Main statements
* `equalizer.ι_mono` states that every equalizer map is a monomorphism
* `is_iso_limit_cone_parallel_pair_of_self` states that the identity on the domain of `f` is an equalizer
of `f` and `f`.
## Implementation notes
As with the other special shapes in the limits library, all the definitions here are given as
`abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about
general limits can be used.
## References
* [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1]
-/
open category_theory
namespace category_theory.limits
local attribute [tidy] tactic.case_bash
universes v u
/-- The type of objects for the diagram indexing a (co)equalizer. -/
@[derive decidable_eq, derive inhabited] inductive walking_parallel_pair : Type v
| zero | one
open walking_parallel_pair
/-- The type family of morphisms for the diagram indexing a (co)equalizer. -/
@[derive decidable_eq] inductive walking_parallel_pair_hom :
walking_parallel_pair → walking_parallel_pair → Type v
| left : walking_parallel_pair_hom zero one
| right : walking_parallel_pair_hom zero one
| id : Π X : walking_parallel_pair.{v}, walking_parallel_pair_hom X X
/-- Satisfying the inhabited linter -/
instance : inhabited (walking_parallel_pair_hom zero one) :=
{ default := walking_parallel_pair_hom.left }
open walking_parallel_pair_hom
/-- Composition of morphisms in the indexing diagram for (co)equalizers. -/
def walking_parallel_pair_hom.comp :
Π (X Y Z : walking_parallel_pair)
(f : walking_parallel_pair_hom X Y) (g : walking_parallel_pair_hom Y Z),
walking_parallel_pair_hom X Z
| _ _ _ (id _) h := h
| _ _ _ left (id one) := left
| _ _ _ right (id one) := right
.
instance walking_parallel_pair_hom_category : small_category walking_parallel_pair :=
{ hom := walking_parallel_pair_hom,
id := walking_parallel_pair_hom.id,
comp := walking_parallel_pair_hom.comp }
@[simp]
lemma walking_parallel_pair_hom_id (X : walking_parallel_pair) :
walking_parallel_pair_hom.id X = 𝟙 X :=
rfl
variables {C : Type u} [category.{v} C]
variables {X Y : C}
/-- `parallel_pair f g` is the diagram in `C` consisting of the two morphisms `f` and `g` with
common domain and codomain. -/
def parallel_pair (f g : X ⟶ Y) : walking_parallel_pair.{v} ⥤ C :=
{ obj := λ x, match x with
| zero := X
| one := Y
end,
map := λ x y h, match x, y, h with
| _, _, (id _) := 𝟙 _
| _, _, left := f
| _, _, right := g
end,
-- `tidy` can cope with this, but it's too slow:
map_comp' := begin rintros (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) ⟨⟩⟨⟩; { unfold_aux, simp; refl }, end, }.
@[simp] lemma parallel_pair_obj_zero (f g : X ⟶ Y) : (parallel_pair f g).obj zero = X := rfl
@[simp] lemma parallel_pair_obj_one (f g : X ⟶ Y) : (parallel_pair f g).obj one = Y := rfl
@[simp] lemma parallel_pair_map_left (f g : X ⟶ Y) : (parallel_pair f g).map left = f := rfl
@[simp] lemma parallel_pair_map_right (f g : X ⟶ Y) : (parallel_pair f g).map right = g := rfl
@[simp] lemma parallel_pair_functor_obj
{F : walking_parallel_pair ⥤ C} (j : walking_parallel_pair) :
(parallel_pair (F.map left) (F.map right)).obj j = F.obj j :=
begin
cases j; refl
end
/-- Every functor indexing a (co)equalizer is naturally isomorphic (actually, equal) to a
`parallel_pair` -/
def diagram_iso_parallel_pair (F : walking_parallel_pair ⥤ C) :
F ≅ parallel_pair (F.map left) (F.map right) :=
nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy
/-- A fork on `f` and `g` is just a `cone (parallel_pair f g)`. -/
abbreviation fork (f g : X ⟶ Y) := cone (parallel_pair f g)
/-- A cofork on `f` and `g` is just a `cocone (parallel_pair f g)`. -/
abbreviation cofork (f g : X ⟶ Y) := cocone (parallel_pair f g)
variables {f g : X ⟶ Y}
@[simp, reassoc] lemma fork.app_zero_left (s : fork f g) :
(s.π).app zero ≫ f = (s.π).app one :=
by rw [←s.w left, parallel_pair_map_left]
@[simp, reassoc] lemma fork.app_zero_right (s : fork f g) :
(s.π).app zero ≫ g = (s.π).app one :=
by rw [←s.w right, parallel_pair_map_right]
@[simp, reassoc] lemma cofork.left_app_one (s : cofork f g) :
f ≫ (s.ι).app one = (s.ι).app zero :=
by rw [←s.w left, parallel_pair_map_left]
@[simp, reassoc] lemma cofork.right_app_one (s : cofork f g) :
g ≫ (s.ι).app one = (s.ι).app zero :=
by rw [←s.w right, parallel_pair_map_right]
/-- A fork on `f g : X ⟶ Y` is determined by the morphism `ι : P ⟶ X` satisfying `ι ≫ f = ι ≫ g`.
-/
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,
{ dsimp, simp, }, -- See note [dsimp, simp].
{ exact w },
{ dsimp, simp, },
end } }
/-- A cofork on `f g : X ⟶ Y` is determined by the morphism `π : Y ⟶ P` satisfying
`f ≫ π = g ≫ π`. -/
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,
{ dsimp, simp, },
{ exact w.symm },
{ dsimp, simp, },
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
@[simp] lemma cofork.of_π_app_zero {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) :
(cofork.of_π π w).ι.app zero = f ≫ π := rfl
@[simp] lemma cofork.of_π_app_one {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) :
(cofork.of_π π w).ι.app one = π := rfl
/-- A fork `t` on the parallel pair `f g : X ⟶ Y` consists of two morphisms `t.π.app zero : t.X ⟶ X`
and `t.π.app one : t.X ⟶ Y`. Of these, only the first one is interesting, and we give it the
shorter name `fork.ι t`. -/
abbreviation fork.ι (t : fork f g) := t.π.app zero
/-- A cofork `t` on the parallel_pair `f g : X ⟶ Y` consists of two morphisms
`t.ι.app zero : X ⟶ t.X` and `t.ι.app one : Y ⟶ t.X`. Of these, only the second one is
interesting, and we give it the shorter name `cofork.π t`. -/
abbreviation cofork.π (t : cofork f g) := t.ι.app one
@[simp] lemma fork.ι_of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) :
fork.ι (fork.of_ι ι w) = ι := rfl
@[simp] lemma cofork.π_of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) :
cofork.π (cofork.of_π π w) = π := rfl
lemma fork.ι_eq_app_zero (t : fork f g) : fork.ι t = t.π.app zero := rfl
lemma cofork.π_eq_app_one (t : cofork f g) : cofork.π t = t.ι.app one := rfl
lemma fork.condition (t : fork f g) : (fork.ι t) ≫ f = (fork.ι t) ≫ g :=
begin
erw [t.w left, ← t.w right], refl
end
lemma cofork.condition (t : cofork f g) : f ≫ (cofork.π t) = g ≫ (cofork.π t) :=
begin
erw [t.w left, ← t.w right], refl
end
/--
To construct an isomorphism between forks,
it suffices to give an isomorphism between the cone points
and check that it commutes with the `ι` morphisms.
-/
def fork.ext {s t : fork f g} (i : s.X ≅ t.X) (w : s.ι = i.hom ≫ t.ι) : s ≅ t :=
cones.ext i
begin
rintro ⟨⟩,
{ exact w, },
{ rw [←fork.app_zero_left, ←fork.ι_eq_app_zero, w],
simp, },
end
/--
To construct an isomorphism between coforks,
it suffices to give an isomorphism between the cocone points
and check that it commutes with the `π` morphisms.
-/
def cofork.ext {s t : cofork f g} (i : s.X ≅ t.X) (w : s.π = t.π ≫ i.inv) : s ≅ t :=
cocones.ext i
begin
rintro ⟨⟩,
{ rw [←cofork.left_app_one, ←cofork.π_eq_app_one, w],
simp, },
{ rw [←cofork.π_eq_app_one, w], simp },
end
/-- To check whether two maps are equalized by both maps of a fork, it suffices to check it for the
first map -/
lemma fork.equalizer_ext (s : fork f g) {W : C} {k l : W ⟶ s.X}
(h : k ≫ fork.ι s = l ≫ fork.ι s) : ∀ (j : walking_parallel_pair),
k ≫ s.π.app j = l ≫ s.π.app j
| zero := h
| one := by rw [←fork.app_zero_left, reassoc_of h]
/-- To check whether two maps are coequalized by both maps of a cofork, it suffices to check it for
the second map -/
lemma cofork.coequalizer_ext (s : cofork f g) {W : C} {k l : s.X ⟶ W}
(h : cofork.π s ≫ k = cofork.π s ≫ l) : ∀ (j : walking_parallel_pair),
s.ι.app j ≫ k = s.ι.app j ≫ l
| zero := by simp only [←cofork.left_app_one, category.assoc, h]
| one := h
lemma fork.is_limit.hom_ext {s : fork f g} (hs : is_limit s) {W : C} {k l : W ⟶ s.X}
(h : k ≫ fork.ι s = l ≫ fork.ι s) : k = l :=
hs.hom_ext $ fork.equalizer_ext _ h
lemma cofork.is_colimit.hom_ext {s : cofork f g} (hs : is_colimit s) {W : C} {k l : s.X ⟶ W}
(h : cofork.π s ≫ k = cofork.π s ≫ l) : k = l :=
hs.hom_ext $ cofork.coequalizer_ext _ h
/-- If `s` is a limit fork over `f` and `g`, then a morphism `k : W ⟶ X` satisfying
`k ≫ f = k ≫ g` induces a morphism `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/
def fork.is_limit.lift' {s : fork f g} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) :
{l : W ⟶ s.X // l ≫ fork.ι s = k} :=
⟨hs.lift $ fork.of_ι _ h, hs.fac _ _⟩
/-- If `s` is a colimit cofork over `f` and `g`, then a morphism `k : Y ⟶ W` satisfying
`f ≫ k = g ≫ k` induces a morphism `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/
def cofork.is_colimit.desc' {s : cofork f g} (hs : is_colimit s) {W : C} (k : Y ⟶ W)
(h : f ≫ k = g ≫ k) : {l : s.X ⟶ W // cofork.π s ≫ l = k} :=
⟨hs.desc $ cofork.of_π _ h, hs.fac _ _⟩
/-- This is a slightly more convenient method to verify that a fork is a limit cone. It
only asks for a proof of facts that carry any mathematical content -/
def fork.is_limit.mk (t : fork f g)
(lift : Π (s : fork f g), s.X ⟶ t.X)
(fac : ∀ (s : fork f g), lift s ≫ fork.ι t = fork.ι s)
(uniq : ∀ (s : fork f g) (m : s.X ⟶ t.X)
(w : ∀ j : walking_parallel_pair, m ≫ t.π.app j = s.π.app j), m = lift s) :
is_limit t :=
{ lift := lift,
fac' := λ s j, walking_parallel_pair.cases_on j (fac s) $
by erw [←s.w left, ←t.w left, ←category.assoc, fac]; refl,
uniq' := uniq }
/-- This is another convenient method to verify that a fork is a limit cone. It
only asks for a proof of facts that carry any mathematical content, and allows access to the
same `s` for all parts. -/
def fork.is_limit.mk' {X Y : C} {f g : X ⟶ Y} (t : fork f g)
(create : Π (s : fork f g), {l // l ≫ t.ι = s.ι ∧ ∀ {m}, m ≫ t.ι = s.ι → m = l}) :
is_limit t :=
fork.is_limit.mk t
(λ s, (create s).1)
(λ s, (create s).2.1)
(λ s m w, (create s).2.2 (w zero))
/-- This is a slightly more convenient method to verify that a cofork is a colimit cocone. It
only asks for a proof of facts that carry any mathematical content -/
def cofork.is_colimit.mk (t : cofork f g)
(desc : Π (s : cofork f g), t.X ⟶ s.X)
(fac : ∀ (s : cofork f g), cofork.π t ≫ desc s = cofork.π s)
(uniq : ∀ (s : cofork f g) (m : t.X ⟶ s.X)
(w : ∀ j : walking_parallel_pair, t.ι.app j ≫ m = s.ι.app j), m = desc s) :
is_colimit t :=
{ desc := desc,
fac' := λ s j, walking_parallel_pair.cases_on j
(by erw [←s.w left, ←t.w left, category.assoc, fac]; refl) (fac s),
uniq' := uniq }
/-- This is another convenient method to verify that a fork is a limit cone. It
only asks for a proof of facts that carry any mathematical content, and allows access to the
same `s` for all parts. -/
def cofork.is_colimit.mk' {X Y : C} {f g : X ⟶ Y} (t : cofork f g)
(create : Π (s : cofork f g), {l : t.X ⟶ s.X // t.π ≫ l = s.π ∧ ∀ {m}, t.π ≫ m = s.π → m = l}) :
is_colimit t :=
cofork.is_colimit.mk t
(λ s, (create s).1)
(λ s, (create s).2.1)
(λ s m w, (create s).2.2 (w one))
/-- This is a helper construction that can be useful when verifying that a category has all
equalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)`, and a fork on `F.map left` and `F.map right`,
we get a cone on `F`.
If you're thinking about using this, have a look at `has_equalizers_of_has_limit_parallel_pair`,
which you may find to be an easier way of achieving your goal. -/
def cone.of_fork
{F : walking_parallel_pair ⥤ 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, by { cases j; cases j'; cases g; dsimp; simp } } }
/-- This is a helper construction that can be useful when verifying that a category has all
coequalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)`, and a cofork on `F.map left` and `F.map right`,
we get a cocone on `F`.
If you're thinking about using this, have a look at
`has_coequalizers_of_has_colimit_parallel_pair`, which you may find to be an easier way of
achieving your goal. -/
def cocone.of_cofork
{F : walking_parallel_pair ⥤ 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, by { cases j; cases j'; cases g; dsimp; simp } } }
@[simp] lemma cone.of_fork_π
{F : walking_parallel_pair ⥤ 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_parallel_pair ⥤ 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
/-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)` and a cone on `F`, we get a fork on
`F.map left` and `F.map right`. -/
def fork.of_cone
{F : walking_parallel_pair ⥤ C} (t : cone F) : fork (F.map left) (F.map right) :=
{ X := t.X,
π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy) } }
/-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as
`parallel_pair (F.map left) (F.map right)` and a cocone on `F`, we get a cofork on
`F.map left` and `F.map right`. -/
def cofork.of_cocone
{F : walking_parallel_pair ⥤ C} (t : cocone F) : cofork (F.map left) (F.map right) :=
{ X := t.X,
ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X } }
@[simp] lemma fork.of_cone_π {F : walking_parallel_pair ⥤ 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_parallel_pair ⥤ C} (t : cocone F) (j) :
(cofork.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
/--
Helper function for constructing morphisms between equalizer forks.
-/
def fork.mk_hom {s t : fork f g} (k : s.X ⟶ t.X) (w : k ≫ t.ι = s.ι) : s ⟶ t :=
{ hom := k,
w' :=
begin
rintro ⟨_|_⟩,
exact w,
simpa using w =≫ f,
end }
variables (f g)
section
/--
`has_equalizer f g` represents a particular choice of limiting cone
for the parallel pair of morphisms `f` and `g`.
-/
abbreviation has_equalizer := has_limit (parallel_pair f g)
variables [has_equalizer f g]
/-- If we have chosen an equalizer of `f` and `g`, we can access the corresponding object by
saying `equalizer f g`. -/
abbreviation equalizer : C := limit (parallel_pair f g)
/-- If we have chosen an equalizer of `f` and `g`, we can access the inclusion
`equalizer f g ⟶ X` by saying `equalizer.ι f g`. -/
abbreviation equalizer.ι : equalizer f g ⟶ X :=
limit.π (parallel_pair f g) zero
/--
The chosen equalizer cone for a parallel pair `f` and `g`.
-/
abbreviation equalizer.fork : fork f g := limit.cone (parallel_pair f g)
@[simp] lemma equalizer.fork_ι :
(equalizer.fork f g).ι = equalizer.ι f g := rfl
@[simp] lemma equalizer.fork_π_app_zero :
(equalizer.fork f g).π.app zero = equalizer.ι f g := rfl
@[reassoc] lemma equalizer.condition : equalizer.ι f g ≫ f = equalizer.ι f g ≫ g :=
fork.condition $ limit.cone $ parallel_pair f g
variables {f g}
/-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` factors through the equalizer of `f` and `g`
via `equalizer.lift : W ⟶ equalizer f g`. -/
abbreviation equalizer.lift {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : W ⟶ equalizer f g :=
limit.lift (parallel_pair f g) (fork.of_ι k h)
@[simp, reassoc]
lemma equalizer.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) :
equalizer.lift k h ≫ equalizer.ι f g = k :=
limit.lift_π _ _
/-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ equalizer f g`
satisfying `l ≫ equalizer.ι f g = k`. -/
def equalizer.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) :
{l : W ⟶ equalizer f g // l ≫ equalizer.ι f g = k} :=
⟨equalizer.lift k h, equalizer.lift_ι _ _⟩
/-- Two maps into an equalizer are equal if they are are equal when composed with the equalizer
map. -/
@[ext] lemma equalizer.hom_ext {W : C} {k l : W ⟶ equalizer f g}
(h : k ≫ equalizer.ι f g = l ≫ equalizer.ι f g) : k = l :=
fork.is_limit.hom_ext (limit.is_limit _) h
/-- An equalizer morphism is a monomorphism -/
instance equalizer.ι_mono : mono (equalizer.ι f g) :=
{ right_cancellation := λ Z h k w, equalizer.hom_ext w }
end
section
variables {f g}
/-- The equalizer morphism in any limit cone is a monomorphism. -/
lemma mono_of_is_limit_parallel_pair {c : cone (parallel_pair f g)} (i : is_limit c) :
mono (fork.ι c) :=
{ right_cancellation := λ Z h k w, fork.is_limit.hom_ext i w }
end
section
variables {f g}
/-- The identity determines a cone on the equalizer diagram of `f` and `g` if `f = g`. -/
def id_fork (h : f = g) : fork f g :=
fork.of_ι (𝟙 X) $ h ▸ rfl
/-- The identity on `X` is an equalizer of `(f, g)`, if `f = g`. -/
def is_limit_id_fork (h : f = g) : is_limit (id_fork h) :=
fork.is_limit.mk _
(λ s, fork.ι s)
(λ s, category.comp_id _)
(λ s m h, by { convert h zero, exact (category.comp_id _).symm })
/-- Every equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def is_iso_limit_cone_parallel_pair_of_eq (h₀ : f = g) {c : cone (parallel_pair f g)}
(h : is_limit c) : is_iso (c.π.app zero) :=
is_iso.of_iso $ is_limit.cone_point_unique_up_to_iso h $ is_limit_id_fork h₀
/-- The equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def equalizer.ι_of_eq [has_equalizer f g] (h : f = g) : is_iso (equalizer.ι f g) :=
is_iso_limit_cone_parallel_pair_of_eq h $ limit.is_limit _
/-- Every equalizer of `(f, f)` is an isomorphism. -/
def is_iso_limit_cone_parallel_pair_of_self {c : cone (parallel_pair f f)} (h : is_limit c) :
is_iso (c.π.app zero) :=
is_iso_limit_cone_parallel_pair_of_eq rfl h
/-- An equalizer that is an epimorphism is an isomorphism. -/
def is_iso_limit_cone_parallel_pair_of_epi {c : cone (parallel_pair f g)}
(h : is_limit c) [epi (c.π.app zero)] : is_iso (c.π.app zero) :=
is_iso_limit_cone_parallel_pair_of_eq ((cancel_epi _).1 (fork.condition c)) h
end
/-- The equalizer inclusion for `(f, f)` is an isomorphism. -/
instance equalizer.ι_of_self [has_equalizer f f] : is_iso (equalizer.ι f f) :=
equalizer.ι_of_eq rfl
/-- The equalizer of a morphism with itself is isomorphic to the source. -/
def equalizer.iso_source_of_self [has_equalizer f f] : equalizer f f ≅ X :=
as_iso (equalizer.ι f f)
@[simp] lemma equalizer.iso_source_of_self_hom [has_equalizer f f] :
(equalizer.iso_source_of_self f).hom = equalizer.ι f f :=
rfl
@[simp] lemma equalizer.iso_source_of_self_inv [has_equalizer f f] :
(equalizer.iso_source_of_self f).inv = equalizer.lift (𝟙 X) (by simp) :=
rfl
/--
Helper function for constructing morphisms between coequalizer coforks.
-/
def cofork.mk_hom {s t : cofork f g} (k : s.X ⟶ t.X) (w : s.π ≫ k = t.π) : s ⟶ t :=
{ hom := k,
w' :=
begin
rintro ⟨_|_⟩,
simpa using f ≫= w,
exact w,
end }
section
/--
`has_coequalizer f g` represents a particular choice of colimiting cocone
for the parallel pair of morphisms `f` and `g`.
-/
abbreviation has_coequalizer := has_colimit (parallel_pair f g)
variables [has_coequalizer f g]
/-- If we have chosen a coequalizer of `f` and `g`, we can access the corresponding object by
saying `coequalizer f g`. -/
abbreviation coequalizer : C := colimit (parallel_pair f g)
/-- If we have chosen a coequalizer of `f` and `g`, we can access the corresponding projection by
saying `coequalizer.π f g`. -/
abbreviation coequalizer.π : Y ⟶ coequalizer f g :=
colimit.ι (parallel_pair f g) one
/--
The chosen coequalizer cocone for a parallel pair `f` and `g`.
-/
abbreviation coequalizer.cofork : cofork f g := colimit.cocone (parallel_pair f g)
@[simp] lemma coequalizer.cofork_π :
(coequalizer.cofork f g).π = coequalizer.π f g := rfl
@[simp] lemma coequalizer.cofork_ι_app_one :
(coequalizer.cofork f g).ι.app one = coequalizer.π f g := rfl
@[reassoc] lemma coequalizer.condition : f ≫ coequalizer.π f g = g ≫ coequalizer.π f g :=
cofork.condition $ colimit.cocone $ parallel_pair f g
variables {f g}
/-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` factors through the coequalizer of `f`
and `g` via `coequalizer.desc : coequalizer f g ⟶ W`. -/
abbreviation coequalizer.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer f g ⟶ W :=
colimit.desc (parallel_pair f g) (cofork.of_π k h)
@[simp, reassoc]
lemma coequalizer.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) :
coequalizer.π f g ≫ coequalizer.desc k h = k :=
colimit.ι_desc _ _
/-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism
`l : coequalizer f g ⟶ W` satisfying `coequalizer.π ≫ g = l`. -/
def coequalizer.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) :
{l : coequalizer f g ⟶ W // coequalizer.π f g ≫ l = k} :=
⟨coequalizer.desc k h, coequalizer.π_desc _ _⟩
/-- Two maps from a coequalizer are equal if they are equal when composed with the coequalizer
map -/
@[ext] lemma coequalizer.hom_ext {W : C} {k l : coequalizer f g ⟶ W}
(h : coequalizer.π f g ≫ k = coequalizer.π f g ≫ l) : k = l :=
cofork.is_colimit.hom_ext (colimit.is_colimit _) h
/-- A coequalizer morphism is an epimorphism -/
instance coequalizer.π_epi : epi (coequalizer.π f g) :=
{ left_cancellation := λ Z h k w, coequalizer.hom_ext w }
end
section
variables {f g}
/-- The coequalizer morphism in any colimit cocone is an epimorphism. -/
lemma epi_of_is_colimit_parallel_pair {c : cocone (parallel_pair f g)} (i : is_colimit c) :
epi (c.ι.app one) :=
{ left_cancellation := λ Z h k w, cofork.is_colimit.hom_ext i w }
end
section
variables {f g}
/-- The identity determines a cocone on the coequalizer diagram of `f` and `g`, if `f = g`. -/
def id_cofork (h : f = g) : cofork f g :=
cofork.of_π (𝟙 Y) $ h ▸ rfl
/-- The identity on `Y` is a coequalizer of `(f, g)`, where `f = g`. -/
def is_colimit_id_cofork (h : f = g) : is_colimit (id_cofork h) :=
cofork.is_colimit.mk _
(λ s, cofork.π s)
(λ s, category.id_comp _)
(λ s m h, by { convert h one, exact (category.id_comp _).symm })
/-- Every coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def is_iso_colimit_cocone_parallel_pair_of_eq (h₀ : f = g) {c : cocone (parallel_pair f g)}
(h : is_colimit c) : is_iso (c.ι.app one) :=
is_iso.of_iso $ is_colimit.cocone_point_unique_up_to_iso (is_colimit_id_cofork h₀) h
/-- The coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/
def coequalizer.π_of_eq [has_coequalizer f g] (h : f = g) :
is_iso (coequalizer.π f g) :=
is_iso_colimit_cocone_parallel_pair_of_eq h $ colimit.is_colimit _
/-- Every coequalizer of `(f, f)` is an isomorphism. -/
def is_iso_colimit_cocone_parallel_pair_of_self {c : cocone (parallel_pair f f)}
(h : is_colimit c) : is_iso (c.ι.app one) :=
is_iso_colimit_cocone_parallel_pair_of_eq rfl h
/-- A coequalizer that is a monomorphism is an isomorphism. -/
def is_iso_limit_cocone_parallel_pair_of_epi {c : cocone (parallel_pair f g)}
(h : is_colimit c) [mono (c.ι.app one)] : is_iso (c.ι.app one) :=
is_iso_colimit_cocone_parallel_pair_of_eq ((cancel_mono _).1 (cofork.condition c)) h
end
/-- The coequalizer projection for `(f, f)` is an isomorphism. -/
instance coequalizer.π_of_self [has_coequalizer f f] : is_iso (coequalizer.π f f) :=
coequalizer.π_of_eq rfl
/-- The coequalizer of a morphism with itself is isomorphic to the target. -/
def coequalizer.iso_target_of_self [has_coequalizer f f] : coequalizer f f ≅ Y :=
(as_iso (coequalizer.π f f)).symm
@[simp] lemma coequalizer.iso_target_of_self_hom [has_coequalizer f f] :
(coequalizer.iso_target_of_self f).hom = coequalizer.desc (𝟙 Y) (by simp) :=
rfl
@[simp] lemma coequalizer.iso_target_of_self_inv [has_coequalizer f f] :
(coequalizer.iso_target_of_self f).inv = coequalizer.π f f :=
rfl
variables (C)
/-- `has_equalizers` represents a choice of equalizer for every pair of morphisms -/
abbreviation has_equalizers := has_limits_of_shape walking_parallel_pair C
/-- `has_coequalizers` represents a choice of coequalizer for every pair of morphisms -/
abbreviation has_coequalizers := has_colimits_of_shape walking_parallel_pair C
/-- If `C` has all limits of diagrams `parallel_pair f g`, then it has all equalizers -/
def has_equalizers_of_has_limit_parallel_pair
[Π {X Y : C} {f g : X ⟶ Y}, has_limit (parallel_pair f g)] : has_equalizers C :=
{ has_limit := λ F, has_limit_of_iso (diagram_iso_parallel_pair F).symm }
/-- If `C` has all colimits of diagrams `parallel_pair f g`, then it has all coequalizers -/
def has_coequalizers_of_has_colimit_parallel_pair
[Π {X Y : C} {f g : X ⟶ Y}, has_colimit (parallel_pair f g)] : has_coequalizers C :=
{ has_colimit := λ F, has_colimit_of_iso (diagram_iso_parallel_pair F) }
section
-- In this section we show that a split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`.
variables {C} [split_mono f]
/--
A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`.
Here we build the cone, and show in `split_mono_equalizes` that it is a limit cone.
-/
def cone_of_split_mono : cone (parallel_pair (𝟙 Y) (retraction f ≫ f)) :=
fork.of_ι f (by tidy)
@[simp] lemma cone_of_split_mono_π_app_zero : (cone_of_split_mono f).π.app zero = f := rfl
@[simp] lemma cone_of_split_mono_π_app_one : (cone_of_split_mono f).π.app one = f ≫ 𝟙 Y := rfl
/--
A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`.
-/
def split_mono_equalizes {X Y : C} (f : X ⟶ Y) [split_mono f] : is_limit (cone_of_split_mono f) :=
{ lift := λ s, s.π.app zero ≫ retraction f,
fac' := λ s,
begin
rintros (⟨⟩|⟨⟩),
{ rw [cone_of_split_mono_π_app_zero],
erw [category.assoc, ← s.π.naturality right, s.π.naturality left, category.comp_id], },
{ erw [cone_of_split_mono_π_app_one, category.comp_id, category.assoc,
← s.π.naturality right, category.id_comp], }
end,
uniq' := λ s m w, begin rw ←(w zero), simp, end, }
end
section
-- In this section we show that a split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`.
variables {C} [split_epi f]
/--
A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`.
Here we build the cocone, and show in `split_epi_coequalizes` that it is a colimit cocone.
-/
def cocone_of_split_epi : cocone (parallel_pair (𝟙 X) (f ≫ section_ f)) :=
cofork.of_π f (by tidy)
@[simp] lemma cocone_of_split_epi_ι_app_one : (cocone_of_split_epi f).ι.app one = f := rfl
@[simp] lemma cocone_of_split_epi_ι_app_zero : (cocone_of_split_epi f).ι.app zero = 𝟙 X ≫ f := rfl
/--
A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`.
-/
def split_epi_coequalizes {X Y : C} (f : X ⟶ Y) [split_epi f] : is_colimit (cocone_of_split_epi f) :=
{ desc := λ s, section_ f ≫ s.ι.app one,
fac' := λ s,
begin
rintros (⟨⟩|⟨⟩),
{ erw [cocone_of_split_epi_ι_app_zero, category.assoc, category.id_comp, ←category.assoc,
s.ι.naturality right, functor.const.obj_map, category.comp_id], },
{ erw [cocone_of_split_epi_ι_app_one, ←category.assoc, s.ι.naturality right,
←s.ι.naturality left, category.id_comp] }
end,
uniq' := λ s m w, begin rw ←(w one), simp, end, }
end
end category_theory.limits
|
3c17fd023317f485b731e0a9c4b07c68e4225769 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/algebra/group_completion.lean | 92074999a91327c0df3f7a6737f928b02ccfd925 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 10,346 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
-/
import algebra.hom.group_instances
import topology.algebra.uniform_group
import topology.algebra.uniform_mul_action
import topology.uniform_space.completion
/-!
# Completion of topological groups:
This files endows the completion of a topological abelian group with a group structure.
More precisely the instance `uniform_space.completion.add_group` builds an abelian group structure
on the completion of an abelian group endowed with a compatible uniform structure.
Then the instance `uniform_space.completion.uniform_add_group` proves this group structure is
compatible with the completed uniform structure. The compatibility condition is `uniform_add_group`.
## Main declarations:
Beyond the instances explained above (that don't have to be explicitly invoked),
the main constructions deal with continuous group morphisms.
* `add_monoid_hom.extension`: extends a continuous group morphism from `G`
to a complete separated group `H` to `completion G`.
* `add_monoid_hom.completion`: promotes a continuous group morphism
from `G` to `H` into a continuous group morphism
from `completion G` to `completion H`.
-/
noncomputable theory
variables {M R α β : Type*}
section group
open uniform_space Cauchy filter set
variables [uniform_space α]
instance [has_zero α] : has_zero (completion α) := ⟨(0 : α)⟩
instance [has_neg α] : has_neg (completion α) := ⟨completion.map (λa, -a : α → α)⟩
instance [has_add α] : has_add (completion α) := ⟨completion.map₂ (+)⟩
instance [has_sub α] : has_sub (completion α) := ⟨completion.map₂ has_sub.sub⟩
@[norm_cast]
lemma uniform_space.completion.coe_zero [has_zero α] : ((0 : α) : completion α) = 0 := rfl
end group
namespace uniform_space.completion
open uniform_space
section has_zero
instance [uniform_space α] [monoid_with_zero M] [has_zero α] [mul_action_with_zero M α]
[has_uniform_continuous_const_smul M α] :
mul_action_with_zero M (completion α) :=
{ smul := (•),
smul_zero := λ r, by rw [← coe_zero, ← coe_smul, mul_action_with_zero.smul_zero r],
zero_smul := ext' (continuous_const_smul _) continuous_const $ λ a,
by rw [← coe_smul, zero_smul, coe_zero],
.. completion.mul_action M α }
end has_zero
section uniform_add_group
variables [uniform_space α] [add_group α] [uniform_add_group α]
@[norm_cast]
lemma coe_neg (a : α) : ((- a : α) : completion α) = - a :=
(map_coe uniform_continuous_neg a).symm
@[norm_cast]
lemma coe_sub (a b : α) : ((a - b : α) : completion α) = a - b :=
(map₂_coe_coe a b has_sub.sub uniform_continuous_sub).symm
@[norm_cast]
lemma coe_add (a b : α) : ((a + b : α) : completion α) = a + b :=
(map₂_coe_coe a b (+) uniform_continuous_add).symm
instance : add_monoid (completion α) :=
{ zero_add := assume a, completion.induction_on a
(is_closed_eq (continuous_map₂ continuous_const continuous_id) continuous_id)
(assume a, show 0 + (a : completion α) = a, by rw_mod_cast zero_add),
add_zero := assume a, completion.induction_on a
(is_closed_eq (continuous_map₂ continuous_id continuous_const) continuous_id)
(assume a, show (a : completion α) + 0 = a, by rw_mod_cast add_zero),
add_assoc := assume a b c, completion.induction_on₃ a b c
(is_closed_eq
(continuous_map₂
(continuous_map₂ continuous_fst (continuous_fst.comp continuous_snd))
(continuous_snd.comp continuous_snd))
(continuous_map₂ continuous_fst
(continuous_map₂
(continuous_fst.comp continuous_snd)
(continuous_snd.comp continuous_snd))))
(assume a b c, show (a : completion α) + b + c = a + (b + c),
by repeat { rw_mod_cast add_assoc }),
nsmul := (•),
nsmul_zero' := λ a, completion.induction_on a (is_closed_eq continuous_map continuous_const)
(λ a, by rw [←coe_smul, ←coe_zero, zero_smul]),
nsmul_succ' := λ n a, completion.induction_on a
(is_closed_eq continuous_map $ continuous_map₂ continuous_id continuous_map)
(λ a, by rw_mod_cast succ_nsmul ),
.. completion.has_zero, ..completion.has_add, }
instance : sub_neg_monoid (completion α) :=
{ sub_eq_add_neg := λ a b, completion.induction_on₂ a b
(is_closed_eq (continuous_map₂ continuous_fst continuous_snd)
(continuous_map₂ continuous_fst (completion.continuous_map.comp continuous_snd)))
(λ a b, by exact_mod_cast congr_arg coe (sub_eq_add_neg a b)),
zsmul := (•),
zsmul_zero' := λ a, completion.induction_on a (is_closed_eq continuous_map continuous_const)
(λ a, by { rw_mod_cast zero_smul, refl} ),
zsmul_succ' := λ n a, completion.induction_on a
(is_closed_eq continuous_map $ continuous_map₂ continuous_id continuous_map)
(λ a, by rw_mod_cast (show int.of_nat n.succ • a = a + int.of_nat n • a,
from sub_neg_monoid.zsmul_succ' n a) ),
zsmul_neg' := λ n a, completion.induction_on a
(is_closed_eq continuous_map $ completion.continuous_map.comp continuous_map)
(λ a, by rw [←coe_smul, ←coe_smul, ←coe_neg, show -[1+ n] • a = -((n.succ : ℤ) • a),
from sub_neg_monoid.zsmul_neg' n a]),
.. completion.add_monoid, .. completion.has_neg, .. completion.has_sub }
instance : add_group (completion α) :=
{ add_left_neg := assume a, completion.induction_on a
(is_closed_eq (continuous_map₂ completion.continuous_map continuous_id) continuous_const)
(assume a, show - (a : completion α) + a = 0, by { rw_mod_cast add_left_neg, refl }),
.. completion.sub_neg_monoid }
instance : uniform_add_group (completion α) :=
⟨uniform_continuous_map₂ has_sub.sub⟩
instance {M} [monoid M] [distrib_mul_action M α] [has_uniform_continuous_const_smul M α] :
distrib_mul_action M (completion α) :=
{ smul := (•),
smul_add := λ r x y, induction_on₂ x y
(is_closed_eq ((continuous_fst.add continuous_snd).const_smul _)
((continuous_fst.const_smul _).add (continuous_snd.const_smul _)))
(λ a b, by simp only [← coe_add, ← coe_smul, smul_add]),
smul_zero := λ r, by rw [← coe_zero, ← coe_smul, smul_zero r],
.. completion.mul_action M α }
/-- The map from a group to its completion as a group hom. -/
@[simps] def to_compl : α →+ completion α :=
{ to_fun := coe,
map_add' := coe_add,
map_zero' := coe_zero }
lemma continuous_to_compl : continuous (to_compl : α → completion α) :=
continuous_coe α
end uniform_add_group
section uniform_add_comm_group
variables [uniform_space α] [add_comm_group α] [uniform_add_group α]
instance : add_comm_group (completion α) :=
{ add_comm := assume a b, completion.induction_on₂ a b
(is_closed_eq (continuous_map₂ continuous_fst continuous_snd)
(continuous_map₂ continuous_snd continuous_fst))
(assume x y, by { change ↑x + ↑y = ↑y + ↑x, rw [← coe_add, ← coe_add, add_comm]}),
.. completion.add_group }
instance [semiring R] [module R α] [has_uniform_continuous_const_smul R α] :
module R (completion α) :=
{ smul := (•),
add_smul := λ a b, ext' (continuous_const_smul _)
((continuous_const_smul _).add (continuous_const_smul _)) $ λ x, by { norm_cast, rw add_smul },
.. completion.distrib_mul_action, .. completion.mul_action_with_zero }
end uniform_add_comm_group
end uniform_space.completion
section add_monoid_hom
variables [uniform_space α] [add_group α] [uniform_add_group α]
[uniform_space β] [add_group β] [uniform_add_group β]
open uniform_space uniform_space.completion
/-- Extension to the completion of a continuous group hom. -/
def add_monoid_hom.extension [complete_space β] [separated_space β] (f : α →+ β)
(hf : continuous f) : completion α →+ β :=
have hf : uniform_continuous f, from uniform_continuous_add_monoid_hom_of_continuous hf,
{ to_fun := completion.extension f,
map_zero' := by rw [← coe_zero, extension_coe hf, f.map_zero],
map_add' := assume a b, completion.induction_on₂ a b
(is_closed_eq
(continuous_extension.comp continuous_add)
((continuous_extension.comp continuous_fst).add (continuous_extension.comp continuous_snd)))
(λ a b, by rw_mod_cast [extension_coe hf, extension_coe hf, extension_coe hf,
f.map_add]) }
lemma add_monoid_hom.extension_coe [complete_space β] [separated_space β] (f : α →+ β)
(hf : continuous f) (a : α) : f.extension hf a = f a :=
extension_coe (uniform_continuous_add_monoid_hom_of_continuous hf) a
@[continuity]
lemma add_monoid_hom.continuous_extension [complete_space β] [separated_space β] (f : α →+ β)
(hf : continuous f) : continuous (f.extension hf) :=
continuous_extension
/-- Completion of a continuous group hom, as a group hom. -/
def add_monoid_hom.completion (f : α →+ β) (hf : continuous f) : completion α →+ completion β :=
(to_compl.comp f).extension (continuous_to_compl.comp hf)
@[continuity]
lemma add_monoid_hom.continuous_completion (f : α →+ β)
(hf : continuous f) : continuous (f.completion hf : completion α → completion β) :=
continuous_map
lemma add_monoid_hom.completion_coe (f : α →+ β)
(hf : continuous f) (a : α) : f.completion hf a = f a :=
map_coe (uniform_continuous_add_monoid_hom_of_continuous hf) a
lemma add_monoid_hom.completion_zero : (0 : α →+ β).completion continuous_const = 0 :=
begin
ext x,
apply completion.induction_on x,
{ apply is_closed_eq ((0 : α →+ β).continuous_completion continuous_const),
simp [continuous_const] },
{ intro a,
simp [(0 : α →+ β).completion_coe continuous_const, coe_zero] }
end
lemma add_monoid_hom.completion_add {γ : Type*} [add_comm_group γ] [uniform_space γ]
[uniform_add_group γ] (f g : α →+ γ) (hf : continuous f) (hg : continuous g) :
(f + g).completion (hf.add hg) = f.completion hf + g.completion hg :=
begin
have hfg := hf.add hg,
ext x,
apply completion.induction_on x,
{ exact is_closed_eq ((f+g).continuous_completion hfg)
((f.continuous_completion hf).add (g.continuous_completion hg)) },
{ intro a,
simp [(f+g).completion_coe hfg, coe_add, f.completion_coe hf, g.completion_coe hg] }
end
end add_monoid_hom
|
015734ad0e9147e768577a4cce8438536dabef79 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/convex/basic.lean | 112a3d30e8d61f6e111243d61bfe39bc40d34c74 | [
"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 | 42,057 | lean | /-
Copyright (c) 2019 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, Yury Kudriashov, Yaël Dillies
-/
import algebra.order.invertible
import algebra.order.module
import linear_algebra.affine_space.midpoint
import linear_algebra.affine_space.affine_subspace
import linear_algebra.ray
/-!
# Convex sets and functions in vector spaces
In a 𝕜-vector space, we define the following objects and properties.
* `segment 𝕜 x y`: Closed segment joining `x` and `y`.
* `open_segment 𝕜 x y`: Open segment joining `x` and `y`.
* `convex 𝕜 s`: A set `s` is convex if for any two points `x y ∈ s` it includes `segment 𝕜 x y`.
* `std_simplex 𝕜 ι`: The standard simplex in `ι → 𝕜` (currently requires `fintype ι`). It is the
intersection of the positive quadrant with the hyperplane `s.sum = 1`.
We also provide various equivalent versions of the definitions above, prove that some specific sets
are convex.
## Notations
We provide the following notation:
* `[x -[𝕜] y] = segment 𝕜 x y` in locale `convex`
## TODO
Generalize all this file to affine spaces.
Should we rename `segment` and `open_segment` to `convex.Icc` and `convex.Ioo`? Should we also
define `clopen_segment`/`convex.Ico`/`convex.Ioc`?
-/
variables {𝕜 E F β : Type*}
open linear_map set
open_locale big_operators classical pointwise
/-! ### Segment -/
section ordered_semiring
variables [ordered_semiring 𝕜] [add_comm_monoid E]
section has_scalar
variables (𝕜) [has_scalar 𝕜 E]
/-- Segments in a vector space. -/
def segment (x y : E) : set E :=
{z : E | ∃ (a b : 𝕜) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z}
/-- Open segment in a vector space. Note that `open_segment 𝕜 x x = {x}` instead of being `∅` when
the base semiring has some element between `0` and `1`. -/
def open_segment (x y : E) : set E :=
{z : E | ∃ (a b : 𝕜) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1), a • x + b • y = z}
localized "notation `[` x ` -[` 𝕜 `] ` y `]` := segment 𝕜 x y" in convex
lemma segment_eq_image₂ (x y : E) :
[x -[𝕜] y] = (λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} :=
by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc]
lemma open_segment_eq_image₂ (x y : E) :
open_segment 𝕜 x y =
(λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 < p.1 ∧ 0 < p.2 ∧ p.1 + p.2 = 1} :=
by simp only [open_segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc]
lemma segment_symm (x y : E) : [x -[𝕜] y] = [y -[𝕜] x] :=
set.ext $ λ z,
⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩,
λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩
lemma open_segment_symm (x y : E) :
open_segment 𝕜 x y = open_segment 𝕜 y x :=
set.ext $ λ z,
⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩,
λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩
lemma open_segment_subset_segment (x y : E) :
open_segment 𝕜 x y ⊆ [x -[𝕜] y] :=
λ z ⟨a, b, ha, hb, hab, hz⟩, ⟨a, b, ha.le, hb.le, hab, hz⟩
lemma segment_subset_iff {x y : E} {s : set E} :
[x -[𝕜] y] ⊆ s ↔ ∀ a b : 𝕜, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s :=
⟨λ H a b ha hb hab, H ⟨a, b, ha, hb, hab, rfl⟩,
λ H z ⟨a, b, ha, hb, hab, hz⟩, hz ▸ H a b ha hb hab⟩
lemma open_segment_subset_iff {x y : E} {s : set E} :
open_segment 𝕜 x y ⊆ s ↔ ∀ a b : 𝕜, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s :=
⟨λ H a b ha hb hab, H ⟨a, b, ha, hb, hab, rfl⟩,
λ H z ⟨a, b, ha, hb, hab, hz⟩, hz ▸ H a b ha hb hab⟩
end has_scalar
open_locale convex
section mul_action_with_zero
variables (𝕜) [mul_action_with_zero 𝕜 E]
lemma left_mem_segment (x y : E) : x ∈ [x -[𝕜] y] :=
⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩
lemma right_mem_segment (x y : E) : y ∈ [x -[𝕜] y] :=
segment_symm 𝕜 y x ▸ left_mem_segment 𝕜 y x
end mul_action_with_zero
section module
variables (𝕜) [module 𝕜 E] {x y z : E} {s : set E}
@[simp] lemma segment_same (x : E) : [x -[𝕜] x] = {x} :=
set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩,
by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz,
λ h, mem_singleton_iff.1 h ▸ left_mem_segment 𝕜 z z⟩
lemma insert_endpoints_open_segment (x y : E) :
insert x (insert y (open_segment 𝕜 x y)) = [x -[𝕜] y] :=
begin
simp only [subset_antisymm_iff, insert_subset, left_mem_segment, right_mem_segment,
open_segment_subset_segment, true_and],
rintro z ⟨a, b, ha, hb, hab, rfl⟩,
refine hb.eq_or_gt.imp _ (λ hb', ha.eq_or_gt.imp _ _),
{ rintro rfl,
rw add_zero at hab,
rw [hab, one_smul, zero_smul, add_zero] },
{ rintro rfl,
rw zero_add at hab,
rw [hab, one_smul, zero_smul, zero_add] },
{ exact λ ha', ⟨a, b, ha', hb', hab, rfl⟩ }
end
variables {𝕜}
lemma mem_open_segment_of_ne_left_right (hx : x ≠ z) (hy : y ≠ z) (hz : z ∈ [x -[𝕜] y]) :
z ∈ open_segment 𝕜 x y :=
begin
rw [← insert_endpoints_open_segment] at hz,
exact ((hz.resolve_left hx.symm).resolve_left hy.symm)
end
lemma open_segment_subset_iff_segment_subset (hx : x ∈ s) (hy : y ∈ s) :
open_segment 𝕜 x y ⊆ s ↔ [x -[𝕜] y] ⊆ s :=
by simp only [← insert_endpoints_open_segment, insert_subset, *, true_and]
end module
end ordered_semiring
open_locale convex
section ordered_ring
variables [ordered_ring 𝕜]
section add_comm_group
variables (𝕜) [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F]
section densely_ordered
variables [nontrivial 𝕜] [densely_ordered 𝕜]
@[simp] lemma open_segment_same (x : E) :
open_segment 𝕜 x x = {x} :=
set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩,
by simpa only [← add_smul, mem_singleton_iff, hab, one_smul, eq_comm] using hz,
λ (h : z = x), begin
obtain ⟨a, ha₀, ha₁⟩ := densely_ordered.dense (0 : 𝕜) 1 zero_lt_one,
refine ⟨a, 1 - a, ha₀, sub_pos_of_lt ha₁, add_sub_cancel'_right _ _, _⟩,
rw [←add_smul, add_sub_cancel'_right, one_smul, h],
end⟩
end densely_ordered
lemma segment_eq_image (x y : E) : [x -[𝕜] y] = (λ θ : 𝕜, (1 - θ) • x + θ • y) '' Icc (0 : 𝕜) 1 :=
set.ext $ λ z,
⟨λ ⟨a, b, ha, hb, hab, hz⟩,
⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩,
λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩
lemma open_segment_eq_image (x y : E) :
open_segment 𝕜 x y = (λ (θ : 𝕜), (1 - θ) • x + θ • y) '' Ioo (0 : 𝕜) 1 :=
set.ext $ λ z,
⟨λ ⟨a, b, ha, hb, hab, hz⟩,
⟨b, ⟨hb, hab ▸ lt_add_of_pos_left _ ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩,
λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1 - θ, θ, sub_pos.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩
lemma segment_eq_image' (x y : E) :
[x -[𝕜] y] = (λ (θ : 𝕜), x + θ • (y - x)) '' Icc (0 : 𝕜) 1 :=
by { convert segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel }
lemma open_segment_eq_image' (x y : E) :
open_segment 𝕜 x y = (λ (θ : 𝕜), x + θ • (y - x)) '' Ioo (0 : 𝕜) 1 :=
by { convert open_segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel }
lemma segment_eq_image_line_map (x y : E) :
[x -[𝕜] y] = affine_map.line_map x y '' Icc (0 : 𝕜) 1 :=
by { convert segment_eq_image 𝕜 x y, ext, exact affine_map.line_map_apply_module _ _ _ }
lemma open_segment_eq_image_line_map (x y : E) :
open_segment 𝕜 x y = affine_map.line_map x y '' Ioo (0 : 𝕜) 1 :=
by { convert open_segment_eq_image 𝕜 x y, ext, exact affine_map.line_map_apply_module _ _ _ }
lemma segment_image (f : E →ₗ[𝕜] F) (a b : E) : f '' [a -[𝕜] b] = [f a -[𝕜] f b] :=
set.ext (λ x, by simp_rw [segment_eq_image, mem_image, exists_exists_and_eq_and, map_add, map_smul])
@[simp] lemma open_segment_image (f : E →ₗ[𝕜] F) (a b : E) :
f '' open_segment 𝕜 a b = open_segment 𝕜 (f a) (f b) :=
set.ext (λ x, by simp_rw [open_segment_eq_image, mem_image, exists_exists_and_eq_and, map_add,
map_smul])
lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b -[𝕜] a + c] ↔ x ∈ [b -[𝕜] c] :=
begin
rw [segment_eq_image', segment_eq_image'],
refine exists_congr (λ θ, and_congr iff.rfl _),
simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj],
end
@[simp] lemma mem_open_segment_translate (a : E) {x b c : E} :
a + x ∈ open_segment 𝕜 (a + b) (a + c) ↔ x ∈ open_segment 𝕜 b c :=
begin
rw [open_segment_eq_image', open_segment_eq_image'],
refine exists_congr (λ θ, and_congr iff.rfl _),
simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj],
end
lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b -[𝕜] a + c] = [b -[𝕜] c] :=
set.ext $ λ x, mem_segment_translate 𝕜 a
lemma open_segment_translate_preimage (a b c : E) :
(λ x, a + x) ⁻¹' open_segment 𝕜 (a + b) (a + c) = open_segment 𝕜 b c :=
set.ext $ λ x, mem_open_segment_translate 𝕜 a
lemma segment_translate_image (a b c : E) : (λ x, a + x) '' [b -[𝕜] c] = [a + b -[𝕜] a + c] :=
segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a
lemma open_segment_translate_image (a b c : E) :
(λ x, a + x) '' open_segment 𝕜 b c = open_segment 𝕜 (a + b) (a + c) :=
open_segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a
end add_comm_group
end ordered_ring
lemma same_ray_of_mem_segment [ordered_comm_ring 𝕜] [add_comm_group E] [module 𝕜 E]
{x y z : E} (h : x ∈ [y -[𝕜] z]) : same_ray 𝕜 (x - y) (z - x) :=
begin
rw segment_eq_image' at h,
rcases h with ⟨θ, ⟨hθ₀, hθ₁⟩, rfl⟩,
simpa only [add_sub_cancel', ← sub_sub, sub_smul, one_smul]
using (same_ray_nonneg_smul_left (z - y) hθ₀).nonneg_smul_right (sub_nonneg.2 hθ₁)
end
section linear_ordered_ring
variables [linear_ordered_ring 𝕜]
section add_comm_group
variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F]
lemma midpoint_mem_segment [invertible (2 : 𝕜)] (x y : E) :
midpoint 𝕜 x y ∈ [x -[𝕜] y] :=
begin
rw segment_eq_image_line_map,
exact ⟨⅟2, ⟨inv_of_nonneg.mpr zero_le_two, inv_of_le_one one_le_two⟩, rfl⟩,
end
lemma mem_segment_sub_add [invertible (2 : 𝕜)] (x y : E) :
x ∈ [x-y -[𝕜] x+y] :=
begin
convert @midpoint_mem_segment 𝕜 _ _ _ _ _ _ _,
rw midpoint_sub_add
end
lemma mem_segment_add_sub [invertible (2 : 𝕜)] (x y : E) :
x ∈ [x+y -[𝕜] x-y] :=
begin
convert @midpoint_mem_segment 𝕜 _ _ _ _ _ _ _,
rw midpoint_add_sub
end
@[simp] lemma left_mem_open_segment_iff [densely_ordered 𝕜] [no_zero_smul_divisors 𝕜 E] {x y : E} :
x ∈ open_segment 𝕜 x y ↔ x = y :=
begin
split,
{ rintro ⟨a, b, ha, hb, hab, hx⟩,
refine smul_right_injective _ hb.ne' ((add_right_inj (a • x)).1 _),
rw [hx, ←add_smul, hab, one_smul] },
{ rintro rfl,
rw open_segment_same,
exact mem_singleton _ }
end
@[simp] lemma right_mem_open_segment_iff [densely_ordered 𝕜] [no_zero_smul_divisors 𝕜 E] {x y : E} :
y ∈ open_segment 𝕜 x y ↔ x = y :=
by rw [open_segment_symm, left_mem_open_segment_iff, eq_comm]
end add_comm_group
end linear_ordered_ring
section linear_ordered_field
variables [linear_ordered_field 𝕜]
section add_comm_group
variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {x y z : E}
lemma mem_segment_iff_same_ray : x ∈ [y -[𝕜] z] ↔ same_ray 𝕜 (x - y) (z - x) :=
begin
refine ⟨same_ray_of_mem_segment, λ h, _⟩,
rcases h.exists_eq_smul_add with ⟨a, b, ha, hb, hab, hxy, hzx⟩,
rw [add_comm, sub_add_sub_cancel] at hxy hzx,
rw [← mem_segment_translate _ (-x), neg_add_self],
refine ⟨b, a, hb, ha, add_comm a b ▸ hab, _⟩,
rw [← sub_eq_neg_add, ← neg_sub, hxy, ← sub_eq_neg_add, hzx, smul_neg, smul_comm, neg_add_self]
end
lemma mem_segment_iff_div : x ∈ [y -[𝕜] z] ↔
∃ a b : 𝕜, 0 ≤ a ∧ 0 ≤ b ∧ 0 < a + b ∧ (a / (a + b)) • y + (b / (a + b)) • z = x :=
begin
split,
{ rintro ⟨a, b, ha, hb, hab, rfl⟩,
use [a, b, ha, hb],
simp * },
{ rintro ⟨a, b, ha, hb, hab, rfl⟩,
refine ⟨a / (a + b), b / (a + b), div_nonneg ha hab.le, div_nonneg hb hab.le, _, rfl⟩,
rw [← add_div, div_self hab.ne'] }
end
lemma mem_open_segment_iff_div : x ∈ open_segment 𝕜 y z ↔
∃ a b : 𝕜, 0 < a ∧ 0 < b ∧ (a / (a + b)) • y + (b / (a + b)) • z = x :=
begin
split,
{ rintro ⟨a, b, ha, hb, hab, rfl⟩,
use [a, b, ha, hb],
rw [hab, div_one, div_one] },
{ rintro ⟨a, b, ha, hb, rfl⟩,
have hab : 0 < a + b, from add_pos ha hb,
refine ⟨a / (a + b), b / (a + b), div_pos ha hab, div_pos hb hab, _, rfl⟩,
rw [← add_div, div_self hab.ne'] }
end
end add_comm_group
end linear_ordered_field
/-!
#### Segments in an ordered space
Relates `segment`, `open_segment` and `set.Icc`, `set.Ico`, `set.Ioc`, `set.Ioo`
-/
section ordered_semiring
variables [ordered_semiring 𝕜]
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E]
lemma segment_subset_Icc {x y : E} (h : x ≤ y) : [x -[𝕜] y] ⊆ Icc x y :=
begin
rintro z ⟨a, b, ha, hb, hab, rfl⟩,
split,
calc
x = a • x + b • x :(convex.combo_self hab _).symm
... ≤ a • x + b • y : add_le_add_left (smul_le_smul_of_nonneg h hb) _,
calc
a • x + b • y
≤ a • y + b • y : add_le_add_right (smul_le_smul_of_nonneg h ha) _
... = y : convex.combo_self hab _,
end
end ordered_add_comm_monoid
section ordered_cancel_add_comm_monoid
variables [ordered_cancel_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E]
lemma open_segment_subset_Ioo {x y : E} (h : x < y) : open_segment 𝕜 x y ⊆ Ioo x y :=
begin
rintro z ⟨a, b, ha, hb, hab, rfl⟩,
split,
calc
x = a • x + b • x : (convex.combo_self hab _).symm
... < a • x + b • y : add_lt_add_left (smul_lt_smul_of_pos h hb) _,
calc
a • x + b • y
< a • y + b • y : add_lt_add_right (smul_lt_smul_of_pos h ha) _
... = y : convex.combo_self hab _,
end
end ordered_cancel_add_comm_monoid
section linear_ordered_add_comm_monoid
variables [linear_ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {𝕜}
lemma segment_subset_interval (x y : E) : [x -[𝕜] y] ⊆ interval x y :=
begin
cases le_total x y,
{ rw interval_of_le h,
exact segment_subset_Icc h },
{ rw [interval_of_ge h, segment_symm],
exact segment_subset_Icc h }
end
lemma convex.min_le_combo (x y : E) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
min x y ≤ a • x + b • y :=
(segment_subset_interval x y ⟨_, _, ha, hb, hab, rfl⟩).1
lemma convex.combo_le_max (x y : E) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
a • x + b • y ≤ max x y :=
(segment_subset_interval x y ⟨_, _, ha, hb, hab, rfl⟩).2
end linear_ordered_add_comm_monoid
end ordered_semiring
section linear_ordered_field
variables [linear_ordered_field 𝕜]
lemma Icc_subset_segment {x y : 𝕜} : Icc x y ⊆ [x -[𝕜] y] :=
begin
rintro z ⟨hxz, hyz⟩,
obtain rfl | h := (hxz.trans hyz).eq_or_lt,
{ rw segment_same,
exact hyz.antisymm hxz },
rw ←sub_nonneg at hxz hyz,
rw ←sub_pos at h,
refine ⟨(y - z) / (y - x), (z - x) / (y - x), div_nonneg hyz h.le, div_nonneg hxz h.le, _, _⟩,
{ rw [←add_div, sub_add_sub_cancel, div_self h.ne'] },
{ rw [smul_eq_mul, smul_eq_mul, ←mul_div_right_comm, ←mul_div_right_comm, ←add_div,
div_eq_iff h.ne', add_comm, sub_mul, sub_mul, mul_comm x, sub_add_sub_cancel, mul_sub] }
end
@[simp] lemma segment_eq_Icc {x y : 𝕜} (h : x ≤ y) : [x -[𝕜] y] = Icc x y :=
(segment_subset_Icc h).antisymm Icc_subset_segment
lemma Ioo_subset_open_segment {x y : 𝕜} : Ioo x y ⊆ open_segment 𝕜 x y :=
λ z hz, mem_open_segment_of_ne_left_right hz.1.ne hz.2.ne'
(Icc_subset_segment $ Ioo_subset_Icc_self hz)
@[simp] lemma open_segment_eq_Ioo {x y : 𝕜} (h : x < y) : open_segment 𝕜 x y = Ioo x y :=
(open_segment_subset_Ioo h).antisymm Ioo_subset_open_segment
lemma segment_eq_Icc' (x y : 𝕜) : [x -[𝕜] y] = Icc (min x y) (max x y) :=
begin
cases le_total x y,
{ rw [segment_eq_Icc h, max_eq_right h, min_eq_left h] },
{ rw [segment_symm, segment_eq_Icc h, max_eq_left h, min_eq_right h] }
end
lemma open_segment_eq_Ioo' {x y : 𝕜} (hxy : x ≠ y) :
open_segment 𝕜 x y = Ioo (min x y) (max x y) :=
begin
cases hxy.lt_or_lt,
{ rw [open_segment_eq_Ioo h, max_eq_right h.le, min_eq_left h.le] },
{ rw [open_segment_symm, open_segment_eq_Ioo h, max_eq_left h.le, min_eq_right h.le] }
end
lemma segment_eq_interval (x y : 𝕜) : [x -[𝕜] y] = interval x y :=
segment_eq_Icc' _ _
/-- A point is in an `Icc` iff it can be expressed as a convex combination of the endpoints. -/
lemma convex.mem_Icc {x y : 𝕜} (h : x ≤ y) {z : 𝕜} :
z ∈ Icc x y ↔ ∃ (a b : 𝕜), 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z :=
begin
rw ←segment_eq_Icc h,
simp_rw [←exists_prop],
refl,
end
/-- A point is in an `Ioo` iff it can be expressed as a strict convex combination of the endpoints.
-/
lemma convex.mem_Ioo {x y : 𝕜} (h : x < y) {z : 𝕜} :
z ∈ Ioo x y ↔ ∃ (a b : 𝕜), 0 < a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z :=
begin
rw ←open_segment_eq_Ioo h,
simp_rw [←exists_prop],
refl,
end
/-- A point is in an `Ioc` iff it can be expressed as a semistrict convex combination of the
endpoints. -/
lemma convex.mem_Ioc {x y : 𝕜} (h : x < y) {z : 𝕜} :
z ∈ Ioc x y ↔ ∃ (a b : 𝕜), 0 ≤ a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z :=
begin
split,
{ rintro hz,
obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ioc_subset_Icc_self hz),
obtain rfl | hb' := hb.eq_or_lt,
{ rw add_zero at hab,
rw [hab, one_mul, zero_mul, add_zero] at hz,
exact (hz.1.ne rfl).elim },
{ exact ⟨a, b, ha, hb', hab, rfl⟩ } },
{ rintro ⟨a, b, ha, hb, hab, rfl⟩,
obtain rfl | ha' := ha.eq_or_lt,
{ rw zero_add at hab,
rwa [hab, one_mul, zero_mul, zero_add, right_mem_Ioc] },
{ exact Ioo_subset_Ioc_self ((convex.mem_Ioo h).2 ⟨a, b, ha', hb, hab, rfl⟩) } }
end
/-- A point is in an `Ico` iff it can be expressed as a semistrict convex combination of the
endpoints. -/
lemma convex.mem_Ico {x y : 𝕜} (h : x < y) {z : 𝕜} :
z ∈ Ico x y ↔ ∃ (a b : 𝕜), 0 < a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z :=
begin
split,
{ rintro hz,
obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ico_subset_Icc_self hz),
obtain rfl | ha' := ha.eq_or_lt,
{ rw zero_add at hab,
rw [hab, one_mul, zero_mul, zero_add] at hz,
exact (hz.2.ne rfl).elim },
{ exact ⟨a, b, ha', hb, hab, rfl⟩ } },
{ rintro ⟨a, b, ha, hb, hab, rfl⟩,
obtain rfl | hb' := hb.eq_or_lt,
{ rw add_zero at hab,
rwa [hab, one_mul, zero_mul, add_zero, left_mem_Ico] },
{ exact Ioo_subset_Ico_self ((convex.mem_Ioo h).2 ⟨a, b, ha, hb', hab, rfl⟩) } }
end
end linear_ordered_field
/-! ### Convexity of sets -/
section ordered_semiring
variables [ordered_semiring 𝕜]
section add_comm_monoid
variables [add_comm_monoid E] [add_comm_monoid F]
section has_scalar
variables (𝕜) [has_scalar 𝕜 E] [has_scalar 𝕜 F] (s : set E)
/-- Convexity of sets. -/
def convex : Prop :=
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 →
a • x + b • y ∈ s
variables {𝕜 s}
lemma convex_iff_segment_subset :
convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x -[𝕜] y] ⊆ s :=
forall₄_congr $ λ x y hx hy, (segment_subset_iff _).symm
lemma convex.segment_subset (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) :
[x -[𝕜] y] ⊆ s :=
convex_iff_segment_subset.1 h hx hy
lemma convex.open_segment_subset (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) :
open_segment 𝕜 x y ⊆ s :=
(open_segment_subset_segment 𝕜 x y).trans (h.segment_subset hx hy)
/-- Alternative definition of set convexity, in terms of pointwise set operations. -/
lemma convex_iff_pointwise_add_subset :
convex 𝕜 s ↔ ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s :=
iff.intro
begin
rintro hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩,
exact hA hu hv ha hb hab
end
(λ h x y hx hy a b ha hb hab,
(h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩))
alias convex_iff_pointwise_add_subset ↔ convex.set_combo_subset _
lemma convex_empty : convex 𝕜 (∅ : set E) :=
λ x y, false.elim
lemma convex_univ : convex 𝕜 (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial
lemma convex.inter {t : set E} (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s ∩ t) :=
λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1),
⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩
lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex 𝕜 s) : convex 𝕜 (⋂₀ S) :=
assume x y hx hy a b ha hb hab s hs,
h s hs (hx s hs) (hy s hs) ha hb hab
lemma convex_Inter {ι : Sort*} {s : ι → set E} (h : ∀ i, convex 𝕜 (s i)) : convex 𝕜 (⋂ i, s i) :=
(sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h
lemma convex_Inter₂ {ι : Sort*} {κ : ι → Sort*} {s : Π i, κ i → set E}
(h : ∀ i j, convex 𝕜 (s i j)) :
convex 𝕜 (⋂ i j, s i j) :=
convex_Inter $ λ i, convex_Inter $ h i
lemma convex.prod {s : set E} {t : set F} (hs : convex 𝕜 s) (ht : convex 𝕜 t) :
convex 𝕜 (s ×ˢ t) :=
begin
intros x y hx hy a b ha hb hab,
apply mem_prod.2,
exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab,
ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩
end
lemma convex_pi {ι : Type*} {E : ι → Type*} [Π i, add_comm_monoid (E i)]
[Π i, has_scalar 𝕜 (E i)] {s : set ι} {t : Π i, set (E i)} (ht : ∀ i, convex 𝕜 (t i)) :
convex 𝕜 (s.pi t) :=
λ x y hx hy a b ha hb hab i hi, ht i (hx i hi) (hy i hi) ha hb hab
lemma directed.convex_Union {ι : Sort*} {s : ι → set E} (hdir : directed (⊆) s)
(hc : ∀ ⦃i : ι⦄, convex 𝕜 (s i)) :
convex 𝕜 (⋃ i, s i) :=
begin
rintro x y hx hy a b ha hb hab,
rw mem_Union at ⊢ hx hy,
obtain ⟨i, hx⟩ := hx,
obtain ⟨j, hy⟩ := hy,
obtain ⟨k, hik, hjk⟩ := hdir i j,
exact ⟨k, hc (hik hx) (hjk hy) ha hb hab⟩,
end
lemma directed_on.convex_sUnion {c : set (set E)} (hdir : directed_on (⊆) c)
(hc : ∀ ⦃A : set E⦄, A ∈ c → convex 𝕜 A) :
convex 𝕜 (⋃₀c) :=
begin
rw sUnion_eq_Union,
exact (directed_on_iff_directed.1 hdir).convex_Union (λ A, hc A.2),
end
end has_scalar
section module
variables [module 𝕜 E] [module 𝕜 F] {s : set E}
lemma convex_iff_open_segment_subset :
convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → open_segment 𝕜 x y ⊆ s :=
convex_iff_segment_subset.trans $ forall₄_congr $ λ x y hx hy,
(open_segment_subset_iff_segment_subset hx hy).symm
lemma convex_iff_forall_pos :
convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1
→ a • x + b • y ∈ s :=
convex_iff_open_segment_subset.trans $ forall₄_congr $ λ x y hx hy,
open_segment_subset_iff 𝕜
lemma convex_iff_pairwise_pos :
convex 𝕜 s ↔ s.pairwise (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s) :=
begin
refine convex_iff_forall_pos.trans ⟨λ h x hx y hy _, h hx hy, _⟩,
intros h x y hx hy a b ha hb hab,
obtain rfl | hxy := eq_or_ne x y,
{ rwa convex.combo_self hab },
{ exact h hx hy hxy ha hb hab },
end
protected lemma set.subsingleton.convex {s : set E} (h : s.subsingleton) : convex 𝕜 s :=
convex_iff_pairwise_pos.mpr (h.pairwise _)
lemma convex_singleton (c : E) : convex 𝕜 ({c} : set E) :=
subsingleton_singleton.convex
lemma convex.linear_image (hs : convex 𝕜 s) (f : E →ₗ[𝕜] F) : convex 𝕜 (f '' s) :=
begin
intros x y hx hy a b ha hb hab,
obtain ⟨x', hx', rfl⟩ := mem_image_iff_bex.1 hx,
obtain ⟨y', hy', rfl⟩ := mem_image_iff_bex.1 hy,
exact ⟨a • x' + b • y', hs hx' hy' ha hb hab, by rw [f.map_add, f.map_smul, f.map_smul]⟩,
end
lemma convex.is_linear_image (hs : convex 𝕜 s) {f : E → F} (hf : is_linear_map 𝕜 f) :
convex 𝕜 (f '' s) :=
hs.linear_image $ hf.mk' f
lemma convex.linear_preimage {s : set F} (hs : convex 𝕜 s) (f : E →ₗ[𝕜] F) :
convex 𝕜 (f ⁻¹' s) :=
begin
intros x y hx hy a b ha hb hab,
rw [mem_preimage, f.map_add, f.map_smul, f.map_smul],
exact hs hx hy ha hb hab,
end
lemma convex.is_linear_preimage {s : set F} (hs : convex 𝕜 s) {f : E → F} (hf : is_linear_map 𝕜 f) :
convex 𝕜 (f ⁻¹' s) :=
hs.linear_preimage $ hf.mk' f
lemma convex.add {t : set E} (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s + t) :=
by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add }
lemma convex.vadd (hs : convex 𝕜 s) (z : E) : convex 𝕜 (z +ᵥ s) :=
by { simp_rw [←image_vadd, vadd_eq_add, ←singleton_add], exact (convex_singleton _).add hs }
lemma convex.translate (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, z + x) '' s) := hs.vadd _
/-- The translation of a convex set is also convex. -/
lemma convex.translate_preimage_right (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, z + x) ⁻¹' s) :=
begin
intros x y hx hy a b ha hb hab,
have h := hs hx hy ha hb hab,
rwa [smul_add, smul_add, add_add_add_comm, ←add_smul, hab, one_smul] at h,
end
/-- The translation of a convex set is also convex. -/
lemma convex.translate_preimage_left (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, x + z) ⁻¹' s) :=
by simpa only [add_comm] using hs.translate_preimage_right z
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β]
lemma convex_Iic (r : β) : convex 𝕜 (Iic r) :=
λ x y hx hy a b ha hb hab,
calc
a • x + b • y
≤ a • r + b • r
: add_le_add (smul_le_smul_of_nonneg hx ha) (smul_le_smul_of_nonneg hy hb)
... = r : convex.combo_self hab _
lemma convex_Ici (r : β) : convex 𝕜 (Ici r) := @convex_Iic 𝕜 βᵒᵈ _ _ _ _ r
lemma convex_Icc (r s : β) : convex 𝕜 (Icc r s) :=
Ici_inter_Iic.subst ((convex_Ici r).inter $ convex_Iic s)
lemma convex_halfspace_le {f : E → β} (h : is_linear_map 𝕜 f) (r : β) :
convex 𝕜 {w | f w ≤ r} :=
(convex_Iic r).is_linear_preimage h
lemma convex_halfspace_ge {f : E → β} (h : is_linear_map 𝕜 f) (r : β) :
convex 𝕜 {w | r ≤ f w} :=
(convex_Ici r).is_linear_preimage h
lemma convex_hyperplane {f : E → β} (h : is_linear_map 𝕜 f) (r : β) :
convex 𝕜 {w | f w = r} :=
begin
simp_rw le_antisymm_iff,
exact (convex_halfspace_le h r).inter (convex_halfspace_ge h r),
end
end ordered_add_comm_monoid
section ordered_cancel_add_comm_monoid
variables [ordered_cancel_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β]
lemma convex_Iio (r : β) : convex 𝕜 (Iio r) :=
begin
intros x y hx hy a b ha hb hab,
obtain rfl | ha' := ha.eq_or_lt,
{ rw zero_add at hab,
rwa [zero_smul, zero_add, hab, one_smul] },
rw mem_Iio at hx hy,
calc
a • x + b • y
< a • r + b • r
: add_lt_add_of_lt_of_le (smul_lt_smul_of_pos hx ha') (smul_le_smul_of_nonneg hy.le hb)
... = r : convex.combo_self hab _
end
lemma convex_Ioi (r : β) : convex 𝕜 (Ioi r) := @convex_Iio 𝕜 βᵒᵈ _ _ _ _ r
lemma convex_Ioo (r s : β) : convex 𝕜 (Ioo r s) :=
Ioi_inter_Iio.subst ((convex_Ioi r).inter $ convex_Iio s)
lemma convex_Ico (r s : β) : convex 𝕜 (Ico r s) :=
Ici_inter_Iio.subst ((convex_Ici r).inter $ convex_Iio s)
lemma convex_Ioc (r s : β) : convex 𝕜 (Ioc r s) :=
Ioi_inter_Iic.subst ((convex_Ioi r).inter $ convex_Iic s)
lemma convex_halfspace_lt {f : E → β} (h : is_linear_map 𝕜 f) (r : β) :
convex 𝕜 {w | f w < r} :=
(convex_Iio r).is_linear_preimage h
lemma convex_halfspace_gt {f : E → β} (h : is_linear_map 𝕜 f) (r : β) :
convex 𝕜 {w | r < f w} :=
(convex_Ioi r).is_linear_preimage h
end ordered_cancel_add_comm_monoid
section linear_ordered_add_comm_monoid
variables [linear_ordered_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β]
lemma convex_interval (r s : β) : convex 𝕜 (interval r s) :=
convex_Icc _ _
end linear_ordered_add_comm_monoid
end module
end add_comm_monoid
section linear_ordered_add_comm_monoid
variables [linear_ordered_add_comm_monoid E] [ordered_add_comm_monoid β] [module 𝕜 E]
[ordered_smul 𝕜 E] {s : set E} {f : E → β}
lemma monotone_on.convex_le (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | f x ≤ r} :=
λ x y hx hy a b ha hb hab, ⟨hs hx.1 hy.1 ha hb hab,
(hf (hs hx.1 hy.1 ha hb hab) (max_rec' s hx.1 hy.1) (convex.combo_le_max x y ha hb hab)).trans
(max_rec' _ hx.2 hy.2)⟩
lemma monotone_on.convex_lt (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | f x < r} :=
λ x y hx hy a b ha hb hab, ⟨hs hx.1 hy.1 ha hb hab,
(hf (hs hx.1 hy.1 ha hb hab) (max_rec' s hx.1 hy.1) (convex.combo_le_max x y ha hb hab)).trans_lt
(max_rec' _ hx.2 hy.2)⟩
lemma monotone_on.convex_ge (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | r ≤ f x} :=
@monotone_on.convex_le 𝕜 Eᵒᵈ βᵒᵈ _ _ _ _ _ _ _ hf.dual hs r
lemma monotone_on.convex_gt (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | r < f x} :=
@monotone_on.convex_lt 𝕜 Eᵒᵈ βᵒᵈ _ _ _ _ _ _ _ hf.dual hs r
lemma antitone_on.convex_le (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | f x ≤ r} :=
@monotone_on.convex_ge 𝕜 E βᵒᵈ _ _ _ _ _ _ _ hf hs r
lemma antitone_on.convex_lt (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | f x < r} :=
@monotone_on.convex_gt 𝕜 E βᵒᵈ _ _ _ _ _ _ _ hf hs r
lemma antitone_on.convex_ge (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | r ≤ f x} :=
@monotone_on.convex_le 𝕜 E βᵒᵈ _ _ _ _ _ _ _ hf hs r
lemma antitone_on.convex_gt (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | r < f x} :=
@monotone_on.convex_lt 𝕜 E βᵒᵈ _ _ _ _ _ _ _ hf hs r
lemma monotone.convex_le (hf : monotone f) (r : β) :
convex 𝕜 {x | f x ≤ r} :=
set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r)
lemma monotone.convex_lt (hf : monotone f) (r : β) :
convex 𝕜 {x | f x ≤ r} :=
set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r)
lemma monotone.convex_ge (hf : monotone f ) (r : β) :
convex 𝕜 {x | r ≤ f x} :=
set.sep_univ.subst ((hf.monotone_on univ).convex_ge convex_univ r)
lemma monotone.convex_gt (hf : monotone f) (r : β) :
convex 𝕜 {x | f x ≤ r} :=
set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r)
lemma antitone.convex_le (hf : antitone f) (r : β) :
convex 𝕜 {x | f x ≤ r} :=
set.sep_univ.subst ((hf.antitone_on univ).convex_le convex_univ r)
lemma antitone.convex_lt (hf : antitone f) (r : β) :
convex 𝕜 {x | f x < r} :=
set.sep_univ.subst ((hf.antitone_on univ).convex_lt convex_univ r)
lemma antitone.convex_ge (hf : antitone f) (r : β) :
convex 𝕜 {x | r ≤ f x} :=
set.sep_univ.subst ((hf.antitone_on univ).convex_ge convex_univ r)
lemma antitone.convex_gt (hf : antitone f) (r : β) :
convex 𝕜 {x | r < f x} :=
set.sep_univ.subst ((hf.antitone_on univ).convex_gt convex_univ r)
end linear_ordered_add_comm_monoid
section add_comm_group
variables [add_comm_group E] [module 𝕜 E] {s t : set E}
lemma convex.combo_eq_vadd {a b : 𝕜} {x y : E} (h : a + b = 1) :
a • x + b • y = b • (y - x) + x :=
calc
a • x + b • y = (b • y - b • x) + (a • x + b • x) : by abel
... = b • (y - x) + x : by rw [smul_sub, convex.combo_self h]
lemma convex_segment (x y : E) : convex 𝕜 [x -[𝕜] y] :=
begin
rintro p q ⟨ap, bp, hap, hbp, habp, rfl⟩ ⟨aq, bq, haq, hbq, habq, rfl⟩ a b ha hb hab,
refine ⟨a * ap + b * aq, a * bp + b * bq,
add_nonneg (mul_nonneg ha hap) (mul_nonneg hb haq),
add_nonneg (mul_nonneg ha hbp) (mul_nonneg hb hbq), _, _⟩,
{ rw [add_add_add_comm, ←mul_add, ←mul_add, habp, habq, mul_one, mul_one, hab] },
{ simp_rw [add_smul, mul_smul, smul_add],
exact add_add_add_comm _ _ _ _ }
end
lemma convex_open_segment (a b : E) : convex 𝕜 (open_segment 𝕜 a b) :=
begin
rw convex_iff_open_segment_subset,
rintro p q ⟨ap, bp, hap, hbp, habp, rfl⟩ ⟨aq, bq, haq, hbq, habq, rfl⟩ z ⟨a, b, ha, hb, hab, rfl⟩,
refine ⟨a * ap + b * aq, a * bp + b * bq,
add_pos (mul_pos ha hap) (mul_pos hb haq),
add_pos (mul_pos ha hbp) (mul_pos hb hbq), _, _⟩,
{ rw [add_add_add_comm, ←mul_add, ←mul_add, habp, habq, mul_one, mul_one, hab] },
{ simp_rw [add_smul, mul_smul, smul_add],
exact add_add_add_comm _ _ _ _ }
end
end add_comm_group
end ordered_semiring
section ordered_comm_semiring
variables [ordered_comm_semiring 𝕜]
section add_comm_monoid
variables [add_comm_monoid E] [add_comm_monoid F] [module 𝕜 E] [module 𝕜 F] {s : set E}
lemma convex.smul (hs : convex 𝕜 s) (c : 𝕜) : convex 𝕜 (c • s) :=
hs.linear_image (linear_map.lsmul _ _ c)
lemma convex.smul_preimage (hs : convex 𝕜 s) (c : 𝕜) : convex 𝕜 ((λ z, c • z) ⁻¹' s) :=
hs.linear_preimage (linear_map.lsmul _ _ c)
lemma convex.affinity (hs : convex 𝕜 s) (z : E) (c : 𝕜) : convex 𝕜 ((λ x, z + c • x) '' s) :=
by simpa only [←image_smul, ←image_vadd, image_image] using (hs.smul c).vadd z
end add_comm_monoid
end ordered_comm_semiring
section ordered_ring
variables [ordered_ring 𝕜]
section add_comm_group
variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s t : set E}
lemma convex.add_smul_mem (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : x + y ∈ s)
{t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : x + t • y ∈ s :=
begin
have h : x + t • y = (1 - t) • x + t • (x + y),
{ rw [smul_add, ←add_assoc, ←add_smul, sub_add_cancel, one_smul] },
rw h,
exact hs hx hy (sub_nonneg_of_le ht.2) ht.1 (sub_add_cancel _ _),
end
lemma convex.smul_mem_of_zero_mem (hs : convex 𝕜 s) {x : E} (zero_mem : (0 : E) ∈ s) (hx : x ∈ s)
{t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : t • x ∈ s :=
by simpa using hs.add_smul_mem zero_mem (by simpa using hx) ht
lemma convex.add_smul_sub_mem (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s)
{t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : x + t • (y - x) ∈ s :=
begin
apply h.segment_subset hx hy,
rw segment_eq_image',
exact mem_image_of_mem _ ht,
end
/-- Affine subspaces are convex. -/
lemma affine_subspace.convex (Q : affine_subspace 𝕜 E) : convex 𝕜 (Q : set E) :=
begin
intros x y hx hy a b ha hb hab,
rw [eq_sub_of_add_eq hab, ← affine_map.line_map_apply_module],
exact affine_map.line_map_mem b hx hy,
end
/--
Applying an affine map to an affine combination of two points yields
an affine combination of the images.
-/
lemma convex.combo_affine_apply {a b : 𝕜} {x y : E} {f : E →ᵃ[𝕜] F} (h : a + b = 1) :
f (a • x + b • y) = a • f x + b • f y :=
begin
simp only [convex.combo_eq_vadd h, ← vsub_eq_sub],
exact f.apply_line_map _ _ _,
end
/-- The preimage of a convex set under an affine map is convex. -/
lemma convex.affine_preimage (f : E →ᵃ[𝕜] F) {s : set F} (hs : convex 𝕜 s) :
convex 𝕜 (f ⁻¹' s) :=
begin
intros x y xs ys a b ha hb hab,
rw [mem_preimage, convex.combo_affine_apply hab],
exact hs xs ys ha hb hab,
end
/-- The image of a convex set under an affine map is convex. -/
lemma convex.affine_image (f : E →ᵃ[𝕜] F) (hs : convex 𝕜 s) : convex 𝕜 (f '' s) :=
begin
rintro x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab,
refine ⟨a • x' + b • y', ⟨hs hx' hy' ha hb hab, _⟩⟩,
rw [convex.combo_affine_apply hab, hx'f, hy'f]
end
lemma convex.neg (hs : convex 𝕜 s) : convex 𝕜 (-s) :=
hs.is_linear_preimage is_linear_map.is_linear_map_neg
lemma convex.sub (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s - t) :=
by { rw sub_eq_add_neg, exact hs.add ht.neg }
end add_comm_group
end ordered_ring
section linear_ordered_field
variables [linear_ordered_field 𝕜]
section add_comm_group
variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s : set E}
/-- Alternative definition of set convexity, using division. -/
lemma convex_iff_div :
convex 𝕜 s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄,
0 ≤ a → 0 ≤ b → 0 < a + b → (a / (a + b)) • x + (b / (a + b)) • y ∈ s :=
begin
simp only [convex_iff_segment_subset, subset_def, mem_segment_iff_div],
refine forall₄_congr (λ x y hx hy, ⟨λ H a b ha hb hab, H _ ⟨a, b, ha, hb, hab, rfl⟩, _⟩),
rintro H _ ⟨a, b, ha, hb, hab, rfl⟩,
exact H ha hb hab
end
lemma convex.mem_smul_of_zero_mem (h : convex 𝕜 s) {x : E} (zero_mem : (0 : E) ∈ s)
(hx : x ∈ s) {t : 𝕜} (ht : 1 ≤ t) :
x ∈ t • s :=
begin
rw mem_smul_set_iff_inv_smul_mem₀ (zero_lt_one.trans_le ht).ne',
exact h.smul_mem_of_zero_mem zero_mem hx ⟨inv_nonneg.2 (zero_le_one.trans ht), inv_le_one ht⟩,
end
lemma convex.add_smul (h_conv : convex 𝕜 s) {p q : 𝕜} (hp : 0 ≤ p) (hq : 0 ≤ q) :
(p + q) • s = p • s + q • s :=
begin
obtain rfl | hs := s.eq_empty_or_nonempty,
{ simp_rw [smul_set_empty, add_empty] },
obtain rfl | hp' := hp.eq_or_lt,
{ rw [zero_add, zero_smul_set hs, zero_add] },
obtain rfl | hq' := hq.eq_or_lt,
{ rw [add_zero, zero_smul_set hs, add_zero] },
ext,
split,
{ rintro ⟨v, hv, rfl⟩,
exact ⟨p • v, q • v, smul_mem_smul_set hv, smul_mem_smul_set hv, (add_smul _ _ _).symm⟩ },
{ rintro ⟨v₁, v₂, ⟨v₁₁, h₁₂, rfl⟩, ⟨v₂₁, h₂₂, rfl⟩, rfl⟩,
have hpq := add_pos hp' hq',
exact mem_smul_set.2 ⟨_, h_conv h₁₂ h₂₂ (div_pos hp' hpq).le (div_pos hq' hpq).le
(by rw [←div_self hpq.ne', add_div] : p / (p + q) + q / (p + q) = 1),
by simp only [← mul_smul, smul_add, mul_div_cancel' _ hpq.ne']⟩ }
end
end add_comm_group
end linear_ordered_field
/-!
#### Convex sets in an ordered space
Relates `convex` and `ord_connected`.
-/
section
lemma set.ord_connected.convex_of_chain [ordered_semiring 𝕜] [ordered_add_comm_monoid E]
[module 𝕜 E] [ordered_smul 𝕜 E] {s : set E} (hs : s.ord_connected) (h : is_chain (≤) s) :
convex 𝕜 s :=
begin
refine convex_iff_segment_subset.mpr (λ x y hx hy, _),
obtain hxy | hyx := h.total hx hy,
{ exact (segment_subset_Icc hxy).trans (hs.out hx hy) },
{ rw segment_symm,
exact (segment_subset_Icc hyx).trans (hs.out hy hx) }
end
lemma set.ord_connected.convex [ordered_semiring 𝕜] [linear_ordered_add_comm_monoid E] [module 𝕜 E]
[ordered_smul 𝕜 E] {s : set E} (hs : s.ord_connected) :
convex 𝕜 s :=
hs.convex_of_chain $ is_chain_of_trichotomous s
lemma convex_iff_ord_connected [linear_ordered_field 𝕜] {s : set 𝕜} :
convex 𝕜 s ↔ s.ord_connected :=
begin
simp_rw [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset],
exact forall_congr (λ x, forall_swap)
end
alias convex_iff_ord_connected ↔ convex.ord_connected _
end
/-! #### Convexity of submodules/subspaces -/
section submodule
open submodule
lemma submodule.convex [ordered_semiring 𝕜] [add_comm_monoid E] [module 𝕜 E] (K : submodule 𝕜 E) :
convex 𝕜 (↑K : set E) :=
by { repeat {intro}, refine add_mem (smul_mem _ _ _) (smul_mem _ _ _); assumption }
lemma subspace.convex [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] (K : subspace 𝕜 E) :
convex 𝕜 (↑K : set E) :=
K.convex
end submodule
/-! ### Simplex -/
section simplex
variables (𝕜) (ι : Type*) [ordered_semiring 𝕜] [fintype ι]
/-- The standard simplex in the space of functions `ι → 𝕜` is the set of vectors with non-negative
coordinates with total sum `1`. This is the free object in the category of convex spaces. -/
def std_simplex : set (ι → 𝕜) :=
{f | (∀ x, 0 ≤ f x) ∧ ∑ x, f x = 1}
lemma std_simplex_eq_inter :
std_simplex 𝕜 ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | ∑ x, f x = 1} :=
by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] }
lemma convex_std_simplex : convex 𝕜 (std_simplex 𝕜 ι) :=
begin
refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩,
{ apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] },
{ erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2,
smul_eq_mul, smul_eq_mul, mul_one, mul_one],
exact hab }
end
variable {ι}
lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:𝕜) 0) ∈ std_simplex 𝕜 ι :=
⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)]⟩
end simplex
|
fb241d42707fb4f5f8f9b23168a1ace43e847d16 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/algebra/group_with_zero_power.lean | 2f137e9d433cd8288645e1be32f401cd8a1f9fd5 | [
"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 | 9,475 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.group_power
/-!
# Powers of elements of groups with an adjoined zero element
In this file we define integer power functions for groups with an adjoined zero element.
This generalises the integer power function on a division ring.
-/
section zero
variables {M : Type*} [monoid_with_zero M]
@[simp] lemma zero_pow' : ∀ n : ℕ, n ≠ 0 → (0 : M) ^ n = 0
| 0 h := absurd rfl h
| (k+1) h := zero_mul _
lemma ne_zero_pow {a : M} {n : ℕ} (hn : n ≠ 0) : a ^ n ≠ 0 → a ≠ 0 :=
by { contrapose!, rintro rfl, exact zero_pow' n hn }
@[simp] lemma zero_pow_eq_zero [nontrivial M] {n : ℕ} : (0 : M) ^ n = 0 ↔ 0 < n :=
begin
split; intro h,
{ rw [nat.pos_iff_ne_zero], rintro rfl, simpa using h },
{ exact zero_pow' n h.ne.symm }
end
theorem pow_eq_zero' [no_zero_divisors M] {a : M} {n : ℕ} (H : a ^ n = 0) : a = 0 :=
begin
induction n with n ih,
{ rw pow_zero at H,
rw [← mul_one a, H, mul_zero] },
exact or.cases_on (mul_eq_zero.1 H) id ih
end
@[field_simps]
theorem pow_ne_zero' [no_zero_divisors M] {a : M} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 :=
mt pow_eq_zero' h
end zero
section group_with_zero
variables {G₀ : Type*} [group_with_zero G₀]
section nat_pow
@[simp, field_simps] theorem inv_pow' (a : G₀) (n : ℕ) : (a⁻¹) ^ n = (a ^ n)⁻¹ :=
by induction n with n ih; [exact inv_one.symm,
rw [pow_succ', pow_succ, ih, mul_inv_rev']]
theorem pow_sub' (a : G₀) {m n : ℕ} (ha : a ≠ 0) (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_div_of_mul_eq (pow_ne_zero' _ ha) h2
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
end nat_pow
end group_with_zero
section int_pow
open int
variables {G₀ : Type*} [group_with_zero G₀]
/--
The power operation in a group with zero.
This extends `monoid.pow` to negative integers
with the definition `a ^ (-n) = (a ^ n)⁻¹`.
-/
def fpow (a : G₀) : ℤ → G₀
| (of_nat n) := a ^ n
| -[1+n] := (a ^ (nat.succ n))⁻¹
@[priority 10] instance : has_pow G₀ ℤ := ⟨fpow⟩
@[simp] theorem fpow_coe_nat (a : G₀) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl
theorem fpow_of_nat (a : G₀) (n : ℕ) : a ^ of_nat n = a ^ n := rfl
@[simp] theorem fpow_neg_succ_of_nat (a : G₀) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl
local attribute [ematch] le_of_lt
@[simp] theorem fpow_zero (a : G₀) : a ^ (0:ℤ) = 1 := rfl
@[simp] theorem fpow_one (a : G₀) : a ^ (1:ℤ) = a := mul_one _
@[simp] theorem one_fpow : ∀ (n : ℤ), (1 : G₀) ^ n = 1
| (n : ℕ) := one_pow _
| -[1+ n] := show _⁻¹=(1:G₀), by rw [one_pow, inv_one]
lemma zero_fpow : ∀ z : ℤ, z ≠ 0 → (0 : G₀) ^ z = 0
| (of_nat n) h := zero_pow' _ $ by rintro rfl; exact h rfl
| -[1+n] h := show (0*0 ^ n)⁻¹ = (0 : G₀), by simp
@[simp] theorem fpow_neg (a : G₀) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹
| (n+1:ℕ) := rfl
| 0 := inv_one.symm
| -[1+ n] := (inv_inv' _).symm
theorem fpow_neg_one (x : G₀) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x
theorem inv_fpow (a : G₀) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹
| (n : ℕ) := inv_pow' a n
| -[1+ n] := congr_arg has_inv.inv $ inv_pow' a (n+1)
lemma fpow_add_one {a : G₀} (ha : a ≠ 0) : ∀ 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, ha]
| -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, fpow_neg, neg_add, neg_add_cancel_right, fpow_neg,
← int.coe_nat_succ, fpow_coe_nat, fpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev', mul_assoc,
inv_mul_cancel ha, mul_one]
lemma fpow_sub_one {a : G₀} (ha : a ≠ 0) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ :=
calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : by rw [mul_assoc, mul_inv_cancel ha, mul_one]
... = a^n * a⁻¹ : by rw [← fpow_add_one ha, sub_add_cancel]
lemma fpow_add {a : G₀} (ha : a ≠ 0) (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, fpow_add_one ha, ihn, mul_assoc] },
{ rw [fpow_sub_one ha, ← mul_assoc, ← ihn, ← fpow_sub_one ha, add_sub_assoc] }
end
lemma fpow_add' {a : G₀} {m n : ℤ} (h : a ≠ 0 ∨ m + n ≠ 0 ∨ m = 0 ∧ n = 0) :
a ^ (m + n) = a ^ m * a ^ n :=
begin
by_cases hm : m = 0, { simp [hm] },
by_cases hn : n = 0, { simp [hn] },
by_cases ha : a = 0,
{ subst a,
simp only [false_or, eq_self_iff_true, not_true, ne.def, hm, hn, false_and, or_false] at h,
rw [zero_fpow _ h, zero_fpow _ hm, zero_mul] },
{ exact fpow_add ha m n }
end
theorem fpow_one_add {a : G₀} (h : a ≠ 0) (i : ℤ) : a ^ (1 + i) = a * a ^ i :=
by rw [fpow_add h, fpow_one]
theorem semiconj_by.fpow_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 + 1)).inv_right'
theorem commute.fpow_right {a b : G₀} (h : commute a b) : ∀ m : ℤ, commute a (b^m) :=
h.fpow_right
theorem commute.fpow_left {a b : G₀} (h : commute a b) (m : ℤ) : commute (a^m) b :=
(h.symm.fpow_right m).symm
theorem commute.fpow_fpow {a b : G₀} (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) :=
(h.fpow_left m).fpow_right n
theorem commute.fpow_self (a : G₀) (n : ℤ) : commute (a^n) a := (commute.refl a).fpow_left n
theorem commute.self_fpow (a : G₀) (n : ℤ) : commute a (a^n) := (commute.refl a).fpow_right n
theorem commute.fpow_fpow_self (a : G₀) (m n : ℤ) : commute (a^m) (a^n) := (commute.refl a).fpow_fpow m n
theorem fpow_bit0 (a : G₀) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n :=
begin
apply fpow_add', right,
by_cases hn : n = 0,
{ simp [hn] },
{ simp [← two_mul, hn, two_ne_zero] }
end
theorem fpow_bit1 (a : G₀) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a :=
begin
rw [← fpow_bit0, bit1, fpow_add', fpow_one],
right, left,
apply bit1_ne_zero
end
theorem fpow_mul (a : G₀) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n
| (m : ℕ) (n : ℕ) := pow_mul _ _ _
| (m : ℕ) -[1+ n] := (fpow_neg _ (m * n.succ)).trans $
show (a ^ (m * n.succ))⁻¹ = _, by rw pow_mul; refl
| -[1+ m] (n : ℕ) := (fpow_neg _ (m.succ * n)).trans $
show (a ^ (m.succ * n))⁻¹ = _, by rw [pow_mul, ← inv_pow']; refl
| -[1+ m] -[1+ n] := (pow_mul a m.succ n.succ).trans $
show _ = (_⁻¹ ^ _)⁻¹, by rw [inv_pow', inv_inv']
theorem fpow_mul' (a : G₀) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m :=
by rw [mul_comm, fpow_mul]
@[simp, norm_cast] lemma units.coe_gpow' (u : units G₀) :
∀ (n : ℤ), ((u ^ n : units G₀) : G₀) = u ^ n
| (n : ℕ) := u.coe_pow n
| -[1+k] := by rw [gpow_neg_succ_of_nat, fpow_neg_succ_of_nat, units.coe_inv', u.coe_pow]
lemma fpow_ne_zero_of_ne_zero {a : G₀} (ha : a ≠ 0) : ∀ (z : ℤ), a ^ z ≠ 0
| (of_nat n) := pow_ne_zero' _ ha
| -[1+n] := inv_ne_zero $ pow_ne_zero' _ ha
lemma fpow_sub {a : G₀} (ha : a ≠ 0) (z1 z2 : ℤ) : a ^ (z1 - z2) = a ^ z1 / a ^ z2 :=
by rw [sub_eq_add_neg, fpow_add ha, fpow_neg]; refl
lemma commute.mul_fpow {a b : G₀} (h : commute a b) :
∀ (i : ℤ), (a * b) ^ i = (a ^ i) * (b ^ i)
| (n : ℕ) := h.mul_pow n
| -[1+n] := by simp [h.mul_pow, (h.pow_pow _ _).eq, mul_inv_rev']
lemma mul_fpow {G₀ : Type*} [comm_group_with_zero G₀] (a b : G₀) (m : ℤ):
(a * b) ^ m = (a ^ m) * (b ^ m) :=
(commute.all a b).mul_fpow m
theorem fpow_bit0' (a : G₀) (n : ℤ) : a ^ bit0 n = (a * a) ^ n :=
(fpow_bit0 a n).trans ((commute.refl a).mul_fpow n).symm
theorem fpow_bit1' (a : G₀) (n : ℤ) : a ^ bit1 n = (a * a) ^ n * a :=
by rw [fpow_bit1, (commute.refl a).mul_fpow]
lemma fpow_eq_zero {x : G₀} {n : ℤ} (h : x ^ n = 0) : x = 0 :=
classical.by_contradiction $ λ hx, fpow_ne_zero_of_ne_zero hx n h
lemma fpow_ne_zero {x : G₀} (n : ℤ) : x ≠ 0 → x ^ n ≠ 0 :=
mt fpow_eq_zero
theorem fpow_neg_mul_fpow_self (n : ℤ) {x : G₀} (h : x ≠ 0) :
x ^ (-n) * x ^ n = 1 :=
begin
rw [fpow_neg],
exact inv_mul_cancel (fpow_ne_zero n h)
end
theorem one_div_pow {a : G₀} (n : ℕ) :
(1 / a) ^ n = 1 / a ^ n :=
by simp only [one_div, inv_pow']
theorem one_div_fpow {a : G₀} (n : ℤ) :
(1 / a) ^ n = 1 / a ^ n :=
by simp only [one_div, inv_fpow]
end int_pow
section
variables {G₀ : Type*} [comm_group_with_zero G₀]
@[simp] theorem div_pow (a b : G₀) (n : ℕ) :
(a / b) ^ n = a ^ n / b ^ n :=
by simp only [div_eq_mul_inv, mul_pow, inv_pow']
@[simp] theorem div_fpow (a : G₀) {b : G₀} (n : ℤ) :
(a / b) ^ n = a ^ n / b ^ n :=
by simp only [div_eq_mul_inv, mul_fpow, inv_fpow]
lemma div_sq_cancel {a : G₀} (ha : a ≠ 0) (b : G₀) : a ^ 2 * b / a = a * b :=
by rw [pow_two, mul_assoc, mul_div_cancel_left _ ha]
end
/-- If a monoid homomorphism `f` between two `group_with_zero`s maps `0` to `0`, then it maps `x^n`,
`n : ℤ`, to `(f x)^n`. -/
lemma monoid_hom.map_fpow {G₀ G₀' : Type*} [group_with_zero G₀] [group_with_zero G₀']
(f : G₀ →* G₀') (h0 : f 0 = 0) (x : G₀) :
∀ n : ℤ, f (x ^ n) = f x ^ n
| (n : ℕ) := f.map_pow x n
| -[1+n] := (f.map_inv' h0 _).trans $ congr_arg _ $ f.map_pow x _
|
d8e5411e62a114c32e91b3f66d3cba18b6f757a0 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/normed_space/add_torsor.lean | 340c15bbe84f44fa8c38dcc58770d75ed78f9b22 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 7,264 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Yury Kudryashov
-/
import analysis.normed_space.basic
import analysis.normed.group.add_torsor
import linear_algebra.affine_space.midpoint
import linear_algebra.affine_space.affine_subspace
import topology.instances.real_vector_space
/-!
# Torsors of normed space actions.
This file contains lemmas about normed additive torsors over normed spaces.
-/
noncomputable theory
open_locale nnreal topological_space
open filter
variables {α V P : Type*} [semi_normed_group V] [pseudo_metric_space P] [normed_add_torsor V P]
variables {W Q : Type*} [normed_group W] [metric_space Q] [normed_add_torsor W Q]
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 V] [normed_space 𝕜 W]
open affine_map
lemma affine_subspace.is_closed_direction_iff (s : affine_subspace 𝕜 Q) :
is_closed (s.direction : set W) ↔ is_closed (s : set Q) :=
begin
rcases s.eq_bot_or_nonempty with rfl|⟨x, hx⟩, { simp [is_closed_singleton] },
rw [← (isometric.vadd_const x).to_homeomorph.symm.is_closed_image,
affine_subspace.coe_direction_eq_vsub_set_right hx],
refl
end
include V
@[simp] lemma dist_center_homothety (p₁ p₂ : P) (c : 𝕜) :
dist p₁ (homothety p₁ c p₂) = ∥c∥ * dist p₁ p₂ :=
by simp [homothety_def, norm_smul, ← dist_eq_norm_vsub, dist_comm]
@[simp] lemma dist_homothety_center (p₁ p₂ : P) (c : 𝕜) :
dist (homothety p₁ c p₂) p₁ = ∥c∥ * dist p₁ p₂ :=
by rw [dist_comm, dist_center_homothety]
@[simp] lemma dist_line_map_line_map (p₁ p₂ : P) (c₁ c₂ : 𝕜) :
dist (line_map p₁ p₂ c₁) (line_map p₁ p₂ c₂) = dist c₁ c₂ * dist p₁ p₂ :=
begin
rw dist_comm p₁ p₂,
simp only [line_map_apply, dist_eq_norm_vsub, vadd_vsub_vadd_cancel_right, ← sub_smul, norm_smul,
vsub_eq_sub],
end
lemma lipschitz_with_line_map (p₁ p₂ : P) :
lipschitz_with (nndist p₁ p₂) (line_map p₁ p₂ : 𝕜 → P) :=
lipschitz_with.of_dist_le_mul $ λ c₁ c₂,
((dist_line_map_line_map p₁ p₂ c₁ c₂).trans (mul_comm _ _)).le
@[simp] lemma dist_line_map_left (p₁ p₂ : P) (c : 𝕜) :
dist (line_map p₁ p₂ c) p₁ = ∥c∥ * dist p₁ p₂ :=
by simpa only [line_map_apply_zero, dist_zero_right] using dist_line_map_line_map p₁ p₂ c 0
@[simp] lemma dist_left_line_map (p₁ p₂ : P) (c : 𝕜) :
dist p₁ (line_map p₁ p₂ c) = ∥c∥ * dist p₁ p₂ :=
(dist_comm _ _).trans (dist_line_map_left _ _ _)
@[simp] lemma dist_line_map_right (p₁ p₂ : P) (c : 𝕜) :
dist (line_map p₁ p₂ c) p₂ = ∥1 - c∥ * dist p₁ p₂ :=
by simpa only [line_map_apply_one, dist_eq_norm'] using dist_line_map_line_map p₁ p₂ c 1
@[simp] lemma dist_right_line_map (p₁ p₂ : P) (c : 𝕜) :
dist p₂ (line_map p₁ p₂ c) = ∥1 - c∥ * dist p₁ p₂ :=
(dist_comm _ _).trans (dist_line_map_right _ _ _)
@[simp] lemma dist_homothety_self (p₁ p₂ : P) (c : 𝕜) :
dist (homothety p₁ c p₂) p₂ = ∥1 - c∥ * dist p₁ p₂ :=
by rw [homothety_eq_line_map, dist_line_map_right]
@[simp] lemma dist_self_homothety (p₁ p₂ : P) (c : 𝕜) :
dist p₂ (homothety p₁ c p₂) = ∥1 - c∥ * dist p₁ p₂ :=
by rw [dist_comm, dist_homothety_self]
section invertible_two
variables [invertible (2:𝕜)]
@[simp] lemma dist_left_midpoint (p₁ p₂ : P) :
dist p₁ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ :=
by rw [midpoint, dist_comm, dist_line_map_left, inv_of_eq_inv, ← norm_inv]
@[simp] lemma dist_midpoint_left (p₁ p₂ : P) :
dist (midpoint 𝕜 p₁ p₂) p₁ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ :=
by rw [dist_comm, dist_left_midpoint]
@[simp] lemma dist_midpoint_right (p₁ p₂ : P) :
dist (midpoint 𝕜 p₁ p₂) p₂ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ :=
by rw [midpoint_comm, dist_midpoint_left, dist_comm]
@[simp] lemma dist_right_midpoint (p₁ p₂ : P) :
dist p₂ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ :=
by rw [dist_comm, dist_midpoint_right]
lemma dist_midpoint_midpoint_le' (p₁ p₂ p₃ p₄ : P) :
dist (midpoint 𝕜 p₁ p₂) (midpoint 𝕜 p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / ∥(2 : 𝕜)∥ :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, midpoint_vsub_midpoint];
try { apply_instance },
rw [midpoint_eq_smul_add, norm_smul, inv_of_eq_inv, norm_inv, ← div_eq_inv_mul],
exact div_le_div_of_le_of_nonneg (norm_add_le _ _) (norm_nonneg _),
end
end invertible_two
omit V
include W
lemma antilipschitz_with_line_map {p₁ p₂ : Q} (h : p₁ ≠ p₂) :
antilipschitz_with (nndist p₁ p₂)⁻¹ (line_map p₁ p₂ : 𝕜 → Q) :=
antilipschitz_with.of_le_mul_dist $ λ c₁ c₂, by rw [dist_line_map_line_map, nnreal.coe_inv,
← dist_nndist, mul_left_comm, inv_mul_cancel (dist_ne_zero.2 h), mul_one]
variables (𝕜)
lemma eventually_homothety_mem_of_mem_interior (x : Q) {s : set Q} {y : Q} (hy : y ∈ interior s) :
∀ᶠ δ in 𝓝 (1 : 𝕜), homothety x δ y ∈ s :=
begin
rw (normed_group.nhds_basis_norm_lt (1 : 𝕜)).eventually_iff,
cases eq_or_ne y x with h h, { use 1, simp [h.symm, interior_subset hy], },
have hxy : 0 < ∥y -ᵥ x∥, { rwa [norm_pos_iff, vsub_ne_zero], },
obtain ⟨u, hu₁, hu₂, hu₃⟩ := mem_interior.mp hy,
obtain ⟨ε, hε, hyε⟩ := metric.is_open_iff.mp hu₂ y hu₃,
refine ⟨ε / ∥y -ᵥ x∥, div_pos hε hxy, λ δ (hδ : ∥δ - 1∥ < ε / ∥y -ᵥ x∥), hu₁ (hyε _)⟩,
rw [lt_div_iff hxy, ← norm_smul, sub_smul, one_smul] at hδ,
rwa [homothety_apply, metric.mem_ball, dist_eq_norm_vsub W, vadd_vsub_eq_sub_vsub],
end
lemma eventually_homothety_image_subset_of_finite_subset_interior
(x : Q) {s : set Q} {t : set Q} (ht : t.finite) (h : t ⊆ interior s) :
∀ᶠ δ in 𝓝 (1 : 𝕜), homothety x δ '' t ⊆ s :=
begin
suffices : ∀ y ∈ t, ∀ᶠ δ in 𝓝 (1 : 𝕜), homothety x δ y ∈ s,
{ simp_rw set.image_subset_iff,
exact (filter.eventually_all_finite ht).mpr this, },
intros y hy,
exact eventually_homothety_mem_of_mem_interior 𝕜 x (h hy),
end
end normed_space
variables [normed_space ℝ V] [normed_space ℝ W]
lemma dist_midpoint_midpoint_le (p₁ p₂ p₃ p₄ : V) :
dist (midpoint ℝ p₁ p₂) (midpoint ℝ p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / 2 :=
by simpa using dist_midpoint_midpoint_le' p₁ p₂ p₃ p₄
include V W
/-- A continuous map between two normed affine spaces is an affine map provided that
it sends midpoints to midpoints. -/
def affine_map.of_map_midpoint (f : P → Q)
(h : ∀ x y, f (midpoint ℝ x y) = midpoint ℝ (f x) (f y))
(hfc : continuous f) :
P →ᵃ[ℝ] Q :=
affine_map.mk' f
↑((add_monoid_hom.of_map_midpoint ℝ ℝ
((affine_equiv.vadd_const ℝ (f $ classical.arbitrary P)).symm ∘ f ∘
(affine_equiv.vadd_const ℝ (classical.arbitrary P))) (by simp)
(λ x y, by simp [h])).to_real_linear_map $ by apply_rules [continuous.vadd, continuous.vsub,
continuous_const, hfc.comp, continuous_id])
(classical.arbitrary P)
(λ p, by simp)
|
e3fed8c398d1ad550564548fe1110aa8b16a2044 | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/algebra/ordered_group.lean | 11c6da9a71f83b9506db1be3915b61f2d1fb536d | [
"Apache-2.0"
] | permissive | molodiuc/mathlib | cae2ba3ef1601c1f42ca0b625c79b061b63fef5b | 98ebe5a6739fbe254f9ee9d401882d4388f91035 | refs/heads/master | 1,674,237,127,059 | 1,606,353,533,000 | 1,606,353,533,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,929 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl
-/
import algebra.ordered_monoid
set_option old_structure_cmd true
/-!
# Ordered groups
This file develops the basics of ordered groups.
## Implementation details
Unfortunately, the number of `'` appended to lemmas in this file
may differ between the multiplicative and the additive version of a lemma.
The reason is that we did not want to change existing names in the library.
-/
universe u
variable {α : Type u}
/-- An ordered additive commutative group is an additive commutative group
with a partial order in which addition is strictly monotone. -/
@[protect_proj, ancestor add_comm_group partial_order]
class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α :=
(add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b)
/-- An ordered commutative group is an commutative group
with a partial order in which multiplication is strictly monotone. -/
@[protect_proj, ancestor comm_group partial_order]
class ordered_comm_group (α : Type u) extends comm_group α, partial_order α :=
(mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b)
attribute [to_additive] ordered_comm_group
/--The units of an ordered commutative monoid form an ordered commutative group. -/
@[to_additive]
instance units.ordered_comm_group [ordered_comm_monoid α] : ordered_comm_group (units α) :=
{ mul_le_mul_left := λ a b h c, mul_le_mul_left' h _,
.. units.partial_order,
.. (infer_instance : comm_group (units α)) }
section ordered_comm_group
variables [ordered_comm_group α] {a b c d : α}
@[to_additive ordered_add_comm_group.add_lt_add_left]
lemma ordered_comm_group.mul_lt_mul_left' (a b : α) (h : a < b) (c : α) : c * a < c * b :=
begin
rw lt_iff_le_not_le at h ⊢,
split,
{ apply ordered_comm_group.mul_le_mul_left _ _ h.1 },
{ intro w,
replace w : c⁻¹ * (c * b) ≤ c⁻¹ * (c * a) := ordered_comm_group.mul_le_mul_left _ _ w _,
simp only [mul_one, mul_comm, mul_left_inv, mul_left_comm] at w,
exact h.2 w },
end
@[to_additive ordered_add_comm_group.le_of_add_le_add_left]
lemma ordered_comm_group.le_of_mul_le_mul_left (h : a * b ≤ a * c) : b ≤ c :=
have a⁻¹ * (a * b) ≤ a⁻¹ * (a * c), from ordered_comm_group.mul_le_mul_left _ _ h _,
begin simp [inv_mul_cancel_left] at this, assumption end
@[to_additive]
lemma ordered_comm_group.lt_of_mul_lt_mul_left (h : a * b < a * c) : b < c :=
have a⁻¹ * (a * b) < a⁻¹ * (a * c), from ordered_comm_group.mul_lt_mul_left' _ _ h _,
begin simp [inv_mul_cancel_left] at this, assumption end
@[priority 100, to_additive] -- see Note [lower instance priority]
instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u)
[s : ordered_comm_group α] : ordered_cancel_comm_monoid α :=
{ mul_left_cancel := @mul_left_cancel α _,
mul_right_cancel := @mul_right_cancel α _,
le_of_mul_le_mul_left := @ordered_comm_group.le_of_mul_le_mul_left α _,
..s }
@[to_additive neg_le_neg]
lemma inv_le_inv' (h : a ≤ b) : b⁻¹ ≤ a⁻¹ :=
have 1 ≤ a⁻¹ * b, from mul_left_inv a ▸ mul_le_mul_left' h _,
have 1 * b⁻¹ ≤ a⁻¹ * b * b⁻¹, from mul_le_mul_right' this _,
by rwa [mul_inv_cancel_right, one_mul] at this
@[to_additive]
lemma le_of_inv_le_inv (h : b⁻¹ ≤ a⁻¹) : a ≤ b :=
suffices (a⁻¹)⁻¹ ≤ (b⁻¹)⁻¹, from
begin simp [inv_inv] at this, assumption end,
inv_le_inv' h
@[to_additive]
lemma one_le_of_inv_le_one (h : a⁻¹ ≤ 1) : 1 ≤ a :=
have a⁻¹ ≤ 1⁻¹, by rwa one_inv,
le_of_inv_le_inv this
@[to_additive]
lemma inv_le_one_of_one_le (h : 1 ≤ a) : a⁻¹ ≤ 1 :=
have a⁻¹ ≤ 1⁻¹, from inv_le_inv' h,
by rwa one_inv at this
@[to_additive nonpos_of_neg_nonneg]
lemma le_one_of_one_le_inv (h : 1 ≤ a⁻¹) : a ≤ 1 :=
have 1⁻¹ ≤ a⁻¹, by rwa one_inv,
le_of_inv_le_inv this
@[to_additive neg_nonneg_of_nonpos]
lemma one_le_inv_of_le_one (h : a ≤ 1) : 1 ≤ a⁻¹ :=
have 1⁻¹ ≤ a⁻¹, from inv_le_inv' h,
by rwa one_inv at this
@[to_additive neg_lt_neg]
lemma inv_lt_inv' (h : a < b) : b⁻¹ < a⁻¹ :=
have 1 < a⁻¹ * b, from mul_left_inv a ▸ mul_lt_mul_left' h (a⁻¹),
have 1 * b⁻¹ < a⁻¹ * b * b⁻¹, from mul_lt_mul_right' this (b⁻¹),
by rwa [mul_inv_cancel_right, one_mul] at this
@[to_additive]
lemma lt_of_inv_lt_inv (h : b⁻¹ < a⁻¹) : a < b :=
inv_inv a ▸ inv_inv b ▸ inv_lt_inv' h
@[to_additive]
lemma one_lt_of_inv_inv (h : a⁻¹ < 1) : 1 < a :=
have a⁻¹ < 1⁻¹, by rwa one_inv,
lt_of_inv_lt_inv this
@[to_additive]
lemma inv_inv_of_one_lt (h : 1 < a) : a⁻¹ < 1 :=
have a⁻¹ < 1⁻¹, from inv_lt_inv' h,
by rwa one_inv at this
@[to_additive neg_of_neg_pos]
lemma inv_of_one_lt_inv (h : 1 < a⁻¹) : a < 1 :=
have 1⁻¹ < a⁻¹, by rwa one_inv,
lt_of_inv_lt_inv this
@[to_additive neg_pos_of_neg]
lemma one_lt_inv_of_inv (h : a < 1) : 1 < a⁻¹ :=
have 1⁻¹ < a⁻¹, from inv_lt_inv' h,
by rwa one_inv at this
@[to_additive]
lemma le_inv_of_le_inv (h : a ≤ b⁻¹) : b ≤ a⁻¹ :=
begin
have h := inv_le_inv' h,
rwa inv_inv at h
end
@[to_additive]
lemma inv_le_of_inv_le (h : a⁻¹ ≤ b) : b⁻¹ ≤ a :=
begin
have h := inv_le_inv' h,
rwa inv_inv at h
end
@[to_additive]
lemma lt_inv_of_lt_inv (h : a < b⁻¹) : b < a⁻¹ :=
begin
have h := inv_lt_inv' h,
rwa inv_inv at h
end
@[to_additive]
lemma inv_lt_of_inv_lt (h : a⁻¹ < b) : b⁻¹ < a :=
begin
have h := inv_lt_inv' h,
rwa inv_inv at h
end
@[to_additive]
lemma mul_le_of_le_inv_mul (h : b ≤ a⁻¹ * c) : a * b ≤ c :=
begin
have h := mul_le_mul_left' h a,
rwa mul_inv_cancel_left at h
end
@[to_additive]
lemma le_inv_mul_of_mul_le (h : a * b ≤ c) : b ≤ a⁻¹ * c :=
begin
have h := mul_le_mul_left' h a⁻¹,
rwa inv_mul_cancel_left at h
end
@[to_additive]
lemma le_mul_of_inv_mul_le (h : b⁻¹ * a ≤ c) : a ≤ b * c :=
begin
have h := mul_le_mul_left' h b,
rwa mul_inv_cancel_left at h
end
@[to_additive]
lemma inv_mul_le_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c :=
begin
have h := mul_le_mul_left' h b⁻¹,
rwa inv_mul_cancel_left at h
end
@[to_additive]
lemma le_mul_of_inv_mul_le_left (h : b⁻¹ * a ≤ c) : a ≤ b * c :=
le_mul_of_inv_mul_le h
@[to_additive]
lemma inv_mul_le_left_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c :=
inv_mul_le_of_le_mul h
@[to_additive]
lemma le_mul_of_inv_mul_le_right (h : c⁻¹ * a ≤ b) : a ≤ b * c :=
by { rw mul_comm, exact le_mul_of_inv_mul_le h }
@[to_additive]
lemma inv_mul_le_right_of_le_mul (h : a ≤ b * c) : c⁻¹ * a ≤ b :=
by { rw mul_comm at h, apply inv_mul_le_left_of_le_mul h }
@[to_additive]
lemma mul_lt_of_lt_inv_mul (h : b < a⁻¹ * c) : a * b < c :=
begin
have h := mul_lt_mul_left' h a,
rwa mul_inv_cancel_left at h
end
@[to_additive]
lemma lt_inv_mul_of_mul_lt (h : a * b < c) : b < a⁻¹ * c :=
begin
have h := mul_lt_mul_left' h (a⁻¹),
rwa inv_mul_cancel_left at h
end
@[to_additive]
lemma lt_mul_of_inv_mul_lt (h : b⁻¹ * a < c) : a < b * c :=
begin
have h := mul_lt_mul_left' h b,
rwa mul_inv_cancel_left at h
end
@[to_additive]
lemma inv_mul_lt_of_lt_mul (h : a < b * c) : b⁻¹ * a < c :=
begin
have h := mul_lt_mul_left' h (b⁻¹),
rwa inv_mul_cancel_left at h
end
@[to_additive]
lemma lt_mul_of_inv_mul_lt_left (h : b⁻¹ * a < c) : a < b * c :=
lt_mul_of_inv_mul_lt h
@[to_additive]
lemma inv_mul_lt_left_of_lt_mul (h : a < b * c) : b⁻¹ * a < c :=
inv_mul_lt_of_lt_mul h
@[to_additive]
lemma lt_mul_of_inv_mul_lt_right (h : c⁻¹ * a < b) : a < b * c :=
by { rw mul_comm, exact lt_mul_of_inv_mul_lt h }
@[to_additive]
lemma inv_mul_lt_right_of_lt_mul (h : a < b * c) : c⁻¹ * a < b :=
by { rw mul_comm at h, exact inv_mul_lt_of_lt_mul h }
@[simp, to_additive]
lemma inv_lt_one_iff_one_lt : a⁻¹ < 1 ↔ 1 < a :=
⟨ one_lt_of_inv_inv, inv_inv_of_one_lt ⟩
@[simp, to_additive]
lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
have a * b * a⁻¹ ≤ a * b * b⁻¹ ↔ a⁻¹ ≤ b⁻¹, from mul_le_mul_iff_left _,
by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] }
@[to_additive neg_le]
lemma inv_le' : a⁻¹ ≤ b ↔ b⁻¹ ≤ a :=
have a⁻¹ ≤ (b⁻¹)⁻¹ ↔ b⁻¹ ≤ a, from inv_le_inv_iff,
by rwa inv_inv at this
@[to_additive le_neg]
lemma le_inv' : a ≤ b⁻¹ ↔ b ≤ a⁻¹ :=
have (a⁻¹)⁻¹ ≤ b⁻¹ ↔ b ≤ a⁻¹, from inv_le_inv_iff,
by rwa inv_inv at this
@[to_additive neg_le_iff_add_nonneg]
lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ a * b :=
(mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma le_inv_iff_mul_le_one : a ≤ b⁻¹ ↔ a * b ≤ 1 :=
(mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self
@[simp, to_additive neg_nonpos]
lemma inv_le_one' : a⁻¹ ≤ 1 ↔ 1 ≤ a :=
have a⁻¹ ≤ 1⁻¹ ↔ 1 ≤ a, from inv_le_inv_iff,
by rwa one_inv at this
@[simp, to_additive neg_nonneg]
lemma one_le_inv' : 1 ≤ a⁻¹ ↔ a ≤ 1 :=
have 1⁻¹ ≤ a⁻¹ ↔ a ≤ 1, from inv_le_inv_iff,
by rwa one_inv at this
@[to_additive]
lemma inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a :=
le_trans (inv_le_one'.2 h) h
@[to_additive]
lemma self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ :=
le_trans h (one_le_inv'.2 h)
@[simp, to_additive]
lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a :=
have a * b * a⁻¹ < a * b * b⁻¹ ↔ a⁻¹ < b⁻¹, from mul_lt_mul_iff_left _,
by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] }
@[to_additive neg_lt_zero]
lemma inv_lt_one' : a⁻¹ < 1 ↔ 1 < a :=
have a⁻¹ < 1⁻¹ ↔ 1 < a, from inv_lt_inv_iff,
by rwa one_inv at this
@[to_additive neg_pos]
lemma one_lt_inv' : 1 < a⁻¹ ↔ a < 1 :=
have 1⁻¹ < a⁻¹ ↔ a < 1, from inv_lt_inv_iff,
by rwa one_inv at this
@[to_additive neg_lt]
lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a :=
have a⁻¹ < (b⁻¹)⁻¹ ↔ b⁻¹ < a, from inv_lt_inv_iff,
by rwa inv_inv at this
@[to_additive lt_neg]
lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ :=
have (a⁻¹)⁻¹ < b⁻¹ ↔ b < a⁻¹, from inv_lt_inv_iff,
by rwa inv_inv at this
@[to_additive]
lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c :=
have a⁻¹ * (a * b) ≤ a⁻¹ * c ↔ a * b ≤ c, from mul_le_mul_iff_left _,
by rwa inv_mul_cancel_left at this
@[simp, to_additive]
lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c :=
have b⁻¹ * a ≤ b⁻¹ * (b * c) ↔ a ≤ b * c, from mul_le_mul_iff_left _,
by rwa inv_mul_cancel_left at this
@[to_additive]
lemma mul_inv_le_iff_le_mul : a * c⁻¹ ≤ b ↔ a ≤ b * c :=
by rw [mul_comm a, mul_comm b, inv_mul_le_iff_le_mul]
@[simp, to_additive]
lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c :=
by rw [← inv_mul_le_iff_le_mul, mul_comm]
@[to_additive]
lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c :=
by rw [inv_mul_le_iff_le_mul, mul_comm]
@[simp, to_additive]
lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c :=
have a⁻¹ * (a * b) < a⁻¹ * c ↔ a * b < c, from mul_lt_mul_iff_left _,
by rwa inv_mul_cancel_left at this
@[simp, to_additive]
lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c :=
have b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c, from mul_lt_mul_iff_left _,
by rwa inv_mul_cancel_left at this
@[to_additive]
lemma inv_mul_lt_iff_lt_mul_right : c⁻¹ * a < b ↔ a < b * c :=
by rw [inv_mul_lt_iff_lt_mul, mul_comm]
@[to_additive add_neg_le_add_neg_iff]
lemma div_le_div_iff' : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b :=
begin
split ; intro h,
have := mul_le_mul_right' (mul_le_mul_right' h b) d,
rwa [inv_mul_cancel_right, mul_assoc _ _ b, mul_comm _ b, ← mul_assoc, inv_mul_cancel_right] at this,
have := mul_le_mul_right' (mul_le_mul_right' h d⁻¹) b⁻¹,
rwa [mul_inv_cancel_right, _root_.mul_assoc, _root_.mul_comm d⁻¹ b⁻¹, ← mul_assoc, mul_inv_cancel_right] at this,
end
end ordered_comm_group
section ordered_add_comm_group
variables [ordered_add_comm_group α] {a b c d : α}
lemma sub_nonneg_of_le (h : b ≤ a) : 0 ≤ a - b :=
begin
have h := add_le_add_right h (-b),
rwa add_right_neg at h
end
lemma le_of_sub_nonneg (h : 0 ≤ a - b) : b ≤ a :=
begin
have h := add_le_add_right h b,
rwa [sub_add_cancel, zero_add] at h
end
lemma sub_nonpos_of_le (h : a ≤ b) : a - b ≤ 0 :=
begin
have h := add_le_add_right h (-b),
rwa add_right_neg at h
end
lemma le_of_sub_nonpos (h : a - b ≤ 0) : a ≤ b :=
begin
have h := add_le_add_right h b,
rwa [sub_add_cancel, zero_add] at h
end
lemma sub_pos_of_lt (h : b < a) : 0 < a - b :=
begin
have h := add_lt_add_right h (-b),
rwa add_right_neg at h
end
lemma lt_of_sub_pos (h : 0 < a - b) : b < a :=
begin
have h := add_lt_add_right h b,
rwa [sub_add_cancel, zero_add] at h
end
lemma sub_neg_of_lt (h : a < b) : a - b < 0 :=
begin
have h := add_lt_add_right h (-b),
rwa add_right_neg at h
end
lemma lt_of_sub_neg (h : a - b < 0) : a < b :=
begin
have h := add_lt_add_right h b,
rwa [sub_add_cancel, zero_add] at h
end
lemma add_le_of_le_sub_left (h : b ≤ c - a) : a + b ≤ c :=
begin
have h := add_le_add_left h a,
rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h
end
lemma le_sub_left_of_add_le (h : a + b ≤ c) : b ≤ c - a :=
begin
have h := add_le_add_right h (-a),
rwa [add_comm a b, add_neg_cancel_right] at h
end
lemma add_le_of_le_sub_right (h : a ≤ c - b) : a + b ≤ c :=
begin
have h := add_le_add_right h b,
rwa sub_add_cancel at h
end
lemma le_sub_right_of_add_le (h : a + b ≤ c) : a ≤ c - b :=
begin
have h := add_le_add_right h (-b),
rwa add_neg_cancel_right at h
end
lemma le_add_of_sub_left_le (h : a - b ≤ c) : a ≤ b + c :=
begin
have h := add_le_add_right h b,
rwa [sub_add_cancel, add_comm] at h
end
lemma sub_left_le_of_le_add (h : a ≤ b + c) : a - b ≤ c :=
begin
have h := add_le_add_right h (-b),
rwa [add_comm b c, add_neg_cancel_right] at h
end
lemma le_add_of_sub_right_le (h : a - c ≤ b) : a ≤ b + c :=
begin
have h := add_le_add_right h c,
rwa sub_add_cancel at h
end
lemma sub_right_le_of_le_add (h : a ≤ b + c) : a - c ≤ b :=
begin
have h := add_le_add_right h (-c),
rwa add_neg_cancel_right at h
end
lemma le_add_of_neg_le_sub_left (h : -a ≤ b - c) : c ≤ a + b :=
le_add_of_neg_add_le_left (add_le_of_le_sub_right h)
lemma neg_le_sub_left_of_le_add (h : c ≤ a + b) : -a ≤ b - c :=
begin
have h := le_neg_add_of_add_le (sub_left_le_of_le_add h),
rwa add_comm at h
end
lemma le_add_of_neg_le_sub_right (h : -b ≤ a - c) : c ≤ a + b :=
le_add_of_sub_right_le (add_le_of_le_sub_left h)
lemma neg_le_sub_right_of_le_add (h : c ≤ a + b) : -b ≤ a - c :=
le_sub_left_of_add_le (sub_right_le_of_le_add h)
lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b :=
sub_left_le_of_le_add (le_add_of_sub_right_le h)
lemma sub_le_sub_left (h : a ≤ b) (c : α) : c - b ≤ c - a :=
add_le_add_left (neg_le_neg h) c
lemma sub_le_sub_right (h : a ≤ b) (c : α) : a - c ≤ b - c :=
add_le_add_right h (-c)
lemma sub_le_sub (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c :=
add_le_add hab (neg_le_neg hcd)
lemma add_lt_of_lt_sub_left (h : b < c - a) : a + b < c :=
begin
have h := add_lt_add_left h a,
rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h
end
lemma lt_sub_left_of_add_lt (h : a + b < c) : b < c - a :=
begin
have h := add_lt_add_right h (-a),
rwa [add_comm a b, add_neg_cancel_right] at h
end
lemma add_lt_of_lt_sub_right (h : a < c - b) : a + b < c :=
begin
have h := add_lt_add_right h b,
rwa sub_add_cancel at h
end
lemma lt_sub_right_of_add_lt (h : a + b < c) : a < c - b :=
begin
have h := add_lt_add_right h (-b),
rwa add_neg_cancel_right at h
end
lemma lt_add_of_sub_left_lt (h : a - b < c) : a < b + c :=
begin
have h := add_lt_add_right h b,
rwa [sub_add_cancel, add_comm] at h
end
lemma sub_left_lt_of_lt_add (h : a < b + c) : a - b < c :=
begin
have h := add_lt_add_right h (-b),
rwa [add_comm b c, add_neg_cancel_right] at h
end
lemma lt_add_of_sub_right_lt (h : a - c < b) : a < b + c :=
begin
have h := add_lt_add_right h c,
rwa sub_add_cancel at h
end
lemma sub_right_lt_of_lt_add (h : a < b + c) : a - c < b :=
begin
have h := add_lt_add_right h (-c),
rwa add_neg_cancel_right at h
end
lemma lt_add_of_neg_lt_sub_left (h : -a < b - c) : c < a + b :=
lt_add_of_neg_add_lt_left (add_lt_of_lt_sub_right h)
lemma neg_lt_sub_left_of_lt_add (h : c < a + b) : -a < b - c :=
begin
have h := lt_neg_add_of_add_lt (sub_left_lt_of_lt_add h),
rwa add_comm at h
end
lemma lt_add_of_neg_lt_sub_right (h : -b < a - c) : c < a + b :=
lt_add_of_sub_right_lt (add_lt_of_lt_sub_left h)
lemma neg_lt_sub_right_of_lt_add (h : c < a + b) : -b < a - c :=
lt_sub_left_of_add_lt (sub_right_lt_of_lt_add h)
lemma sub_lt_of_sub_lt (h : a - b < c) : a - c < b :=
sub_left_lt_of_lt_add (lt_add_of_sub_right_lt h)
lemma sub_lt_sub_left (h : a < b) (c : α) : c - b < c - a :=
add_lt_add_left (neg_lt_neg h) c
lemma sub_lt_sub_right (h : a < b) (c : α) : a - c < b - c :=
add_lt_add_right h (-c)
lemma sub_lt_sub (hab : a < b) (hcd : c < d) : a - d < b - c :=
add_lt_add hab (neg_lt_neg hcd)
lemma sub_lt_sub_of_le_of_lt (hab : a ≤ b) (hcd : c < d) : a - d < b - c :=
add_lt_add_of_le_of_lt hab (neg_lt_neg hcd)
lemma sub_lt_sub_of_lt_of_le (hab : a < b) (hcd : c ≤ d) : a - d < b - c :=
add_lt_add_of_lt_of_le hab (neg_le_neg hcd)
lemma sub_le_self (a : α) {b : α} (h : 0 ≤ b) : a - b ≤ a :=
calc
a - b = a + -b : rfl
... ≤ a + 0 : add_le_add_left (neg_nonpos_of_nonneg h) _
... = a : by rw add_zero
lemma sub_lt_self (a : α) {b : α} (h : 0 < b) : a - b < a :=
calc
a - b = a + -b : rfl
... < a + 0 : add_lt_add_left (neg_neg_of_pos h) _
... = a : by rw add_zero
lemma sub_le_sub_iff : a - b ≤ c - d ↔ a + d ≤ c + b := add_neg_le_add_neg_iff
@[simp]
lemma sub_le_sub_iff_left (a : α) {b c : α} : a - b ≤ a - c ↔ c ≤ b :=
(add_le_add_iff_left _).trans neg_le_neg_iff
@[simp]
lemma sub_le_sub_iff_right (c : α) : a - c ≤ b - c ↔ a ≤ b :=
add_le_add_iff_right _
@[simp]
lemma sub_lt_sub_iff_left (a : α) {b c : α} : a - b < a - c ↔ c < b :=
(add_lt_add_iff_left _).trans neg_lt_neg_iff
@[simp]
lemma sub_lt_sub_iff_right (c : α) : a - c < b - c ↔ a < b :=
add_lt_add_iff_right _
@[simp] lemma sub_nonneg : 0 ≤ a - b ↔ b ≤ a :=
have a - a ≤ a - b ↔ b ≤ a, from sub_le_sub_iff_left a,
by rwa sub_self at this
@[simp] lemma sub_nonpos : a - b ≤ 0 ↔ a ≤ b :=
have a - b ≤ b - b ↔ a ≤ b, from sub_le_sub_iff_right b,
by rwa sub_self at this
@[simp] lemma sub_pos : 0 < a - b ↔ b < a :=
have a - a < a - b ↔ b < a, from sub_lt_sub_iff_left a,
by rwa sub_self at this
@[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b :=
have a - b < b - b ↔ a < b, from sub_lt_sub_iff_right b,
by rwa sub_self at this
lemma le_sub_iff_add_le' : b ≤ c - a ↔ a + b ≤ c :=
by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le]
lemma le_sub_iff_add_le : a ≤ c - b ↔ a + b ≤ c :=
by rw [le_sub_iff_add_le', add_comm]
lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c :=
by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add]
lemma sub_le_iff_le_add : a - c ≤ b ↔ a ≤ b + c :=
by rw [sub_le_iff_le_add', add_comm]
@[simp] lemma neg_le_sub_iff_le_add : -b ≤ a - c ↔ c ≤ a + b :=
le_sub_iff_add_le.trans neg_add_le_iff_le_add'
lemma neg_le_sub_iff_le_add' : -a ≤ b - c ↔ c ≤ a + b :=
by rw [neg_le_sub_iff_le_add, add_comm]
lemma sub_le : a - b ≤ c ↔ a - c ≤ b :=
sub_le_iff_le_add'.trans sub_le_iff_le_add.symm
theorem le_sub : a ≤ b - c ↔ c ≤ b - a :=
le_sub_iff_add_le'.trans le_sub_iff_add_le.symm
lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c :=
by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt]
lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c :=
by rw [lt_sub_iff_add_lt', add_comm]
lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c :=
by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add]
lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c :=
by rw [sub_lt_iff_lt_add', add_comm]
@[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b :=
lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right
lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b :=
by rw [neg_lt_sub_iff_lt_add, add_comm]
lemma sub_lt : a - b < c ↔ a - c < b :=
sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm
theorem lt_sub : a < b - c ↔ c < b - a :=
lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm
lemma sub_le_self_iff (a : α) {b : α} : a - b ≤ a ↔ 0 ≤ b :=
sub_le_iff_le_add'.trans (le_add_iff_nonneg_left _)
lemma sub_lt_self_iff (a : α) {b : α} : a - b < a ↔ 0 < b :=
sub_lt_iff_lt_add'.trans (lt_add_iff_pos_left _)
end ordered_add_comm_group
/-- A decidable linearly ordered additive commutative group is an
additive commutative group with a decidable linear order in which
addition is strictly monotone. -/
@[protect_proj] class linear_ordered_add_comm_group (α : Type u)
extends add_comm_group α, linear_order α :=
(add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b)
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_comm_group.to_ordered_add_comm_group (α : Type u)
[s : linear_ordered_add_comm_group α] : ordered_add_comm_group α :=
{ add := s.add, ..s }
section linear_ordered_add_comm_group
variables [linear_ordered_add_comm_group α] {a b c : α}
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_add_comm_group.to_linear_ordered_cancel_add_comm_monoid :
linear_ordered_cancel_add_comm_monoid α :=
{ le_of_add_le_add_left := λ x y z, le_of_add_le_add_left,
add_left_cancel := λ x y z, add_left_cancel,
add_right_cancel := λ x y z, add_right_cancel,
..‹linear_ordered_add_comm_group α› }
lemma linear_ordered_add_comm_group.add_lt_add_left
(a b : α) (h : a < b) (c : α) : c + a < c + b :=
ordered_add_comm_group.add_lt_add_left a b h c
lemma min_neg_neg (a b : α) : min (-a) (-b) = -max a b :=
eq.symm $ @monotone.map_max α (order_dual α) _ _ has_neg.neg a b $ λ a b, neg_le_neg
lemma max_neg_neg (a b : α) : max (-a) (-b) = -min a b :=
eq.symm $ @monotone.map_min α (order_dual α) _ _ has_neg.neg a b $ λ a b, neg_le_neg
lemma min_sub_sub_right (a b c : α) : min (a - c) (b - c) = min a b - c :=
min_add_add_right a b (-c)
lemma max_sub_sub_right (a b c : α) : max (a - c) (b - c) = max a b - c :=
max_add_add_right a b (-c)
lemma min_sub_sub_left (a b c : α) : min (a - b) (a - c) = a - max b c :=
by simp only [sub_eq_add_neg, min_add_add_left, min_neg_neg]
lemma max_sub_sub_left (a b c : α) : max (a - b) (a - c) = a - min b c :=
by simp only [sub_eq_add_neg, max_add_add_left, max_neg_neg]
lemma max_zero_sub_eq_self (a : α) : max a 0 - max (-a) 0 = a :=
begin
rcases le_total a 0,
{ rw [max_eq_right h, max_eq_left, zero_sub, neg_neg], { rwa [le_neg, neg_zero] } },
{ rw [max_eq_left, max_eq_right, sub_zero], { rwa [neg_le, neg_zero] }, exact h }
end
/-- `abs a` is the absolute value of `a`. -/
def abs (a : α) : α := max a (-a)
lemma abs_of_nonneg (h : 0 ≤ a) : abs a = a :=
max_eq_left $ (neg_nonpos.2 h).trans h
lemma abs_of_pos (h : 0 < a) : abs a = a :=
abs_of_nonneg h.le
lemma abs_of_nonpos (h : a ≤ 0) : abs a = -a :=
max_eq_right $ h.trans (neg_nonneg.2 h)
lemma abs_of_neg (h : a < 0) : abs a = -a :=
abs_of_nonpos h.le
@[simp] lemma abs_zero : abs 0 = (0:α) :=
abs_of_nonneg le_rfl
@[simp] lemma abs_neg (a : α) : abs (-a) = abs a :=
begin unfold abs, rw [max_comm, neg_neg] end
@[simp] lemma abs_pos : 0 < abs a ↔ a ≠ 0 :=
begin
rcases lt_trichotomy a 0 with (ha|rfl|ha),
{ simp [abs_of_neg ha, neg_pos, ha.ne, ha] },
{ simp },
{ simp [abs_of_pos ha, ha, ha.ne.symm] }
end
lemma abs_pos_of_pos (h : 0 < a) : 0 < abs a := abs_pos.2 h.ne.symm
lemma abs_pos_of_neg (h : a < 0) : 0 < abs a := abs_pos.2 h.ne
lemma abs_sub (a b : α) : abs (a - b) = abs (b - a) :=
by rw [← neg_sub, abs_neg]
theorem abs_le' : abs a ≤ b ↔ a ≤ b ∧ -a ≤ b := max_le_iff
theorem abs_le : abs a ≤ b ↔ - b ≤ a ∧ a ≤ b :=
by rw [abs_le', and.comm, neg_le]
lemma le_abs_self (a : α) : a ≤ abs a := le_max_left _ _
lemma neg_le_abs_self (a : α) : -a ≤ abs a := le_max_right _ _
lemma abs_nonneg (a : α) : 0 ≤ abs a :=
(le_total 0 a).elim (λ h, h.trans (le_abs_self a)) (λ h, (neg_nonneg.2 h).trans $ neg_le_abs_self a)
@[simp] lemma abs_abs (a : α) : abs (abs a) = abs a :=
abs_of_nonneg $ abs_nonneg a
@[simp] lemma abs_eq_zero : abs a = 0 ↔ a = 0 :=
not_iff_not.1 $ ne_comm.trans $ (abs_nonneg a).lt_iff_ne.symm.trans abs_pos
@[simp] lemma abs_nonpos_iff {a : α} : abs a ≤ 0 ↔ a = 0 :=
(abs_nonneg a).le_iff_eq.trans abs_eq_zero
lemma abs_lt {a b : α} : abs a < b ↔ - b < a ∧ a < b :=
max_lt_iff.trans $ and.comm.trans $ by rw [neg_lt]
lemma lt_abs {a b : α} : a < abs b ↔ a < b ∨ a < -b := lt_max_iff
lemma max_sub_min_eq_abs' (a b : α) : max a b - min a b = abs (a - b) :=
begin
cases le_total a b with ab ba,
{ rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos },
{ rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], exact sub_nonneg_of_le ba }
end
lemma max_sub_min_eq_abs (a b : α) : max a b - min a b = abs (b - a) :=
by { rw [abs_sub], exact max_sub_min_eq_abs' _ _ }
lemma abs_add (a b : α) : abs (a + b) ≤ abs a + abs b :=
abs_le.2 ⟨(neg_add (abs a) (abs b)).symm ▸
add_le_add (neg_le.2 $ neg_le_abs_self _) (neg_le.2 $ neg_le_abs_self _),
add_le_add (le_abs_self _) (le_abs_self _)⟩
lemma abs_sub_le_iff : abs (a - b) ≤ c ↔ a - b ≤ c ∧ b - a ≤ c :=
by rw [abs_le, neg_le_sub_iff_le_add, @sub_le_iff_le_add' _ _ b, and_comm]
lemma abs_sub_lt_iff : abs (a - b) < c ↔ a - b < c ∧ b - a < c :=
by rw [abs_lt, neg_lt_sub_iff_lt_add, @sub_lt_iff_lt_add' _ _ b, and_comm]
lemma abs_sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) :=
sub_le_iff_le_add.2 $
calc abs a = abs (a - b + b) : by rw [sub_add_cancel]
... ≤ abs (a - b) + abs b : abs_add _ _
lemma abs_abs_sub_abs_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) :=
abs_sub_le_iff.2 ⟨abs_sub_abs_le_abs_sub _ _, by rw abs_sub; apply abs_sub_abs_le_abs_sub⟩
lemma abs_eq (hb : 0 ≤ b) : abs a = b ↔ a = b ∨ a = -b :=
iff.intro
begin
cases le_total a 0 with a_nonpos a_nonneg,
{ rw [abs_of_nonpos a_nonpos, neg_eq_iff_neg_eq, eq_comm], exact or.inr },
{ rw [abs_of_nonneg a_nonneg, eq_comm], exact or.inl }
end
(by intro h; cases h; subst h; try { rw abs_neg }; exact abs_of_nonneg hb)
lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : abs b ≤ max (abs a) (abs c) :=
abs_le'.2
⟨by simp [hbc.trans (le_abs_self c)],
by simp [(neg_le_neg hab).trans (neg_le_abs_self a)]⟩
theorem abs_le_abs (h₀ : a ≤ b) (h₁ : -a ≤ b) : abs a ≤ abs b :=
(abs_le'.2 ⟨h₀, h₁⟩).trans (le_abs_self b)
lemma abs_max_sub_max_le_abs (a b c : α) : abs (max a c - max b c) ≤ abs (a - b) :=
begin
simp_rw [abs_le, le_sub_iff_add_le, sub_le_iff_le_add, ← max_add_add_left],
split; apply max_le_max; simp only [← le_sub_iff_add_le, ← sub_le_iff_le_add, sub_self, neg_le,
neg_le_abs_self, neg_zero, abs_nonneg, le_abs_self]
end
lemma eq_zero_of_neg_eq {a : α} (h : -a = a) : a = 0 :=
match lt_trichotomy a 0 with
| or.inl h₁ :=
have 0 < a, from h ▸ neg_pos_of_neg h₁,
absurd h₁ this.asymm
| or.inr (or.inl h₁) := h₁
| or.inr (or.inr h₁) :=
have a < 0, from h ▸ neg_neg_of_pos h₁,
absurd h₁ this.asymm
end
lemma eq_of_abs_sub_eq_zero {a b : α} (h : abs (a - b) = 0) : a = b :=
sub_eq_zero.1 $ abs_eq_zero.1 h
lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) :=
sup_ind _ _ h1 h2
lemma abs_sub_le (a b c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) :=
calc
abs (a - c) = abs (a - b + (b - c)) : by rw [sub_add_sub_cancel]
... ≤ abs (a - b) + abs (b - c) : abs_add _ _
lemma abs_add_three (a b c : α) : abs (a + b + c) ≤ abs a + abs b + abs c :=
(abs_add _ _).trans (add_le_add_right (abs_add _ _) _)
lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub)
(hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb :=
abs_sub_le_iff.2 ⟨sub_le_sub hau hbl, sub_le_sub hbu hal⟩
lemma eq_of_abs_sub_nonpos (h : abs (a - b) ≤ 0) : a = b :=
eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b)))
lemma exists_gt_zero [nontrivial α] : ∃ (a:α), 0 < a :=
begin
obtain ⟨y, hy⟩ := exists_ne (0 : α),
cases hy.lt_or_lt,
{ exact ⟨- y, neg_pos.mpr h⟩ },
{ exact ⟨y, h⟩ }
end
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_add_comm_group.to_no_top_order [nontrivial α] :
no_top_order α :=
⟨ begin
obtain ⟨y, hy⟩ : ∃ (a:α), 0 < a := exists_gt_zero,
exact λ a, ⟨a + y, lt_add_of_pos_right a hy⟩
end ⟩
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_add_comm_group.to_no_bot_order [nontrivial α] : no_bot_order α :=
⟨ begin
obtain ⟨y, hy⟩ : ∃ (a:α), 0 < a := exists_gt_zero,
exact λ a, ⟨a - y, sub_lt_self a hy⟩
end ⟩
end linear_ordered_add_comm_group
/-- This is not so much a new structure as a construction mechanism
for ordered groups, by specifying only the "positive cone" of the group. -/
class nonneg_add_comm_group (α : Type*) extends add_comm_group α :=
(nonneg : α → Prop)
(pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a))
(pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac)
(zero_nonneg : nonneg 0)
(add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b))
(nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0)
namespace nonneg_add_comm_group
variable [s : nonneg_add_comm_group α]
include s
@[reducible, priority 100] -- see Note [lower instance priority]
instance to_ordered_add_comm_group : ordered_add_comm_group α :=
{ le := λ a b, nonneg (b - a),
lt := λ a b, pos (b - a),
lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp,
le_refl := λ a, by simp [zero_nonneg],
le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg];
rw ← sub_add_sub_cancel; exact add_nonneg nbc nab,
le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $
nonneg_antisymm nba (by rw neg_sub; exact nab),
add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab,
..s }
theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a :=
show _ ↔ nonneg _, by simp
theorem pos_def {a : α} : pos a ↔ 0 < a :=
show _ ↔ pos _, by simp
theorem not_zero_pos : ¬ pos (0 : α) :=
mt pos_def.1 (lt_irrefl _)
theorem zero_lt_iff_nonneg_nonneg {a : α} :
0 < a ↔ nonneg a ∧ ¬ nonneg (-a) :=
pos_def.symm.trans (pos_iff _)
theorem nonneg_total_iff :
(∀ a : α, nonneg a ∨ nonneg (-a)) ↔
(∀ a b : α, a ≤ b ∨ b ≤ a) :=
⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this,
λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩
/--
A `nonneg_add_comm_group` is a `linear_ordered_add_comm_group`
if `nonneg` is total and decidable.
-/
def to_linear_ordered_add_comm_group
[decidable_pred (@nonneg α _)]
(nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a))
: linear_ordered_add_comm_group α :=
{ le := (≤),
lt := (<),
le_total := nonneg_total_iff.1 nonneg_total,
decidable_le := by apply_instance,
decidable_lt := by apply_instance,
..@nonneg_add_comm_group.to_ordered_add_comm_group _ s }
end nonneg_add_comm_group
namespace order_dual
instance [ordered_add_comm_group α] : ordered_add_comm_group (order_dual α) :=
{ add_left_neg := λ a : α, add_left_neg a,
..order_dual.ordered_add_comm_monoid,
..show add_comm_group α, by apply_instance }
instance [linear_ordered_add_comm_group α] :
linear_ordered_add_comm_group (order_dual α) :=
{ add_le_add_left := λ a b h c, @add_le_add_left α _ b a h _,
..order_dual.linear_order α,
..show add_comm_group α, by apply_instance }
end order_dual
namespace prod
variables {G H : Type*}
@[to_additive]
instance [ordered_comm_group G] [ordered_comm_group H] :
ordered_comm_group (G × H) :=
{ .. prod.comm_group, .. prod.partial_order G H, .. prod.ordered_cancel_comm_monoid }
end prod
section type_tags
instance [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) :=
{ ..multiplicative.comm_group,
..multiplicative.ordered_comm_monoid }
instance [ordered_comm_group α] : ordered_add_comm_group (additive α) :=
{ ..additive.add_comm_group,
..additive.ordered_add_comm_monoid }
end type_tags
|
9bc75f3bdcb03d5a9d81690ecfcb84c84b90a66a | 94e33a31faa76775069b071adea97e86e218a8ee | /src/linear_algebra/matrix/spectrum.lean | edec7098efc255f5f38b15f3bedb5650fbce996d | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 3,743 | lean | /-
Copyright (c) 2022 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp
-/
import analysis.inner_product_space.spectrum
import linear_algebra.matrix.hermitian
/-! # Spectral theory of hermitian matrices
This file proves the spectral theorem for matrices. The proof of the spectral theorem is based on
the spectral theorem for linear maps (`diagonalization_basis_apply_self_apply`).
## Tags
spectral theorem, diagonalization theorem
-/
namespace matrix
variables {𝕜 : Type*} [is_R_or_C 𝕜] [decidable_eq 𝕜] {n : Type*} [fintype n] [decidable_eq n]
variables {A : matrix n n 𝕜}
open_locale matrix
namespace is_hermitian
variables (hA : A.is_hermitian)
/-- The eigenvalues of a hermitian matrix, indexed by `fin (fintype.card n)` where `n` is the index
type of the matrix. -/
noncomputable def eigenvalues₀ : fin (fintype.card n) → ℝ :=
@inner_product_space.is_self_adjoint.eigenvalues 𝕜 _ _ (pi_Lp 2 (λ (_ : n), 𝕜)) _ A.to_lin'
(is_hermitian_iff_is_self_adjoint.1 hA) _ (fintype.card n) finrank_euclidean_space
/-- The eigenvalues of a hermitian matrix, reusing the index `n` of the matrix entries. -/
noncomputable def eigenvalues : n → ℝ :=
λ i, hA.eigenvalues₀ $ (fintype.equiv_of_card_eq (fintype.card_fin _)).symm i
/-- A choice of an orthonormal basis of eigenvectors of a hermitian matrix. -/
noncomputable def eigenvector_basis : basis n 𝕜 (n → 𝕜) :=
(@inner_product_space.is_self_adjoint.eigenvector_basis 𝕜 _ _
(pi_Lp 2 (λ (_ : n), 𝕜)) _ A.to_lin' (is_hermitian_iff_is_self_adjoint.1 hA) _
(fintype.card n) finrank_euclidean_space).reindex
(fintype.equiv_of_card_eq (fintype.card_fin _))
/-- A matrix whose columns are an orthonormal basis of eigenvectors of a hermitian matrix. -/
noncomputable def eigenvector_matrix : matrix n n 𝕜 :=
(pi.basis_fun 𝕜 n).to_matrix (eigenvector_basis hA)
/-- The inverse of `eigenvector_matrix` -/
noncomputable def eigenvector_matrix_inv : matrix n n 𝕜 :=
(eigenvector_basis hA).to_matrix (pi.basis_fun 𝕜 n)
lemma eigenvector_matrix_mul_inv :
hA.eigenvector_matrix ⬝ hA.eigenvector_matrix_inv = 1 :=
by apply basis.to_matrix_mul_to_matrix_flip
/-- *Diagonalization theorem*, *spectral theorem* for matrices; A hermitian matrix can be
diagonalized by a change of basis.
For the spectral theorem on linear maps, see `diagonalization_basis_apply_self_apply`. -/
theorem spectral_theorem :
hA.eigenvector_matrix_inv ⬝ A =
diagonal (coe ∘ hA.eigenvalues) ⬝ hA.eigenvector_matrix_inv :=
begin
rw [eigenvector_matrix_inv, basis_to_matrix_basis_fun_mul],
ext i j,
convert @inner_product_space.is_self_adjoint.diagonalization_basis_apply_self_apply 𝕜 _ _
(pi_Lp 2 (λ (_ : n), 𝕜)) _ A.to_lin' (is_hermitian_iff_is_self_adjoint.1 hA) _ (fintype.card n)
finrank_euclidean_space (euclidean_space.single j 1)
((fintype.equiv_of_card_eq (fintype.card_fin _)).symm i),
{ rw [eigenvector_basis, inner_product_space.is_self_adjoint.diagonalization_basis,
to_lin'_apply],
simp only [basis.to_matrix, basis.coe_to_orthonormal_basis_repr, basis.equiv_fun_apply],
simp_rw [basis.reindex_repr, euclidean_space.single, pi_Lp.equiv_symm_apply', mul_vec_single,
mul_one],
refl },
{ simp only [diagonal_mul, (∘), eigenvalues, eigenvector_basis,
inner_product_space.is_self_adjoint.diagonalization_basis],
rw [basis.to_matrix_apply, basis.coe_to_orthonormal_basis_repr, basis.reindex_repr,
basis.equiv_fun_apply, pi.basis_fun_apply, eigenvalues₀, linear_map.coe_std_basis,
euclidean_space.single, pi_Lp.equiv_symm_apply'] }
end
end is_hermitian
end matrix
|
161b33bfc8f16c1fcf7ac0d44915741eae21dcb5 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Lean/Meta/Match/CaseArraySizes.lean | 16ccca1ecb77cb1f8bda16cba94ef5c3e2d873e1 | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 3,825 | 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.Tactic.Assert
import Lean.Meta.Match.CaseValues
namespace Lean.Meta
structure CaseArraySizesSubgoal where
mvarId : MVarId
elems : Array FVarId := #[]
diseqs : Array FVarId := #[]
subst : FVarSubst := {}
instance : Inhabited CaseArraySizesSubgoal :=
⟨{ mvarId := arbitrary }⟩
def getArrayArgType (a : Expr) : MetaM Expr := do
let aType ← inferType a
let aType ← whnfD aType
unless aType.isAppOfArity `Array 1 do
throwError "array expected{indentExpr a}"
pure aType.appArg!
private def mkArrayGetLit (a : Expr) (i : Nat) (n : Nat) (h : Expr) : MetaM Expr := do
let lt ← mkLt (mkNatLit i) (mkNatLit n)
let ltPrf ← mkDecideProof lt
mkAppM `Array.getLit #[a, mkNatLit i, h, ltPrf]
private partial def introArrayLit (mvarId : MVarId) (a : Expr) (n : Nat) (xNamePrefix : Name) (aSizeEqN : Expr) : MetaM MVarId := do
let α ← getArrayArgType a
let rec loop (i : Nat) (xs : Array Expr) (args : Array Expr) := do
if i < n then
withLocalDeclD (xNamePrefix.appendIndexAfter (i+1)) α fun xi => do
let xs := xs.push xi
let ai ← mkArrayGetLit a i n aSizeEqN
let args := args.push ai
loop (i+1) xs args
else
let xsLit ← mkArrayLit α xs.toList
let aEqXsLit ← mkEq a xsLit
let aEqLitPrf ← mkAppM `Array.toArrayLitEq #[a, mkNatLit n, aSizeEqN]
withLocalDeclD `hEqALit aEqXsLit fun heq => do
let target ← getMVarType mvarId
let newTarget ← mkForallFVars (xs.push heq) target
pure (newTarget, args.push aEqLitPrf)
let (newTarget, args) ← loop 0 #[] #[]
let tag ← getMVarTag mvarId
let newMVar ← mkFreshExprSyntheticOpaqueMVar newTarget tag
assignExprMVar mvarId (mkAppN newMVar args)
pure newMVar.mvarId!
/--
Split goal `... |- C a` into sizes.size + 1 subgoals
1) `..., x_1 ... x_{sizes[0]} |- C #[x_1, ... x_{sizes[0]}]`
...
n) `..., x_1 ... x_{sizes[n-1]} |- C #[x_1, ..., x_{sizes[n-1]}]`
n+1) `..., (h_1 : a.size != sizes[0]), ..., (h_n : a.size != sizes[n-1]) |- C a`
where `n = sizes.size` -/
def caseArraySizes (mvarId : MVarId) (fvarId : FVarId) (sizes : Array Nat) (xNamePrefix := `x) (hNamePrefix := `h) : MetaM (Array CaseArraySizesSubgoal) :=
withMVarContext mvarId do
let a := mkFVar fvarId
let α ← getArrayArgType a
let aSize ← mkAppM `Array.size #[a]
let mvarId ← assertExt mvarId `aSize (mkConst `Nat) aSize
let (aSizeFVarId, mvarId) ← intro1 mvarId
let (hEq, mvarId) ← intro1 mvarId
let subgoals ← caseValues mvarId aSizeFVarId (sizes.map mkNatLit) hNamePrefix
subgoals.mapIdxM fun i subgoal => do
let subst := subgoal.subst
let mvarId := subgoal.mvarId
let hEqSz := (subst.get hEq).fvarId!
if h : i.val < sizes.size then
let n := sizes.get ⟨i, h⟩
let mvarId ← clear mvarId subgoal.newHs[0]
let mvarId ← clear mvarId (subst.get aSizeFVarId).fvarId!
withMVarContext mvarId do
let hEqSzSymm ← mkEqSymm (mkFVar hEqSz)
let mvarId ← introArrayLit mvarId a n xNamePrefix hEqSzSymm
let (xs, mvarId) ← introN mvarId n
let (hEqLit, mvarId) ← intro1 mvarId
let mvarId ← clear mvarId hEqSz
let (subst, mvarId) ← substCore mvarId hEqLit false subst
pure { mvarId := mvarId, elems := xs, subst := subst }
else
let (subst, mvarId) ← substCore mvarId hEq false subst
let diseqs := subgoal.newHs.map fun fvarId => (subst.get fvarId).fvarId!
pure { mvarId := mvarId, diseqs := diseqs, subst := subst }
end Lean.Meta
|
51cb3d9ac984788bcc83f229e187c80b2eece0e0 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/order/well_founded_set.lean | d80a49d86ad96eee7594c727957f6aaaa1f5c1a0 | [
"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 | 35,762 | lean | /-
Copyright (c) 2021 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import data.set.pointwise
import order.antichain
import order.order_iso_nat
import order.well_founded
/-!
# Well-founded sets
A well-founded subset of an ordered type is one on which the relation `<` is well-founded.
## Main Definitions
* `set.well_founded_on s r` indicates that the relation `r` is
well-founded when restricted to the set `s`.
* `set.is_wf s` indicates that `<` is well-founded when restricted to `s`.
* `set.partially_well_ordered_on s r` indicates that the relation `r` is
partially well-ordered (also known as well quasi-ordered) when restricted to the set `s`.
* `set.is_pwo s` indicates that any infinite sequence of elements in `s`
contains an infinite monotone subsequence. Note that
### Definitions for Hahn Series
* `set.add_antidiagonal s t a` and `set.mul_antidiagonal s t a` are the sets of pairs of elements
from `s` and `t` that add/multiply to `a`.
* `finset.add_antidiagonal` and `finset.mul_antidiagonal` are finite versions of
`set.add_antidiagonal` and `set.mul_antidiagonal` defined when `s` and `t` are well-founded.
## Main Results
* Higman's Lemma, `set.partially_well_ordered_on.partially_well_ordered_on_sublist_forall₂`,
shows that if `r` is partially well-ordered on `s`, then `list.sublist_forall₂` is partially
well-ordered on the set of lists of elements of `s`. The result was originally published by
Higman, but this proof more closely follows Nash-Williams.
* `set.well_founded_on_iff` relates `well_founded_on` to the well-foundedness of a relation on the
original type, to avoid dealing with subtypes.
* `set.is_wf.mono` shows that a subset of a well-founded subset is well-founded.
* `set.is_wf.union` shows that the union of two well-founded subsets is well-founded.
* `finset.is_wf` shows that all `finset`s are well-founded.
## TODO
Prove that `s` is partial well ordered iff it has no infinite descending chain or antichain.
## References
* [Higman, *Ordering by Divisibility in Abstract Algebras*][Higman52]
* [Nash-Williams, *On Well-Quasi-Ordering Finite Trees*][Nash-Williams63]
-/
open_locale pointwise
variables {α : Type*}
namespace set
/-- `s.well_founded_on r` indicates that the relation `r` is well-founded when restricted to `s`. -/
def well_founded_on (s : set α) (r : α → α → Prop) : Prop :=
well_founded (λ (a : s) (b : s), r a b)
@[simp] lemma well_founded_on_empty (r : α → α → Prop) : well_founded_on ∅ r :=
well_founded_of_empty _
lemma well_founded_on_iff {s : set α} {r : α → α → Prop} :
s.well_founded_on r ↔ well_founded (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) :=
begin
have f : rel_embedding (λ (a : s) (b : s), r a b) (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) :=
⟨⟨coe, subtype.coe_injective⟩, λ a b, by simp⟩,
refine ⟨λ h, _, f.well_founded⟩,
rw well_founded.well_founded_iff_has_min,
intros t ht,
by_cases hst : (s ∩ t).nonempty,
{ rw ← subtype.preimage_coe_nonempty at hst,
rcases h.has_min (coe ⁻¹' t) hst with ⟨⟨m, ms⟩, mt, hm⟩,
exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hm ⟨x, xs⟩ xt xm⟩ },
{ rcases ht with ⟨m, mt⟩,
exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hst ⟨m, ⟨ms, mt⟩⟩⟩ }
end
lemma well_founded_on.induction {s : set α} {r : α → α → Prop} (hs : s.well_founded_on r) {x : α}
(hx : x ∈ s) {P : α → Prop} (hP : ∀ (y ∈ s), (∀ (z ∈ s), r z y → P z) → P y) :
P x :=
begin
let Q : s → Prop := λ y, P y,
change Q ⟨x, hx⟩,
refine well_founded.induction hs ⟨x, hx⟩ _,
rintros ⟨y, ys⟩ ih,
exact hP _ ys (λ z zs zy, ih ⟨z, zs⟩ zy),
end
instance is_strict_order.subset {s : set α} {r : α → α → Prop} [is_strict_order α r] :
is_strict_order α (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) :=
{ to_is_irrefl := ⟨λ a con, irrefl_of r a con.1 ⟩,
to_is_trans := ⟨λ a b c ab bc, ⟨trans_of r ab.1 bc.1, ab.2.1, bc.2.2⟩ ⟩ }
theorem well_founded_on_iff_no_descending_seq {s : set α} {r : α → α → Prop} [is_strict_order α r] :
s.well_founded_on r ↔ ∀ (f : ((>) : ℕ → ℕ → Prop) ↪r r), ¬ (range f) ⊆ s :=
begin
rw [well_founded_on_iff, rel_embedding.well_founded_iff_no_descending_seq],
refine ⟨λ h f con, begin
refine h.elim' ⟨⟨f, f.injective⟩, λ a b, _⟩,
simp only [con (mem_range_self a), con (mem_range_self b), and_true, gt_iff_lt,
function.embedding.coe_fn_mk, f.map_rel_iff]
end, λ h, ⟨λ con, _⟩⟩,
rcases con with ⟨f, hf⟩,
have hfs' : ∀ n : ℕ, f n ∈ s := λ n, (hf.2 n.lt_succ_self).2.2,
refine h ⟨f, λ a b, _⟩ (λ n hn, _),
{ rw ← hf,
exact ⟨λ h, ⟨h, hfs' _, hfs' _⟩, λ h, h.1⟩ },
{ rcases set.mem_range.1 hn with ⟨m, hm⟩,
rw ← hm,
apply hfs' }
end
section has_lt
variables [has_lt α]
/-- `s.is_wf` indicates that `<` is well-founded when restricted to `s`. -/
def is_wf (s : set α) : Prop := well_founded_on s (<)
@[simp] lemma is_wf_empty : is_wf (∅ : set α) := well_founded_of_empty _
lemma is_wf_univ_iff : is_wf (univ : set α) ↔ well_founded ((<) : α → α → Prop) :=
by simp [is_wf, well_founded_on_iff]
variables {s t : set α}
theorem is_wf.mono (h : is_wf t) (st : s ⊆ t) : is_wf s :=
begin
rw [is_wf, well_founded_on_iff] at *,
refine subrelation.wf (λ x y xy, _) h,
exact ⟨xy.1, st xy.2.1, st xy.2.2⟩,
end
end has_lt
section partial_order
variables [partial_order α] {s t : set α} {a : α}
theorem is_wf_iff_no_descending_seq : is_wf s ↔ ∀ f : ℕᵒᵈ ↪o α, ¬ (range f) ⊆ s :=
begin
haveI : is_strict_order α (λ (a b : α), a < b ∧ a ∈ s ∧ b ∈ s) :=
{ to_is_irrefl := ⟨λ x con, lt_irrefl x con.1⟩,
to_is_trans := ⟨λ a b c ab bc, ⟨lt_trans ab.1 bc.1, ab.2.1, bc.2.2⟩⟩, },
rw [is_wf, well_founded_on_iff_no_descending_seq],
exact ⟨λ h f, h f.lt_embedding, λ h f, h (order_embedding.of_strict_mono
f (λ _ _, f.map_rel_iff.2))⟩,
end
theorem is_wf.union (hs : is_wf s) (ht : is_wf t) : is_wf (s ∪ t) :=
begin
classical,
rw [is_wf_iff_no_descending_seq] at *,
rintros f fst,
have h : (f ⁻¹' s).infinite ∨ (f ⁻¹' t).infinite,
{ have h : (univ : set ℕ).infinite := infinite_univ,
have hpre : f ⁻¹' (s ∪ t) = set.univ,
{ rw [← image_univ, image_subset_iff, univ_subset_iff] at fst,
exact fst },
rw preimage_union at hpre,
rw ← hpre at h,
rw [set.infinite, set.infinite],
rw set.infinite at h,
contrapose! h,
exact finite.union h.1 h.2, },
rw [← infinite_coe_iff, ← infinite_coe_iff] at h,
cases h with inf inf; haveI := inf,
{ apply hs ((nat.order_embedding_of_set (f ⁻¹' s)).dual.trans f),
change range (function.comp f (nat.order_embedding_of_set (f ⁻¹' s))) ⊆ s,
rw [range_comp, image_subset_iff],
simp },
{ apply ht ((nat.order_embedding_of_set (f ⁻¹' t)).dual.trans f),
change range (function.comp f (nat.order_embedding_of_set (f ⁻¹' t))) ⊆ t,
rw [range_comp, image_subset_iff],
simp }
end
end partial_order
end set
namespace set
/-- A subset is partially well-ordered by a relation `r` when any infinite sequence contains
two elements where the first is related to the second by `r`. -/
def partially_well_ordered_on (s) (r : α → α → Prop) : Prop :=
∀ (f : ℕ → α), range f ⊆ s → ∃ (m n : ℕ), m < n ∧ r (f m) (f n)
@[simp] theorem partially_well_ordered_on_empty (r : α → α → Prop) :
partially_well_ordered_on (∅ : set α) r :=
λ f h, begin
rw subset_empty_iff at h,
exact ((range_nonempty f).ne_empty h).elim
end
/-- A subset of a preorder is partially well-ordered when any infinite sequence contains
a monotone subsequence of length 2 (or equivalently, an infinite monotone subsequence). -/
def is_pwo [preorder α] (s) : Prop :=
partially_well_ordered_on s ((≤) : α → α → Prop)
@[simp] theorem is_pwo_empty [preorder α] : is_pwo (∅ : set α) := partially_well_ordered_on_empty _
theorem partially_well_ordered_on.mono {s t : set α} {r : α → α → Prop}
(ht : t.partially_well_ordered_on r) (hsub : s ⊆ t) :
s.partially_well_ordered_on r :=
λ f hf, ht f (set.subset.trans hf hsub)
theorem is_pwo.mono [preorder α] {s t : set α}
(ht : t.is_pwo) (hsub : s ⊆ t) :
s.is_pwo :=
partially_well_ordered_on.mono ht hsub
theorem partially_well_ordered_on.image_of_monotone_on {s : set α}
{r : α → α → Prop} {β : Type*} {r' : β → β → Prop}
(hs : s.partially_well_ordered_on r) {f : α → β}
(hf : ∀ a1 a2 : α, a1 ∈ s → a2 ∈ s → r a1 a2 → r' (f a1) (f a2)) :
(f '' s).partially_well_ordered_on r' :=
λ g hg, begin
have h := λ (n : ℕ), ((mem_image _ _ _).1 (hg (mem_range_self n))),
obtain ⟨m, n, hlt, hmn⟩ := hs (λ n, classical.some (h n)) _,
{ refine ⟨m, n, hlt, _⟩,
rw [← (classical.some_spec (h m)).2,
← (classical.some_spec (h n)).2],
exact hf _ _ (classical.some_spec (h m)).1 (classical.some_spec (h n)).1 hmn },
{ rintros _ ⟨n, rfl⟩,
exact (classical.some_spec (h n)).1 }
end
lemma _root_.is_antichain.finite_of_partially_well_ordered_on {s : set α} {r : α → α → Prop}
(ha : is_antichain r s) (hp : s.partially_well_ordered_on r) :
s.finite :=
begin
refine finite_or_infinite.resolve_right (λ hi, _),
obtain ⟨m, n, hmn, h⟩ := hp (λ n, hi.nat_embedding _ n) (range_subset_iff.2 $
λ n, (hi.nat_embedding _ n).2),
exact hmn.ne ((hi.nat_embedding _).injective $ subtype.val_injective $
ha.eq (hi.nat_embedding _ m).2 (hi.nat_embedding _ n).2 h),
end
lemma finite.partially_well_ordered_on {s : set α} {r : α → α → Prop} [is_refl α r]
(hs : s.finite) :
s.partially_well_ordered_on r :=
begin
intros f hf,
obtain ⟨m, n, hmn, h⟩ := hs.exists_lt_map_eq_of_range_subset hf,
exact ⟨m, n, hmn, h.subst $ refl (f m)⟩,
end
lemma _root_.is_antichain.partially_well_ordered_on_iff {s : set α} {r : α → α → Prop} [is_refl α r]
(hs : is_antichain r s) :
s.partially_well_ordered_on r ↔ s.finite :=
⟨hs.finite_of_partially_well_ordered_on, finite.partially_well_ordered_on⟩
lemma partially_well_ordered_on_iff_finite_antichains {s : set α} {r : α → α → Prop} [is_refl α r]
[is_symm α r] :
s.partially_well_ordered_on r ↔ ∀ t ⊆ s, is_antichain r t → t.finite :=
begin
refine ⟨λ h t ht hrt, hrt.finite_of_partially_well_ordered_on (h.mono ht), _⟩,
rintro hs f hf,
by_contra' H,
refine set.infinite_range_of_injective (λ m n hmn, _) (hs _ hf _),
{ obtain h | h | h := lt_trichotomy m n,
{ refine (H _ _ h _).elim,
rw hmn,
exact refl _ },
{ exact h },
{ refine (H _ _ h _).elim,
rw hmn,
exact refl _ } },
rintro _ ⟨m, hm, rfl⟩ _ ⟨n, hn, rfl⟩ hmn,
obtain h | h := (ne_of_apply_ne _ hmn).lt_or_lt,
{ exact H _ _ h },
{ exact mt symm (H _ _ h) }
end
section partial_order
variables {s : set α} {t : set α} {r : α → α → Prop}
theorem partially_well_ordered_on.exists_monotone_subseq [is_refl α r] [is_trans α r]
(h : s.partially_well_ordered_on r) (f : ℕ → α) (hf : range f ⊆ s) :
∃ (g : ℕ ↪o ℕ), ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) :=
begin
obtain ⟨g, h1 | h2⟩ := exists_increasing_or_nonincreasing_subseq r f,
{ refine ⟨g, λ m n hle, _⟩,
obtain hlt | heq := lt_or_eq_of_le hle,
{ exact h1 m n hlt, },
{ rw [heq],
apply refl_of r } },
{ exfalso,
obtain ⟨m, n, hlt, hle⟩ := h (f ∘ g) (subset.trans (range_comp_subset_range _ _) hf),
exact h2 m n hlt hle }
end
theorem partially_well_ordered_on_iff_exists_monotone_subseq [is_refl α r] [is_trans α r] :
s.partially_well_ordered_on r ↔
∀ f : ℕ → α, range f ⊆ s → ∃ (g : ℕ ↪o ℕ), ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) :=
begin
classical,
split; intros h f hf,
{ exact h.exists_monotone_subseq f hf },
{ obtain ⟨g, gmon⟩ := h f hf,
refine ⟨g 0, g 1, g.lt_iff_lt.2 zero_lt_one, gmon _ _ zero_le_one⟩, }
end
lemma partially_well_ordered_on.well_founded_on [is_partial_order α r]
(h : s.partially_well_ordered_on r) :
s.well_founded_on (λ a b, r a b ∧ a ≠ b) :=
begin
haveI : is_strict_order α (λ a b, r a b ∧ a ≠ b) :=
{ to_is_irrefl := ⟨λ a con, con.2 rfl⟩,
to_is_trans := ⟨λ a b c ab bc, ⟨trans ab.1 bc.1,
λ ac, ab.2 (antisymm ab.1 (ac.symm ▸ bc.1))⟩⟩ },
rw well_founded_on_iff_no_descending_seq,
intros f con,
obtain ⟨m, n, hlt, hle⟩ := h f con,
exact (f.map_rel_iff.2 hlt).2 (antisymm hle (f.map_rel_iff.2 hlt).1).symm,
end
variables [partial_order α]
lemma is_pwo.is_wf (h : s.is_pwo) :
s.is_wf :=
begin
rw [is_wf],
convert h.well_founded_on,
ext x y,
rw lt_iff_le_and_ne,
end
theorem is_pwo.exists_monotone_subseq
(h : s.is_pwo) (f : ℕ → α) (hf : range f ⊆ s) :
∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) :=
h.exists_monotone_subseq f hf
theorem is_pwo_iff_exists_monotone_subseq :
s.is_pwo ↔
∀ f : ℕ → α, range f ⊆ s → ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) :=
partially_well_ordered_on_iff_exists_monotone_subseq
lemma is_pwo.prod (hs : s.is_pwo)
(ht : t.is_pwo) :
(s ×ˢ t).is_pwo :=
begin
classical,
rw is_pwo_iff_exists_monotone_subseq at *,
intros f hf,
obtain ⟨g1, h1⟩ := hs (prod.fst ∘ f) _,
swap,
{ rw [range_comp, image_subset_iff],
refine subset.trans hf _,
rintros ⟨x1, x2⟩ hx,
simp only [mem_preimage, hx.1] },
obtain ⟨g2, h2⟩ := ht (prod.snd ∘ f ∘ g1) _,
refine ⟨g2.trans g1, λ m n mn, _⟩,
swap,
{ rw [range_comp, image_subset_iff],
refine subset.trans (range_comp_subset_range _ _) (subset.trans hf _),
rintros ⟨x1, x2⟩ hx,
simp only [mem_preimage, hx.2] },
simp only [rel_embedding.coe_trans, function.comp_app],
exact ⟨h1 (g2.le_iff_le.2 mn), h2 mn⟩,
end
theorem is_pwo.image_of_monotone {β : Type*} [partial_order β]
(hs : s.is_pwo) {f : α → β} (hf : monotone f) :
is_pwo (f '' s) :=
hs.image_of_monotone_on (λ _ _ _ _ ab, hf ab)
theorem is_pwo.union (hs : is_pwo s) (ht : is_pwo t) : is_pwo (s ∪ t) :=
begin
classical,
rw [is_pwo_iff_exists_monotone_subseq] at *,
rintros f fst,
have h : (f ⁻¹' s).infinite ∨ (f ⁻¹' t).infinite,
{ have h : (univ : set ℕ).infinite := infinite_univ,
have hpre : f ⁻¹' (s ∪ t) = set.univ,
{ rw [← image_univ, image_subset_iff, univ_subset_iff] at fst,
exact fst },
rw preimage_union at hpre,
rw ← hpre at h,
rw [set.infinite, set.infinite],
rw set.infinite at h,
contrapose! h,
exact finite.union h.1 h.2, },
rw [← infinite_coe_iff, ← infinite_coe_iff] at h,
cases h with inf inf; haveI := inf,
{ obtain ⟨g, hg⟩ := hs (f ∘ (nat.order_embedding_of_set (f ⁻¹' s))) _,
{ rw [function.comp.assoc, ← rel_embedding.coe_trans] at hg,
exact ⟨_, hg⟩ },
rw [range_comp, image_subset_iff],
simp },
{ obtain ⟨g, hg⟩ := ht (f ∘ (nat.order_embedding_of_set (f ⁻¹' t))) _,
{ rw [function.comp.assoc, ← rel_embedding.coe_trans] at hg,
exact ⟨_, hg⟩ },
rw [range_comp, image_subset_iff],
simp }
end
end partial_order
theorem is_wf.is_pwo [linear_order α] {s : set α}
(hs : s.is_wf) : s.is_pwo :=
λ f hf, begin
rw [is_wf, well_founded_on_iff] at hs,
have hrange : (range f).nonempty := ⟨f 0, mem_range_self 0⟩,
let a := hs.min (range f) hrange,
obtain ⟨m, hm⟩ := hs.min_mem (range f) hrange,
refine ⟨m, m.succ, m.lt_succ_self, le_of_not_lt (λ con, _)⟩,
rw hm at con,
apply hs.not_lt_min (range f) hrange (mem_range_self m.succ)
⟨con, hf (mem_range_self m.succ), hf _⟩,
rw ← hm,
apply mem_range_self,
end
theorem is_wf_iff_is_pwo [linear_order α] {s : set α} :
s.is_wf ↔ s.is_pwo :=
⟨is_wf.is_pwo, is_pwo.is_wf⟩
end set
namespace finset
@[simp] lemma partially_well_ordered_on {r : α → α → Prop} [is_refl α r] (s : finset α) :
(s : set α).partially_well_ordered_on r :=
s.finite_to_set.partially_well_ordered_on
@[simp]
theorem is_pwo [partial_order α] (f : finset α) :
set.is_pwo (↑f : set α) :=
f.partially_well_ordered_on
@[simp]
theorem well_founded_on {r : α → α → Prop} [is_strict_order α r] (f : finset α) :
set.well_founded_on (↑f : set α) r :=
begin
rw [set.well_founded_on_iff_no_descending_seq],
intros g con,
apply set.infinite_of_injective_forall_mem g.injective (set.range_subset_iff.1 con),
exact f.finite_to_set,
end
@[simp]
theorem is_wf [partial_order α] (f : finset α) : set.is_wf (↑f : set α) :=
f.is_pwo.is_wf
end finset
namespace set
variables [partial_order α] {s : set α} {a : α}
theorem finite.is_pwo (h : s.finite) : s.is_pwo :=
begin
rw ← h.coe_to_finset,
exact h.to_finset.is_pwo,
end
@[simp]
theorem fintype.is_pwo [fintype α] : s.is_pwo := s.to_finite.is_pwo
@[simp]
theorem is_pwo_singleton (a) : is_pwo ({a} : set α) :=
(finite_singleton a).is_pwo
theorem is_pwo.insert (a) (hs : is_pwo s) : is_pwo (insert a s) :=
by { rw ← union_singleton, exact hs.union (is_pwo_singleton a) }
/-- `is_wf.min` returns a minimal element of a nonempty well-founded set. -/
noncomputable def is_wf.min (hs : is_wf s) (hn : s.nonempty) : α :=
hs.min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype)
lemma is_wf.min_mem (hs : is_wf s) (hn : s.nonempty) : hs.min hn ∈ s :=
(well_founded.min hs univ (nonempty_iff_univ_nonempty.1 hn.to_subtype)).2
lemma is_wf.not_lt_min (hs : is_wf s) (hn : s.nonempty) (ha : a ∈ s) : ¬ a < hs.min hn :=
hs.not_lt_min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) (mem_univ (⟨a, ha⟩ : s))
@[simp]
lemma is_wf_min_singleton (a) {hs : is_wf ({a} : set α)} {hn : ({a} : set α).nonempty} :
hs.min hn = a :=
eq_of_mem_singleton (is_wf.min_mem hs hn)
end set
theorem finset.is_wf_sup {ι : Type*} [partial_order α] (f : finset ι) (g : ι → set α)
(hf : ∀ i : ι, i ∈ f → (g i).is_wf) : (f.sup g).is_wf :=
finset.sup_induction set.is_pwo_empty.is_wf (λ a ha b hb, ha.union hb) hf
theorem finset.is_pwo_sup {ι : Type*} [partial_order α] (f : finset ι) (g : ι → set α)
(hf : ∀ i : ι, i ∈ f → (g i).is_pwo) : (f.sup g).is_pwo :=
finset.sup_induction set.is_pwo_empty (λ a ha b hb, ha.union hb) hf
namespace set
variables [linear_order α] {s t : set α} {a : α}
lemma is_wf.min_le
(hs : s.is_wf) (hn : s.nonempty) (ha : a ∈ s) : hs.min hn ≤ a :=
le_of_not_lt (hs.not_lt_min hn ha)
lemma is_wf.le_min_iff
(hs : s.is_wf) (hn : s.nonempty) :
a ≤ hs.min hn ↔ ∀ b, b ∈ s → a ≤ b :=
⟨λ ha b hb, le_trans ha (hs.min_le hn hb), λ h, h _ (hs.min_mem _)⟩
lemma is_wf.min_le_min_of_subset
{hs : s.is_wf} {hsn : s.nonempty} {ht : t.is_wf} {htn : t.nonempty} (hst : s ⊆ t) :
ht.min htn ≤ hs.min hsn :=
(is_wf.le_min_iff _ _).2 (λ b hb, ht.min_le htn (hst hb))
lemma is_wf.min_union (hs : s.is_wf) (hsn : s.nonempty) (ht : t.is_wf) (htn : t.nonempty) :
(hs.union ht).min (union_nonempty.2 (or.intro_left _ hsn)) = min (hs.min hsn) (ht.min htn) :=
begin
refine le_antisymm (le_min (is_wf.min_le_min_of_subset (subset_union_left _ _))
(is_wf.min_le_min_of_subset (subset_union_right _ _))) _,
rw min_le_iff,
exact ((mem_union _ _ _).1 ((hs.union ht).min_mem
(union_nonempty.2 (or.intro_left _ hsn)))).imp (hs.min_le _) (ht.min_le _),
end
end set
namespace set
variables {s : set α} {t : set α}
@[to_additive]
theorem is_pwo.mul [ordered_cancel_comm_monoid α] (hs : s.is_pwo) (ht : t.is_pwo) :
is_pwo (s * t) :=
begin
rw ← image_mul_prod,
exact (is_pwo.prod hs ht).image_of_monotone (λ _ _ h, mul_le_mul' h.1 h.2),
end
variable [linear_ordered_cancel_comm_monoid α]
@[to_additive]
theorem is_wf.mul (hs : s.is_wf) (ht : t.is_wf) : is_wf (s * t) :=
(hs.is_pwo.mul ht.is_pwo).is_wf
@[to_additive]
theorem is_wf.min_mul (hs : s.is_wf) (ht : t.is_wf) (hsn : s.nonempty) (htn : t.nonempty) :
(hs.mul ht).min (hsn.mul htn) = hs.min hsn * ht.min htn :=
begin
refine le_antisymm (is_wf.min_le _ _ (mem_mul.2 ⟨_, _, hs.min_mem _, ht.min_mem _, rfl⟩)) _,
rw is_wf.le_min_iff,
rintros _ ⟨x, y, hx, hy, rfl⟩,
exact mul_le_mul' (hs.min_le _ hx) (ht.min_le _ hy),
end
end set
namespace set
namespace partially_well_ordered_on
/-- In the context of partial well-orderings, a bad sequence is a nonincreasing sequence
whose range is contained in a particular set `s`. One exists if and only if `s` is not
partially well-ordered. -/
def is_bad_seq (r : α → α → Prop) (s : set α) (f : ℕ → α) : Prop :=
set.range f ⊆ s ∧ ∀ (m n : ℕ), m < n → ¬ r (f m) (f n)
lemma iff_forall_not_is_bad_seq (r : α → α → Prop) (s : set α) :
s.partially_well_ordered_on r ↔
∀ f, ¬ is_bad_seq r s f :=
begin
rw [set.partially_well_ordered_on],
apply forall_congr (λ f, _),
simp [is_bad_seq]
end
/-- This indicates that every bad sequence `g` that agrees with `f` on the first `n`
terms has `rk (f n) ≤ rk (g n)`. -/
def is_min_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) : Prop :=
∀ g : ℕ → α, (∀ (m : ℕ), m < n → f m = g m) → rk (g n) < rk (f n) → ¬ is_bad_seq r s g
/-- Given a bad sequence `f`, this constructs a bad sequence that agrees with `f` on the first `n`
terms and is minimal at `n`.
-/
noncomputable def min_bad_seq_of_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α)
(n : ℕ) (f : ℕ → α) (hf : is_bad_seq r s f) :
{ g : ℕ → α // (∀ (m : ℕ), m < n → f m = g m) ∧ is_bad_seq r s g ∧ is_min_bad_seq r rk s n g } :=
begin
classical,
have h : ∃ (k : ℕ) (g : ℕ → α), (∀ m, m < n → f m = g m) ∧ is_bad_seq r s g
∧ rk (g n) = k :=
⟨_, f, λ _ _, rfl, hf, rfl⟩,
obtain ⟨h1, h2, h3⟩ := classical.some_spec (nat.find_spec h),
refine ⟨classical.some (nat.find_spec h), h1, by convert h2, λ g hg1 hg2 con, _⟩,
refine nat.find_min h _ ⟨g, λ m mn, (h1 m mn).trans (hg1 m mn), by convert con, rfl⟩,
rwa ← h3,
end
lemma exists_min_bad_of_exists_bad (r : α → α → Prop) (rk : α → ℕ) (s : set α) :
(∃ f, is_bad_seq r s f) → ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f :=
begin
rintro ⟨f0, (hf0 : is_bad_seq r s f0)⟩,
let fs : Π (n : ℕ), { f : ℕ → α // is_bad_seq r s f ∧ is_min_bad_seq r rk s n f },
{ refine nat.rec _ _,
{ exact ⟨(min_bad_seq_of_bad_seq r rk s 0 f0 hf0).1,
(min_bad_seq_of_bad_seq r rk s 0 f0 hf0).2.2⟩, },
{ exact λ n fn, ⟨(min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).1,
(min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).2.2⟩ } },
have h : ∀ m n, m ≤ n → (fs m).1 m = (fs n).1 m,
{ intros m n mn,
obtain ⟨k, rfl⟩ := exists_add_of_le mn,
clear mn,
induction k with k ih,
{ refl },
rw [ih, ((min_bad_seq_of_bad_seq r rk s (m + k).succ (fs (m + k)).1 (fs (m + k)).2.1).2.1 m
(nat.lt_succ_iff.2 (nat.add_le_add_left k.zero_le m)))],
refl },
refine ⟨λ n, (fs n).1 n, ⟨set.range_subset_iff.2 (λ n, ((fs n).2).1.1 (mem_range_self n)),
λ m n mn, _⟩, λ n g hg1 hg2, _⟩,
{ dsimp,
rw [← subtype.val_eq_coe, h m n (le_of_lt mn)],
convert (fs n).2.1.2 m n mn },
{ convert (fs n).2.2 g (λ m mn, eq.trans _ (hg1 m mn)) (lt_of_lt_of_le hg2 le_rfl),
rw ← h m n (le_of_lt mn) },
end
lemma iff_not_exists_is_min_bad_seq {r : α → α → Prop} (rk : α → ℕ) {s : set α} :
s.partially_well_ordered_on r ↔ ¬ ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f :=
begin
rw [iff_forall_not_is_bad_seq, ← not_exists, not_congr],
split,
{ apply exists_min_bad_of_exists_bad },
rintro ⟨f, hf1, hf2⟩,
exact ⟨f, hf1⟩,
end
/-- Higman's Lemma, which states that for any reflexive, transitive relation `r` which is
partially well-ordered on a set `s`, the relation `list.sublist_forall₂ r` is partially
well-ordered on the set of lists of elements of `s`. That relation is defined so that
`list.sublist_forall₂ r l₁ l₂` whenever `l₁` related pointwise by `r` to a sublist of `l₂`. -/
lemma partially_well_ordered_on_sublist_forall₂ (r : α → α → Prop) [is_refl α r] [is_trans α r]
{s : set α} (h : s.partially_well_ordered_on r) :
{ l : list α | ∀ x, x ∈ l → x ∈ s }.partially_well_ordered_on (list.sublist_forall₂ r) :=
begin
rcases s.eq_empty_or_nonempty with rfl | ⟨as, has⟩,
{ apply partially_well_ordered_on.mono (finset.partially_well_ordered_on {list.nil}),
{ intros l hl,
rw [finset.mem_coe, finset.mem_singleton, list.eq_nil_iff_forall_not_mem],
exact hl, },
apply_instance },
haveI : inhabited α := ⟨as⟩,
rw [iff_not_exists_is_min_bad_seq (list.length)],
rintro ⟨f, hf1, hf2⟩,
have hnil : ∀ n, f n ≠ list.nil :=
λ n con, (hf1).2 n n.succ n.lt_succ_self (con.symm ▸ list.sublist_forall₂.nil),
obtain ⟨g, hg⟩ := h.exists_monotone_subseq (list.head ∘ f) _,
swap, { simp only [set.range_subset_iff, function.comp_apply],
exact λ n, hf1.1 (set.mem_range_self n) _ (list.head_mem_self (hnil n)) },
have hf' := hf2 (g 0) (λ n, if n < g 0 then f n else list.tail (f (g (n - g 0))))
(λ m hm, (if_pos hm).symm) _,
swap, { simp only [if_neg (lt_irrefl (g 0)), tsub_self],
rw [list.length_tail, ← nat.pred_eq_sub_one],
exact nat.pred_lt (λ con, hnil _ (list.length_eq_zero.1 con)) },
rw [is_bad_seq] at hf',
push_neg at hf',
obtain ⟨m, n, mn, hmn⟩ := hf' _,
swap, { rw set.range_subset_iff,
rintro n x hx,
split_ifs at hx with hn hn,
{ exact hf1.1 (set.mem_range_self _) _ hx },
{ refine hf1.1 (set.mem_range_self _) _ (list.tail_subset _ hx), } },
by_cases hn : n < g 0,
{ apply hf1.2 m n mn,
rwa [if_pos hn, if_pos (mn.trans hn)] at hmn },
{ obtain ⟨n', rfl⟩ := exists_add_of_le (not_lt.1 hn),
rw [if_neg hn, add_comm (g 0) n', add_tsub_cancel_right] at hmn,
split_ifs at hmn with hm hm,
{ apply hf1.2 m (g n') (lt_of_lt_of_le hm (g.monotone n'.zero_le)),
exact trans hmn (list.tail_sublist_forall₂_self _) },
{ rw [← (tsub_lt_iff_left (le_of_not_lt hm))] at mn,
apply hf1.2 _ _ (g.lt_iff_lt.2 mn),
rw [← list.cons_head_tail (hnil (g (m - g 0))), ← list.cons_head_tail (hnil (g n'))],
exact list.sublist_forall₂.cons (hg _ _ (le_of_lt mn)) hmn, } }
end
end partially_well_ordered_on
namespace is_pwo
@[to_additive]
lemma submonoid_closure [ordered_cancel_comm_monoid α] {s : set α} (hpos : ∀ x : α, x ∈ s → 1 ≤ x)
(h : s.is_pwo) : is_pwo ((submonoid.closure s) : set α) :=
begin
have hl : ((submonoid.closure s) : set α) ⊆ list.prod '' { l : list α | ∀ x, x ∈ l → x ∈ s },
{ intros x hx,
rw set_like.mem_coe at hx,
refine submonoid.closure_induction hx (λ x hx, ⟨_, λ y hy, _, list.prod_singleton⟩)
⟨_, λ y hy, (list.not_mem_nil _ hy).elim, list.prod_nil⟩ _,
{ rwa list.mem_singleton.1 hy },
rintros _ _ ⟨l, hl, rfl⟩ ⟨l', hl', rfl⟩,
refine ⟨_, λ y hy, _, list.prod_append⟩,
cases list.mem_append.1 hy with hy hy,
{ exact hl _ hy },
{ exact hl' _ hy } },
apply ((h.partially_well_ordered_on_sublist_forall₂ (≤)).image_of_monotone_on _).mono hl,
exact λ l1 l2 hl1 hl2 h12, h12.prod_le_prod' (λ x hx, hpos x $ hl2 x hx)
end
end is_pwo
/-- `set.mul_antidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t`
that multiply to `a`. -/
@[to_additive "`set.add_antidiagonal s t a` is the set of all pairs of an element in `s`
and an element in `t` that add to `a`."]
def mul_antidiagonal [monoid α] (s t : set α) (a : α) : set (α × α) :=
{ x | x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t }
namespace mul_antidiagonal
@[simp, to_additive]
lemma mem_mul_antidiagonal [monoid α] {s t : set α} {a : α} {x : α × α} :
x ∈ mul_antidiagonal s t a ↔ x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t := iff.refl _
section cancel_comm_monoid
variables [cancel_comm_monoid α] {s t : set α} {a : α}
@[to_additive]
lemma fst_eq_fst_iff_snd_eq_snd {x y : (mul_antidiagonal s t a)} :
(x : α × α).fst = (y : α × α).fst ↔ (x : α × α).snd = (y : α × α).snd :=
⟨λ h, begin
have hx := x.2.1,
rw [subtype.val_eq_coe, h] at hx,
apply mul_left_cancel (hx.trans y.2.1.symm),
end, λ h, begin
have hx := x.2.1,
rw [subtype.val_eq_coe, h] at hx,
apply mul_right_cancel (hx.trans y.2.1.symm),
end⟩
@[to_additive]
lemma eq_of_fst_eq_fst {x y : (mul_antidiagonal s t a)}
(h : (x : α × α).fst = (y : α × α).fst) : x = y :=
subtype.ext (prod.ext h (mul_antidiagonal.fst_eq_fst_iff_snd_eq_snd.1 h))
@[to_additive]
lemma eq_of_snd_eq_snd {x y : (mul_antidiagonal s t a)}
(h : (x : α × α).snd = (y : α × α).snd) : x = y :=
subtype.ext (prod.ext (mul_antidiagonal.fst_eq_fst_iff_snd_eq_snd.2 h) h)
end cancel_comm_monoid
section ordered_cancel_comm_monoid
variables [ordered_cancel_comm_monoid α] (s t : set α) (a : α)
@[to_additive]
lemma eq_of_fst_le_fst_of_snd_le_snd {x y : (mul_antidiagonal s t a)}
(h1 : (x : α × α).fst ≤ (y : α × α).fst) (h2 : (x : α × α).snd ≤ (y : α × α).snd ) :
x = y :=
begin
apply eq_of_fst_eq_fst,
cases eq_or_lt_of_le h1 with heq hlt,
{ exact heq },
exfalso,
exact ne_of_lt (mul_lt_mul_of_lt_of_le hlt h2)
((mem_mul_antidiagonal.1 x.2).1.trans (mem_mul_antidiagonal.1 y.2).1.symm)
end
variables {s} {t}
@[to_additive]
theorem finite_of_is_pwo (hs : s.is_pwo) (ht : t.is_pwo) (a) :
(mul_antidiagonal s t a).finite :=
begin
by_contra h,
rw [← set.infinite] at h,
have h1 : (mul_antidiagonal s t a).partially_well_ordered_on (prod.fst ⁻¹'o (≤)),
{ intros f hf,
refine hs (prod.fst ∘ f) _,
rw range_comp,
rintros _ ⟨⟨x, y⟩, hxy, rfl⟩,
exact (mem_mul_antidiagonal.1 (hf hxy)).2.1 },
have h2 : (mul_antidiagonal s t a).partially_well_ordered_on (prod.snd ⁻¹'o (≤)),
{ intros f hf,
refine ht (prod.snd ∘ f) _,
rw range_comp,
rintros _ ⟨⟨x, y⟩, hxy, rfl⟩,
exact (mem_mul_antidiagonal.1 (hf hxy)).2.2 },
obtain ⟨g, hg⟩ := h1.exists_monotone_subseq (λ x, h.nat_embedding _ x) _,
swap, { rintro _ ⟨k, rfl⟩,
exact ((infinite.nat_embedding (s.mul_antidiagonal t a) h) _).2 },
obtain ⟨m, n, mn, h2'⟩ := h2 (λ x, (h.nat_embedding _) (g x)) _,
swap, { rintro _ ⟨k, rfl⟩,
exact ((infinite.nat_embedding (s.mul_antidiagonal t a) h) _).2, },
apply ne_of_lt mn (g.injective ((h.nat_embedding _).injective _)),
exact eq_of_fst_le_fst_of_snd_le_snd _ _ _ (hg _ _ (le_of_lt mn)) h2',
end
end ordered_cancel_comm_monoid
@[to_additive]
theorem finite_of_is_wf [linear_ordered_cancel_comm_monoid α] {s t : set α}
(hs : s.is_wf) (ht : t.is_wf) (a) :
(mul_antidiagonal s t a).finite :=
finite_of_is_pwo hs.is_pwo ht.is_pwo a
end mul_antidiagonal
end set
namespace finset
variables [ordered_cancel_comm_monoid α]
variables {s t : set α} (hs : s.is_pwo) (ht : t.is_pwo) (a : α)
/-- `finset.mul_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in
`s` and an element in `t` that multiply to `a`, but its construction requires proofs
`hs` and `ht` that `s` and `t` are well-ordered. -/
@[to_additive "`finset.add_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in
`s` and an element in `t` that add to `a`, but its construction requires proofs
`hs` and `ht` that `s` and `t` are well-ordered."]
noncomputable def mul_antidiagonal : finset (α × α) :=
(set.mul_antidiagonal.finite_of_is_pwo hs ht a).to_finset
variables {hs} {ht} {u : set α} {hu : u.is_pwo} {a} {x : α × α}
@[simp, to_additive]
lemma mem_mul_antidiagonal :
x ∈ mul_antidiagonal hs ht a ↔ x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t :=
by simp [mul_antidiagonal]
@[to_additive]
lemma mul_antidiagonal_mono_left (hus : u ⊆ s) :
(finset.mul_antidiagonal hu ht a) ⊆ (finset.mul_antidiagonal hs ht a) :=
λ x hx, begin
rw mem_mul_antidiagonal at *,
exact ⟨hx.1, hus hx.2.1, hx.2.2⟩,
end
@[to_additive]
lemma mul_antidiagonal_mono_right (hut : u ⊆ t) :
(finset.mul_antidiagonal hs hu a) ⊆ (finset.mul_antidiagonal hs ht a) :=
λ x hx, begin
rw mem_mul_antidiagonal at *,
exact ⟨hx.1, hx.2.1, hut hx.2.2⟩,
end
@[to_additive]
lemma support_mul_antidiagonal_subset_mul :
{ a : α | (mul_antidiagonal hs ht a).nonempty } ⊆ s * t :=
(λ x ⟨⟨a1, a2⟩, ha⟩, begin
obtain ⟨hmul, h1, h2⟩ := mem_mul_antidiagonal.1 ha,
exact ⟨a1, a2, h1, h2, hmul⟩,
end)
@[to_additive]
theorem is_pwo_support_mul_antidiagonal :
{ a : α | (mul_antidiagonal hs ht a).nonempty }.is_pwo :=
(hs.mul ht).mono support_mul_antidiagonal_subset_mul
@[to_additive]
theorem mul_antidiagonal_min_mul_min {α} [linear_ordered_cancel_comm_monoid α] {s t : set α}
(hs : s.is_wf) (ht : t.is_wf)
(hns : s.nonempty) (hnt : t.nonempty) :
mul_antidiagonal hs.is_pwo ht.is_pwo ((hs.min hns) * (ht.min hnt)) =
{(hs.min hns, ht.min hnt)} :=
begin
ext ⟨a1, a2⟩,
rw [mem_mul_antidiagonal, finset.mem_singleton, prod.ext_iff],
split,
{ rintro ⟨hast, has, hat⟩,
cases eq_or_lt_of_le (hs.min_le hns has) with heq hlt,
{ refine ⟨heq.symm, _⟩,
rw heq at hast,
exact mul_left_cancel hast },
{ contrapose hast,
exact ne_of_gt (mul_lt_mul_of_lt_of_le hlt (ht.min_le hnt hat)) } },
{ rintro ⟨ha1, ha2⟩,
rw [ha1, ha2],
exact ⟨rfl, hs.min_mem _, ht.min_mem _⟩ }
end
end finset
lemma well_founded.is_wf [has_lt α] (h : well_founded ((<) : α → α → Prop)) (s : set α) :
s.is_wf :=
(set.is_wf_univ_iff.2 h).mono (set.subset_univ s)
/-- A version of **Dickson's lemma** any subset of functions `Π s : σ, α s` is partially well
ordered, when `σ` is a `fintype` and each `α s` is a linear well order.
This includes the classical case of Dickson's lemma that `ℕ ^ n` is a well partial order.
Some generalizations would be possible based on this proof, to include cases where the target
is partially well ordered, and also to consider the case of `partially_well_ordered_on` instead of
`is_pwo`. -/
lemma pi.is_pwo {σ : Type*} {α : σ → Type*} [∀ s, linear_order (α s)] [∀ s, is_well_order (α s) (<)]
[fintype σ] (S : set (Π s : σ, α s)) : S.is_pwo :=
begin
classical,
refine set.is_pwo.mono _ (set.subset_univ _),
rw set.is_pwo_iff_exists_monotone_subseq,
simp_rw [monotone, pi.le_def],
suffices : ∀ s : finset σ, ∀ (f : ℕ → (Π s, α s)), set.range f ⊆ set.univ → ∃ (g : ℕ ↪o ℕ),
∀ ⦃a b : ℕ⦄, a ≤ b → ∀ (x : σ) (hs : x ∈ s), (f ∘ g) a x ≤ (f ∘ g) b x,
{ simpa only [forall_true_left, finset.mem_univ] using this finset.univ, },
apply' finset.induction,
{ intros f hf, existsi rel_embedding.refl (≤),
simp only [is_empty.forall_iff, implies_true_iff, forall_const, finset.not_mem_empty], },
{ intros x s hx ih f hf,
obtain ⟨g, hg⟩ := (is_well_founded.wf.is_wf (set.univ : set _)).is_pwo.exists_monotone_subseq
((λ mo : Π s : σ, α s, mo x) ∘ f) (set.subset_univ _),
obtain ⟨g', hg'⟩ := ih (f ∘ g) (set.subset_univ _),
refine ⟨g'.trans g, λ a b hab, _⟩,
simp only [finset.mem_insert, rel_embedding.coe_trans, function.comp_app, forall_eq_or_imp],
exact ⟨hg (order_hom_class.mono g' hab), hg' hab⟩, },
end
|
93c8c30da0466cfcb58119d084a735f6d387ece3 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/computability/turing_machine_auto.lean | 0cdbc6b6fda6ccdface43b432093d9804fb23e29 | [] | 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 | 91,687 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.order
import Mathlib.data.fintype.basic
import Mathlib.data.pfun
import Mathlib.tactic.apply_fun
import Mathlib.logic.function.iterate
import Mathlib.PostPort
universes u_1 u_2 u v l u_3 u_4
namespace Mathlib
/-!
# Turing machines
This file defines a sequence of simple machine languages, starting with Turing machines and working
up to more complex languages based on Wang B-machines.
## Naming conventions
Each model of computation in this file shares a naming convention for the elements of a model of
computation. These are the parameters for the language:
* `Γ` is the alphabet on the tape.
* `Λ` is the set of labels, or internal machine states.
* `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and
later models achieve this by mixing it into `Λ`.
* `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks.
All of these variables denote "essentially finite" types, but for technical reasons it is
convenient to allow them to be infinite anyway. When using an infinite type, we will be interested
to prove that only finitely many values of the type are ever interacted with.
Given these parameters, there are a few common structures for the model that arise:
* `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is
finite, and for later models it is an infinite inductive type representing "possible program
texts".
* `cfg` is the set of instantaneous configurations, that is, the state of the machine together with
its environment.
* `machine` is the set of all machines in the model. Usually this is approximately a function
`Λ → stmt`, although different models have different ways of halting and other actions.
* `step : cfg → option cfg` is the function that describes how the state evolves over one step.
If `step c = none`, then `c` is a terminal state, and the result of the computation is read off
from `c`. Because of the type of `step`, these models are all deterministic by construction.
* `init : input → cfg` sets up the initial state. The type `input` depends on the model;
in most cases it is `list Γ`.
* `eval : machine → input → roption output`, given a machine `M` and input `i`, starts from
`init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to
the final state to obtain the result. The type `output` depends on the model.
* `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and
can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input
cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when
convenient, and prove that only finitely many of these states are actually accessible. This
formalizes "essentially finite" mentioned above.
-/
namespace turing
/-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding
blanks (`default Γ`) to the end of `l₁`. -/
def blank_extends {Γ : Type u_1} [Inhabited Γ] (l₁ : List Γ) (l₂ : List Γ) :=
∃ (n : ℕ), l₂ = l₁ ++ list.repeat Inhabited.default n
theorem blank_extends.refl {Γ : Type u_1} [Inhabited Γ] (l : List Γ) : blank_extends l l := sorry
theorem blank_extends.trans {Γ : Type u_1} [Inhabited Γ] {l₁ : List Γ} {l₂ : List Γ} {l₃ : List Γ} :
blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ :=
sorry
theorem blank_extends.below_of_le {Γ : Type u_1} [Inhabited Γ] {l : List Γ} {l₁ : List Γ}
{l₂ : List Γ} :
blank_extends l l₁ →
blank_extends l l₂ → list.length l₁ ≤ list.length l₂ → blank_extends l₁ l₂ :=
sorry
/-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the
longer of `l₁` and `l₂`). -/
def blank_extends.above {Γ : Type u_1} [Inhabited Γ] {l : List Γ} {l₁ : List Γ} {l₂ : List Γ}
(h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) :
Subtype fun (l' : List Γ) => blank_extends l₁ l' ∧ blank_extends l₂ l' :=
dite (list.length l₁ ≤ list.length l₂)
(fun (h : list.length l₁ ≤ list.length l₂) => { val := l₂, property := sorry })
fun (h : ¬list.length l₁ ≤ list.length l₂) => { val := l₁, property := sorry }
theorem blank_extends.above_of_le {Γ : Type u_1} [Inhabited Γ] {l : List Γ} {l₁ : List Γ}
{l₂ : List Γ} :
blank_extends l₁ l →
blank_extends l₂ l → list.length l₁ ≤ list.length l₂ → blank_extends l₁ l₂ :=
sorry
/-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence
relation. Two lists are related by `blank_rel` if one extends the other by blanks. -/
def blank_rel {Γ : Type u_1} [Inhabited Γ] (l₁ : List Γ) (l₂ : List Γ) :=
blank_extends l₁ l₂ ∨ blank_extends l₂ l₁
theorem blank_rel.refl {Γ : Type u_1} [Inhabited Γ] (l : List Γ) : blank_rel l l :=
Or.inl (blank_extends.refl l)
theorem blank_rel.symm {Γ : Type u_1} [Inhabited Γ] {l₁ : List Γ} {l₂ : List Γ} :
blank_rel l₁ l₂ → blank_rel l₂ l₁ :=
or.symm
theorem blank_rel.trans {Γ : Type u_1} [Inhabited Γ] {l₁ : List Γ} {l₂ : List Γ} {l₃ : List Γ} :
blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ :=
sorry
/-- Given two `blank_rel` lists, there exists (constructively) a common join. -/
def blank_rel.above {Γ : Type u_1} [Inhabited Γ] {l₁ : List Γ} {l₂ : List Γ} (h : blank_rel l₁ l₂) :
Subtype fun (l : List Γ) => blank_extends l₁ l ∧ blank_extends l₂ l :=
dite (list.length l₁ ≤ list.length l₂)
(fun (hl : list.length l₁ ≤ list.length l₂) => { val := l₂, property := sorry })
fun (hl : ¬list.length l₁ ≤ list.length l₂) => { val := l₁, property := sorry }
/-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/
def blank_rel.old_below {Γ : Type u_1} [Inhabited Γ] {l₁ : List Γ} {l₂ : List Γ}
(h : blank_rel l₁ l₂) : Subtype fun (l : List Γ) => blank_extends l l₁ ∧ blank_extends l l₂ :=
dite (list.length l₁ ≤ list.length l₂)
(fun (hl : list.length l₁ ≤ list.length l₂) =>
{ val := l₁, property := blank_rel.below._proof_1 h hl })
fun (hl : ¬list.length l₁ ≤ list.length l₂) =>
{ val := l₂, property := blank_rel.below._proof_2 h hl }
theorem blank_rel.equivalence (Γ : Type u_1) [Inhabited Γ] : equivalence blank_rel :=
{ left := blank_rel.refl, right := { left := blank_rel.symm, right := blank_rel.trans } }
/-- Construct a setoid instance for `blank_rel`. -/
def blank_rel.setoid (Γ : Type u_1) [Inhabited Γ] : setoid (List Γ) :=
setoid.mk blank_rel (blank_rel.equivalence Γ)
/-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to
represent half-tapes of a Turing machine, so that we can pretend that the list continues
infinitely with blanks. -/
def list_blank (Γ : Type u_1) [Inhabited Γ] := quotient (blank_rel.setoid Γ)
protected instance list_blank.inhabited {Γ : Type u_1} [Inhabited Γ] : Inhabited (list_blank Γ) :=
{ default := quotient.mk' [] }
protected instance list_blank.has_emptyc {Γ : Type u_1} [Inhabited Γ] : has_emptyc (list_blank Γ) :=
has_emptyc.mk (quotient.mk' [])
/-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger
precondition `blank_extends` instead of `blank_rel`. -/
protected def list_blank.lift_on {Γ : Type u_1} [Inhabited Γ] {α : Sort u_2} (l : list_blank Γ)
(f : List Γ → α) (H : ∀ (a b : List Γ), blank_extends a b → f a = f b) : α :=
quotient.lift_on' l f sorry
/-- The quotient map turning a `list` into a `list_blank`. -/
def list_blank.mk {Γ : Type u_1} [Inhabited Γ] : List Γ → list_blank Γ := quotient.mk'
protected theorem list_blank.induction_on {Γ : Type u_1} [Inhabited Γ] {p : list_blank Γ → Prop}
(q : list_blank Γ) (h : ∀ (a : List Γ), p (list_blank.mk a)) : p q :=
quotient.induction_on' q h
/-- The head of a `list_blank` is well defined. -/
def list_blank.head {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) : Γ :=
list_blank.lift_on l list.head sorry
@[simp] theorem list_blank.head_mk {Γ : Type u_1} [Inhabited Γ] (l : List Γ) :
list_blank.head (list_blank.mk l) = list.head l :=
rfl
/-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/
def list_blank.tail {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) : list_blank Γ :=
list_blank.lift_on l (fun (l : List Γ) => list_blank.mk (list.tail l)) sorry
@[simp] theorem list_blank.tail_mk {Γ : Type u_1} [Inhabited Γ] (l : List Γ) :
list_blank.tail (list_blank.mk l) = list_blank.mk (list.tail l) :=
rfl
/-- We can cons an element onto a `list_blank`. -/
def list_blank.cons {Γ : Type u_1} [Inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ :=
list_blank.lift_on l (fun (l : List Γ) => list_blank.mk (a :: l)) sorry
@[simp] theorem list_blank.cons_mk {Γ : Type u_1} [Inhabited Γ] (a : Γ) (l : List Γ) :
list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) :=
rfl
@[simp] theorem list_blank.head_cons {Γ : Type u_1} [Inhabited Γ] (a : Γ) (l : list_blank Γ) :
list_blank.head (list_blank.cons a l) = a :=
quotient.ind' fun (l : List Γ) => rfl
@[simp] theorem list_blank.tail_cons {Γ : Type u_1} [Inhabited Γ] (a : Γ) (l : list_blank Γ) :
list_blank.tail (list_blank.cons a l) = l :=
quotient.ind' fun (l : List Γ) => rfl
/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where
this only holds for nonempty lists. -/
@[simp] theorem list_blank.cons_head_tail {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) :
list_blank.cons (list_blank.head l) (list_blank.tail l) = l :=
sorry
/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where
this only holds for nonempty lists. -/
theorem list_blank.exists_cons {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) :
∃ (a : Γ), ∃ (l' : list_blank Γ), l = list_blank.cons a l' :=
Exists.intro (list_blank.head l)
(Exists.intro (list_blank.tail l) (Eq.symm (list_blank.cons_head_tail l)))
/-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/
def list_blank.nth {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ :=
list_blank.lift_on l (fun (l : List Γ) => list.inth l n) sorry
@[simp] theorem list_blank.nth_mk {Γ : Type u_1} [Inhabited Γ] (l : List Γ) (n : ℕ) :
list_blank.nth (list_blank.mk l) n = list.inth l n :=
rfl
@[simp] theorem list_blank.nth_zero {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) :
list_blank.nth l 0 = list_blank.head l :=
sorry
@[simp] theorem list_blank.nth_succ {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) (n : ℕ) :
list_blank.nth l (n + 1) = list_blank.nth (list_blank.tail l) n :=
sorry
theorem list_blank.ext {Γ : Type u_1} [Inhabited Γ] {L₁ : list_blank Γ} {L₂ : list_blank Γ} :
(∀ (i : ℕ), list_blank.nth L₁ i = list_blank.nth L₂ i) → L₁ = L₂ :=
sorry
/-- Apply a function to a value stored at the nth position of the list. -/
@[simp] def list_blank.modify_nth {Γ : Type u_1} [Inhabited Γ] (f : Γ → Γ) :
ℕ → list_blank Γ → list_blank Γ :=
sorry
theorem list_blank.nth_modify_nth {Γ : Type u_1} [Inhabited Γ] (f : Γ → Γ) (n : ℕ) (i : ℕ)
(L : list_blank Γ) :
list_blank.nth (list_blank.modify_nth f n L) i =
ite (i = n) (f (list_blank.nth L i)) (list_blank.nth L i) :=
sorry
/-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/
structure pointed_map (Γ : Type u) (Γ' : Type v) [Inhabited Γ] [Inhabited Γ'] where
f : Γ → Γ'
map_pt' : f Inhabited.default = Inhabited.default
protected instance pointed_map.inhabited {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ]
[Inhabited Γ'] : Inhabited (pointed_map Γ Γ') :=
{ default := pointed_map.mk (fun (_x : Γ) => Inhabited.default) sorry }
protected instance pointed_map.has_coe_to_fun {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ]
[Inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') :=
has_coe_to_fun.mk (fun (x : pointed_map Γ Γ') => Γ → Γ') pointed_map.f
@[simp] theorem pointed_map.mk_val {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : Γ → Γ') (pt : f Inhabited.default = Inhabited.default) : ⇑(pointed_map.mk f pt) = f :=
rfl
@[simp] theorem pointed_map.map_pt {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') : coe_fn f Inhabited.default = Inhabited.default :=
pointed_map.map_pt' f
@[simp] theorem pointed_map.head_map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (l : List Γ) : list.head (list.map (⇑f) l) = coe_fn f (list.head l) :=
list.cases_on l (Eq.symm (pointed_map.map_pt f))
fun (l_hd : Γ) (l_tl : List Γ) => Eq.refl (list.head (list.map (⇑f) (l_hd :: l_tl)))
/-- The `map` function on lists is well defined on `list_blank`s provided that the map is
pointed. -/
def list_blank.map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' :=
list_blank.lift_on l (fun (l : List Γ) => list_blank.mk (list.map (⇑f) l)) sorry
@[simp] theorem list_blank.map_mk {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (l : List Γ) :
list_blank.map f (list_blank.mk l) = list_blank.mk (list.map (⇑f) l) :=
rfl
@[simp] theorem list_blank.head_map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) :
list_blank.head (list_blank.map f l) = coe_fn f (list_blank.head l) :=
sorry
@[simp] theorem list_blank.tail_map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) :
list_blank.tail (list_blank.map f l) = list_blank.map f (list_blank.tail l) :=
sorry
@[simp] theorem list_blank.map_cons {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) :
list_blank.map f (list_blank.cons a l) = list_blank.cons (coe_fn f a) (list_blank.map f l) :=
sorry
@[simp] theorem list_blank.nth_map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) :
list_blank.nth (list_blank.map f l) n = coe_fn f (list_blank.nth l n) :=
sorry
/-- The `i`-th projection as a pointed map. -/
def proj {ι : Type u_1} {Γ : ι → Type u_2} [(i : ι) → Inhabited (Γ i)] (i : ι) :
pointed_map ((i : ι) → Γ i) (Γ i) :=
pointed_map.mk (fun (a : (i : ι) → Γ i) => a i) sorry
theorem proj_map_nth {ι : Type u_1} {Γ : ι → Type u_2} [(i : ι) → Inhabited (Γ i)] (i : ι)
(L : list_blank ((i : ι) → Γ i)) (n : ℕ) :
list_blank.nth (list_blank.map (proj i) L) n = list_blank.nth L n i :=
sorry
theorem list_blank.map_modify_nth {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ')
(H : ∀ (x : Γ), coe_fn F (f x) = f' (coe_fn F x)) (n : ℕ) (L : list_blank Γ) :
list_blank.map F (list_blank.modify_nth f n L) =
list_blank.modify_nth f' n (list_blank.map F L) :=
sorry
/-- Append a list on the left side of a list_blank. -/
@[simp] def list_blank.append {Γ : Type u_1} [Inhabited Γ] : List Γ → list_blank Γ → list_blank Γ :=
sorry
@[simp] theorem list_blank.append_mk {Γ : Type u_1} [Inhabited Γ] (l₁ : List Γ) (l₂ : List Γ) :
list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) :=
sorry
theorem list_blank.append_assoc {Γ : Type u_1} [Inhabited Γ] (l₁ : List Γ) (l₂ : List Γ)
(l₃ : list_blank Γ) :
list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) :=
sorry
/-- The `bind` function on lists is well defined on `list_blank`s provided that the default element
is sent to a sequence of default elements. -/
def list_blank.bind {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (l : list_blank Γ)
(f : Γ → List Γ') (hf : ∃ (n : ℕ), f Inhabited.default = list.repeat Inhabited.default n) :
list_blank Γ' :=
list_blank.lift_on l (fun (l : List Γ) => list_blank.mk (list.bind l f)) sorry
@[simp] theorem list_blank.bind_mk {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(l : List Γ) (f : Γ → List Γ')
(hf : ∃ (n : ℕ), f Inhabited.default = list.repeat Inhabited.default n) :
list_blank.bind (list_blank.mk l) f hf = list_blank.mk (list.bind l f) :=
rfl
@[simp] theorem list_blank.cons_bind {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(a : Γ) (l : list_blank Γ) (f : Γ → List Γ')
(hf : ∃ (n : ℕ), f Inhabited.default = list.repeat Inhabited.default n) :
list_blank.bind (list_blank.cons a l) f hf = list_blank.append (f a) (list_blank.bind l f hf) :=
sorry
/-- The tape of a Turing machine is composed of a head element (which we imagine to be the
current position of the head), together with two `list_blank`s denoting the portions of the tape
going off to the left and right. When the Turing machine moves right, an element is pulled from the
right side and becomes the new head, while the head element is consed onto the left side. -/
structure tape (Γ : Type u_1) [Inhabited Γ] where
head : Γ
left : list_blank Γ
right : list_blank Γ
protected instance tape.inhabited {Γ : Type u_1} [Inhabited Γ] : Inhabited (tape Γ) :=
{ default := tape.mk Inhabited.default Inhabited.default Inhabited.default }
/-- A direction for the turing machine `move` command, either
left or right. -/
inductive dir where
| left : dir
| right : dir
/-- The "inclusive" left side of the tape, including both `left` and `head`. -/
def tape.left₀ {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : list_blank Γ :=
list_blank.cons (tape.head T) (tape.left T)
/-- The "inclusive" right side of the tape, including both `right` and `head`. -/
def tape.right₀ {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : list_blank Γ :=
list_blank.cons (tape.head T) (tape.right T)
/-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes
`T.left` smaller; the Turing machine is moving left and the tape is moving right. -/
def tape.move {Γ : Type u_1} [Inhabited Γ] : dir → tape Γ → tape Γ := sorry
@[simp] theorem tape.move_left_right {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) :
tape.move dir.right (tape.move dir.left T) = T :=
sorry
@[simp] theorem tape.move_right_left {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) :
tape.move dir.left (tape.move dir.right T) = T :=
sorry
/-- Construct a tape from a left side and an inclusive right side. -/
def tape.mk' {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) : tape Γ :=
tape.mk (list_blank.head R) L (list_blank.tail R)
@[simp] theorem tape.mk'_left {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) :
tape.left (tape.mk' L R) = L :=
rfl
@[simp] theorem tape.mk'_head {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) :
tape.head (tape.mk' L R) = list_blank.head R :=
rfl
@[simp] theorem tape.mk'_right {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) :
tape.right (tape.mk' L R) = list_blank.tail R :=
rfl
@[simp] theorem tape.mk'_right₀ {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) :
tape.right₀ (tape.mk' L R) = R :=
list_blank.cons_head_tail R
@[simp] theorem tape.mk'_left_right₀ {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) :
tape.mk' (tape.left T) (tape.right₀ T) = T :=
sorry
theorem tape.exists_mk' {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) :
∃ (L : list_blank Γ), ∃ (R : list_blank Γ), T = tape.mk' L R :=
Exists.intro (tape.left T) (Exists.intro (tape.right₀ T) (Eq.symm (tape.mk'_left_right₀ T)))
@[simp] theorem tape.move_left_mk' {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ)
(R : list_blank Γ) :
tape.move dir.left (tape.mk' L R) =
tape.mk' (list_blank.tail L) (list_blank.cons (list_blank.head L) R) :=
sorry
@[simp] theorem tape.move_right_mk' {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ)
(R : list_blank Γ) :
tape.move dir.right (tape.mk' L R) =
tape.mk' (list_blank.cons (list_blank.head R) L) (list_blank.tail R) :=
sorry
/-- Construct a tape from a left side and an inclusive right side. -/
def tape.mk₂ {Γ : Type u_1} [Inhabited Γ] (L : List Γ) (R : List Γ) : tape Γ :=
tape.mk' (list_blank.mk L) (list_blank.mk R)
/-- Construct a tape from a list, with the head of the list at the TM head and the rest going
to the right. -/
def tape.mk₁ {Γ : Type u_1} [Inhabited Γ] (l : List Γ) : tape Γ := tape.mk₂ [] l
/-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes
on the left and positive indexes on the right. (Picture a number line.) -/
def tape.nth {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : ℤ → Γ := sorry
@[simp] theorem tape.nth_zero {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) :
tape.nth T 0 = tape.head T :=
rfl
theorem tape.right₀_nth {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) (n : ℕ) :
list_blank.nth (tape.right₀ T) n = tape.nth T ↑n :=
sorry
@[simp] theorem tape.mk'_nth_nat {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ)
(n : ℕ) : tape.nth (tape.mk' L R) ↑n = list_blank.nth R n :=
sorry
@[simp] theorem tape.move_left_nth {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) (i : ℤ) :
tape.nth (tape.move dir.left T) i = tape.nth T (i - 1) :=
sorry
@[simp] theorem tape.move_right_nth {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) (i : ℤ) :
tape.nth (tape.move dir.right T) i = tape.nth T (i + 1) :=
sorry
@[simp] theorem tape.move_right_n_head {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) (i : ℕ) :
tape.head (nat.iterate (tape.move dir.right) i T) = tape.nth T ↑i :=
sorry
/-- Replace the current value of the head on the tape. -/
def tape.write {Γ : Type u_1} [Inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ :=
tape.mk b (tape.left T) (tape.right T)
@[simp] theorem tape.write_self {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) :
tape.write (tape.head T) T = T :=
tape.cases_on T
fun (T_head : Γ) (T_left T_right : list_blank Γ) =>
Eq.refl
(tape.write (tape.head (tape.mk T_head T_left T_right)) (tape.mk T_head T_left T_right))
@[simp] theorem tape.write_nth {Γ : Type u_1} [Inhabited Γ] (b : Γ) (T : tape Γ) {i : ℤ} :
tape.nth (tape.write b T) i = ite (i = 0) b (tape.nth T i) :=
sorry
@[simp] theorem tape.write_mk' {Γ : Type u_1} [Inhabited Γ] (a : Γ) (b : Γ) (L : list_blank Γ)
(R : list_blank Γ) :
tape.write b (tape.mk' L (list_blank.cons a R)) = tape.mk' L (list_blank.cons b R) :=
sorry
/-- Apply a pointed map to a tape to change the alphabet. -/
def tape.map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ')
(T : tape Γ) : tape Γ' :=
tape.mk (coe_fn f (tape.head T)) (list_blank.map f (tape.left T))
(list_blank.map f (tape.right T))
@[simp] theorem tape.map_fst {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (T : tape Γ) : tape.head (tape.map f T) = coe_fn f (tape.head T) :=
tape.cases_on T
fun (T_head : Γ) (T_left T_right : list_blank Γ) =>
Eq.refl (tape.head (tape.map f (tape.mk T_head T_left T_right)))
@[simp] theorem tape.map_write {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (b : Γ) (T : tape Γ) :
tape.map f (tape.write b T) = tape.write (coe_fn f b) (tape.map f T) :=
tape.cases_on T
fun (T_head : Γ) (T_left T_right : list_blank Γ) =>
Eq.refl (tape.map f (tape.write b (tape.mk T_head T_left T_right)))
@[simp] theorem tape.write_move_right_n {Γ : Type u_1} [Inhabited Γ] (f : Γ → Γ) (L : list_blank Γ)
(R : list_blank Γ) (n : ℕ) :
tape.write (f (list_blank.nth R n)) (nat.iterate (tape.move dir.right) n (tape.mk' L R)) =
nat.iterate (tape.move dir.right) n (tape.mk' L (list_blank.modify_nth f n R)) :=
sorry
theorem tape.map_move {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (T : tape Γ) (d : dir) :
tape.map f (tape.move d T) = tape.move d (tape.map f T) :=
sorry
theorem tape.map_mk' {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (L : list_blank Γ) (R : list_blank Γ) :
tape.map f (tape.mk' L R) = tape.mk' (list_blank.map f L) (list_blank.map f R) :=
sorry
theorem tape.map_mk₂ {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (L : List Γ) (R : List Γ) :
tape.map f (tape.mk₂ L R) = tape.mk₂ (list.map (⇑f) L) (list.map (⇑f) R) :=
sorry
theorem tape.map_mk₁ {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ']
(f : pointed_map Γ Γ') (l : List Γ) : tape.map f (tape.mk₁ l) = tape.mk₁ (list.map (⇑f) l) :=
tape.map_mk₂ f [] l
/-- Run a state transition function `σ → option σ` "to completion". The return value is the last
state returned before a `none` result. If the state transition function always returns `some`,
then the computation diverges, returning `roption.none`. -/
def eval {σ : Type u_1} (f : σ → Option σ) : σ → roption σ :=
pfun.fix fun (s : σ) => roption.some (option.elim (f s) (sum.inl s) sum.inr)
/-- The reflexive transitive closure of a state transition function. `reaches f a b` means
there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.
This relation permits zero steps of the state transition function. -/
def reaches {σ : Type u_1} (f : σ → Option σ) : σ → σ → Prop :=
relation.refl_trans_gen fun (a b : σ) => b ∈ f a
/-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a
nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.
This relation does not permit zero steps of the state transition function. -/
def reaches₁ {σ : Type u_1} (f : σ → Option σ) : σ → σ → Prop :=
relation.trans_gen fun (a b : σ) => b ∈ f a
theorem reaches₁_eq {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ} (h : f a = f b) :
reaches₁ f a c ↔ reaches₁ f b c :=
sorry
theorem reaches_total {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ} :
reaches f a b → reaches f a c → reaches f b c ∨ reaches f c b :=
relation.refl_trans_gen.total_of_right_unique fun (_x _x_1 _x_2 : σ) => option.mem_unique
theorem reaches₁_fwd {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ} (h₁ : reaches₁ f a c)
(h₂ : b ∈ f a) : reaches f b c :=
sorry
/-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then
`reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with
equivalent states without taking a step. -/
def reaches₀ {σ : Type u_1} (f : σ → Option σ) (a : σ) (b : σ) :=
∀ (c : σ), reaches₁ f b c → reaches₁ f a c
theorem reaches₀.trans {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ}
(h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c :=
fun (c_1 : σ) (ᾰ : reaches₁ f c c_1) => idRhs (reaches₁ f a c_1) (h₁ c_1 (h₂ c_1 ᾰ))
theorem reaches₀.refl {σ : Type u_1} {f : σ → Option σ} (a : σ) : reaches₀ f a a :=
fun (c : σ) (ᾰ : reaches₁ f a c) => idRhs (reaches₁ f a c) ᾰ
theorem reaches₀.single {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (h : b ∈ f a) :
reaches₀ f a b :=
fun (c : σ) (ᾰ : reaches₁ f b c) =>
idRhs (relation.trans_gen (fun (a b : σ) => b ∈ f a) a c) (relation.trans_gen.head h ᾰ)
theorem reaches₀.head {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ} (h : b ∈ f a)
(h₂ : reaches₀ f b c) : reaches₀ f a c :=
reaches₀.trans (reaches₀.single h) h₂
theorem reaches₀.tail {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ}
(h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c :=
reaches₀.trans h₁ (reaches₀.single h)
theorem reaches₀_eq {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (e : f a = f b) :
reaches₀ f a b :=
fun (c : σ) (ᾰ : reaches₁ f b c) => idRhs (reaches₁ f a c) (iff.mpr (reaches₁_eq e) ᾰ)
theorem reaches₁.to₀ {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (h : reaches₁ f a b) :
reaches₀ f a b :=
fun (c : σ) (ᾰ : reaches₁ f b c) =>
idRhs (relation.trans_gen (fun (a b : σ) => b ∈ f a) a c) (relation.trans_gen.trans h ᾰ)
theorem reaches.to₀ {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (h : reaches f a b) :
reaches₀ f a b :=
fun (c : σ) (ᾰ : reaches₁ f b c) =>
idRhs (relation.trans_gen (fun (a b : σ) => b ∈ f a) a c) (relation.trans_gen.trans_right h ᾰ)
theorem reaches₀.tail' {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ}
(h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c :=
h c (relation.trans_gen.single h₂)
/-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b`
which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it
holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if
`eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/
def eval_induction {σ : Type u_1} {f : σ → Option σ} {b : σ} {C : σ → Sort u_2} {a : σ}
(h : b ∈ eval f a)
(H : (a : σ) → b ∈ eval f a → ((a' : σ) → b ∈ eval f a' → f a = some a' → C a') → C a) : C a :=
pfun.fix_induction h
fun (a' : σ)
(ha' : b ∈ pfun.fix (fun (s : σ) => roption.some (option.elim (f s) (sum.inl s) sum.inr)) a')
(h' :
(a'_1 : σ) →
b ∈ pfun.fix (fun (s : σ) => roption.some (option.elim (f s) (sum.inl s) sum.inr)) a'_1 →
sum.inr a'_1 ∈ roption.some (option.elim (f a') (sum.inl a') sum.inr) → C a'_1) =>
H a' ha' fun (b' : σ) (hb' : b ∈ eval f b') (e : f a' = some b') => h' b' hb' sorry
theorem mem_eval {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} :
b ∈ eval f a ↔ reaches f a b ∧ f b = none :=
sorry
theorem eval_maximal₁ {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (h : b ∈ eval f a) (c : σ) :
¬reaches₁ f b c :=
sorry
theorem eval_maximal {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (h : b ∈ eval f a) {c : σ} :
reaches f b c ↔ c = b :=
sorry
theorem reaches_eval {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (ab : reaches f a b) :
eval f a = eval f b :=
sorry
/-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions
`f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds
initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a
state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates.
Such a relation `tr` is also known as a refinement. -/
def respects {σ₁ : Type u_1} {σ₂ : Type u_2} (f₁ : σ₁ → Option σ₁) (f₂ : σ₂ → Option σ₂)
(tr : σ₁ → σ₂ → Prop) :=
{a₁ : σ₁} → {a₂ : σ₂} → tr a₁ a₂ → sorry
theorem tr_reaches₁ {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂}
{tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {a₂ : σ₂} (aa : tr a₁ a₂) {b₁ : σ₁}
(ab : reaches₁ f₁ a₁ b₁) : ∃ (b₂ : σ₂), tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ :=
sorry
theorem tr_reaches {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂}
{tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {a₂ : σ₂} (aa : tr a₁ a₂) {b₁ : σ₁}
(ab : reaches f₁ a₁ b₁) : ∃ (b₂ : σ₂), tr b₁ b₂ ∧ reaches f₂ a₂ b₂ :=
sorry
theorem tr_reaches_rev {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂}
{tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {a₂ : σ₂} (aa : tr a₁ a₂) {b₂ : σ₂}
(ab : reaches f₂ a₂ b₂) :
∃ (c₁ : σ₁), ∃ (c₂ : σ₂), reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ :=
sorry
theorem tr_eval {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂}
{tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {b₁ : σ₁} {a₂ : σ₂} (aa : tr a₁ a₂)
(ab : b₁ ∈ eval f₁ a₁) : ∃ (b₂ : σ₂), tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ :=
sorry
theorem tr_eval_rev {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂}
{tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {b₂ : σ₂} {a₂ : σ₂} (aa : tr a₁ a₂)
(ab : b₂ ∈ eval f₂ a₂) : ∃ (b₁ : σ₁), tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ :=
sorry
theorem tr_eval_dom {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂}
{tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {a₂ : σ₂} (aa : tr a₁ a₂) :
roption.dom (eval f₂ a₂) ↔ roption.dom (eval f₁ a₁) :=
sorry
/-- A simpler version of `respects` when the state transition relation `tr` is a function. -/
def frespects {σ₁ : Type u_1} {σ₂ : Type u_2} (f₂ : σ₂ → Option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) :
Option σ₁ → Prop :=
sorry
theorem frespects_eq {σ₁ : Type u_1} {σ₂ : Type u_2} {f₂ : σ₂ → Option σ₂} {tr : σ₁ → σ₂} {a₂ : σ₂}
{b₂ : σ₂} (h : f₂ a₂ = f₂ b₂) {b₁ : Option σ₁} :
frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁ :=
sorry
theorem fun_respects {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂}
{tr : σ₁ → σ₂} :
(respects f₁ f₂ fun (a : σ₁) (b : σ₂) => tr a = b) ↔
∀ {a₁ : σ₁}, frespects f₂ tr (tr a₁) (f₁ a₁) :=
sorry
theorem tr_eval' {σ₁ : Type u_1} {σ₂ : Type u_1} (f₁ : σ₁ → Option σ₁) (f₂ : σ₂ → Option σ₂)
(tr : σ₁ → σ₂) (H : respects f₁ f₂ fun (a : σ₁) (b : σ₂) => tr a = b) (a₁ : σ₁) :
eval f₂ (tr a₁) = tr <$> eval f₁ a₁ :=
sorry
/-!
## The TM0 model
A TM0 turing machine is essentially a Post-Turing machine, adapted for type theory.
A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function
`Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a`
for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and
an instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of
the machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the
`step` function:
* If `M q T.head = none`, then the machine halts.
* If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions
to state `q'`.
The initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head
of the tape and the rest of the list extends to the right, with the left side all blank. The final
state takes the entire right side of the tape right or equal to the current position of the
machine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level
of generality, where the output ends. If equality to `default Γ` is decidable we can trim the list
to remove the infinite tail of blanks.)
-/
namespace TM0
/-- A Turing machine "statement" is just a command to either move
left or right, or write a symbol on the tape. -/
inductive stmt (Γ : Type u_1) [Inhabited Γ] where
| move : dir → stmt Γ
| write : Γ → stmt Γ
protected instance stmt.inhabited (Γ : Type u_1) [Inhabited Γ] : Inhabited (stmt Γ) :=
{ default := stmt.write Inhabited.default }
/-- A Post-Turing machine with symbol type `Γ` and label type `Λ`
is a function which, given the current state `q : Λ` and
the tape head `a : Γ`, either halts (returns `none`) or returns
a new state `q' : Λ` and a `stmt` describing what to do,
either a move left or right, or a write command.
Both `Λ` and `Γ` are required to be inhabited; the default value
for `Γ` is the "blank" tape value, and the default value of `Λ` is
the initial state. -/
def machine (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) [Inhabited Λ] := Λ → Γ → Option (Λ × stmt Γ)
protected instance machine.inhabited (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) [Inhabited Λ] :
Inhabited (machine Γ Λ) :=
eq.mpr sorry (pi.inhabited Λ)
/-- The configuration state of a Turing machine during operation
consists of a label (machine state), and a tape, represented in
the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R`
with the machine currently reading the `a`. The lists are
automatically extended with blanks as the machine moves around. -/
structure cfg (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) [Inhabited Λ] where
q : Λ
tape : tape Γ
protected instance cfg.inhabited (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) [Inhabited Λ] :
Inhabited (cfg Γ Λ) :=
{ default := cfg.mk Inhabited.default Inhabited.default }
/-- Execution semantics of the Turing machine. -/
def step {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ) :
cfg Γ Λ → Option (cfg Γ Λ) :=
sorry
/-- The statement `reaches M s₁ s₂` means that `s₂` is obtained
starting from `s₁` after a finite number of steps from `s₂`. -/
def reaches {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ) :
cfg Γ Λ → cfg Γ Λ → Prop :=
relation.refl_trans_gen fun (a b : cfg Γ Λ) => b ∈ step M a
/-- The initial configuration. -/
def init {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (l : List Γ) : cfg Γ Λ :=
cfg.mk Inhabited.default (tape.mk₁ l)
/-- Evaluate a Turing machine on initial input to a final state,
if it terminates. -/
def eval {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ) (l : List Γ) :
roption (list_blank Γ) :=
roption.map (fun (c : cfg Γ Λ) => tape.right₀ (cfg.tape c)) (eval (step M) (init l))
/-- The raw definition of a Turing machine does not require that
`Γ` and `Λ` are finite, and in practice we will be interested
in the infinite `Λ` case. We recover instead a notion of
"effectively finite" Turing machines, which only make use of a
finite subset of their states. We say that a set `S ⊆ Λ`
supports a Turing machine `M` if `S` is closed under the
transition function and contains the initial state. -/
def supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ)
(S : set Λ) :=
Inhabited.default ∈ S ∧ ∀ {q : Λ} {a : Γ} {q' : Λ} {s : stmt Γ}, (q', s) ∈ M q a → q ∈ S → q' ∈ S
theorem step_supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ)
{S : set Λ} (ss : supports M S) {c : cfg Γ Λ} {c' : cfg Γ Λ} :
c' ∈ step M c → cfg.q c ∈ S → cfg.q c' ∈ S :=
sorry
theorem univ_supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ) :
supports M set.univ :=
{ left := trivial,
right :=
fun (q : Λ) (a : Γ) (q' : Λ) (s : stmt Γ) (h₁ : (q', s) ∈ M q a) (h₂ : q ∈ set.univ) =>
trivial }
/-- Map a TM statement across a function. This does nothing to move statements and maps the write
values. -/
def stmt.map {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ'] (f : pointed_map Γ Γ') :
stmt Γ → stmt Γ' :=
sorry
/-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and
`g : Λ → Λ'` a map of the machine states. -/
def cfg.map {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ'] {Λ : Type u_3} [Inhabited Λ]
{Λ' : Type u_4} [Inhabited Λ'] (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' :=
sorry
/-- Because the state transition function uses the alphabet and machine states in both the input
and output, to map a machine from one alphabet and machine state space to another we need functions
in both directions, essentially an `equiv` without the laws. -/
def machine.map {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ'] {Λ : Type u_3}
[Inhabited Λ] {Λ' : Type u_4} [Inhabited Λ'] (M : machine Γ Λ) (f₁ : pointed_map Γ Γ')
(f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) : machine Γ' Λ' :=
sorry
theorem machine.map_step {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ'] {Λ : Type u_3}
[Inhabited Λ] {Λ' : Type u_4} [Inhabited Λ'] (M : machine Γ Λ) (f₁ : pointed_map Γ Γ')
(f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) {S : set Λ}
(f₂₁ : function.right_inverse ⇑f₁ ⇑f₂) (g₂₁ : ∀ (q : Λ), q ∈ S → g₂ (g₁ q) = q) (c : cfg Γ Λ) :
cfg.q c ∈ S →
option.map (cfg.map f₁ g₁) (step M c) =
step (machine.map M f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c) :=
sorry
theorem map_init {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ'] {Λ : Type u_3}
[Inhabited Λ] {Λ' : Type u_4} [Inhabited Λ'] (f₁ : pointed_map Γ Γ') (g₁ : pointed_map Λ Λ')
(l : List Γ) : cfg.map f₁ (⇑g₁) (init l) = init (list.map (⇑f₁) l) :=
congr (congr_arg cfg.mk (pointed_map.map_pt g₁)) (tape.map_mk₁ f₁ l)
theorem machine.map_respects {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ']
{Λ : Type u_3} [Inhabited Λ] {Λ' : Type u_4} [Inhabited Λ'] (M : machine Γ Λ)
(f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ)
{S : set Λ} (ss : supports M S) (f₂₁ : function.right_inverse ⇑f₁ ⇑f₂)
(g₂₁ : ∀ (q : Λ), q ∈ S → g₂ (coe_fn g₁ q) = q) :
respects (step M) (step (machine.map M f₁ f₂ (⇑g₁) g₂))
fun (a : cfg Γ Λ) (b : cfg Γ' Λ') => cfg.q a ∈ S ∧ cfg.map f₁ (⇑g₁) a = b :=
sorry
end TM0
/-!
## The TM1 model
The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of
Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables
that may be accessed and updated at any time.
A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which
is a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local
variables and the value `T.head` on the tape to calculate what to write or how to change local
state, but the statements themselves have a fixed structure. The `stmt`s can be as follows:
* `move d q`: move left or right, and then do `q`
* `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q`
* `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head`
* `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse`
* `goto (f : Γ → σ → Λ)`: Go to label `f a T.head`
* `halt`: Transition to the halting state, which halts on the following step
Note that here most statements do not have labels; `goto` commands can only go to a new function.
Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on
statements and so take 0 steps. (There is a uniform bound on many statements can be executed before
the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.)
The `halt` command has a one step stutter before actually halting so that any changes made before
the halt have a chance to be "committed", since the `eval` relation uses the final configuration
before the halt as the output, and `move` and `write` etc. take 0 steps in this model.
-/
namespace TM1
/-- The TM1 model is a simplification and extension of TM0
(Post-Turing model) in the direction of Wang B-machines. The machine's
internal state is extended with a (finite) store `σ` of variables
that may be accessed and updated at any time.
A machine is given by a `Λ` indexed set of procedures or functions.
Each function has a body which is a `stmt`, which can either be a
`move` or `write` command, a `branch` (if statement based on the
current tape value), a `load` (set the variable value),
a `goto` (call another function), or `halt`. Note that here
most statements do not have labels; `goto` commands can only
go to a new function. All commands have access to the variable value
and current tape value. -/
inductive stmt (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) (σ : Type u_3) where
| move : dir → stmt Γ Λ σ → stmt Γ Λ σ
| write : (Γ → σ → Γ) → stmt Γ Λ σ → stmt Γ Λ σ
| load : (Γ → σ → σ) → stmt Γ Λ σ → stmt Γ Λ σ
| branch : (Γ → σ → Bool) → stmt Γ Λ σ → stmt Γ Λ σ → stmt Γ Λ σ
| goto : (Γ → σ → Λ) → stmt Γ Λ σ
| halt : stmt Γ Λ σ
protected instance stmt.inhabited (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) (σ : Type u_3) :
Inhabited (stmt Γ Λ σ) :=
{ default := stmt.halt }
/-- The configuration of a TM1 machine is given by the currently
evaluating statement, the variable store value, and the tape. -/
structure cfg (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) (σ : Type u_3) where
l : Option Λ
var : σ
tape : tape Γ
protected instance cfg.inhabited (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) (σ : Type u_3)
[Inhabited σ] : Inhabited (cfg Γ Λ σ) :=
{ default := cfg.mk Inhabited.default Inhabited.default Inhabited.default }
/-- The semantics of TM1 evaluation. -/
def step_aux {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} :
stmt Γ Λ σ → σ → tape Γ → cfg Γ Λ σ :=
sorry
/-- The state transition function. -/
def step {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} (M : Λ → stmt Γ Λ σ) :
cfg Γ Λ σ → Option (cfg Γ Λ σ) :=
sorry
/-- A set `S` of labels supports the statement `q` if all the `goto`
statements in `q` refer only to other functions in `S`. -/
def supports_stmt {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} (S : finset Λ) :
stmt Γ Λ σ → Prop :=
sorry
/-- The subterm closure of a statement. -/
def stmts₁ {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} :
stmt Γ Λ σ → finset (stmt Γ Λ σ) :=
sorry
theorem stmts₁_self {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} {q : stmt Γ Λ σ} :
q ∈ stmts₁ q :=
sorry
theorem stmts₁_trans {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} {q₁ : stmt Γ Λ σ}
{q₂ : stmt Γ Λ σ} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=
sorry
theorem stmts₁_supports_stmt_mono {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3}
{S : finset Λ} {q₁ : stmt Γ Λ σ} {q₂ : stmt Γ Λ σ} (h : q₁ ∈ stmts₁ q₂)
(hs : supports_stmt S q₂) : supports_stmt S q₁ :=
sorry
/-- The set of all statements in a turing machine, plus one extra value `none` representing the
halt state. This is used in the TM1 to TM0 reduction. -/
def stmts {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} (M : Λ → stmt Γ Λ σ)
(S : finset Λ) : finset (Option (stmt Γ Λ σ)) :=
finset.insert_none (finset.bUnion S fun (q : Λ) => stmts₁ (M q))
theorem stmts_trans {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} {M : Λ → stmt Γ Λ σ}
{S : finset Λ} {q₁ : stmt Γ Λ σ} {q₂ : stmt Γ Λ σ} (h₁ : q₁ ∈ stmts₁ q₂) :
some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=
sorry
/-- A set `S` of labels supports machine `M` if all the `goto`
statements in the functions in `S` refer only to other functions
in `S`. -/
def supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} [Inhabited Λ]
(M : Λ → stmt Γ Λ σ) (S : finset Λ) :=
Inhabited.default ∈ S ∧ ∀ (q : Λ), q ∈ S → supports_stmt S (M q)
theorem stmts_supports_stmt {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} [Inhabited Λ]
{M : Λ → stmt Γ Λ σ} {S : finset Λ} {q : stmt Γ Λ σ} (ss : supports M S) :
some q ∈ stmts M S → supports_stmt S q :=
sorry
theorem step_supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} [Inhabited Λ]
(M : Λ → stmt Γ Λ σ) {S : finset Λ} (ss : supports M S) {c : cfg Γ Λ σ} {c' : cfg Γ Λ σ} :
c' ∈ step M c → cfg.l c ∈ finset.insert_none S → cfg.l c' ∈ finset.insert_none S :=
sorry
/-- The initial state, given a finite input that is placed on the tape starting at the TM head and
going to the right. -/
def init {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} [Inhabited Λ] [Inhabited σ]
(l : List Γ) : cfg Γ Λ σ :=
cfg.mk (some Inhabited.default) Inhabited.default (tape.mk₁ l)
/-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate
number of blanks on the end). -/
def eval {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} [Inhabited Λ] [Inhabited σ]
(M : Λ → stmt Γ Λ σ) (l : List Γ) : roption (list_blank Γ) :=
roption.map (fun (c : cfg Γ Λ σ) => tape.right₀ (cfg.tape c)) (eval (step M) (init l))
end TM1
/-!
## TM1 emulator in TM0
To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a
TM0 program. So suppose a TM1 program is given. We take the following:
* The alphabet `Γ` is the same for both TM1 and TM0
* The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none`
representing halt, and the possible settings of the internal variables.
Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume
that from the initial TM1 state, only finitely many other labels are reachable, and there are
only finitely many statements that appear in all of these functions.
Even though `stmt₁` contains a statement called `halt`, we must separate it from `none`
(`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the
TM1 semantics.
-/
namespace TM1to0
/-- The base machine state space is a pair of an `option stmt₁` representing the current program
to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM,
not the tape). Because there are an infinite number of programs, this state space is infinite, but
for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are
reachable. -/
-- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here.
-- But they are parameters so we cannot easily skip them for just this definition.
def Λ' {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
(M : Λ → TM1.stmt Γ Λ σ) :=
Option (TM1.stmt Γ Λ σ) × σ
protected instance Λ'.inhabited {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ]
{σ : Type u_3} [Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) : Inhabited (Λ' M) :=
{ default := (some (M Inhabited.default), Inhabited.default) }
/-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the
`stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular
instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the
latter case we emit a dummy `write s` step and transition to the new target location. -/
def tr_aux {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
(M : Λ → TM1.stmt Γ Λ σ) (s : Γ) : TM1.stmt Γ Λ σ → σ → Λ' M × TM0.stmt Γ :=
sorry
/-- The translated TM0 machine (given the TM1 machine input). -/
def tr {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
(M : Λ → TM1.stmt Γ Λ σ) : TM0.machine Γ (Λ' M) :=
sorry
/-- Translate configurations from TM1 to TM0. -/
def tr_cfg {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
(M : Λ → TM1.stmt Γ Λ σ) : TM1.cfg Γ Λ σ → TM0.cfg Γ (Λ' M) :=
sorry
theorem tr_respects {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3}
[Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) :
respects (TM1.step M) (TM0.step (tr M))
fun (c₁ : TM1.cfg Γ Λ σ) (c₂ : TM0.cfg Γ (Λ' M)) => tr_cfg M c₁ = c₂ :=
sorry
theorem tr_eval {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3}
[Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) (l : List Γ) : TM0.eval (tr M) l = TM1.eval M l :=
sorry
/-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible
machine states in the target (even though the type `Λ'` is infinite). -/
def tr_stmts {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
(M : Λ → TM1.stmt Γ Λ σ) [fintype σ] (S : finset Λ) : finset (Λ' M) :=
finset.product (TM1.stmts M S) finset.univ
theorem tr_supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3}
[Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) [fintype σ] {S : finset Λ} (ss : TM1.supports M S) :
TM0.supports (tr M) ↑(tr_stmts M S) :=
sorry
end TM1to0
/-!
## TM1(Γ) emulator in TM1(bool)
The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`.
Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the
alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly.
The basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a
fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine
wants to read a symbol from the tape, it traverses over the block, performing `n` `branch`
instructions to each any of the `2^n` results.
For the `write` instruction, we have to use a `goto` because we need to follow a different code
path depending on the local state, which is not available in the TM1 model, so instead we jump to
a label computed using the read value and the local state, which performs the writing and returns
to normal execution.
Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are
exploiting the 0-step behavior of regular commands to avoid taking steps, but there are
nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are
finitely long.
-/
namespace TM1to1
theorem exists_enc_dec {Γ : Type u_1} [Inhabited Γ] [fintype Γ] :
∃ (n : ℕ),
∃ (enc : Γ → vector Bool n),
∃ (dec : vector Bool n → Γ),
enc Inhabited.default = vector.repeat false n ∧ ∀ (a : Γ), dec (enc a) = a :=
sorry
/-- The configuration state of the TM. -/
inductive Λ' {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
where
| normal : Λ → Λ'
| write : Γ → TM1.stmt Γ Λ σ → Λ'
protected instance Λ'.inhabited {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ]
{σ : Type u_3} [Inhabited σ] : Inhabited Λ' :=
{ default := Λ'.normal Inhabited.default }
/-- Read a vector of length `n` from the tape. -/
def read_aux {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
(n : ℕ) : (vector Bool n → TM1.stmt Bool Λ' σ) → TM1.stmt Bool Λ' σ :=
sorry
/-- A move left or right corresponds to `n` moves across the super-cell. -/
def move {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
{n : ℕ} (d : dir) (q : TM1.stmt Bool Λ' σ) : TM1.stmt Bool Λ' σ :=
nat.iterate (TM1.stmt.move d) n q
/-- To read a symbol from the tape, we use `read_aux` to traverse the symbol,
then return to the original position with `n` moves to the left. -/
def read {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
{n : ℕ} (dec : vector Bool n → Γ) (f : Γ → TM1.stmt Bool Λ' σ) : TM1.stmt Bool Λ' σ :=
read_aux n fun (v : vector Bool n) => move dir.left (f (dec v))
/-- Write a list of bools on the tape. -/
def write {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] :
List Bool → TM1.stmt Bool Λ' σ → TM1.stmt Bool Λ' σ :=
sorry
/-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that
we can access the current value of the tape. -/
def tr_normal {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
{n : ℕ} (dec : vector Bool n → Γ) : TM1.stmt Γ Λ σ → TM1.stmt Bool Λ' σ :=
sorry
theorem step_aux_move {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3}
[Inhabited σ] {n : ℕ} (d : dir) (q : TM1.stmt Bool Λ' σ) (v : σ) (T : tape Bool) :
TM1.step_aux (move d q) v T = TM1.step_aux q v (nat.iterate (tape.move d) n T) :=
sorry
theorem supports_stmt_move {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3}
[Inhabited σ] {n : ℕ} {S : finset Λ'} {d : dir} {q : TM1.stmt Bool Λ' σ} :
TM1.supports_stmt S (move d q) = TM1.supports_stmt S q :=
sorry
theorem supports_stmt_write {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3}
[Inhabited σ] {S : finset Λ'} {l : List Bool} {q : TM1.stmt Bool Λ' σ} :
TM1.supports_stmt S (write l q) = TM1.supports_stmt S q :=
sorry
theorem supports_stmt_read {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3}
[Inhabited σ] {n : ℕ} (dec : vector Bool n → Γ) {S : finset Λ'} {f : Γ → TM1.stmt Bool Λ' σ} :
(∀ (a : Γ), TM1.supports_stmt S (f a)) → TM1.supports_stmt S (read dec f) :=
sorry
/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/
def tr_tape' {Γ : Type u_1} [Inhabited Γ] {n : ℕ} {enc : Γ → vector Bool n}
(enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank Γ) (R : list_blank Γ) :
tape Bool :=
tape.mk' (list_blank.bind L (fun (x : Γ) => list.reverse (vector.to_list (enc x))) sorry)
(list_blank.bind R (fun (x : Γ) => vector.to_list (enc x)) sorry)
/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/
def tr_tape {Γ : Type u_1} [Inhabited Γ] {n : ℕ} {enc : Γ → vector Bool n}
(enc0 : enc Inhabited.default = vector.repeat false n) (T : tape Γ) : tape Bool :=
tr_tape' enc0 (tape.left T) (tape.right₀ T)
theorem tr_tape_mk' {Γ : Type u_1} [Inhabited Γ] {n : ℕ} {enc : Γ → vector Bool n}
(enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank Γ) (R : list_blank Γ) :
tr_tape enc0 (tape.mk' L R) = tr_tape' enc0 L R :=
sorry
/-- The top level program. -/
def tr {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
{n : ℕ} (enc : Γ → vector Bool n) (dec : vector Bool n → Γ) (M : Λ → TM1.stmt Γ Λ σ) :
Λ' → TM1.stmt Bool Λ' σ :=
sorry
/-- The machine configuration translation. -/
def tr_cfg {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
{n : ℕ} {enc : Γ → vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) :
TM1.cfg Γ Λ σ → TM1.cfg Bool Λ' σ :=
sorry
theorem tr_tape'_move_left {Γ : Type u_1} [Inhabited Γ] {n : ℕ} {enc : Γ → vector Bool n}
(enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank Γ) (R : list_blank Γ) :
nat.iterate (tape.move dir.left) n (tr_tape' enc0 L R) =
tr_tape' enc0 (list_blank.tail L) (list_blank.cons (list_blank.head L) R) :=
sorry
theorem tr_tape'_move_right {Γ : Type u_1} [Inhabited Γ] {n : ℕ} {enc : Γ → vector Bool n}
(enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank Γ) (R : list_blank Γ) :
nat.iterate (tape.move dir.right) n (tr_tape' enc0 L R) =
tr_tape' enc0 (list_blank.cons (list_blank.head R) L) (list_blank.tail R) :=
sorry
theorem step_aux_write {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3}
[Inhabited σ] {n : ℕ} {enc : Γ → vector Bool n}
(enc0 : enc Inhabited.default = vector.repeat false n) (q : TM1.stmt Bool Λ' σ) (v : σ) (a : Γ)
(b : Γ) (L : list_blank Γ) (R : list_blank Γ) :
TM1.step_aux (write (vector.to_list (enc a)) q) v (tr_tape' enc0 L (list_blank.cons b R)) =
TM1.step_aux q v (tr_tape' enc0 (list_blank.cons a L) R) :=
sorry
theorem step_aux_read {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3}
[Inhabited σ] {n : ℕ} {enc : Γ → vector Bool n} (dec : vector Bool n → Γ)
(enc0 : enc Inhabited.default = vector.repeat false n) (encdec : ∀ (a : Γ), dec (enc a) = a)
(f : Γ → TM1.stmt Bool Λ' σ) (v : σ) (L : list_blank Γ) (R : list_blank Γ) :
TM1.step_aux (read dec f) v (tr_tape' enc0 L R) =
TM1.step_aux (f (list_blank.head R)) v (tr_tape' enc0 L R) :=
sorry
theorem tr_respects {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3}
[Inhabited σ] {n : ℕ} {enc : Γ → vector Bool n} (dec : vector Bool n → Γ)
(enc0 : enc Inhabited.default = vector.repeat false n) (M : Λ → TM1.stmt Γ Λ σ)
(encdec : ∀ (a : Γ), dec (enc a) = a) :
respects (TM1.step M) (TM1.step (tr enc dec M))
fun (c₁ : TM1.cfg Γ Λ σ) (c₂ : TM1.cfg Bool Λ' σ) => tr_cfg enc0 c₁ = c₂ :=
sorry
/-- The set of accessible `Λ'.write` machine states. -/
def writes {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
[fintype Γ] : TM1.stmt Γ Λ σ → finset Λ' :=
sorry
/-- The set of accessible machine states, assuming that the input machine is supported on `S`,
are the normal states embedded from `S`, plus all write states accessible from these states. -/
def tr_supp {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ]
(M : Λ → TM1.stmt Γ Λ σ) [fintype Γ] (S : finset Λ) : finset Λ' :=
finset.bUnion S fun (l : Λ) => insert (Λ'.normal l) (writes (M l))
theorem tr_supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3}
[Inhabited σ] {n : ℕ} {enc : Γ → vector Bool n} (dec : vector Bool n → Γ)
(M : Λ → TM1.stmt Γ Λ σ) [fintype Γ] {S : finset Λ} (ss : TM1.supports M S) :
TM1.supports (tr enc dec M) (tr_supp M S) :=
sorry
end TM1to1
/-!
## TM0 emulator in TM1
To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator
in TM1. The main complication here is that TM0 allows an action to depend on the value at the head
and local state, while TM1 doesn't (in order to have more programming language-like semantics).
So we use a computed `goto` to go to a state that performes the desired action and then returns to
normal execution.
One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step
to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an
unreachable branch).
-/
namespace TM0to1
/-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded
as `normal q` states, but the actual operation is split into two parts, a jump to `act s q`
followed by the action and a jump to the next `normal` state. -/
inductive Λ' {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] where
| normal : Λ → Λ'
| act : TM0.stmt Γ → Λ → Λ'
protected instance Λ'.inhabited {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] :
Inhabited Λ' :=
{ default := Λ'.normal Inhabited.default }
/-- The program. -/
def tr {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : TM0.machine Γ Λ) :
Λ' → TM1.stmt Γ Λ' Unit :=
sorry
/-- The configuration translation. -/
def tr_cfg {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : TM0.machine Γ Λ) :
TM0.cfg Γ Λ → TM1.cfg Γ Λ' Unit :=
sorry
theorem tr_respects {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ]
(M : TM0.machine Γ Λ) :
respects (TM0.step M) (TM1.step (tr M))
fun (a : TM0.cfg Γ Λ) (b : TM1.cfg Γ Λ' Unit) => tr_cfg M a = b :=
sorry
end TM0to1
/-!
## The TM2 model
The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite)
collection of stacks, each with elements of different types (the alphabet of stack `k : K` is
`Γ k`). The statements are:
* `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`.
* `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, and removes this element from the stack, then does `q`.
* `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, then does `q`.
* `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`.
* `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`.
* `goto (f : σ → Λ)` jumps to label `f a`.
* `halt` halts on the next step.
The configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or
`none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)`
is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not
`list_blank`s, they have definite ends that can be detected by the `pop` command.)
Given a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the
stacks empty except the designated "input" stack; in `eval` this designated stack also functions
as the output stack.
-/
namespace TM2
/-- The TM2 model removes the tape entirely from the TM1 model,
replacing it with an arbitrary (finite) collection of stacks.
The operation `push` puts an element on one of the stacks,
and `pop` removes an element from a stack (and modifying the
internal state based on the result). `peek` modifies the
internal state but does not remove an element. -/
inductive stmt {K : Type u_1} [DecidableEq K] (Γ : K → Type u_2) (Λ : Type u_3) (σ : Type u_4) where
| push : (k : K) → (σ → Γ k) → stmt Γ Λ σ → stmt Γ Λ σ
| peek : (k : K) → (σ → Option (Γ k) → σ) → stmt Γ Λ σ → stmt Γ Λ σ
| pop : (k : K) → (σ → Option (Γ k) → σ) → stmt Γ Λ σ → stmt Γ Λ σ
| load : (σ → σ) → stmt Γ Λ σ → stmt Γ Λ σ
| branch : (σ → Bool) → stmt Γ Λ σ → stmt Γ Λ σ → stmt Γ Λ σ
| goto : (σ → Λ) → stmt Γ Λ σ
| halt : stmt Γ Λ σ
protected instance stmt.inhabited {K : Type u_1} [DecidableEq K] (Γ : K → Type u_2) (Λ : Type u_3)
(σ : Type u_4) : Inhabited (stmt Γ Λ σ) :=
{ default := stmt.halt }
/-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of
local variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite
size.) -/
structure cfg {K : Type u_1} [DecidableEq K] (Γ : K → Type u_2) (Λ : Type u_3) (σ : Type u_4) where
l : Option Λ
var : σ
stk : (k : K) → List (Γ k)
protected instance cfg.inhabited {K : Type u_1} [DecidableEq K] (Γ : K → Type u_2) (Λ : Type u_3)
(σ : Type u_4) [Inhabited σ] : Inhabited (cfg Γ Λ σ) :=
{ default := cfg.mk Inhabited.default Inhabited.default Inhabited.default }
/-- The step function for the TM2 model. -/
@[simp] def step_aux {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3}
{σ : Type u_4} : stmt Γ Λ σ → σ → ((k : K) → List (Γ k)) → cfg Γ Λ σ :=
sorry
/-- The step function for the TM2 model. -/
@[simp] def step {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4}
(M : Λ → stmt Γ Λ σ) : cfg Γ Λ σ → Option (cfg Γ Λ σ) :=
sorry
/-- The (reflexive) reachability relation for the TM2 model. -/
def reaches {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4}
(M : Λ → stmt Γ Λ σ) : cfg Γ Λ σ → cfg Γ Λ σ → Prop :=
relation.refl_trans_gen fun (a b : cfg Γ Λ σ) => b ∈ step M a
/-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/
def supports_stmt {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4}
(S : finset Λ) : stmt Γ Λ σ → Prop :=
sorry
/-- The set of subtree statements in a statement. -/
def stmts₁ {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} :
stmt Γ Λ σ → finset (stmt Γ Λ σ) :=
sorry
theorem stmts₁_self {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4}
{q : stmt Γ Λ σ} : q ∈ stmts₁ q :=
sorry
theorem stmts₁_trans {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4}
{q₁ : stmt Γ Λ σ} {q₂ : stmt Γ Λ σ} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=
sorry
theorem stmts₁_supports_stmt_mono {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3}
{σ : Type u_4} {S : finset Λ} {q₁ : stmt Γ Λ σ} {q₂ : stmt Γ Λ σ} (h : q₁ ∈ stmts₁ q₂)
(hs : supports_stmt S q₂) : supports_stmt S q₁ :=
sorry
/-- The set of statements accessible from initial set `S` of labels. -/
def stmts {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4}
(M : Λ → stmt Γ Λ σ) (S : finset Λ) : finset (Option (stmt Γ Λ σ)) :=
finset.insert_none (finset.bUnion S fun (q : Λ) => stmts₁ (M q))
theorem stmts_trans {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4}
{M : Λ → stmt Γ Λ σ} {S : finset Λ} {q₁ : stmt Γ Λ σ} {q₂ : stmt Γ Λ σ} (h₁ : q₁ ∈ stmts₁ q₂) :
some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=
sorry
/-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in
`S` jump only to other states in `S`. -/
def supports {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4}
[Inhabited Λ] (M : Λ → stmt Γ Λ σ) (S : finset Λ) :=
Inhabited.default ∈ S ∧ ∀ (q : Λ), q ∈ S → supports_stmt S (M q)
theorem stmts_supports_stmt {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3}
{σ : Type u_4} [Inhabited Λ] {M : Λ → stmt Γ Λ σ} {S : finset Λ} {q : stmt Γ Λ σ}
(ss : supports M S) : some q ∈ stmts M S → supports_stmt S q :=
sorry
theorem step_supports {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3}
{σ : Type u_4} [Inhabited Λ] (M : Λ → stmt Γ Λ σ) {S : finset Λ} (ss : supports M S)
{c : cfg Γ Λ σ} {c' : cfg Γ Λ σ} :
c' ∈ step M c → cfg.l c ∈ finset.insert_none S → cfg.l c' ∈ finset.insert_none S :=
sorry
/-- The initial state of the TM2 model. The input is provided on a designated stack. -/
def init {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4}
[Inhabited Λ] [Inhabited σ] (k : K) (L : List (Γ k)) : cfg Γ Λ σ :=
cfg.mk (some Inhabited.default) Inhabited.default (function.update (fun (_x : K) => []) k L)
/-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/
def eval {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4}
[Inhabited Λ] [Inhabited σ] (M : Λ → stmt Γ Λ σ) (k : K) (L : List (Γ k)) :
roption (List (Γ k)) :=
roption.map (fun (c : cfg Γ Λ σ) => cfg.stk c k) (eval (step M) (init k L))
end TM2
/-!
## TM2 emulator in TM1
To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a
TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of
stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack
1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this:
```
bottom: ... | _ | T | _ | _ | _ | _ | ...
stack 1: ... | _ | b | a | _ | _ | _ | ...
stack 2: ... | _ | f | e | d | c | _ | ...
```
where a tape element is a vertical slice through the diagram. Here the alphabet is
`Γ' := bool × ∀ k, option (Γ k)`, where:
* `bottom : bool` is marked only in one place, the initial position of the TM, and represents the
tail of all stacks. It is never modified.
* `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is
the blank value). Note that the head of the stack is at the far end; this is so that push and pop
don't have to do any shifting.
In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions,
it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the
end of the appropriate stack, make its changes, and then return to the bottom. So the states are:
* `normal (l : Λ)`: waiting at `bottom` to execute function `l`
* `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in
order to perform stack action `s`, and later continue with executing `q`
* `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing
`q` once we arrive
Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the
length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)`
steps to run when emulated in TM1, where `m` is the length of the input.
-/
namespace TM2to1
-- A displaced lemma proved in unnecessary generality
theorem stk_nth_val {K : Type u_1} {Γ : K → Type u_2} {L : list_blank ((k : K) → Option (Γ k))}
{k : K} {S : List (Γ k)} (n : ℕ)
(hL : list_blank.map (proj k) L = list_blank.mk (list.reverse (list.map some S))) :
list_blank.nth L n k = list.nth (list.reverse S) n :=
sorry
/-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom,
plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/
-- the decidable_eq assumption, and this is a local definition anyway so it's not important.
def Γ' {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} := Bool × ((k : K) → Option (Γ k))
protected instance Γ'.inhabited {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} : Inhabited Γ' :=
{ default := (false, fun (_x : K) => none) }
protected instance Γ'.fintype {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} [fintype K]
[(k : K) → fintype (Γ k)] : fintype Γ' :=
prod.fintype Bool ((k : K) → Option (Γ k))
/-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function
to express the program state in terms of a tape with only the stacks themselves. -/
def add_bottom {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2}
(L : list_blank ((k : K) → Option (Γ k))) : list_blank Γ' :=
list_blank.cons (tt, list_blank.head L)
(list_blank.map (pointed_map.mk (Prod.mk false) sorry) (list_blank.tail L))
theorem add_bottom_map {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2}
(L : list_blank ((k : K) → Option (Γ k))) :
list_blank.map (pointed_map.mk prod.snd rfl) (add_bottom L) = L :=
sorry
theorem add_bottom_modify_nth {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2}
(f : ((k : K) → Option (Γ k)) → (k : K) → Option (Γ k))
(L : list_blank ((k : K) → Option (Γ k))) (n : ℕ) :
list_blank.modify_nth (fun (a : Γ') => (prod.fst a, f (prod.snd a))) n (add_bottom L) =
add_bottom (list_blank.modify_nth f n L) :=
sorry
theorem add_bottom_nth_snd {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2}
(L : list_blank ((k : K) → Option (Γ k))) (n : ℕ) :
prod.snd (list_blank.nth (add_bottom L) n) = list_blank.nth L n :=
sorry
theorem add_bottom_nth_succ_fst {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2}
(L : list_blank ((k : K) → Option (Γ k))) (n : ℕ) :
prod.fst (list_blank.nth (add_bottom L) (n + 1)) = false :=
sorry
theorem add_bottom_head_fst {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2}
(L : list_blank ((k : K) → Option (Γ k))) : prod.fst (list_blank.head (add_bottom L)) = tt :=
sorry
/-- A stack action is a command that interacts with the top of a stack. Our default position
is at the bottom of all the stacks, so we have to hold on to this action while going to the end
to modify the stack. -/
inductive st_act {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {σ : Type u_4} [Inhabited σ]
(k : K)
where
| push : (σ → Γ k) → st_act k
| peek : (σ → Option (Γ k) → σ) → st_act k
| pop : (σ → Option (Γ k) → σ) → st_act k
protected instance st_act.inhabited {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {σ : Type u_4}
[Inhabited σ] {k : K} : Inhabited (st_act k) :=
{ default := st_act.peek fun (s : σ) (_x : Option (Γ k)) => s }
/-- The TM2 statement corresponding to a stack action. -/
-- it is worth to omit the typeclass assumption without breaking the parameters
def st_run {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] {k : K} : st_act k → TM2.stmt Γ Λ σ → TM2.stmt Γ Λ σ :=
sorry
/-- The effect of a stack action on the local variables, given the value of the stack. -/
def st_var {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {σ : Type u_4} [Inhabited σ] {k : K}
(v : σ) (l : List (Γ k)) : st_act k → σ :=
sorry
/-- The effect of a stack action on the stack. -/
def st_write {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {σ : Type u_4} [Inhabited σ] {k : K}
(v : σ) (l : List (Γ k)) : st_act k → List (Γ k) :=
sorry
/-- We have partitioned the TM2 statements into "stack actions", which require going to the end
of the stack, and all other actions, which do not. This is a modified recursor which lumps the
stack actions into one. -/
def stmt_st_rec {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] {C : TM2.stmt Γ Λ σ → Sort l}
(H₁ : (k : K) → (s : st_act k) → (q : TM2.stmt Γ Λ σ) → C q → C (st_run s q))
(H₂ : (a : σ → σ) → (q : TM2.stmt Γ Λ σ) → C q → C (TM2.stmt.load a q))
(H₃ : (p : σ → Bool) → (q₁ q₂ : TM2.stmt Γ Λ σ) → C q₁ → C q₂ → C (TM2.stmt.branch p q₁ q₂))
(H₄ : (l : σ → Λ) → C (TM2.stmt.goto l)) (H₅ : C TM2.stmt.halt) (n : TM2.stmt Γ Λ σ) : C n :=
sorry
theorem supports_run {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] (S : finset Λ) {k : K} (s : st_act k) (q : TM2.stmt Γ Λ σ) :
TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q :=
st_act.cases_on s (fun (s : σ → Γ k) => iff.refl (TM2.supports_stmt S (st_run (st_act.push s) q)))
(fun (s : σ → Option (Γ k) → σ) => iff.refl (TM2.supports_stmt S (st_run (st_act.peek s) q)))
fun (s : σ → Option (Γ k) → σ) => iff.refl (TM2.supports_stmt S (st_run (st_act.pop s) q))
/-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the
next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and
return to the bottom, respectively. -/
inductive Λ' {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ]
where
| normal : Λ → Λ'
| go : (k : K) → st_act k → TM2.stmt Γ Λ σ → Λ'
| ret : TM2.stmt Γ Λ σ → Λ'
protected instance Λ'.inhabited {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3}
[Inhabited Λ] {σ : Type u_4} [Inhabited σ] : Inhabited Λ' :=
{ default := Λ'.normal Inhabited.default }
/-- The program corresponding to state transitions at the end of a stack. Here we start out just
after the top of the stack, and should end just after the new top of the stack. -/
def tr_st_act {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] {k : K} (q : TM1.stmt Γ' Λ' σ) : st_act k → TM1.stmt Γ' Λ' σ :=
sorry
/-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty
except for the input stack, and the stack bottom mark is set at the head. -/
def tr_init {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} (k : K) (L : List (Γ k)) : List Γ' :=
let L' : List Γ' :=
list.map (fun (a : Γ k) => (false, function.update (fun (_x : K) => none) k ↑a))
(list.reverse L);
(tt, prod.snd (list.head L')) :: list.tail L'
theorem step_run {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] {k : K} (q : TM2.stmt Γ Λ σ) (v : σ) (S : (k : K) → List (Γ k))
(s : st_act k) :
TM2.step_aux (st_run s q) v S =
TM2.step_aux q (st_var v (S k) s) (function.update S k (st_write v (S k) s)) :=
sorry
/-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents,
but stack actions are deferred by going to the corresponding `go` state, so that we can find the
appropriate stack top. -/
def tr_normal {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] : TM2.stmt Γ Λ σ → TM1.stmt Γ' Λ' σ :=
sorry
theorem tr_normal_run {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] {k : K} (s : st_act k) (q : TM2.stmt Γ Λ σ) :
tr_normal (st_run s q) = TM1.stmt.goto fun (_x : Γ') (_x : σ) => Λ'.go k s q :=
st_act.cases_on s (fun (s : σ → Γ k) => Eq.refl (tr_normal (st_run (st_act.push s) q)))
(fun (s : σ → Option (Γ k) → σ) => Eq.refl (tr_normal (st_run (st_act.peek s) q)))
fun (s : σ → Option (Γ k) → σ) => Eq.refl (tr_normal (st_run (st_act.pop s) q))
/-- The set of machine states accessible from an initial TM2 statement. -/
def tr_stmts₁ {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] : TM2.stmt Γ Λ σ → finset Λ' :=
sorry
theorem tr_stmts₁_run {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] {k : K} {s : st_act k} {q : TM2.stmt Γ Λ σ} :
tr_stmts₁ (st_run s q) = insert (Λ'.go k s q) (singleton (Λ'.ret q)) ∪ tr_stmts₁ q :=
sorry
theorem tr_respects_aux₂ {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3}
[Inhabited Λ] {σ : Type u_4} [Inhabited σ] {k : K} {q : TM1.stmt Γ' Λ' σ} {v : σ}
{S : (k : K) → List (Γ k)} {L : list_blank ((k : K) → Option (Γ k))}
(hL : ∀ (k : K), list_blank.map (proj k) L = list_blank.mk (list.reverse (list.map some (S k))))
(o : st_act k) :
let v' : σ := st_var v (S k) o;
let Sk' : List (Γ k) := st_write v (S k) o;
let S' : (k : K) → List (Γ k) := function.update S k Sk';
∃ (L' : list_blank ((k : K) → Option (Γ k))),
(∀ (k : K),
list_blank.map (proj k) L' = list_blank.mk (list.reverse (list.map some (S' k)))) ∧
TM1.step_aux (tr_st_act q o) v
(nat.iterate (tape.move dir.right) (list.length (S k)) (tape.mk' ∅ (add_bottom L))) =
TM1.step_aux q v'
(nat.iterate (tape.move dir.right) (list.length (S' k))
(tape.mk' ∅ (add_bottom L'))) :=
sorry
/-- The TM2 emulator machine states written as a TM1 program.
This handles the `go` and `ret` states, which shuttle to and from a stack top. -/
def tr {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4}
[Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) : Λ' → TM1.stmt Γ' Λ' σ :=
sorry
/-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/
inductive tr_cfg {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) : TM2.cfg Γ Λ σ → TM1.cfg Γ' Λ' σ → Prop
where
| mk :
∀ {q : Option Λ} {v : σ} {S : (k : K) → List (Γ k)} (L : list_blank ((k : K) → Option (Γ k))),
(∀ (k : K), list_blank.map (proj k) L = list_blank.mk (list.reverse (list.map some (S k)))) →
tr_cfg M (TM2.cfg.mk q v S)
(TM1.cfg.mk (option.map Λ'.normal q) v (tape.mk' ∅ (add_bottom L)))
theorem tr_respects_aux₁ {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3}
[Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) {k : K} (o : st_act k)
(q : TM2.stmt Γ Λ σ) (v : σ) {S : List (Γ k)} {L : list_blank ((k : K) → Option (Γ k))}
(hL : list_blank.map (proj k) L = list_blank.mk (list.reverse (list.map some S))) (n : ℕ)
(H : n ≤ list.length S) :
reaches₀ (TM1.step (tr M)) (TM1.cfg.mk (some (Λ'.go k o q)) v (tape.mk' ∅ (add_bottom L)))
(TM1.cfg.mk (some (Λ'.go k o q)) v
(nat.iterate (tape.move dir.right) n (tape.mk' ∅ (add_bottom L)))) :=
sorry
theorem tr_respects_aux₃ {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3}
[Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) {q : TM2.stmt Γ Λ σ} {v : σ}
{L : list_blank ((k : K) → Option (Γ k))} (n : ℕ) :
reaches₀ (TM1.step (tr M))
(TM1.cfg.mk (some (Λ'.ret q)) v
(nat.iterate (tape.move dir.right) n (tape.mk' ∅ (add_bottom L))))
(TM1.cfg.mk (some (Λ'.ret q)) v (tape.mk' ∅ (add_bottom L))) :=
sorry
theorem tr_respects_aux {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3}
[Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) {q : TM2.stmt Γ Λ σ} {v : σ}
{T : list_blank ((i : K) → Option (Γ i))} {k : K} {S : (k : K) → List (Γ k)}
(hT : ∀ (k : K), list_blank.map (proj k) T = list_blank.mk (list.reverse (list.map some (S k))))
(o : st_act k)
(IH :
∀ {v : σ} {S : (k : K) → List (Γ k)} {T : list_blank ((i : K) → Option (Γ i))},
(∀ (k : K),
list_blank.map (proj k) T = list_blank.mk (list.reverse (list.map some (S k)))) →
∃ (b : TM1.cfg Γ' Λ' σ),
tr_cfg M (TM2.step_aux q v S) b ∧
reaches (TM1.step (tr M)) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T)))
b) :
∃ (b : TM1.cfg Γ' Λ' σ),
tr_cfg M (TM2.step_aux (st_run o q) v S) b ∧
reaches (TM1.step (tr M))
(TM1.step_aux (tr_normal (st_run o q)) v (tape.mk' ∅ (add_bottom T))) b :=
sorry
theorem tr_respects {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) :
respects (TM2.step M) (TM1.step (tr M)) (tr_cfg M) :=
sorry
theorem tr_cfg_init {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) (k : K) (L : List (Γ k)) :
tr_cfg M (TM2.init k L) (TM1.init (tr_init k L)) :=
sorry
theorem tr_eval_dom {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) (k : K) (L : List (Γ k)) :
roption.dom (TM1.eval (tr M) (tr_init k L)) ↔ roption.dom (TM2.eval M k L) :=
tr_eval_dom (tr_respects M) (tr_cfg_init M k L)
theorem tr_eval {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) (k : K) (L : List (Γ k))
{L₁ : list_blank Γ'} {L₂ : List (Γ k)} (H₁ : L₁ ∈ TM1.eval (tr M) (tr_init k L))
(H₂ : L₂ ∈ TM2.eval M k L) :
∃ (S : (k : K) → List (Γ k)),
∃ (L' : list_blank ((k : K) → Option (Γ k))),
add_bottom L' = L₁ ∧
(∀ (k : K),
list_blank.map (proj k) L' = list_blank.mk (list.reverse (list.map some (S k)))) ∧
S k = L₂ :=
sorry
/-- The support of a set of TM2 states in the TM2 emulator. -/
def tr_supp {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) (S : finset Λ) : finset Λ' :=
finset.bUnion S fun (l : Λ) => insert (Λ'.normal l) (tr_stmts₁ (M l))
theorem tr_supports {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ]
{σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) {S : finset Λ} (ss : TM2.supports M S) :
TM1.supports (tr M) (tr_supp M S) :=
sorry
end Mathlib |
e5b43917bb44ae4bdc7dde3d5c3e7490c103816a | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/decl_cmds.lean | 7678932e95bd64c196c2dc7b69eee3c2d0a7feb3 | [] | 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 | 291 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.meta.tactic
import Mathlib.Lean3Lib.init.meta.rb_map
namespace Mathlib
|
45ba887766b4b6110a1f9a074a09c5ecfd9090a6 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/data/sum.lean | 46a0f51f16d892df85ca2cf1372e61eb466d4921 | [
"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 | 4,090 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
More theorems about the sum type.
-/
import tactic.lint
universes u v
variables {α : Type u} {β : Type v}
open sum
attribute [derive decidable_eq] sum
@[simp] theorem sum.forall {p : α ⊕ β → Prop} : (∀ x, p x) ↔ (∀ a, p (inl a)) ∧ (∀ b, p (inr b)) :=
⟨λ h, ⟨λ a, h _, λ b, h _⟩, λ ⟨h₁, h₂⟩, sum.rec h₁ h₂⟩
@[simp] theorem sum.exists {p : α ⊕ β → Prop} : (∃ x, p x) ↔ (∃ a, p (inl a)) ∨ ∃ b, p (inr b) :=
⟨λ h, match h with
| ⟨inl a, h⟩ := or.inl ⟨a, h⟩
| ⟨inr b, h⟩ := or.inr ⟨b, h⟩
end, λ h, match h with
| or.inl ⟨a, h⟩ := ⟨inl a, h⟩
| or.inr ⟨b, h⟩ := ⟨inr b, h⟩
end⟩
namespace sum
protected def map {α α' β β'} (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β'
| (sum.inl x) := sum.inl (f x)
| (sum.inr x) := sum.inr (g x)
theorem inl.inj_iff {a b} : (inl a : α ⊕ β) = inl b ↔ a = b :=
⟨inl.inj, congr_arg _⟩
theorem inr.inj_iff {a b} : (inr a : α ⊕ β) = inr b ↔ a = b :=
⟨inr.inj, congr_arg _⟩
theorem inl_ne_inr {a : α} {b : β} : inl a ≠ inr b.
theorem inr_ne_inl {a : α} {b : β} : inr b ≠ inl a.
protected def elim {α β γ : Sort*} (f : α → γ) (g : β → γ) : α ⊕ β → γ := λ x, sum.rec_on x f g
@[simp] lemma elim_inl {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : α) :
sum.elim f g (inl x) = f x := rfl
@[simp] lemma elim_inr {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : β) :
sum.elim f g (inr x) = g x := rfl
lemma elim_injective {α β γ : Sort*} {f : α → γ} {g : β → γ}
(hf : function.injective f) (hg : function.injective g)
(hfg : ∀ a b, f a ≠ g b) : function.injective (sum.elim f g) :=
λ x y, sum.rec_on x
(sum.rec_on y (λ x y hxy, by rw hf hxy) (λ x y hxy, false.elim $ hfg _ _ hxy))
(sum.rec_on y (λ x y hxy, false.elim $ hfg x y hxy.symm) (λ x y hxy, by rw hg hxy))
section
variables (ra : α → α → Prop) (rb : β → β → Prop)
/-- Lexicographic order for sum. Sort all the `inl a` before the `inr b`,
otherwise use the respective order on `α` or `β`. -/
inductive lex : α ⊕ β → α ⊕ β → Prop
| inl {a₁ a₂} (h : ra a₁ a₂) : lex (inl a₁) (inl a₂)
| inr {b₁ b₂} (h : rb b₁ b₂) : lex (inr b₁) (inr b₂)
| sep (a b) : lex (inl a) (inr b)
variables {ra rb}
@[simp] theorem lex_inl_inl {a₁ a₂} : lex ra rb (inl a₁) (inl a₂) ↔ ra a₁ a₂ :=
⟨λ h, by cases h; assumption, lex.inl⟩
@[simp] theorem lex_inr_inr {b₁ b₂} : lex ra rb (inr b₁) (inr b₂) ↔ rb b₁ b₂ :=
⟨λ h, by cases h; assumption, lex.inr⟩
@[simp] theorem lex_inr_inl {b a} : ¬ lex ra rb (inr b) (inl a) :=
λ h, by cases h
attribute [simp] lex.sep
theorem lex_acc_inl {a} (aca : acc ra a) : acc (lex ra rb) (inl a) :=
begin
induction aca with a H IH,
constructor, intros y h,
cases h with a' _ h',
exact IH _ h'
end
theorem lex_acc_inr (aca : ∀ a, acc (lex ra rb) (inl a)) {b} (acb : acc rb b) : acc (lex ra rb) (inr b) :=
begin
induction acb with b H IH,
constructor, intros y h,
cases h with _ _ _ b' _ h' a,
{ exact IH _ h' },
{ exact aca _ }
end
theorem lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) :=
have aca : ∀ a, acc (lex ra rb) (inl a), from λ a, lex_acc_inl (ha.apply a),
⟨λ x, sum.rec_on x aca (λ b, lex_acc_inr aca (hb.apply b))⟩
end
/-- Swap the factors of a sum type -/
@[simp] def swap : α ⊕ β → β ⊕ α
| (inl a) := inr a
| (inr b) := inl b
@[simp] lemma swap_swap (x : α ⊕ β) : swap (swap x) = x :=
by cases x; refl
@[simp] lemma swap_swap_eq : swap ∘ swap = @id (α ⊕ β) :=
funext $ swap_swap
@[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap :=
swap_swap
@[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap :=
swap_swap
end sum
|
26c637fb611d0e6b864fc90f31783f89fe8eb5e5 | 7a468d7c7c0949ab8b191bb62ff6d4d2af9f3917 | /src/smt2/default.lean | c81b6acc7c3e699cc8254308b0671ad365240b62 | [
"Apache-2.0"
] | permissive | seanpm2001/LeanProver_SMT2_Interface | c15b2fba021c406d965655b182eef54a14121b82 | 7ff0ce248b68ea4db2a2d4966a97b5786da05ed7 | refs/heads/master | 1,688,599,220,366 | 1,547,825,187,000 | 1,547,825,187,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,830 | lean | import system.io
import .solvers.z3
import .syntax
import .builder
import .tactic
import .attributes
import .lol
import init.data.option.basic
declare_trace smt2
open tactic
open smt2.builder
open native
meta structure smt2_state : Type :=
(ctxt : lol.context)
(type_map : rb_map expr lol.type)
meta def smt2_state.initial : smt2_state :=
⟨ lol.context.empty, rb_map.mk _ _ ⟩
@[reducible] meta def smt2_m (α : Type) :=
state_t smt2_state tactic α
meta instance tactic_to_smt2_m (α : Type) : has_coe (tactic α) (smt2_m α) :=
⟨ fun tc, state_t.mk (fun s, do res ← tc, return (res, s)) ⟩
namespace smt2
meta def trace_smt2 (msg : string) : smt2_m unit :=
tactic.when_tracing `smt2 (tactic.trace msg)
meta def fail {α : Type} (msg : string) : smt2_m α :=
tactic.fail $ "smt2_tactic: " ++ msg
meta def mangle_name (n : name) : string :=
"lean_" ++ n^.to_string_with_sep "-"
meta def insert_type (n : string) (ty : expr) (lty : lol.type) : smt2_m unit :=
do st ← get,
put ⟨
st.ctxt.declare_type n lty,
st.type_map.insert ty lty
⟩
meta def fn_type : expr → (list expr × expr)
| (expr.pi _ _ ty rest) :=
let (args, rt) := fn_type rest
in (ty :: args, rt)
| rt := ([], rt)
-- Currently we only support first order fn types
meta def compile_arrow_type (ty : expr) (cb : expr → smt2_m lol.type) : smt2_m lol.type :=
let (args, rt) := fn_type ty
in lol.type.fn <$> monad.mapm cb args <*> cb rt
meta def compile_type : expr → smt2_m lol.type :=
fun ty,
do st ← get,
match st.type_map.find ty with
| some lty := return lty
| none := do
lty ← match ty with
| `(int) := pure $ lol.type.int
| `(nat) := pure $ lol.type.refinement lol.type.int (fun x, lol.term.lte (lol.term.int 0) (lol.term.var x))
| `(Prop) := pure $ lol.type.bool
| _ := if ty.is_arrow
then compile_arrow_type ty compile_type
else if ty.is_constant
then do insert_type (mangle_name ty.const_name) ty (lol.type.fn [] (lol.type.var $ mangle_name ty.const_name)),
return $ (lol.type.fn [] (lol.type.var $ mangle_name ty.const_name))
else fail $ "unsupported type: " ++ to_string ty
end,
-- insert_type ty lty,
return lty
end
meta def add_decl (n : name) (ty : expr) : smt2_m unit :=
do st ← get,
ct ← compile_type ty,
let d := lol.decl.fn (mangle_name n) ct none,
put { st with ctxt := st.ctxt.declare d }
-- meta def ensure_constant (e : expr) (n : name) : smt2_m lol.decl :=
-- do ty ← infer_type e,
-- let (arg_tys, ret_ty) := fn_type ty,
-- let mangled_name := mangle_name n,
-- arg_sorts ← monad.mapm compile_type arg_tys,
-- ret_sort ← compile_type ret_ty,
-- -- ensure_constant_core e (return $ (mangled_name, arg_sorts, ret_sort)),
-- return $ lol.decl.fn mangled_name arg_sorts ret_sort
-- meta def formula_type_from_arrow (n : name) (e : expr) : smt2_m formula_type :=
-- do (lol.decl.fn _ arg_sorts ret_sort) ← ensure_constant e n,
-- return $ formula_type.fn n arg_sorts ret_sort
-- /-- The goal of this function is to categorize the set of formulas in the hypotheses,
-- and goal. We want to narrow down from the full term language of Lean to a fragment
-- of formula's we suppose. The below code makes some assumptions:
-- A local constant of the form `(P : Prop)`, must be reflected as declaration
-- in SMT2 that is `(declare-const P Bool)`.
-- An occurence of a proof of `P`, `(p : P)`, must be transformed into
-- `(assert P)`. If P is a formula, not an atom, we must transform P into a corresponding
-- SMT2 formula and `(assert P)`.
-- -/
meta def extract_coe_args (args : list expr) : smt2_m (expr × expr × expr) :=
match args with
| (source :: target :: inst :: e :: []) := return (source, target, e)
| _ := fail "internal tactic error expected `coe` to have exactly 4 arguments"
end
meta def reflect_coercion (source target e : expr) (callback : expr → smt2_m lol.term) : smt2_m lol.term :=
if source = `(nat) ∧ target = `(int)
then callback e
else fail $ "unsupported coercion between " ++ "`" ++ to_string source ++ "` and `" ++ to_string target ++ "`"
meta def reflect_application (fn : expr) (args : list expr) (callback : expr → smt2_m lol.term) : smt2_m lol.term :=
if fn.is_constant
then if fn.const_name = `coe
then do (source, target, e) ← extract_coe_args args,
reflect_coercion source target e callback
else do ty ← infer_type fn,
let mangled := (mangle_name fn.const_name),
add_decl fn.const_name ty,
lol.term.apply mangled <$> monad.mapm callback args
else if fn.is_local_constant
then lol.term.apply (mangle_name fn.local_uniq_name) <$> monad.mapm callback args
else fail $ "unsupported head symbol `" ++ to_string fn ++ "`"
-- meta def is_supported_head_symbol (e : expr) : bool := true
meta def is_supported_numeric_ty (ty : expr) : bool :=
(ty = `(int) ∨ ty = `(nat))
-- /-- This function is the meat of the tactic, it takes a propositional formula in Lean, and transforms
-- it into a corresponding term in SMT2. -/
meta def reflect_arith_formula (reflect_base : expr → smt2_m lol.term) : expr → smt2_m lol.term
| `(%%a + %%b) := lol.term.add <$> reflect_arith_formula a <*> reflect_arith_formula b
| `(%%a - %%b) := lol.term.sub <$> reflect_arith_formula a <*> reflect_arith_formula b
| `(%%a * %%b) := lol.term.mul <$> reflect_arith_formula a <*> reflect_arith_formula b
| `(%%a / %%b) := lol.term.div <$> reflect_arith_formula a <*> reflect_arith_formula b
| `(%%a % %%b) := lol.term.mod <$> reflect_arith_formula a <*> reflect_arith_formula b
| `(- %%a) := lol.term.neg <$> reflect_arith_formula a
-- /- Constants -/
| `(has_zero.zero _) := lol.term.int <$> eval_expr int `(has_zero.zero int)
| `(has_one.one _) := lol.term.int <$> eval_expr int `(has_one.one int)
| `(bit0 %%Bits) :=
do ty ← infer_type Bits,
if is_supported_numeric_ty ty
then lol.term.int <$> eval_expr int `(bit0 %%Bits : int)
else if (ty = `(nat))
then lol.term.int <$> int.of_nat <$> eval_expr nat `(bit0 %%Bits : nat)
else fail $ "unknown numeric literal: " ++ (to_string ```(bit0 %%Bits : int))
| `(bit1 %%Bits) :=
do ty ← infer_type Bits,
if is_supported_numeric_ty ty
then lol.term.int <$> eval_expr int `(bit1 %%Bits : int)
else if (ty = `(nat))
then lol.term.int <$> (int.of_nat <$> eval_expr nat `(bit1 %%Bits : nat))
else fail $ "unknown numeric literal: " ++ (to_string `(bit1 %%Bits : int))
| a :=
if a.is_local_constant
then return $ lol.term.var (mangle_name a.local_uniq_name)
else if a.is_constant
then return $ lol.term.var (mangle_name a.const_name)
else if a.is_app
then reflect_application (a.get_app_fn) (a.get_app_args) reflect_base
else fail $ "unsupported arithmetic formula: " ++ to_string a
-- /-- Check if the type is an `int` or logically a subtype of an `int` like nat. -/
meta def is_int (e : expr) : tactic bool :=
do ty ← infer_type e,
return $ (ty = `(int)) || (ty = `(nat))
meta def unsupported_ordering_on {α : Type} (elem : expr) : tactic α :=
do ty ← infer_type elem,
tactic.fail $ "unable to translate orderings for values of type: " ++ to_string ty
meta def reflect_ordering (reflect_arith : expr → smt2_m lol.term) (R : lol.term → lol.term → lol.term) (P Q : expr) : smt2_m lol.term :=
do is ← is_int P, -- NB: P and Q should have the same type.
if is
then R <$> (reflect_arith P) <*> (reflect_arith Q)
else unsupported_ordering_on P
meta def supported_pi_binder (ty : expr) : bool :=
match ty with
| `(int) := tt
| `(nat) := tt
| `(Prop) := tt
| _ := if ty.is_constant
then tt
else ff
end
meta def add_assertion (t : lol.term) : smt2_m unit :=
do st ← get,
put { st with ctxt := st.ctxt.assert t }
meta def compile_pi (e : expr) (cb : expr → smt2_m lol.term) : smt2_m lol.term :=
if supported_pi_binder e.binding_domain
then do loc ← tactic.mk_local' e.binding_name e.binding_info e.binding_domain,
lol.term.forallq
(mangle_name $ loc.local_uniq_name) <$>
(compile_type $ e.binding_domain) <*>
(cb (expr.instantiate_var (e.binding_body) loc))
else fail $ "arbitrary Π types are not supported, unable to translate term: `" ++ to_string e ++ "`"
meta def reflect_prop_formula' : expr → smt2_m lol.term
| `(¬ %%P) := lol.term.not <$> (reflect_prop_formula' P)
| `(%%P = %% Q) := lol.term.equals <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q)
| `(%%P ∧ %%Q) := lol.term.and <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q)
| `(%%P ∨ %%Q) := lol.term.or <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q)
| `(%%P ↔ %%Q) := lol.term.iff <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q)
| `(%%P < %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.lt P Q
| `(%%P <= %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.lte P Q
| `(%%P > %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.gt P Q
| `(%%P >= %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.gte P Q
| `(true) := return $ lol.term.true
| `(false) := return $ lol.term.false
| e := do ty ← infer_type e,
if e.is_local_constant
then pure $ lol.term.var (mangle_name e.local_uniq_name)
else if e.is_arrow
then lol.term.implies <$> (reflect_prop_formula' e.binding_domain) <*> (reflect_prop_formula' e.binding_body )
else if e.is_pi
then compile_pi e reflect_prop_formula'
else if is_supported_numeric_ty ty
then reflect_arith_formula reflect_prop_formula' e
else if e.is_app
then reflect_application (e.get_app_fn) (e.get_app_args) reflect_prop_formula'
else tactic.fail $ "unsupported propositional formula : " ++ to_string e
meta def reflect_prop_formula (e : expr) : smt2_m unit :=
reflect_prop_formula' e >>= add_assertion
-- meta def warn_unable_to_trans_local (e : expr) : smt2_m (builder unit) := do
-- trace_smt2 $ "unable to translate local variable: " ++ to_string e,
-- return $ return ()
meta def is_builtin_type : expr → bool
| `(int) := tt
| `(Prop) := tt
| `(nat) := tt
| _ := ff
meta def unsupported_formula (e : expr) : smt2_m unit :=
fail $ "unsupported formula: " ++ to_string e
meta def compile_local (e : expr) : smt2_m unit :=
do ty ← infer_type e,
prop_sorted ← is_prop ty,
if e.is_local_constant
then if is_builtin_type ty
then add_decl e.local_uniq_name ty
else if ty.is_arrow
then add_decl e.local_uniq_name ty
else if prop_sorted
then reflect_prop_formula ty
else unsupported_formula ty
else if e.is_constant
then if is_builtin_type ty ∨ ty.is_arrow
then add_decl e.const_name ty
else if prop_sorted
then reflect_prop_formula ty
else unsupported_formula ty
else if (ty = `(Prop))
then reflect_prop_formula e
else unsupported_formula e
meta def reflect_attr_decl (n : name) : smt2_m unit :=
do exp ← mk_const n,
compile_local exp
/- Reflect the environment consisting of declarations with the `smt2` attribute. -/
meta def reflect_environment : smt2_m unit :=
do decls ← attribute.get_instances `smt2,
bs ← monad.mapm reflect_attr_decl decls.reverse,
return ()
meta def reflect_context : smt2_m unit :=
do ls ← local_context,
bs ← monad.mapm (fun e, compile_local e) ls,
return ()
meta def reflect_goal : smt2_m unit :=
do tgt ← target,
-- SMT solvers are looking for satisfiabiltiy, so we must negate to check validity.
reflect_prop_formula `(_root_.not %%tgt),
return ()
meta def reflect : smt2_m (builder unit) :=
do reflect_environment,
reflect_context,
reflect_goal,
st ← get,
return $ (lol.to_builder (lol.smt2_compiler_state.mk (rb_map.mk _ _) st.ctxt []) lol.compile >> check_sat)
end smt2
universe u
@[smt2] lemma int_of_nat_is_pos :
forall (n : nat), 0 <= int.of_nat n :=
begin
intros, trivial
end
axiom proof_by_z3 (A : Sort u) : A
meta def z3 (log_file : option string := none) : tactic unit :=
do (builder, _) ← smt2.reflect.run smt2_state.initial,
resp ← unsafe_run_io (smt2 builder log_file),
match resp with
| smt2.response.sat := fail "z3 was unable to prove the goal"
| smt2.response.unknown := fail "z3 was unable to prove the goal"
| smt2.response.other str := fail $ "z3 communication error, unexpected response:\n\n" ++ str ++ "\n"
| smt2.response.unsat := do
tgt ← target,
sry ← to_expr $ ``(proof_by_z3 %%tgt),
exact sry
end
|
818558ca4d363b44462f727f0eb018daec88a9f6 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/calculus/taylor.lean | 6afa45503665cc43d4657a341f096245d9f770b7 | [
"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 | 18,782 | 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.calculus.iterated_deriv
import analysis.calculus.mean_value
import measure_theory.integral.interval_integral
import data.polynomial.basic
import data.polynomial.module
/-!
# Taylor's theorem
This file defines the Taylor polynomial of a real function `f : ℝ → E`,
where `E` is a normed vector space over `ℝ` and proves Taylor's theorem,
which states that if `f` is sufficiently smooth, then
`f` can be approximated by the Taylor polynomial up to an explicit error term.
## Main definitions
* `taylor_coeff_within`: the Taylor coefficient using `deriv_within`
* `taylor_within`: the Taylor polynomial using `deriv_within`
## Main statements
* `taylor_mean_remainder`: Taylor's theorem with the general form of the remainder term
* `taylor_mean_remainder_lagrange`: Taylor's theorem with the Lagrange remainder
* `taylor_mean_remainder_cauchy`: Taylor's theorem with the Cauchy remainder
* `exists_taylor_mean_remainder_bound`: Taylor's theorem for vector valued functions with a
polynomial bound on the remainder
## TODO
* the Peano form of the remainder
* the integral form of the remainder
* Generalization to higher dimensions
## Tags
Taylor polynomial, Taylor's theorem
-/
open_locale big_operators interval topological_space nat
open set
variables {𝕜 E F : Type*}
variables [normed_add_comm_group E] [normed_space ℝ E]
/-- The `k`th coefficient of the Taylor polynomial. -/
noncomputable
def taylor_coeff_within (f : ℝ → E) (k : ℕ) (s : set ℝ) (x₀ : ℝ) : E :=
(k! : ℝ)⁻¹ • (iterated_deriv_within k f s x₀)
/-- The Taylor polynomial with derivatives inside of a set `s`.
The Taylor polynomial is given by
$$∑_{k=0}^n \frac{(x - x₀)^k}{k!} f^{(k)}(x₀),$$
where $f^{(k)}(x₀)$ denotes the iterated derivative in the set `s`. -/
noncomputable
def taylor_within (f : ℝ → E) (n : ℕ) (s : set ℝ) (x₀ : ℝ) : polynomial_module ℝ E :=
(finset.range (n+1)).sum (λ k,
polynomial_module.comp (polynomial.X - polynomial.C x₀)
(polynomial_module.single ℝ k (taylor_coeff_within f k s x₀)))
/-- The Taylor polynomial with derivatives inside of a set `s` considered as a function `ℝ → E`-/
noncomputable
def taylor_within_eval (f : ℝ → E) (n : ℕ) (s : set ℝ) (x₀ x : ℝ) : E :=
polynomial_module.eval x (taylor_within f n s x₀)
lemma taylor_within_succ (f : ℝ → E) (n : ℕ) (s : set ℝ) (x₀ : ℝ) :
taylor_within f (n+1) s x₀ = taylor_within f n s x₀
+ polynomial_module.comp (polynomial.X - polynomial.C x₀)
(polynomial_module.single ℝ (n+1) (taylor_coeff_within f (n+1) s x₀)) :=
begin
dunfold taylor_within,
rw finset.sum_range_succ,
end
@[simp] lemma taylor_within_eval_succ (f : ℝ → E) (n : ℕ) (s : set ℝ) (x₀ x : ℝ) :
taylor_within_eval f (n+1) s x₀ x = taylor_within_eval f n s x₀ x
+ (((n + 1 : ℝ) * n!)⁻¹ * (x - x₀)^(n+1)) • iterated_deriv_within (n + 1) f s x₀ :=
begin
simp_rw [taylor_within_eval, taylor_within_succ, linear_map.map_add, polynomial_module.comp_eval],
congr,
simp only [polynomial.eval_sub, polynomial.eval_X, polynomial.eval_C,
polynomial_module.eval_single, mul_inv_rev],
dunfold taylor_coeff_within,
rw [←mul_smul, mul_comm, nat.factorial_succ, nat.cast_mul, nat.cast_add, nat.cast_one,
mul_inv_rev],
end
/-- The Taylor polynomial of order zero evaluates to `f x`. -/
@[simp] lemma taylor_within_zero_eval (f : ℝ → E) (s : set ℝ) (x₀ x : ℝ) :
taylor_within_eval f 0 s x₀ x = f x₀ :=
begin
dunfold taylor_within_eval,
dunfold taylor_within,
dunfold taylor_coeff_within,
simp,
end
/-- Evaluating the Taylor polynomial at `x = x₀` yields `f x`. -/
@[simp] lemma taylor_within_eval_self (f : ℝ → E) (n : ℕ) (s : set ℝ) (x₀ : ℝ) :
taylor_within_eval f n s x₀ x₀ = f x₀ :=
begin
induction n with k hk,
{ exact taylor_within_zero_eval _ _ _ _},
simp [hk]
end
lemma taylor_within_apply (f : ℝ → E) (n : ℕ) (s : set ℝ) (x₀ x : ℝ) :
taylor_within_eval f n s x₀ x = ∑ k in finset.range (n+1),
((k! : ℝ)⁻¹ * (x - x₀)^k) • iterated_deriv_within k f s x₀ :=
begin
induction n with k hk,
{ simp },
rw [taylor_within_eval_succ, finset.sum_range_succ, hk],
simp,
end
/-- If `f` is `n` times continuous differentiable on a set `s`, then the Taylor polynomial
`taylor_within_eval f n s x₀ x` is continuous in `x₀`. -/
lemma continuous_on_taylor_within_eval {f : ℝ → E} {x : ℝ} {n : ℕ} {s : set ℝ}
(hs : unique_diff_on ℝ s) (hf : cont_diff_on ℝ n f s) :
continuous_on (λ t, taylor_within_eval f n s t x) s :=
begin
simp_rw taylor_within_apply,
refine continuous_on_finset_sum (finset.range (n+1)) (λ i hi, _),
refine (continuous_on_const.mul ((continuous_on_const.sub continuous_on_id).pow _)).smul _,
rw cont_diff_on_iff_continuous_on_differentiable_on_deriv hs at hf,
cases hf,
specialize hf_left i,
simp only [finset.mem_range] at hi,
refine (hf_left _),
simp only [with_top.coe_le_coe],
exact nat.lt_succ_iff.mp hi,
end
/-- Helper lemma for calculating the derivative of the monomial that appears in Taylor expansions.-/
lemma monomial_has_deriv_aux (t x : ℝ) (n : ℕ) :
has_deriv_at (λ y, (x - y)^(n+1)) (-(n+1) * (x - t)^n) t :=
begin
simp_rw sub_eq_neg_add,
rw [←neg_one_mul, mul_comm (-1 : ℝ), mul_assoc, mul_comm (-1 : ℝ), ←mul_assoc],
convert @has_deriv_at.pow _ _ _ _ _ (n+1) ((has_deriv_at_id t).neg.add_const x),
simp only [nat.cast_add, nat.cast_one],
end
lemma has_deriv_within_at_taylor_coeff_within {f : ℝ → E} {x y : ℝ} {k : ℕ} {s s' : set ℝ}
(hs'_unique : unique_diff_within_at ℝ s' y)
(hs' : s' ∈ 𝓝[s] y) (hy : y ∈ s') (h : s' ⊆ s)
(hf' : differentiable_on ℝ (iterated_deriv_within (k+1) f s) s') :
has_deriv_within_at (λ t,
(((k+1 : ℝ) * k!)⁻¹ * (x - t)^(k+1)) • iterated_deriv_within (k+1) f s t)
((((k+1 : ℝ) * k!)⁻¹ * (x - y)^(k+1)) • iterated_deriv_within (k+2) f s y -
((k! : ℝ)⁻¹ * (x - y)^k) • iterated_deriv_within (k+1) f s y) s' y :=
begin
have hf'' : has_deriv_within_at (λ t, iterated_deriv_within (k+1) f s t)
(iterated_deriv_within (k+2) f s y) s' y :=
begin
convert (hf' y hy).has_deriv_within_at,
rw iterated_deriv_within_succ (hs'_unique.mono h),
refine (deriv_within_subset h hs'_unique _).symm,
exact (hf' y hy).antimono h hs',
end,
have : has_deriv_within_at (λ t, (((k+1 : ℝ) * k!)⁻¹ * (x - t)^(k+1)))
(-((k! : ℝ)⁻¹ * (x - y)^k)) s' y :=
begin
-- Commuting the factors:
have : (-((k! : ℝ)⁻¹ * (x - y)^k)) =
(((k+1 : ℝ) * k!)⁻¹ * (-(k+1) *(x - y)^k)) :=
by { field_simp [nat.cast_add_one_ne_zero k, nat.factorial_ne_zero k], ring_nf },
rw this,
exact (monomial_has_deriv_aux y x _).has_deriv_within_at.const_mul _,
end,
convert this.smul hf'',
field_simp [nat.cast_add_one_ne_zero k, nat.factorial_ne_zero k],
rw [neg_div, neg_smul, sub_eq_add_neg],
end
/-- Calculate the derivative of the Taylor polynomial with respect to `x₀`.
Version for arbitrary sets -/
lemma has_deriv_within_at_taylor_within_eval {f : ℝ → E} {x y : ℝ} {n : ℕ} {s s' : set ℝ}
(hs'_unique : unique_diff_within_at ℝ s' y) (hs_unique : unique_diff_on ℝ s)
(hs' : s' ∈ 𝓝[s] y) (hy : y ∈ s') (h : s' ⊆ s)
(hf : cont_diff_on ℝ n f s)
(hf' : differentiable_on ℝ (iterated_deriv_within n f s) s') :
has_deriv_within_at (λ t, taylor_within_eval f n s t x)
(((n! : ℝ)⁻¹ * (x - y)^n) • (iterated_deriv_within (n+1) f s y)) s' y :=
begin
induction n with k hk,
{ simp only [taylor_within_zero_eval, nat.factorial_zero, nat.cast_one, inv_one, pow_zero,
mul_one, zero_add, one_smul],
simp only [iterated_deriv_within_zero] at hf',
rw iterated_deriv_within_one hs_unique (h hy),
refine has_deriv_within_at.mono _ h,
refine differentiable_within_at.has_deriv_within_at _,
exact (hf' y hy).antimono h hs' },
simp_rw [nat.add_succ, taylor_within_eval_succ],
simp only [add_zero, nat.factorial_succ, nat.cast_mul, nat.cast_add, nat.cast_one],
have hdiff : differentiable_on ℝ (iterated_deriv_within k f s) s' :=
begin
have coe_lt_succ : (k : with_top ℕ) < k.succ :=
by { rw [with_top.coe_lt_coe], exact lt_add_one k },
refine differentiable_on.mono _ h,
exact hf.differentiable_on_iterated_deriv_within coe_lt_succ hs_unique,
end,
specialize hk (cont_diff_on.of_succ hf) hdiff,
convert hk.add (has_deriv_within_at_taylor_coeff_within hs'_unique hs' hy h hf'),
exact (add_sub_cancel'_right _ _).symm,
end
/-- Calculate the derivative of the Taylor polynomial with respect to `x₀`.
Version for open intervals -/
lemma taylor_within_eval_has_deriv_at_Ioo {f : ℝ → E} {a b t : ℝ} (x : ℝ) {n : ℕ}
(hx : a < b) (ht : t ∈ Ioo a b)
(hf : cont_diff_on ℝ n f (Icc a b))
(hf' : differentiable_on ℝ (iterated_deriv_within n f (Icc a b)) (Ioo a b)) :
has_deriv_at (λ y, taylor_within_eval f n (Icc a b) y x)
(((n! : ℝ)⁻¹ * (x - t)^n) • (iterated_deriv_within (n+1) f (Icc a b) t)) t :=
begin
have h_nhds := is_open.mem_nhds is_open_Ioo ht,
exact (has_deriv_within_at_taylor_within_eval (unique_diff_within_at_Ioo ht)
(unique_diff_on_Icc hx) (nhds_within_le_nhds h_nhds) ht Ioo_subset_Icc_self hf hf')
.has_deriv_at h_nhds,
end
/-- Calculate the derivative of the Taylor polynomial with respect to `x₀`.
Version for closed intervals -/
lemma has_deriv_within_taylor_within_eval_at_Icc {f : ℝ → E} {a b t : ℝ} (x : ℝ) {n : ℕ}
(hx : a < b) (ht : t ∈ Icc a b) (hf : cont_diff_on ℝ n f (Icc a b))
(hf' : differentiable_on ℝ (iterated_deriv_within n f (Icc a b)) (Icc a b)) :
has_deriv_within_at (λ y, taylor_within_eval f n (Icc a b) y x)
(((n! : ℝ)⁻¹ * (x - t)^n) • (iterated_deriv_within (n+1) f (Icc a b) t)) (Icc a b) t :=
has_deriv_within_at_taylor_within_eval (unique_diff_on_Icc hx t ht) (unique_diff_on_Icc hx)
self_mem_nhds_within ht rfl.subset hf hf'
/-! ### Taylor's theorem with mean value type remainder estimate -/
/-- **Taylor's theorem** with the general mean value form of the remainder.
We assume that `f` is `n+1`-times continuously differentiable in the closed set `Icc x₀ x` and
`n+1`-times differentiable on the open set `Ioo x₀ x`, and `g` is a differentiable function on
`Ioo x₀ x` and continuous on `Icc x₀ x`. Then there exists a `x' ∈ Ioo x₀ x` such that
$$f(x) - (P_n f)(x₀, x) = \frac{(x - x')^n}{n!} \frac{g(x) - g(x₀)}{g' x'},$$
where $P_n f$ denotes the Taylor polynomial of degree $n$. -/
lemma taylor_mean_remainder {f : ℝ → ℝ} {g g' : ℝ → ℝ} {x x₀ : ℝ} {n : ℕ} (hx : x₀ < x)
(hf : cont_diff_on ℝ n f (Icc x₀ x))
(hf' : differentiable_on ℝ (iterated_deriv_within n f (Icc x₀ x)) (Ioo x₀ x))
(gcont : continuous_on g (Icc x₀ x))
(gdiff : ∀ (x_1 : ℝ), x_1 ∈ Ioo x₀ x → has_deriv_at g (g' x_1) x_1)
(g'_ne : ∀ (x_1 : ℝ), x_1 ∈ Ioo x₀ x → g' x_1 ≠ 0) :
∃ (x' : ℝ) (hx' : x' ∈ Ioo x₀ x), f x - taylor_within_eval f n (Icc x₀ x) x₀ x =
((x - x')^n /n! * (g x - g x₀) / g' x') •
(iterated_deriv_within (n+1) f (Icc x₀ x) x')
:=
begin
-- We apply the mean value theorem
rcases exists_ratio_has_deriv_at_eq_ratio_slope (λ t, taylor_within_eval f n (Icc x₀ x) t x)
(λ t, ((n! : ℝ)⁻¹ * (x - t)^n) • (iterated_deriv_within (n+1) f (Icc x₀ x) t)) hx
(continuous_on_taylor_within_eval (unique_diff_on_Icc hx) hf)
(λ _ hy, taylor_within_eval_has_deriv_at_Ioo x hx hy hf hf')
g g' gcont gdiff with ⟨y, hy, h⟩,
use [y, hy],
-- The rest is simplifications and trivial calculations
simp only [taylor_within_eval_self] at h,
rw [mul_comm, ←div_left_inj' (g'_ne y hy), mul_div_cancel _ (g'_ne y hy)] at h,
rw ←h,
field_simp [g'_ne y hy, nat.factorial_ne_zero n],
ring,
end
/-- **Taylor's theorem** with the Lagrange form of the remainder.
We assume that `f` is `n+1`-times continuously differentiable in the closed set `Icc x₀ x` and
`n+1`-times differentiable on the open set `Ioo x₀ x`. Then there exists a `x' ∈ Ioo x₀ x` such that
$$f(x) - (P_n f)(x₀, x) = \frac{f^{(n+1)}(x') (x - x₀)^{n+1}}{(n+1)!},$$
where $P_n f$ denotes the Taylor polynomial of degree $n$ and $f^{(n+1)}$ is the $n+1$-th iterated
derivative. -/
lemma taylor_mean_remainder_lagrange {f : ℝ → ℝ} {x x₀ : ℝ} {n : ℕ} (hx : x₀ < x)
(hf : cont_diff_on ℝ n f (Icc x₀ x))
(hf' : differentiable_on ℝ (iterated_deriv_within n f (Icc x₀ x)) (Ioo x₀ x)) :
∃ (x' : ℝ) (hx' : x' ∈ Ioo x₀ x), f x - taylor_within_eval f n (Icc x₀ x) x₀ x =
(iterated_deriv_within (n+1) f (Icc x₀ x) x') * (x - x₀)^(n+1) /(n+1)! :=
begin
have gcont : continuous_on (λ (t : ℝ), (x - t) ^ (n + 1)) (Icc x₀ x) :=
by { refine continuous.continuous_on _, continuity },
have xy_ne : ∀ (y : ℝ), y ∈ Ioo x₀ x → (x - y)^n ≠ 0 :=
begin
intros y hy,
refine pow_ne_zero _ _,
rw [mem_Ioo] at hy,
rw sub_ne_zero,
exact hy.2.ne.symm,
end,
have hg' : ∀ (y : ℝ), y ∈ Ioo x₀ x → -(↑n + 1) * (x - y) ^ n ≠ 0 :=
λ y hy, mul_ne_zero (neg_ne_zero.mpr (nat.cast_add_one_ne_zero n)) (xy_ne y hy),
-- We apply the general theorem with g(t) = (x - t)^(n+1)
rcases taylor_mean_remainder hx hf hf' gcont (λ y _, monomial_has_deriv_aux y x _) hg'
with ⟨y, hy, h⟩,
use [y, hy],
simp only [sub_self, zero_pow', ne.def, nat.succ_ne_zero, not_false_iff, zero_sub, mul_neg] at h,
rw [h, neg_div, ←div_neg, neg_mul, neg_neg],
field_simp [nat.cast_add_one_ne_zero n, nat.factorial_ne_zero n, xy_ne y hy],
ring,
end
/-- **Taylor's theorem** with the Cauchy form of the remainder.
We assume that `f` is `n+1`-times continuously differentiable on the closed set `Icc x₀ x` and
`n+1`-times differentiable on the open set `Ioo x₀ x`. Then there exists a `x' ∈ Ioo x₀ x` such that
$$f(x) - (P_n f)(x₀, x) = \frac{f^{(n+1)}(x') (x - x')^n (x-x₀)}{n!},$$
where $P_n f$ denotes the Taylor polynomial of degree $n$ and $f^{(n+1)}$ is the $n+1$-th iterated
derivative. -/
lemma taylor_mean_remainder_cauchy {f : ℝ → ℝ} {x x₀ : ℝ} {n : ℕ} (hx : x₀ < x)
(hf : cont_diff_on ℝ n f (Icc x₀ x))
(hf' : differentiable_on ℝ (iterated_deriv_within n f (Icc x₀ x)) (Ioo x₀ x)) :
∃ (x' : ℝ) (hx' : x' ∈ Ioo x₀ x), f x - taylor_within_eval f n (Icc x₀ x) x₀ x =
(iterated_deriv_within (n+1) f (Icc x₀ x) x') * (x - x')^n /n! * (x - x₀) :=
begin
have gcont : continuous_on id (Icc x₀ x) := continuous.continuous_on (by continuity),
have gdiff : (∀ (x_1 : ℝ), x_1 ∈ Ioo x₀ x → has_deriv_at id
((λ (t : ℝ), (1 : ℝ)) x_1) x_1) := λ _ _, has_deriv_at_id _,
-- We apply the general theorem with g = id
rcases taylor_mean_remainder hx hf hf' gcont gdiff (λ _ _, by simp) with ⟨y, hy, h⟩,
use [y, hy],
rw h,
field_simp [nat.factorial_ne_zero n],
ring,
end
/-- **Taylor's theorem** with a polynomial bound on the remainder
We assume that `f` is `n+1`-times continuously differentiable on the closed set `Icc a b`.
The difference of `f` and its `n`-th Taylor polynomial can be estimated by
`C * (x - a)^(n+1) / n!` where `C` is a bound for the `n+1`-th iterated derivative of `f`. -/
lemma taylor_mean_remainder_bound {f : ℝ → E} {a b C x : ℝ} {n : ℕ}
(hab : a ≤ b) (hf : cont_diff_on ℝ (n+1) f (Icc a b)) (hx : x ∈ Icc a b)
(hC : ∀ y ∈ Icc a b, ∥iterated_deriv_within (n + 1) f (Icc a b) y∥ ≤ C) :
∥f x - taylor_within_eval f n (Icc a b) a x∥ ≤ C * (x - a)^(n+1) / n! :=
begin
rcases eq_or_lt_of_le hab with rfl|h,
{ rw [Icc_self, mem_singleton_iff] at hx,
simp [hx] },
-- The nth iterated derivative is differentiable
have hf' : differentiable_on ℝ (iterated_deriv_within n f (Icc a b)) (Icc a b) :=
hf.differentiable_on_iterated_deriv_within (with_top.coe_lt_coe.mpr n.lt_succ_self)
(unique_diff_on_Icc h),
-- natural numbers are non-negative
have fac_nonneg : 0 ≤ (n! : ℝ) := n!.cast_nonneg,
-- We can uniformly bound the derivative of the Taylor polynomial
have h' : ∀ (y : ℝ) (hy : y ∈ Ico a x),
∥((n! : ℝ)⁻¹ * (x - y) ^ n) • iterated_deriv_within (n + 1) f (Icc a b) y∥
≤ (n! : ℝ)⁻¹ * |(x - a)|^n * C,
{ intros y hy,
rw [norm_smul, real.norm_eq_abs],
-- Estimate the iterated derivative by `C`
refine mul_le_mul _ (hC y ⟨hy.1, hy.2.le.trans hx.2⟩) (by positivity) (by positivity),
-- The rest is a trivial calculation
rw [abs_mul, abs_pow, abs_inv, nat.abs_cast],
mono*,
any_goals { positivity },
{ exact hy.1 },
{ linarith [hx.1, hy.2] } },
-- Apply the mean value theorem for vector valued functions:
have A : ∀ t ∈ Icc a x, has_deriv_within_at (λ y, taylor_within_eval f n (Icc a b) y x)
(((↑n!)⁻¹ * (x - t) ^ n) • iterated_deriv_within (n + 1) f (Icc a b) t) (Icc a x) t,
{ assume t ht,
have I : Icc a x ⊆ Icc a b := Icc_subset_Icc_right hx.2,
exact (has_deriv_within_taylor_within_eval_at_Icc x h (I ht) hf.of_succ hf').mono I },
have := norm_image_sub_le_of_norm_deriv_le_segment' A h' x (right_mem_Icc.2 hx.1),
simp only [taylor_within_eval_self] at this,
refine le_trans this (le_of_eq _),
-- The rest is a trivial calculation
rw [abs_of_nonneg (sub_nonneg.mpr hx.1)],
ring_exp,
end
/-- **Taylor's theorem** with a polynomial bound on the remainder
We assume that `f` is `n+1`-times continuously differentiable on the closed set `Icc a b`.
There exists a constant `C` such that for all `x ∈ Icc a b` the difference of `f` and its `n`-th
Taylor polynomial can be estimated by `C * (x - a)^(n+1)`. -/
lemma exists_taylor_mean_remainder_bound {f : ℝ → E} {a b : ℝ} {n : ℕ}
(hab : a ≤ b) (hf : cont_diff_on ℝ (n+1) f (Icc a b)) :
∃ C, ∀ x ∈ Icc a b, ∥f x - taylor_within_eval f n (Icc a b) a x∥ ≤ C * (x - a)^(n+1) :=
begin
rcases eq_or_lt_of_le hab with rfl|h,
{ refine ⟨0, λ x hx, _⟩,
have : a = x, by simpa [← le_antisymm_iff] using hx,
simp [← this] },
-- We estimate by the supremum of the norm of the iterated derivative
let g : ℝ → ℝ := λ y, ∥iterated_deriv_within (n + 1) f (Icc a b) y∥,
use [has_Sup.Sup (g '' Icc a b) / n!],
intros x hx,
rw div_mul_eq_mul_div₀,
refine taylor_mean_remainder_bound hab hf hx (λ y, _),
exact (hf.continuous_on_iterated_deriv_within rfl.le $ unique_diff_on_Icc h)
.norm.le_Sup_image_Icc,
end
|
55d3a781f4faf228752771797f41d26232f9e5e3 | f5a711bc61b4fe426425fc39edfb9aa84b06f644 | /leanpkg/leanpkg/main.lean | 50ae4bab484f5c22ec685e358e6cb46f4858aedd | [
"Apache-2.0"
] | permissive | ChrisHughes24/lean | 89697c262783aa4fc1e3cc9bd7adf16d049e2be0 | 8ba2c1a8b4b9edd11c96482356b47df8322b3785 | refs/heads/master | 1,610,100,259,751 | 1,582,175,143,000 | 1,582,175,143,000 | 241,995,683 | 0 | 0 | Apache-2.0 | 1,582,234,740,000 | 1,582,234,739,000 | null | UTF-8 | Lean | false | false | 12,359 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Gabriel Ebner
-/
import leanpkg.resolve leanpkg.git
namespace leanpkg
def write_file (fn : string) (cnts : string) (mode := io.mode.write) : io unit := do
h ← io.mk_file_handle fn io.mode.write,
io.fs.write h cnts.to_char_buffer,
io.fs.close h
/--
.toml files that refer to Lean versions hosted externally will use the syntax "community/lean:3.5.0".
We need to strip the prefix, if it exists, to avoid an incorrect warning from leanpkg.
-/
def external_lean_version (s : string) : string :=
list.ilast $ s.split $ λ c, c = ':'
def read_manifest : io manifest := do
m ← manifest.from_file leanpkg_toml_fn,
when (external_lean_version m.lean_version ≠ lean_version_string) $
io.print_ln $ "\nWARNING: Lean version mismatch: installed version is " ++ lean_version_string
++ ", but package requires " ++ m.lean_version ++ "\n",
return m
def write_manifest (d : manifest) (fn := leanpkg_toml_fn) : io unit :=
write_file fn (repr d)
-- TODO(gabriel): implement a cross-platform api
def get_dot_lean_dir : io string := do
some home ← io.env.get "HOME" | io.fail "environment variable HOME is not set",
return $ home ++ "/.lean"
def mk_path_file : ∀ (paths : list string), string
| [] := "builtin_path\n"
| (x :: xs) := mk_path_file xs ++ "path " ++ x ++ "\n"
def configure : io unit := do
d ← read_manifest,
io.put_str_ln $ "configuring " ++ d.name ++ " " ++ d.version,
when (d.path ≠ some "src") $ io.put_str_ln "WARNING: leanpkg configurations not specifying `path = \"src\"` are deprecated.",
assg ← solve_deps d,
path_file_cnts ← mk_path_file <$> construct_path assg,
write_file "leanpkg.path" path_file_cnts
def make (lean_args : list string) : io unit := do
manifest ← read_manifest,
exec_cmd {
cmd := "lean",
args := (match manifest.timeout with some t := ["-T", repr t] | none := [] end) ++
["--make"] ++ manifest.effective_path ++ lean_args,
env := [("LEAN_PATH", none)]
}
def build (lean_args : list string) := configure >> make lean_args
def make_test (lean_args : list string) : io unit :=
exec_cmd { cmd := "lean", args := ["--make", "test"] ++ lean_args, env := [("LEAN_PATH", none)] }
def test (lean_args : list string) := build lean_args >> make_test lean_args
def init_gitignore_contents :=
"*.olean
/_target
/leanpkg.path
"
def init_pkg (n : string) (from_new : bool) : io unit := do
write_manifest { name := n, path := "src", version := "0.1" } leanpkg_toml_fn,
src_ex ← io.fs.dir_exists "src",
when (¬src_ex) (do
when ¬from_new $ io.put_str_ln "Move existing .lean files into the 'src' folder.",
io.fs.mkdir "src" >> return ()),
write_file ".gitignore" init_gitignore_contents io.mode.append,
git_ex ← io.fs.dir_exists ".git",
when (¬git_ex) (do {
exec_cmd {cmd := "git", args := ["init", "-q"]},
when (upstream_git_branch ≠ "master") $
exec_cmd {cmd := "git", args := ["checkout", "-b", upstream_git_branch]}
} <|> io.print_ln "WARNING: failed to initialize git repository"),
configure
def init (n : string) := init_pkg n false
-- TODO(gabriel): windows
def basename (s : string) : string :=
s.fold "" $ λ s c, if c = '/' then "" else s.str c
def add_dep_to_manifest (dep : dependency) : io unit := do
d ← read_manifest,
let d' := { d with dependencies := d.dependencies.filter (λ old_dep, old_dep.name ≠ dep.name) ++ [dep] },
write_manifest d'
def strip_dot_git (url : string) : string :=
if url.backn 4 = ".git" then url.popn_back 4 else url
def looks_like_git_url (dep : string) : bool :=
':' ∈ dep.to_list
def parse_add_dep (dep : string) (branch : option string) : io dependency :=
if looks_like_git_url dep then
pure { name := basename (strip_dot_git dep), src := source.git dep (git_default_revision branch) branch }
else do
ex ← io.fs.dir_exists dep,
if ex then match branch with
| some branch := io.fail sformat!"extraneous trailing path argument '{branch}'"
| none := pure { name := basename dep, src := source.path dep }
end
else do
[user, repo] ← pure $ dep.split (= '/')
| io.fail sformat!"path '{dep}' does not exist",
pure { name := repo, src := source.git sformat!"https://github.com/{user}/{repo}" (git_default_revision branch) branch }
def absolutize_dep (dep : dependency) : io dependency :=
match dep.src with
| source.path p := do
cwd ← io.env.get_cwd,
pure {src := source.path (resolve_dir p cwd), ..dep}
| _ := pure dep
end
def parse_install_dep (dep : string) (branch : option string) : io dependency := do
dep ← parse_add_dep dep none,
dep ← absolutize_dep dep,
dot_lean_dir ← get_dot_lean_dir,
io.fs.mkdir dot_lean_dir tt,
let user_toml_fn := dot_lean_dir ++ "/" ++ leanpkg_toml_fn,
ex ← io.fs.file_exists user_toml_fn,
when (¬ ex) $ write_manifest {
name := "_user_local_packages",
version := "1"
} user_toml_fn,
change_dir dot_lean_dir,
return dep
def fixup_git_version (dir : string) : ∀ (src : source), io source
| (source.git url _ _) := do
rev ← git_head_revision dir,
return $ source.git url rev none
| src := return src
def add (dep : dependency) : io unit := do
(_, assg) ← (materialize "." dep).run assignment.empty,
some downloaded_path ← return (assg.find dep.name),
manif ← manifest.from_file (downloaded_path ++ "/" ++ leanpkg_toml_fn),
src ← fixup_git_version downloaded_path dep.src,
let dep := { dep with name := manif.name, src := src },
add_dep_to_manifest dep,
configure
def new (dir : string) := do
ex ← io.fs.dir_exists dir,
when ex $ io.fail $ "directory already exists: " ++ dir,
io.fs.mkdir dir tt,
change_dir dir,
init_pkg (basename dir) true
def upgrade_dep (assg : assignment) (d : dependency) : io dependency :=
match d.src with
| (source.git url rev branch) := (do
some path ← return (assg.find d.name) | io.fail "unresolved dependency",
new_rev ← git_latest_origin_revision path branch,
return {d with src := source.git url new_rev branch})
<|> return d
| _ := return d
end
def upgrade := do
m ← read_manifest,
assg ← solve_deps m,
ds' ← m.dependencies.mmap (upgrade_dep assg),
write_manifest {m with dependencies := ds'},
configure
def usage :=
"Lean package manager, version " ++ ui_lean_version_string ++ "
Usage: leanpkg <command>
configure download dependencies
build [-- <lean-args>] download dependencies and build *.olean files
test [-- <lean-args>] download dependencies, build *.olean files, and run test files
new <dir> create a Lean package in a new directory
init <name> create a Lean package in the current directory
add <url> [branch] add a dependency from a git repository (uses latest upstream revision)
add <dir> add a local dependency
upgrade upgrade all git dependencies to the latest upstream version
install <url> [branch] install a user-wide package from git
install <dir> install a user-wide package from a local directory
dump print the parsed leanpkg.toml file (for debugging)
See `leanpkg help <command>` for more information on a specific command."
def main : ∀ (cmd : string) (leanpkg_args lean_args : list string), io unit
| "configure" [] [] := configure
| "build" _ lean_args := build lean_args
| "test" _ lean_args := test lean_args
| "new" [dir] [] := new dir
| "init" [name] [] := init name
| "add" [dep] [] := parse_add_dep dep none >>= add
| "add" [dep] [branch] := parse_add_dep dep branch >>= add
| "upgrade" [] [] := upgrade
| "install" [dep] [] := parse_install_dep dep none >>= add >> build []
| "install" [dep] [branch] := parse_install_dep dep branch >>= add >> build []
| "dump" [] [] := read_manifest >>= io.print_ln ∘ repr
| "help" ["configure"] [] := io.print_ln "Download dependencies
Usage:
leanpkg configure
This command sets up the `_target/deps` directory and the `leanpkg.path` file.
For each (transitive) git dependency, the specified commit is checked out
into a sub-directory of `_target/deps`. If there are dependencies on multiple
versions of the same package, the version materialized is undefined.
The `leanpkg.path` file used to resolve Lean imports is populated with paths
to the `src` directories of all (transitive) dependencies. No copy is made
of local dependencies."
| "help" ["build"] [] := io.print_ln "Download dependencies and build *.olean files
Usage:
leanpkg build [-- <lean-args>]
This command invokes `leanpkg configure` followed by
`lean --make src <lean-args>`, building the package's Lean files as well as
(transitively) imported files of dependencies. If defined, the `package.timeout`
configuration value is passed to Lean via its `-T` parameter."
| "help" ["test"] [] := io.print_ln "Download dependencies, build *.olean files, and run test files
Usage:
leanpkg test [-- <lean-args>]
This command invokes `leanpkg build <lean-args>` followed by
`lean --make test <lean-args>`, executing the package's test files. A failed
test should generate a Lean error message, which makes this command return a
non-zero exit code."
| "help" ["add"] [] := io.print_ln sformat!"Add a dependency
Usage:
leanpkg add <local-path>
leanpkg add <git-url>
leanpkg add <github-user>/<github-repo>
Examples:
leanpkg add ../mathlib
leanpkg add https://github.com/leanprover/mathlib
leanpkg add leanprover/mathlib
This command adds the specified local or git dependency, then calls
`leanpkg configure`. For git dependencies, the pinned commit is
the head of the branch `lean-<version>` (e.g. `lean-3.3.0`) on stable
releases of Lean, or else `master` (current branch: {upstream_git_branch})."
| "help" ["new"] [] := io.print_ln "Create a new Lean package in a new directory
Usage:
leanpkg new <path>/.../<name>
This command creates a new Lean package named '<name>' in a new directory
`<path>/.../<name>`. A new git repository is initialized to the branch name
expected by `leanpkg add` (see `leanpkg help add`).
For converting an existing directory into a Lean package, use `leanpkg init`."
| "help" ["init"] [] := io.print_ln "Create a new Lean package in the current directory
Usage:
leanpkg init <name>
This command creates a new Lean package with the given name in the current
directory. Existing Lean source files should be moved into the new `src`
directory."
| "help" ["upgrade"] [] := io.print_ln "Upgrade all git dependencies to the latest upstream version
Usage:
leanpkg upgrade
This command fetches the remote repositories of all git dependencies and updates
the pinned commits to the head of the respective branch (see
`leanpkg help add`)."
| "help" ["install"] [] := io.print_ln "Install a user-wide package
Usage:
leanpkg install <local-path>
leanpkg install <git-url>
leanpkg install <github-user>/<github-repo>
This command adds a dependency to a user-wide \"meta\" package in `~/.lean`.
For files not part of a Lean package, Lean falls back to the core library
and this meta package for import resolution.
For removing or upgrading user-wide dependencies, you currently have to change
into `~/.lean` yourself and edit the leanpkg.toml file or execute
`leanpkg upgrade`, respectively."
| "help" _ [] := io.print_ln usage
| _ _ _ := io.fail usage
private def split_cmdline_args_core : list string → list string × list string
| [] := ([], [])
| (arg::args) := if arg = "--"
then ([], args)
else match split_cmdline_args_core args with
| (outer_args, inner_args) := (arg::outer_args, inner_args)
end
def split_cmdline_args : list string → io (string × list string × list string)
| [] := io.fail usage
| [cmd] := return (cmd, [], [])
| (cmd::rest) := match split_cmdline_args_core rest with
| (outer_args, inner_args) := return (cmd, outer_args, inner_args)
end
end leanpkg
def main : io unit :=
do (cmd, outer_args, inner_args) ← io.cmdline_args >>= leanpkg.split_cmdline_args,
leanpkg.main cmd outer_args inner_args
|
2d02d7099bcc69b5aec90ac8ee228b92644421c2 | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/linear_algebra/finsupp.lean | 1557f91df652e277d5376a94a53f23fdaf5394e7 | [
"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 | 17,018 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Linear structures on function with finite support `α →₀ M`.
-/
import data.monoid_algebra
noncomputable theory
open set linear_map submodule
open_locale classical
namespace finsupp
variables {α : Type*} {M : Type*} {R : Type*}
variables [ring R] [add_comm_group M] [module R M]
def lsingle (a : α) : M →ₗ[R] (α →₀ M) :=
⟨single a, assume a b, single_add, assume c b, (smul_single _ _ _).symm⟩
def lapply (a : α) : (α →₀ M) →ₗ[R] M := ⟨λg, g a, assume a b, rfl, assume a b, rfl⟩
section lsubtype_domain
variables (s : set α)
def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) :=
⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩
lemma lsubtype_domain_apply (f : α →₀ M) :
(lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl
end lsubtype_domain
@[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b :=
rfl
@[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a :=
rfl
@[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ :=
ker_eq_bot.2 (injective_single a)
lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) :
(⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a)) :=
begin
refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi],
assume b hb a₂ h₂,
have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩,
exact single_eq_of_ne this
end
lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ :=
begin
simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply],
exact assume a h, finsupp.ext h
end
lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ :=
begin
refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _),
rw [← sum_single f],
refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem _ a $ set.mem_image_of_mem _ trivial)
end
lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) :
disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a).range) :=
begin
refine disjoint.mono
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl s)
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl t)
(le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot),
classical,
by_cases his : i ∈ s,
{ by_cases hit : i ∈ t,
{ exact (hs ⟨his, hit⟩).elim },
exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) },
exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his)
end
lemma span_single_image (s : set M) (a : α) :
submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) :=
by rw ← span_image; refl
variables (M R)
def supported (s : set α) : submodule R (α →₀ M) :=
begin
refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩,
{ simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply],
assume h ha, exact (ha rfl).elim },
{ assume p q hp hq,
refine subset.trans
(subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq),
rw [finset.coe_union] },
{ assume a p hp,
refine subset.trans (finset.coe_subset.2 support_smul) hp }
end
variables {M}
lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s :=
iff.rfl
lemma mem_supported' {s : set α} (p : α →₀ M) :
p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 :=
by haveI := classical.dec_pred (λ (x : α), x ∈ s);
simp [mem_supported, set.subset_def, not_imp_comm]
lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) :
single a b ∈ supported M R s :=
set.subset.trans support_single_subset (finset.singleton_subset_set_iff.2 h)
lemma supported_eq_span_single (s : set α) :
supported R R s = span R ((λ i, single i 1) '' s) :=
begin
refine (span_eq_of_le _ _ (le_def'.2 $ λ l hl, _)).symm,
{ rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp },
{ rw ← l.sum_single,
refine sum_mem _ (λ i il, _),
convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _,
{ simp },
apply subset_span,
apply set.mem_image_of_mem _ (hl il) }
end
variables (M R)
def restrict_dom (s : set α) : (α →₀ M) →ₗ supported M R s :=
linear_map.cod_restrict _
{ to_fun := filter (∈ s),
add := λ l₁ l₂, filter_add,
smul := λ a l, filter_smul }
(λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l)
variables {M R}
section
@[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) :
((restrict_dom M R s : (α →₀ M) →ₗ supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl
end
theorem restrict_dom_comp_subtype (s : set α) :
(restrict_dom M R s).comp (submodule.subtype _) = linear_map.id :=
begin
ext l,
apply subtype.coe_ext.2,
simp,
ext a,
by_cases a ∈ s,
{ simp [h] },
{ rw [filter_apply_neg (λ x, x ∈ s) _ h],
exact ((mem_supported' R l.1).1 l.2 a h).symm }
end
theorem range_restrict_dom (s : set α) :
(restrict_dom M R s).range = ⊤ :=
begin
have := linear_map.range_comp (submodule.subtype _) (restrict_dom M R s),
rw [restrict_dom_comp_subtype, linear_map.range_id] at this,
exact eq_top_mono (submodule.map_mono le_top) this.symm
end
theorem supported_mono {s t : set α} (st : s ⊆ t) :
supported M R s ≤ supported M R t :=
λ l h, set.subset.trans h st
@[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ :=
eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $
by ext; simp [*, mem_supported'] at *
@[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ :=
eq_top_iff.2 $ λ l _, set.subset_univ _
theorem supported_Union {δ : Type*} (s : δ → set α) :
supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) :=
begin
refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _),
haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)),
suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i),
{ rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this },
rw [range_le_iff_comap, eq_top_iff],
rintro l ⟨⟩,
apply finsupp.induction l, {exact zero_mem _},
refine λ x a l hl a0, add_mem _ _,
haveI := classical.dec_pred (λ x, ∃ i, x ∈ s i),
by_cases (∃ i, x ∈ s i); simp [h],
{ cases h with i hi,
exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) },
{ rw filter_single_of_neg,
{ simp },
{ exact h } }
end
theorem supported_union (s t : set α) :
supported M R (s ∪ t) = supported M R s ⊔ supported M R t :=
by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl
theorem supported_Inter {ι : Type*} (s : ι → set α) :
supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) :=
begin
refine le_antisymm (le_infi $ λ i, supported_mono $ set.Inter_subset _ _) _,
simp [le_def, infi_coe, set.subset_def],
exact λ l, set.subset_Inter
end
section
def supported_equiv_finsupp (s : set α) :
(supported M R s) ≃ₗ[R] (s →₀ M) :=
(restrict_support_equiv s).to_linear_equiv
begin
show is_linear_map R ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp
(submodule.subtype (supported M R s))),
exact linear_map.is_linear _
end
end
def lsum (f : α → R →ₗ[R] M) : (α →₀ R) →ₗ[R] M :=
⟨λ d, d.sum (λ i, f i),
assume d₁ d₂, by simp [sum_add_index],
assume a d, by simp [sum_smul_index, smul_sum, -smul_eq_mul, smul_eq_mul.symm]⟩
@[simp] theorem lsum_apply (f : α → R →ₗ[R] M) (l : α →₀ R) :
(finsupp.lsum f : (α →₀ R) →ₗ M) l = l.sum (λ b, f b) := rfl
section lmap_domain
variables {α' : Type*} {α'' : Type*} (M R)
def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) :=
⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩
@[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) :
(lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl
@[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id :=
linear_map.ext $ λ l, map_domain_id
theorem lmap_domain_comp (f : α → α') (g : α' → α'') :
lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) :=
linear_map.ext $ λ l, map_domain_comp
theorem supported_comap_lmap_domain (f : α → α') (s : set α') :
supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) :=
λ l (hl : ↑l.support ⊆ f ⁻¹' s),
show ↑(map_domain f l).support ⊆ s, begin
rw [← set.image_subset_iff, ← finset.coe_image] at hl,
exact set.subset.trans map_domain_support hl
end
theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) :
(supported M R s).map (lmap_domain M R f) = supported M R (f '' s) :=
begin
inhabit α,
refine le_antisymm (map_le_iff_le_comap.2 $
le_trans (supported_mono $ set.subset_preimage_image _ _)
(supported_comap_lmap_domain _ _ _ _)) _,
intros l hl,
refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ α →₀ M) l, λ x hx, _, _⟩,
{ rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩,
exact function.inv_fun_on_mem (by simpa using hl hc) },
{ rw [← linear_map.comp_apply, ← lmap_domain_comp],
refine (map_domain_congr $ λ c hc, _).trans map_domain_id,
exact function.inv_fun_on_eq (by simpa using hl hc) }
end
theorem lmap_domain_disjoint_ker (f : α → α') {s : set α}
(H : ∀ a b ∈ s, f a = f b → a = b) :
disjoint (supported M R s) (lmap_domain M R f).ker :=
begin
rintro l ⟨h₁, h₂⟩,
rw [mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂,
simp, ext x,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases xs : x ∈ s,
{ have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl},
rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this,
{ simpa [finsupp.single_apply] },
{ intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] },
{ simp {contextual := tt} } },
{ by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) }
end
end lmap_domain
section total
variables (α) {α' : Type*} (M) {M' : Type*} (R)
[add_comm_group M'] [module R M']
(v : α → M) {v' : α' → M'}
/-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and
evaluates this linear combination. -/
protected def total : (α →₀ R) →ₗ M := finsupp.lsum (λ i, linear_map.id.smul_right (v i))
variables {α M v}
theorem total_apply (l : α →₀ R) :
finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl
@[simp] theorem total_single (c : R) (a : α) :
finsupp.total α M R v (single a c) = c • (v a) :=
by simp [total_apply, sum_single_index]
theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ :=
begin
apply range_eq_top.2,
intros x,
apply exists.elim (h x),
exact λ i hi, ⟨single i 1, by simp [hi]⟩
end
lemma range_total : (finsupp.total α M R v).range = span R (range v) :=
begin
ext x,
split,
{ intros hx,
rw [linear_map.mem_range] at hx,
rcases hx with ⟨l, hl⟩,
rw ← hl,
rw finsupp.total_apply,
unfold finsupp.sum,
apply sum_mem (span R (range v)),
exact λ i hi, submodule.smul _ _ (subset_span (mem_range_self i)) },
{ apply span_le.2,
intros x hx,
rcases hx with ⟨i, hi⟩,
rw [mem_coe, linear_map.mem_range],
use finsupp.single i 1,
simp [hi] }
end
theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) :
(finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) :=
by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h]
theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) :
(finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply]
theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) :
(finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
begin
have : map_domain f l = emb_domain ⟨f, hf⟩ l,
{ rw emb_domain_eq_map_domain ⟨f, hf⟩,
refl },
rw this,
apply total_emb_domain R ⟨f, hf⟩ l
end
theorem span_eq_map_total (s : set α):
span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) :=
begin
apply span_eq_of_le,
{ intros x hx,
rw set.mem_image at hx,
apply exists.elim hx,
intros i hi,
exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ },
{ refine map_le_iff_le_comap.2 (λ z hz, _),
have : ∀i, z i • v i ∈ span R (v '' s),
{ intro c,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases c ∈ s,
{ exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) },
{ simp [(finsupp.mem_supported' R _).1 hz _ h] } },
refine sum_mem _ _, simp [this] }
end
theorem mem_span_iff_total {s : set α} {x : M} :
x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x :=
by rw span_eq_map_total; simp
variables (α) (M) (v)
protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) :=
linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $
λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩
variables {α} {M} {v}
theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ :=
by rw [finsupp.total_on, linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap,
range_subtype, map_top, linear_map.range_comp, range_subtype]; exact le_of_eq (span_eq_map_total _ _)
theorem total_comp (f : α' → α) :
(finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) :=
begin
ext l,
simp [total_apply],
rw sum_map_domain_index; simp [add_smul],
end
lemma total_comap_domain
(f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) :
finsupp.total α M R v (finsupp.comap_domain f l hf) = (l.support.preimage hf).sum (λ i, (l (f i)) • (v i)) :=
by rw finsupp.total_apply; refl
end total
protected def dom_lcongr
{α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) :
(α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) :=
(finsupp.dom_congr e).to_linear_equiv
begin
change is_linear_map R (lmap_domain M R e : (α₁ →₀ M) →ₗ[R] (α₂ →₀ M)),
exact linear_map.is_linear _
end
noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) :
supported M R s ≃ₗ[R] supported M R t :=
begin
haveI := classical.dec_pred (λ x, x ∈ s),
haveI := classical.dec_pred (λ x, x ∈ t),
refine linear_equiv.trans (finsupp.supported_equiv_finsupp s)
(linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm),
exact finsupp.dom_lcongr e
end
end finsupp
variables {R : Type*} {M : Type*} {N : Type*}
variables [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N]
lemma linear_map.map_finsupp_total
(f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) :
f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l :=
by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul]
lemma submodule.exists_finset_of_mem_supr
{ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) :
∃ s : finset ι, m ∈ ⨆ i ∈ s, p i :=
begin
obtain ⟨f, hf, rfl⟩ : ∃ f ∈ finsupp.supported R R (⋃ i, ↑(p i)), finsupp.total M M R id f = m,
{ have aux : (id : M → M) '' (⋃ (i : ι), ↑(p i)) = (⋃ (i : ι), ↑(p i)) := set.image_id _,
rwa [supr_eq_span, ← aux, finsupp.mem_span_iff_total R] at hm },
let t : finset M := f.support,
have ht : ∀ x : {x // x ∈ t}, ∃ i, ↑x ∈ p i,
{ intros x,
rw finsupp.mem_supported at hf,
specialize hf x.2,
rwa set.mem_Union at hf },
choose g hg using ht,
let s : finset ι := finset.univ.image g,
use s,
simp only [mem_supr, supr_le_iff],
assume N hN,
rw [finsupp.total_apply, finsupp.sum, ← submodule.mem_coe],
apply is_add_submonoid.finset_sum_mem,
assume x hx,
apply submodule.smul_mem,
let i : ι := g ⟨x, hx⟩,
have hi : i ∈ s, { rw finset.mem_image, exact ⟨⟨x, hx⟩, finset.mem_univ _, rfl⟩ },
exact hN i hi (hg _),
end
|
95991d2b1e3f3fc2d2007088eed9b1a19ffe716f | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/order/synonym.lean | f04b5957db6d0549fa21ac5d0f0389bae831c76a | [
"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 | 4,774 | lean | /-
Copyright (c) 2020 Johan Commelin, Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Damiano Testa, Yaël Dillies
-/
import logic.equiv.defs
import logic.nontrivial
import order.basic
/-!
# Type synonyms
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides two type synonyms for order theory:
* `order_dual α`: Type synonym of `α` to equip it with the dual order (`a ≤ b` becomes `b ≤ a`).
* `lex α`: Type synonym of `α` to equip it with its lexicographic order. The precise meaning depends
on the type we take the lex of. Examples include `prod`, `sigma`, `list`, `finset`.
## Notation
`αᵒᵈ` is notation for `order_dual α`.
The general rule for notation of `lex` types is to append `ₗ` to the usual notation.
## Implementation notes
One should not abuse definitional equality between `α` and `αᵒᵈ`/`lex α`. Instead, explicit
coercions should be inserted:
* `order_dual`: `order_dual.to_dual : α → αᵒᵈ` and `order_dual.of_dual : αᵒᵈ → α`
* `lex`: `to_lex : α → lex α` and `of_lex : lex α → α`.
In fact, those are bundled as `equiv`s to put goals in the right syntactic form for rewriting with
the `equiv` API (`⇑to_lex a` where `⇑` is `coe_fn : (α ≃ lex α) → α → lex α`, instead of a bare
`to_lex a`).
## See also
This file is similar to `algebra.group.type_tags`.
-/
variables {α β γ : Type*}
/-! ### Order dual -/
namespace order_dual
instance [h : nontrivial α] : nontrivial (αᵒᵈ) := h
/-- `to_dual` is the identity function to the `order_dual` of a linear order. -/
def to_dual : α ≃ αᵒᵈ := equiv.refl _
/-- `of_dual` is the identity function from the `order_dual` of a linear order. -/
def of_dual : αᵒᵈ ≃ α := equiv.refl _
@[simp] lemma to_dual_symm_eq : (@to_dual α).symm = of_dual := rfl
@[simp] lemma of_dual_symm_eq : (@of_dual α).symm = to_dual := rfl
@[simp] lemma to_dual_of_dual (a : αᵒᵈ) : to_dual (of_dual a) = a := rfl
@[simp] lemma of_dual_to_dual (a : α) : of_dual (to_dual a) = a := rfl
@[simp] lemma to_dual_inj {a b : α} : to_dual a = to_dual b ↔ a = b := iff.rfl
@[simp] lemma of_dual_inj {a b : αᵒᵈ} : of_dual a = of_dual b ↔ a = b := iff.rfl
@[simp] lemma to_dual_le_to_dual [has_le α] {a b : α} : to_dual a ≤ to_dual b ↔ b ≤ a := iff.rfl
@[simp] lemma to_dual_lt_to_dual [has_lt α] {a b : α} : to_dual a < to_dual b ↔ b < a := iff.rfl
@[simp] lemma of_dual_le_of_dual [has_le α] {a b : αᵒᵈ} : of_dual a ≤ of_dual b ↔ b ≤ a := iff.rfl
@[simp] lemma of_dual_lt_of_dual [has_lt α] {a b : αᵒᵈ} : of_dual a < of_dual b ↔ b < a := iff.rfl
lemma le_to_dual [has_le α] {a : αᵒᵈ} {b : α} : a ≤ to_dual b ↔ b ≤ of_dual a := iff.rfl
lemma lt_to_dual [has_lt α] {a : αᵒᵈ} {b : α} : a < to_dual b ↔ b < of_dual a := iff.rfl
lemma to_dual_le [has_le α] {a : α} {b : αᵒᵈ} : to_dual a ≤ b ↔ of_dual b ≤ a := iff.rfl
lemma to_dual_lt [has_lt α] {a : α} {b : αᵒᵈ} : to_dual a < b ↔ of_dual b < a := iff.rfl
/-- Recursor for `αᵒᵈ`. -/
@[elab_as_eliminator]
protected def rec {C : αᵒᵈ → Sort*} (h₂ : Π a : α, C (to_dual a)) : Π a : αᵒᵈ, C a := h₂
@[simp] protected lemma «forall» {p : αᵒᵈ → Prop} : (∀ a, p a) ↔ ∀ a, p (to_dual a) := iff.rfl
@[simp] protected lemma «exists» {p : αᵒᵈ → Prop} : (∃ a, p a) ↔ ∃ a, p (to_dual a) := iff.rfl
alias to_dual_le_to_dual ↔ _ _root_.has_le.le.dual
alias to_dual_lt_to_dual ↔ _ _root_.has_lt.lt.dual
alias of_dual_le_of_dual ↔ _ _root_.has_le.le.of_dual
alias of_dual_lt_of_dual ↔ _ _root_.has_lt.lt.of_dual
end order_dual
/-! ### Lexicographic order -/
/-- A type synonym to equip a type with its lexicographic order. -/
def lex (α : Type*) := α
/-- `to_lex` is the identity function to the `lex` of a type. -/
@[pattern] def to_lex : α ≃ lex α := equiv.refl _
/-- `of_lex` is the identity function from the `lex` of a type. -/
@[pattern] def of_lex : lex α ≃ α := equiv.refl _
@[simp] lemma to_lex_symm_eq : (@to_lex α).symm = of_lex := rfl
@[simp] lemma of_lex_symm_eq : (@of_lex α).symm = to_lex := rfl
@[simp] lemma to_lex_of_lex (a : lex α) : to_lex (of_lex a) = a := rfl
@[simp] lemma of_lex_to_lex (a : α) : of_lex (to_lex a) = a := rfl
@[simp] lemma to_lex_inj {a b : α} : to_lex a = to_lex b ↔ a = b := iff.rfl
@[simp] lemma of_lex_inj {a b : lex α} : of_lex a = of_lex b ↔ a = b := iff.rfl
/-- A recursor for `lex`. Use as `induction x using lex.rec`. -/
protected def lex.rec {β : lex α → Sort*} (h : Π a, β (to_lex a)) : Π a, β a := λ a, h (of_lex a)
|
fbdf6fd36f12ea0cbc1265ffeca060031fd2564a | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Lean/Environment.lean | f7382565d9c3bab5ac36854605dfd6ea2364b136 | [
"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 | 42,115 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.HashMap
import Lean.ImportingFlag
import Lean.Data.SMap
import Lean.Declaration
import Lean.LocalContext
import Lean.Util.Path
import Lean.Util.FindExpr
import Lean.Util.Profile
import Lean.Util.InstantiateLevelParams
namespace Lean
/-- Opaque environment extension state. -/
opaque EnvExtensionStateSpec : (α : Type) × Inhabited α := ⟨Unit, ⟨()⟩⟩
def EnvExtensionState : Type := EnvExtensionStateSpec.fst
instance : Inhabited EnvExtensionState := EnvExtensionStateSpec.snd
def ModuleIdx := Nat
deriving BEq, ToString
abbrev ModuleIdx.toNat (midx : ModuleIdx) : Nat := midx
instance : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat)
abbrev ConstMap := SMap Name ConstantInfo
structure Import where
module : Name
runtimeOnly : Bool := false
deriving Repr, Inhabited
instance : ToString Import := ⟨fun imp => toString imp.module ++ if imp.runtimeOnly then " (runtime)" else ""⟩
/--
A compacted region holds multiple Lean objects in a contiguous memory region, which can be read/written to/from disk.
Objects inside the region do not have reference counters and cannot be freed individually. The contents of .olean
files are compacted regions. -/
def CompactedRegion := USize
@[extern "lean_compacted_region_is_memory_mapped"]
opaque CompactedRegion.isMemoryMapped : CompactedRegion → Bool
/-- Free a compacted region and its contents. No live references to the contents may exist at the time of invocation. -/
@[extern "lean_compacted_region_free"]
unsafe opaque CompactedRegion.free : CompactedRegion → IO Unit
/-- Opaque persistent environment extension entry. -/
opaque EnvExtensionEntrySpec : NonemptyType.{0}
def EnvExtensionEntry : Type := EnvExtensionEntrySpec.type
instance : Nonempty EnvExtensionEntry := EnvExtensionEntrySpec.property
/-- Content of a .olean file.
We use `compact.cpp` to generate the image of this object in disk. -/
structure ModuleData where
imports : Array Import
/--
`constNames` contains all constant names in `constants`.
This information is redundant. It is equal to `constants.map fun c => c.name`,
but it improves the performance of `importModules`. `perf` reports that 12% of the
runtime was being spent on `ConstantInfo.name` when importing a file containing only `import Lean`
-/
constNames : Array Name
constants : Array ConstantInfo
/--
Extra entries for the `const2ModIdx` map in the `Environment` object.
The code generator creates auxiliary declarations that are not in the
mapping `constants`, but we want to know in which module they were generated.
-/
extraConstNames : Array Name
entries : Array (Name × Array EnvExtensionEntry)
deriving Inhabited
/-- Environment fields that are not used often. -/
structure EnvironmentHeader where
/--
The trust level used by the kernel. For example,
the kernel assumes imported constants are type correct when the trust level is greater than zero.
-/
trustLevel : UInt32 := 0
/--
`quotInit = true` if the command `init_quot` has already been executed for the environment, and
`Quot` declarations have been added to the environment.
-/
quotInit : Bool := false
/--
Name of the module being compiled.
-/
mainModule : Name := default
/-- Direct imports -/
imports : Array Import := #[]
/-- Compacted regions for all imported modules. Objects in compacted memory regions do no require any memory management. -/
regions : Array CompactedRegion := #[]
/-- Name of all imported modules (directly and indirectly). -/
moduleNames : Array Name := #[]
/-- Module data for all imported modules. -/
moduleData : Array ModuleData := #[]
deriving Inhabited
/--
An environment stores declarations provided by the user. The kernel
currently supports different kinds of declarations such as definitions, theorems,
and inductive families. Each has a unique identifier (i.e., `Name`), and can be
parameterized by a sequence of universe parameters.
A constant in Lean is just a reference to a `ConstantInfo` object. The main task of
the kernel is to type check these declarations and refuse type incorrect ones. The
kernel does not allow declarations containing metavariables and/or free variables
to be added to an environment. Environments are never destructively updated.
The environment also contains a collection of extensions. For example, the `simp` theorems
declared by users are stored in an environment extension. Users can declare new extensions
using meta-programming.
-/
structure Environment where
/--
Mapping from constant name to module (index) where constant has been declared.
Recall that a Lean file has a header where previously compiled modules can be imported.
Each imported module has a unique `ModuleIdx`.
Many extensions use the `ModuleIdx` to efficiently retrieve information stored in imported modules.
Remark: this mapping also contains auxiliary constants, created by the code generator, that are **not** in
the field `constants`. These auxiliary constants are invisible to the Lean kernel and elaborator.
Only the code generator uses them.
-/
const2ModIdx : HashMap Name ModuleIdx
/--
Mapping from constant name to `ConstantInfo`. It contains all constants (definitions, theorems, axioms, etc)
that have been already type checked by the kernel.
-/
constants : ConstMap
/--
Environment extensions. It also includes user-defined extensions.
-/
extensions : Array EnvExtensionState
/--
Constant names to be saved in the field `extraConstNames` at `ModuleData`.
It contains auxiliary declaration names created by the code generator which are not in `constants`.
When importing modules, we want to insert them at `const2ModIdx`.
-/
extraConstNames : NameSet
/-- The header contains additional information that is not updated often. -/
header : EnvironmentHeader := {}
deriving Inhabited
namespace Environment
def addAux (env : Environment) (cinfo : ConstantInfo) : Environment :=
{ env with constants := env.constants.insert cinfo.name cinfo }
/--
Save an extra constant name that is used to populate `const2ModIdx` when we import
.olean files. We use this feature to save in which module an auxiliary declaration
created by the code generator has been created.
-/
def addExtraName (env : Environment) (name : Name) : Environment :=
if env.constants.contains name then
env
else
{ env with extraConstNames := env.extraConstNames.insert name }
@[export lean_environment_find]
def find? (env : Environment) (n : Name) : Option ConstantInfo :=
/- It is safe to use `find'` because we never overwrite imported declarations. -/
env.constants.find?' n
def contains (env : Environment) (n : Name) : Bool :=
env.constants.contains n
def imports (env : Environment) : Array Import :=
env.header.imports
def allImportedModuleNames (env : Environment) : Array Name :=
env.header.moduleNames
@[export lean_environment_set_main_module]
def setMainModule (env : Environment) (m : Name) : Environment :=
{ env with header := { env.header with mainModule := m } }
@[export lean_environment_main_module]
def mainModule (env : Environment) : Name :=
env.header.mainModule
@[export lean_environment_mark_quot_init]
private def markQuotInit (env : Environment) : Environment :=
{ env with header := { env.header with quotInit := true } }
@[export lean_environment_quot_init]
private def isQuotInit (env : Environment) : Bool :=
env.header.quotInit
@[export lean_environment_trust_level]
private def getTrustLevel (env : Environment) : UInt32 :=
env.header.trustLevel
def getModuleIdxFor? (env : Environment) (declName : Name) : Option ModuleIdx :=
env.const2ModIdx.find? declName
def isConstructor (env : Environment) (declName : Name) : Bool :=
match env.find? declName with
| ConstantInfo.ctorInfo _ => true
| _ => false
def getModuleIdx? (env : Environment) (moduleName : Name) : Option ModuleIdx :=
env.header.moduleNames.findIdx? (· == moduleName)
end Environment
/-- Exceptions that can be raised by the Kernel when type checking new declarations. -/
inductive KernelException where
| unknownConstant (env : Environment) (name : Name)
| alreadyDeclared (env : Environment) (name : Name)
| declTypeMismatch (env : Environment) (decl : Declaration) (givenType : Expr)
| declHasMVars (env : Environment) (name : Name) (expr : Expr)
| declHasFVars (env : Environment) (name : Name) (expr : Expr)
| funExpected (env : Environment) (lctx : LocalContext) (expr : Expr)
| typeExpected (env : Environment) (lctx : LocalContext) (expr : Expr)
| letTypeMismatch (env : Environment) (lctx : LocalContext) (name : Name) (givenType : Expr) (expectedType : Expr)
| exprTypeMismatch (env : Environment) (lctx : LocalContext) (expr : Expr) (expectedType : Expr)
| appTypeMismatch (env : Environment) (lctx : LocalContext) (app : Expr) (funType : Expr) (argType : Expr)
| invalidProj (env : Environment) (lctx : LocalContext) (proj : Expr)
| other (msg : String)
namespace Environment
/-- Type check given declaration and add it to the environment -/
@[extern "lean_add_decl"]
opaque addDecl (env : Environment) (decl : @& Declaration) : Except KernelException Environment
end Environment
namespace ConstantInfo
def instantiateTypeLevelParams (c : ConstantInfo) (ls : List Level) : Expr :=
c.type.instantiateLevelParams c.levelParams ls
def instantiateValueLevelParams! (c : ConstantInfo) (ls : List Level) : Expr :=
c.value!.instantiateLevelParams c.levelParams ls
end ConstantInfo
/-- Interface for managing environment extensions. -/
structure EnvExtensionInterface where
ext : Type → Type
inhabitedExt : Inhabited σ → Inhabited (ext σ)
registerExt (mkInitial : IO σ) : IO (ext σ)
setState (e : ext σ) (env : Environment) : σ → Environment
modifyState (e : ext σ) (env : Environment) : (σ → σ) → Environment
getState [Inhabited σ] (e : ext σ) (env : Environment) : σ
mkInitialExtStates : IO (Array EnvExtensionState)
ensureExtensionsSize : Environment → IO Environment
instance : Inhabited EnvExtensionInterface where
default := {
ext := id
inhabitedExt := id
ensureExtensionsSize := fun env => pure env
registerExt := fun mk => mk
setState := fun _ env _ => env
modifyState := fun _ env _ => env
getState := fun ext _ => ext
mkInitialExtStates := pure #[]
}
/-! # Unsafe implementation of `EnvExtensionInterface` -/
namespace EnvExtensionInterfaceUnsafe
structure Ext (σ : Type) where
idx : Nat
mkInitial : IO σ
deriving Inhabited
private builtin_initialize envExtensionsRef : IO.Ref (Array (Ext EnvExtensionState)) ← IO.mkRef #[]
/--
User-defined environment extensions are declared using the `initialize` command.
This command is just syntax sugar for the `init` attribute.
When we `import` lean modules, the vector stored at `envExtensionsRef` may increase in size because of
user-defined environment extensions. When this happens, we must adjust the size of the `env.extensions`.
This method is invoked when processing `import`s.
-/
partial def ensureExtensionsArraySize (env : Environment) : IO Environment := do
loop env.extensions.size env
where
loop (i : Nat) (env : Environment) : IO Environment := do
let envExtensions ← envExtensionsRef.get
if i < envExtensions.size then
let s ← envExtensions[i]!.mkInitial
let env := { env with extensions := env.extensions.push s }
loop (i + 1) env
else
return env
private def invalidExtMsg := "invalid environment extension has been accessed"
unsafe def setState {σ} (ext : Ext σ) (env : Environment) (s : σ) : Environment :=
if h : ext.idx < env.extensions.size then
{ env with extensions := env.extensions.set ⟨ext.idx, h⟩ (unsafeCast s) }
else
panic! invalidExtMsg
@[inline] unsafe def modifyState {σ : Type} (ext : Ext σ) (env : Environment) (f : σ → σ) : Environment :=
if ext.idx < env.extensions.size then
{ env with
extensions := env.extensions.modify ext.idx fun s =>
let s : σ := unsafeCast s
let s : σ := f s
unsafeCast s }
else
panic! invalidExtMsg
unsafe def getState {σ} [Inhabited σ] (ext : Ext σ) (env : Environment) : σ :=
if h : ext.idx < env.extensions.size then
let s : EnvExtensionState := env.extensions.get ⟨ext.idx, h⟩
unsafeCast s
else
panic! invalidExtMsg
unsafe def registerExt {σ} (mkInitial : IO σ) : IO (Ext σ) := do
unless (← initializing) do
throw (IO.userError "failed to register environment, extensions can only be registered during initialization")
let exts ← envExtensionsRef.get
let idx := exts.size
let ext : Ext σ := {
idx := idx,
mkInitial := mkInitial,
}
envExtensionsRef.modify fun exts => exts.push (unsafeCast ext)
pure ext
def mkInitialExtStates : IO (Array EnvExtensionState) := do
let exts ← envExtensionsRef.get
exts.mapM fun ext => ext.mkInitial
unsafe def imp : EnvExtensionInterface := {
ext := Ext
ensureExtensionsSize := ensureExtensionsArraySize
inhabitedExt := fun _ => ⟨default⟩
registerExt := registerExt
setState := setState
modifyState := modifyState
getState := getState
mkInitialExtStates := mkInitialExtStates
}
end EnvExtensionInterfaceUnsafe
@[implemented_by EnvExtensionInterfaceUnsafe.imp]
opaque EnvExtensionInterfaceImp : EnvExtensionInterface
def EnvExtension (σ : Type) : Type := EnvExtensionInterfaceImp.ext σ
private def ensureExtensionsArraySize (env : Environment) : IO Environment :=
EnvExtensionInterfaceImp.ensureExtensionsSize env
namespace EnvExtension
instance {σ} [s : Inhabited σ] : Inhabited (EnvExtension σ) := EnvExtensionInterfaceImp.inhabitedExt s
def setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := EnvExtensionInterfaceImp.setState ext env s
def modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := EnvExtensionInterfaceImp.modifyState ext env f
def getState {σ : Type} [Inhabited σ] (ext : EnvExtension σ) (env : Environment) : σ := EnvExtensionInterfaceImp.getState ext env
end EnvExtension
/-- Environment extensions can only be registered during initialization.
Reasons:
1- Our implementation assumes the number of extensions does not change after an environment object is created.
2- We do not use any synchronization primitive to access `envExtensionsRef`.
Note that by default, extension state is *not* stored in .olean files and will not propagate across `import`s.
For that, you need to register a persistent environment extension. -/
def registerEnvExtension {σ : Type} (mkInitial : IO σ) : IO (EnvExtension σ) := EnvExtensionInterfaceImp.registerExt mkInitial
private def mkInitialExtensionStates : IO (Array EnvExtensionState) := EnvExtensionInterfaceImp.mkInitialExtStates
@[export lean_mk_empty_environment]
def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do
let initializing ← IO.initializing
if initializing then throw (IO.userError "environment objects cannot be created during initialization")
let exts ← mkInitialExtensionStates
pure {
const2ModIdx := {}
constants := {}
header := { trustLevel := trustLevel }
extraConstNames := {}
extensions := exts
}
structure PersistentEnvExtensionState (α : Type) (σ : Type) where
importedEntries : Array (Array α) -- entries per imported module
state : σ
structure ImportM.Context where
env : Environment
opts : Options
abbrev ImportM := ReaderT Lean.ImportM.Context IO
/-- An environment extension with support for storing/retrieving entries from a .olean file.
- α is the type of the entries that are stored in .olean files.
- β is the type of values used to update the state.
- σ is the actual state.
Remark: for most extensions α and β coincide.
Note that `addEntryFn` is not in `IO`. This is intentional, and allows us to write simple functions such as
```
def addAlias (env : Environment) (a : Name) (e : Name) : Environment :=
aliasExtension.addEntry env (a, e)
```
without using `IO`. We have many functions like `addAlias`.
`α` and ‵β` do not coincide for extensions where the data used to update the state contains, for example,
closures which we currently cannot store in files. -/
structure PersistentEnvExtension (α : Type) (β : Type) (σ : Type) where
toEnvExtension : EnvExtension (PersistentEnvExtensionState α σ)
name : Name
addImportedFn : Array (Array α) → ImportM σ
addEntryFn : σ → β → σ
exportEntriesFn : σ → Array α
statsFn : σ → Format
instance {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) :=
⟨{importedEntries := #[], state := default }⟩
instance {α β σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α β σ) where
default := {
toEnvExtension := default,
name := default,
addImportedFn := fun _ => default,
addEntryFn := fun s _ => s,
exportEntriesFn := fun _ => #[],
statsFn := fun _ => Format.nil
}
namespace PersistentEnvExtension
def getModuleEntries {α β σ : Type} [Inhabited σ] (ext : PersistentEnvExtension α β σ) (env : Environment) (m : ModuleIdx) : Array α :=
(ext.toEnvExtension.getState env).importedEntries.get! m
def addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) : Environment :=
ext.toEnvExtension.modifyState env fun s =>
let state := ext.addEntryFn s.state b;
{ s with state := state }
/-- Get the current state of the given extension in the given environment. -/
def getState {α β σ : Type} [Inhabited σ] (ext : PersistentEnvExtension α β σ) (env : Environment) : σ :=
(ext.toEnvExtension.getState env).state
/-- Set the current state of the given extension in the given environment. This change is *not* persisted across files. -/
def setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) : Environment :=
ext.toEnvExtension.modifyState env fun ps => { ps with state := s }
/-- Modify the state of the given extension in the given environment by applying the given function. This change is *not* persisted across files. -/
def modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment :=
ext.toEnvExtension.modifyState env fun ps => { ps with state := f (ps.state) }
end PersistentEnvExtension
builtin_initialize persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) ← IO.mkRef #[]
structure PersistentEnvExtensionDescr (α β σ : Type) where
name : Name := by exact decl_name%
mkInitial : IO σ
addImportedFn : Array (Array α) → ImportM σ
addEntryFn : σ → β → σ
exportEntriesFn : σ → Array α
statsFn : σ → Format := fun _ => Format.nil
unsafe def registerPersistentEnvExtensionUnsafe {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := do
let pExts ← persistentEnvExtensionsRef.get
if pExts.any (fun ext => ext.name == descr.name) then throw (IO.userError s!"invalid environment extension, '{descr.name}' has already been used")
let ext ← registerEnvExtension do
let initial ← descr.mkInitial
let s : PersistentEnvExtensionState α σ := {
importedEntries := #[],
state := initial
}
pure s
let pExt : PersistentEnvExtension α β σ := {
toEnvExtension := ext,
name := descr.name,
addImportedFn := descr.addImportedFn,
addEntryFn := descr.addEntryFn,
exportEntriesFn := descr.exportEntriesFn,
statsFn := descr.statsFn
}
persistentEnvExtensionsRef.modify fun pExts => pExts.push (unsafeCast pExt)
return pExt
@[implemented_by registerPersistentEnvExtensionUnsafe]
opaque registerPersistentEnvExtension {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ)
/-- Simple `PersistentEnvExtension` that implements `exportEntriesFn` using a list of entries. -/
def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α α (List α × σ)
@[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ :=
as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState
structure SimplePersistentEnvExtensionDescr (α σ : Type) where
name : Name := by exact decl_name%
addEntryFn : σ → α → σ
addImportedFn : Array (Array α) → σ
toArrayFn : List α → Array α := fun es => es.toArray
def registerSimplePersistentEnvExtension {α σ : Type} [Inhabited σ] (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) :=
registerPersistentEnvExtension {
name := descr.name,
mkInitial := pure ([], descr.addImportedFn #[]),
addImportedFn := fun as => pure ([], descr.addImportedFn as),
addEntryFn := fun s e => match s with
| (entries, s) => (e::entries, descr.addEntryFn s e),
exportEntriesFn := fun s => descr.toArrayFn s.1.reverse,
statsFn := fun s => format "number of local entries: " ++ format s.1.length
}
namespace SimplePersistentEnvExtension
instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) :=
inferInstanceAs (Inhabited (PersistentEnvExtension α α (List α × σ)))
/-- Get the list of values used to update the state of the given
`SimplePersistentEnvExtension` in the current file. -/
def getEntries {α σ : Type} [Inhabited σ] (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α :=
(PersistentEnvExtension.getState ext env).1
/-- Get the current state of the given `SimplePersistentEnvExtension`. -/
def getState {α σ : Type} [Inhabited σ] (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ :=
(PersistentEnvExtension.getState ext env).2
/-- Set the current state of the given `SimplePersistentEnvExtension`. This change is *not* persisted across files. -/
def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment :=
PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s))
/-- Modify the state of the given extension in the given environment by applying the given function. This change is *not* persisted across files. -/
def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment :=
PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s))
end SimplePersistentEnvExtension
/-- Environment extension for tagging declarations.
Declarations must only be tagged in the module where they were declared. -/
def TagDeclarationExtension := SimplePersistentEnvExtension Name NameSet
def mkTagDeclarationExtension (name : Name := by exact decl_name%) : IO TagDeclarationExtension :=
registerSimplePersistentEnvExtension {
name := name,
addImportedFn := fun _ => {},
addEntryFn := fun s n => s.insert n,
toArrayFn := fun es => es.toArray.qsort Name.quickLt
}
namespace TagDeclarationExtension
instance : Inhabited TagDeclarationExtension :=
inferInstanceAs (Inhabited (SimplePersistentEnvExtension Name NameSet))
def tag (ext : TagDeclarationExtension) (env : Environment) (declName : Name) : Environment :=
assert! env.getModuleIdxFor? declName |>.isNone -- See comment at `TagDeclarationExtension`
ext.addEntry env declName
def isTagged (ext : TagDeclarationExtension) (env : Environment) (declName : Name) : Bool :=
match env.getModuleIdxFor? declName with
| some modIdx => (ext.getModuleEntries env modIdx).binSearchContains declName Name.quickLt
| none => (ext.getState env).contains declName
end TagDeclarationExtension
/-- Environment extension for mapping declarations to values.
Declarations must only be inserted into the mapping in the module where they were declared. -/
def MapDeclarationExtension (α : Type) := SimplePersistentEnvExtension (Name × α) (NameMap α)
def mkMapDeclarationExtension [Inhabited α] (name : Name := by exact decl_name%) : IO (MapDeclarationExtension α) :=
registerSimplePersistentEnvExtension {
name := name,
addImportedFn := fun _ => {},
addEntryFn := fun s n => s.insert n.1 n.2 ,
toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1)
}
namespace MapDeclarationExtension
instance : Inhabited (MapDeclarationExtension α) :=
inferInstanceAs (Inhabited (SimplePersistentEnvExtension ..))
def insert (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) (val : α) : Environment :=
assert! env.getModuleIdxFor? declName |>.isNone -- See comment at `MapDeclarationExtension`
ext.addEntry env (declName, val)
def find? [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Option α :=
match env.getModuleIdxFor? declName with
| some modIdx =>
match (ext.getModuleEntries env modIdx).binSearch (declName, default) (fun a b => Name.quickLt a.1 b.1) with
| some e => some e.2
| none => none
| none => (ext.getState env).find? declName
def contains [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Bool :=
match env.getModuleIdxFor? declName with
| some modIdx => (ext.getModuleEntries env modIdx).binSearchContains (declName, default) (fun a b => Name.quickLt a.1 b.1)
| none => (ext.getState env).contains declName
end MapDeclarationExtension
@[extern "lean_save_module_data"]
opaque saveModuleData (fname : @& System.FilePath) (mod : @& Name) (data : @& ModuleData) : IO Unit
@[extern "lean_read_module_data"]
opaque readModuleData (fname : @& System.FilePath) : IO (ModuleData × CompactedRegion)
/--
Free compacted regions of imports. No live references to imported objects may exist at the time of invocation; in
particular, `env` should be the last reference to any `Environment` derived from these imports. -/
@[noinline, export lean_environment_free_regions]
unsafe def Environment.freeRegions (env : Environment) : IO Unit :=
/-
NOTE: This assumes `env` is not inferred as a borrowed parameter, and is freed after extracting the `header` field.
Otherwise, we would encounter undefined behavior when the constant map in `env`, which may reference objects in
compacted regions, is freed after the regions.
In the currently produced IR, we indeed see:
```
def Lean.Environment.freeRegions (x_1 : obj) (x_2 : obj) : obj :=
let x_3 : obj := proj[3] x_1;
inc x_3;
dec x_1;
...
```
TODO: statically check for this. -/
env.header.regions.forM CompactedRegion.free
def mkModuleData (env : Environment) : IO ModuleData := do
let pExts ← persistentEnvExtensionsRef.get
let entries := pExts.map fun pExt =>
let state := pExt.getState env
(pExt.name, pExt.exportEntriesFn state)
let constNames := env.constants.foldStage2 (fun names name _ => names.push name) #[]
let constants := env.constants.foldStage2 (fun cs _ c => cs.push c) #[]
return {
imports := env.header.imports
extraConstNames := env.extraConstNames.toArray
constNames, constants, entries
}
@[export lean_write_module]
def writeModule (env : Environment) (fname : System.FilePath) : IO Unit := do
saveModuleData fname env.mainModule (← mkModuleData env)
/--
Construct a mapping from persistent extension name to entension index at the array of persistent extensions.
We only consider extensions starting with index `>= startingAt`.
-/
private def mkExtNameMap (startingAt : Nat) : IO (HashMap Name Nat) := do
let descrs ← persistentEnvExtensionsRef.get
let mut result := {}
for h : i in [startingAt : descrs.size] do
have : i < descrs.size := h.upper
let descr := descrs[i]
result := result.insert descr.name i
return result
private def setImportedEntries (env : Environment) (mods : Array ModuleData) (startingAt : Nat := 0) : IO Environment := do
let mut env := env
let extDescrs ← persistentEnvExtensionsRef.get
/- For extensions starting at `startingAt`, ensure their `importedEntries` array have size `mods.size`. -/
for extDescr in extDescrs[startingAt:] do
env := extDescr.toEnvExtension.modifyState env fun s => { s with importedEntries := mkArray mods.size #[] }
/- For each module `mod`, and `mod.entries`, if the extension name is one of the extensions after `startingAt`, set `entries` -/
let extNameIdx ← mkExtNameMap startingAt
for h : modIdx in [:mods.size] do
have : modIdx < mods.size := h.upper
let mod := mods[modIdx]
for (extName, entries) in mod.entries do
if let some entryIdx := extNameIdx.find? extName then
env := extDescrs[entryIdx]!.toEnvExtension.modifyState env fun s => { s with importedEntries := s.importedEntries.set! modIdx entries }
return env
/--
"Forward declaration" needed for updating the attribute table with user-defined attributes.
User-defined attributes are declared using the `initialize` command. The `initialize` command is just syntax sugar for the `init` attribute.
The `init` attribute is initialized after the `attributeExtension` is initialized. We cannot change the order since the `init` attribute is an attribute,
and requires this extension.
The `attributeExtension` initializer uses `attributeMapRef` to initialize the attribute mapping.
When we a new user-defined attribute declaration is imported, `attributeMapRef` is updated.
Later, we set this method with code that adds the user-defined attributes that were imported after we initialized `attributeExtension`.
-/
@[extern 2 "lean_update_env_attributes"] opaque updateEnvAttributes : Environment → IO Environment
/-- "Forward declaration" for retrieving the number of builtin attributes. -/
@[extern 1 "lean_get_num_attributes"] opaque getNumBuiltinAttributes : IO Nat
private partial def finalizePersistentExtensions (env : Environment) (mods : Array ModuleData) (opts : Options) : IO Environment := do
loop 0 env
where
loop (i : Nat) (env : Environment) : IO Environment := do
-- Recall that the size of the array stored `persistentEnvExtensionRef` may increase when we import user-defined environment extensions.
let pExtDescrs ← persistentEnvExtensionsRef.get
if i < pExtDescrs.size then
let extDescr := pExtDescrs[i]!
let s := extDescr.toEnvExtension.getState env
let prevSize := (← persistentEnvExtensionsRef.get).size
let prevAttrSize ← getNumBuiltinAttributes
let newState ← extDescr.addImportedFn s.importedEntries { env := env, opts := opts }
let mut env := extDescr.toEnvExtension.setState env { s with state := newState }
env ← ensureExtensionsArraySize env
if (← persistentEnvExtensionsRef.get).size > prevSize || (← getNumBuiltinAttributes) > prevAttrSize then
-- This branch is executed when `pExtDescrs[i]` is the extension associated with the `init` attribute, and
-- a user-defined persistent extension is imported.
-- Thus, we invoke `setImportedEntries` to update the array `importedEntries` with the entries for the new extensions.
env ← setImportedEntries env mods prevSize
-- See comment at `updateEnvAttributesRef`
env ← updateEnvAttributes env
loop (i + 1) env
else
return env
structure ImportState where
moduleNameSet : NameHashSet := {}
moduleNames : Array Name := #[]
moduleData : Array ModuleData := #[]
regions : Array CompactedRegion := #[]
def throwAlreadyImported (s : ImportState) (const2ModIdx : HashMap Name ModuleIdx) (modIdx : Nat) (cname : Name) : IO α := do
let modName := s.moduleNames[modIdx]!
let constModName := s.moduleNames[const2ModIdx[cname].get!.toNat]!
throw <| IO.userError s!"import {modName} failed, environment already contains '{cname}' from {constModName}"
@[export lean_import_modules]
partial def importModules (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) : IO Environment := profileitIO "import" opts do
for imp in imports do
if imp.module matches .anonymous then
throw <| IO.userError "import failed, trying to import module with anonymous name"
withImporting do
let (_, s) ← importMods imports |>.run {}
let mut numConsts := 0
for mod in s.moduleData do
numConsts := numConsts + mod.constants.size + mod.extraConstNames.size
let mut modIdx : Nat := 0
let mut const2ModIdx : HashMap Name ModuleIdx := mkHashMap (capacity := numConsts)
let mut constantMap : HashMap Name ConstantInfo := mkHashMap (capacity := numConsts)
for mod in s.moduleData do
for cname in mod.constNames, cinfo in mod.constants do
match constantMap.insert' cname cinfo with
| (constantMap', replaced) =>
constantMap := constantMap'
if replaced then
throwAlreadyImported s const2ModIdx modIdx cname
const2ModIdx := const2ModIdx.insert cname modIdx
for cname in mod.extraConstNames do
const2ModIdx := const2ModIdx.insert cname modIdx
modIdx := modIdx + 1
let constants : ConstMap := SMap.fromHashMap constantMap false
let exts ← mkInitialExtensionStates
let env : Environment := {
const2ModIdx := const2ModIdx
constants := constants
extraConstNames := {}
extensions := exts
header := {
quotInit := !imports.isEmpty -- We assume `core.lean` initializes quotient module
trustLevel := trustLevel
imports := imports.toArray
regions := s.regions
moduleNames := s.moduleNames
moduleData := s.moduleData
}
}
let env ← setImportedEntries env s.moduleData
let env ← finalizePersistentExtensions env s.moduleData opts
pure env
where
importMods : List Import → StateRefT ImportState IO Unit
| [] => pure ()
| i::is => do
if i.runtimeOnly || (← get).moduleNameSet.contains i.module then
importMods is
else do
modify fun s => { s with moduleNameSet := s.moduleNameSet.insert i.module }
let mFile ← findOLean i.module
unless (← mFile.pathExists) do
throw <| IO.userError s!"object file '{mFile}' of module {i.module} does not exist"
let (mod, region) ← readModuleData mFile
importMods mod.imports.toList
modify fun s => { s with
moduleData := s.moduleData.push mod
regions := s.regions.push region
moduleNames := s.moduleNames.push i.module
}
importMods is
/--
Create environment object from imports and free compacted regions after calling `act`. No live references to the
environment object or imported objects may exist after `act` finishes. -/
unsafe def withImportModules {α : Type} (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) (x : Environment → IO α) : IO α := do
let env ← importModules imports opts trustLevel
try x env finally env.freeRegions
/--
Environment extension for tracking all `namespace` declared by users.
-/
builtin_initialize namespacesExt : SimplePersistentEnvExtension Name NameSSet ←
registerSimplePersistentEnvExtension {
addImportedFn := fun as =>
/-
We compute a `HashMap Name Unit` and then convert to `NameSSet` to improve Lean startup time.
Note: we have used `perf` to profile Lean startup cost when processing a file containing just `import Lean`.
6.18% of the runtime is here. It was 9.31% before the `HashMap` optimization.
-/
let capacity := as.foldl (init := 0) fun r e => r + e.size
let map : HashMap Name Unit := mkHashMap capacity
let map := mkStateFromImportedEntries (fun map name => map.insert name ()) map as
SMap.fromHashMap map |>.switch
addEntryFn := fun s n => s.insert n
}
namespace Environment
/-- Register a new namespace in the environment. -/
def registerNamespace (env : Environment) (n : Name) : Environment :=
if (namespacesExt.getState env).contains n then env else namespacesExt.addEntry env n
/-- Return `true` if `n` is the name of a namespace in `env`. -/
def isNamespace (env : Environment) (n : Name) : Bool :=
(namespacesExt.getState env).contains n
/-- Return a set containing all namespaces in `env`. -/
def getNamespaceSet (env : Environment) : NameSSet :=
namespacesExt.getState env
private def isNamespaceName : Name → Bool
| .str .anonymous _ => true
| .str p _ => isNamespaceName p
| _ => false
private def registerNamePrefixes : Environment → Name → Environment
| env, .str p _ => if isNamespaceName p then registerNamePrefixes (registerNamespace env p) p else env
| env, _ => env
@[export lean_environment_add]
def add (env : Environment) (cinfo : ConstantInfo) : Environment :=
let env := registerNamePrefixes env cinfo.name
env.addAux cinfo
@[export lean_display_stats]
def displayStats (env : Environment) : IO Unit := do
let pExtDescrs ← persistentEnvExtensionsRef.get
IO.println ("direct imports: " ++ toString env.header.imports);
IO.println ("number of imported modules: " ++ toString env.header.regions.size);
IO.println ("number of memory-mapped modules: " ++ toString (env.header.regions.filter (·.isMemoryMapped) |>.size));
IO.println ("number of consts: " ++ toString env.constants.size);
IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1);
IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2);
IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets);
IO.println ("trust level: " ++ toString env.header.trustLevel);
IO.println ("number of extensions: " ++ toString env.extensions.size);
pExtDescrs.forM fun extDescr => do
IO.println ("extension '" ++ toString extDescr.name ++ "'")
let s := extDescr.toEnvExtension.getState env
let fmt := extDescr.statsFn s.state
unless fmt.isNil do IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state)))
IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0))
/--
Evaluate the given declaration under the given environment to a value of the given type.
This function is only safe to use if the type matches the declaration's type in the environment
and if `enableInitializersExecution` has been used before importing any modules. -/
@[extern "lean_eval_const"]
unsafe opaque evalConst (α) (env : @& Environment) (opts : @& Options) (constName : @& Name) : Except String α
private def throwUnexpectedType {α} (typeName : Name) (constName : Name) : ExceptT String Id α :=
throw ("unexpected type at '" ++ toString constName ++ "', `" ++ toString typeName ++ "` expected")
/-- Like `evalConst`, but first check that `constName` indeed is a declaration of type `typeName`.
Note that this function cannot guarantee that `typeName` is in fact the name of the type `α`. -/
unsafe def evalConstCheck (α) (env : Environment) (opts : Options) (typeName : Name) (constName : Name) : ExceptT String Id α :=
match env.find? constName with
| none => throw ("unknown constant '" ++ toString constName ++ "'")
| some info =>
match info.type with
| Expr.const c _ =>
if c != typeName then throwUnexpectedType typeName constName
else env.evalConst α opts constName
| _ => throwUnexpectedType typeName constName
def hasUnsafe (env : Environment) (e : Expr) : Bool :=
let c? := e.find? fun e => match e with
| Expr.const c _ =>
match env.find? c with
| some cinfo => cinfo.isUnsafe
| none => false
| _ => false;
c?.isSome
end Environment
namespace Kernel
/-! # Kernel API -/
/--
Kernel isDefEq predicate. We use it mainly for debugging purposes.
Recall that the Kernel type checker does not support metavariables.
When implementing automation, consider using the `MetaM` methods. -/
@[extern "lean_kernel_is_def_eq"]
opaque isDefEq (env : Environment) (lctx : LocalContext) (a b : Expr) : Except KernelException Bool
def isDefEqGuarded (env : Environment) (lctx : LocalContext) (a b : Expr) : Bool :=
if let .ok result := isDefEq env lctx a b then result else false
/--
Kernel WHNF function. We use it mainly for debugging purposes.
Recall that the Kernel type checker does not support metavariables.
When implementing automation, consider using the `MetaM` methods. -/
@[extern "lean_kernel_whnf"]
opaque whnf (env : Environment) (lctx : LocalContext) (a : Expr) : Except KernelException Expr
end Kernel
class MonadEnv (m : Type → Type) where
getEnv : m Environment
modifyEnv : (Environment → Environment) → m Unit
export MonadEnv (getEnv modifyEnv)
@[always_inline]
instance (m n) [MonadLift m n] [MonadEnv m] : MonadEnv n where
getEnv := liftM (getEnv : m Environment)
modifyEnv := fun f => liftM (modifyEnv f : m Unit)
end Lean
|
3850141ed4565086c6d456ba02e15fd500e6ed25 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/nat_add_assoc_no_axioms.lean | 1ea67e4f1b98dd667760480947804cd31e03c435 | [
"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 | 28 | lean | #print axioms nat.add_assoc
|
7778a83c218cdb5bb69a513b3f151a7d0d791d09 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/normed_space/enorm.lean | 5326b4c7d872929a6dc45d71e7a2d4a929065a2b | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 7,853 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import analysis.normed_space.basic
/-!
# Extended norm
In this file we define a structure `enorm 𝕜 V` representing an extended norm (i.e., a norm that can
take the value `∞`) on a vector space `V` over a normed field `𝕜`. We do not use `class` for
an `enorm` because the same space can have more than one extended norm. For example, the space of
measurable functions `f : α → ℝ` has a family of `L_p` extended norms.
We prove some basic inequalities, then define
* `emetric_space` structure on `V` corresponding to `e : enorm 𝕜 V`;
* the subspace of vectors with finite norm, called `e.finite_subspace`;
* a `normed_space` structure on this space.
The last definition is an instance because the type involves `e`.
## Implementation notes
We do not define extended normed groups. They can be added to the chain once someone will need them.
## Tags
normed space, extended norm
-/
noncomputable theory
local attribute [instance, priority 1001] classical.prop_decidable
open_locale ennreal
/-- Extended norm on a vector space. As in the case of normed spaces, we require only
`‖c • x‖ ≤ ‖c‖ * ‖x‖` in the definition, then prove an equality in `map_smul`. -/
structure enorm (𝕜 : Type*) (V : Type*) [normed_field 𝕜] [add_comm_group V] [module 𝕜 V] :=
(to_fun : V → ℝ≥0∞)
(eq_zero' : ∀ x, to_fun x = 0 → x = 0)
(map_add_le' : ∀ x y : V, to_fun (x + y) ≤ to_fun x + to_fun y)
(map_smul_le' : ∀ (c : 𝕜) (x : V), to_fun (c • x) ≤ ‖c‖₊ * to_fun x)
namespace enorm
variables {𝕜 : Type*} {V : Type*} [normed_field 𝕜] [add_comm_group V] [module 𝕜 V]
(e : enorm 𝕜 V)
instance : has_coe_to_fun (enorm 𝕜 V) (λ _, V → ℝ≥0∞) := ⟨enorm.to_fun⟩
lemma coe_fn_injective : function.injective (coe_fn : enorm 𝕜 V → (V → ℝ≥0∞)) :=
λ e₁ e₂ h, by cases e₁; cases e₂; congr; exact h
@[ext] lemma ext {e₁ e₂ : enorm 𝕜 V} (h : ∀ x, e₁ x = e₂ x) : e₁ = e₂ :=
coe_fn_injective $ funext h
lemma ext_iff {e₁ e₂ : enorm 𝕜 V} : e₁ = e₂ ↔ ∀ x, e₁ x = e₂ x :=
⟨λ h x, h ▸ rfl, ext⟩
@[simp, norm_cast] lemma coe_inj {e₁ e₂ : enorm 𝕜 V} : (e₁ : V → ℝ≥0∞) = e₂ ↔ e₁ = e₂ :=
coe_fn_injective.eq_iff
@[simp] lemma map_smul (c : 𝕜) (x : V) : e (c • x) = ‖c‖₊ * e x :=
le_antisymm (e.map_smul_le' c x) $
begin
by_cases hc : c = 0, { simp [hc] },
calc (‖c‖₊ : ℝ≥0∞) * e x = ‖c‖₊ * e (c⁻¹ • c • x) : by rw [inv_smul_smul₀ hc]
... ≤ ‖c‖₊ * (‖c⁻¹‖₊ * e (c • x)) : _
... = e (c • x) : _,
{ exact ennreal.mul_le_mul le_rfl (e.map_smul_le' _ _) },
{ rw [← mul_assoc, nnnorm_inv, ennreal.coe_inv,
ennreal.mul_inv_cancel _ ennreal.coe_ne_top, one_mul]; simp [hc] }
end
@[simp] lemma map_zero : e 0 = 0 :=
by { rw [← zero_smul 𝕜 (0:V), e.map_smul], norm_num }
@[simp] lemma eq_zero_iff {x : V} : e x = 0 ↔ x = 0 :=
⟨e.eq_zero' x, λ h, h.symm ▸ e.map_zero⟩
@[simp] lemma map_neg (x : V) : e (-x) = e x :=
calc e (-x) = ‖(-1 : 𝕜)‖₊ * e x : by rw [← map_smul, neg_one_smul]
... = e x : by simp
lemma map_sub_rev (x y : V) : e (x - y) = e (y - x) :=
by rw [← neg_sub, e.map_neg]
lemma map_add_le (x y : V) : e (x + y) ≤ e x + e y := e.map_add_le' x y
lemma map_sub_le (x y : V) : e (x - y) ≤ e x + e y :=
calc e (x - y) = e (x + -y) : by rw sub_eq_add_neg
... ≤ e x + e (-y) : e.map_add_le x (-y)
... = e x + e y : by rw [e.map_neg]
instance : partial_order (enorm 𝕜 V) :=
{ le := λ e₁ e₂, ∀ x, e₁ x ≤ e₂ x,
le_refl := λ e x, le_rfl,
le_trans := λ e₁ e₂ e₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x),
le_antisymm := λ e₁ e₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x) }
/-- The `enorm` sending each non-zero vector to infinity. -/
noncomputable instance : has_top (enorm 𝕜 V) :=
⟨{ to_fun := λ x, if x = 0 then 0 else ⊤,
eq_zero' := λ x, by { split_ifs; simp [*] },
map_add_le' := λ x y,
begin
split_ifs with hxy hx hy hy hx hy hy; try { simp [*] },
simpa [hx, hy] using hxy
end,
map_smul_le' := λ c x,
begin
split_ifs with hcx hx hx; simp only [smul_eq_zero, not_or_distrib] at hcx,
{ simp only [mul_zero, le_refl] },
{ have : c = 0, by tauto,
simp [this] },
{ tauto },
{ simp [hcx.1] }
end }⟩
noncomputable instance : inhabited (enorm 𝕜 V) := ⟨⊤⟩
lemma top_map {x : V} (hx : x ≠ 0) : (⊤ : enorm 𝕜 V) x = ⊤ := if_neg hx
noncomputable instance : order_top (enorm 𝕜 V) :=
{ top := ⊤,
le_top := λ e x, if h : x = 0 then by simp [h] else by simp [top_map h] }
noncomputable instance : semilattice_sup (enorm 𝕜 V) :=
{ le := (≤),
lt := (<),
sup := λ e₁ e₂,
{ to_fun := λ x, max (e₁ x) (e₂ x),
eq_zero' := λ x h, e₁.eq_zero_iff.1 (ennreal.max_eq_zero_iff.1 h).1,
map_add_le' := λ x y, max_le
(le_trans (e₁.map_add_le _ _) $ add_le_add (le_max_left _ _) (le_max_left _ _))
(le_trans (e₂.map_add_le _ _) $ add_le_add (le_max_right _ _) (le_max_right _ _)),
map_smul_le' := λ c x, le_of_eq $ by simp only [map_smul, ennreal.mul_max] },
le_sup_left := λ e₁ e₂ x, le_max_left _ _,
le_sup_right := λ e₁ e₂ x, le_max_right _ _,
sup_le := λ e₁ e₂ e₃ h₁ h₂ x, max_le (h₁ x) (h₂ x),
.. enorm.partial_order }
@[simp, norm_cast] lemma coe_max (e₁ e₂ : enorm 𝕜 V) : ⇑(e₁ ⊔ e₂) = λ x, max (e₁ x) (e₂ x) := rfl
@[norm_cast]
lemma max_map (e₁ e₂ : enorm 𝕜 V) (x : V) : (e₁ ⊔ e₂) x = max (e₁ x) (e₂ x) := rfl
/-- Structure of an `emetric_space` defined by an extended norm. -/
@[reducible] def emetric_space : emetric_space V :=
{ edist := λ x y, e (x - y),
edist_self := λ x, by simp,
eq_of_edist_eq_zero := λ x y, by simp [sub_eq_zero],
edist_comm := e.map_sub_rev,
edist_triangle := λ x y z,
calc e (x - z) = e ((x - y) + (y - z)) : by rw [sub_add_sub_cancel]
... ≤ e (x - y) + e (y - z) : e.map_add_le (x - y) (y - z) }
/-- The subspace of vectors with finite enorm. -/
def finite_subspace : subspace 𝕜 V :=
{ carrier := {x | e x < ⊤},
zero_mem' := by simp,
add_mem' := λ x y hx hy, lt_of_le_of_lt (e.map_add_le x y) (ennreal.add_lt_top.2 ⟨hx, hy⟩),
smul_mem' := λ c x (hx : _ < _),
calc e (c • x) = ‖c‖₊ * e x : e.map_smul c x
... < ⊤ : ennreal.mul_lt_top ennreal.coe_ne_top hx.ne }
/-- Metric space structure on `e.finite_subspace`. We use `emetric_space.to_metric_space`
to ensure that this definition agrees with `e.emetric_space`. -/
instance : metric_space e.finite_subspace :=
begin
letI := e.emetric_space,
refine emetric_space.to_metric_space (λ x y, _),
change e (x - y) ≠ ⊤,
exact ne_top_of_le_ne_top (ennreal.add_lt_top.2 ⟨x.2, y.2⟩).ne (e.map_sub_le x y)
end
lemma finite_dist_eq (x y : e.finite_subspace) : dist x y = (e (x - y)).to_real := rfl
lemma finite_edist_eq (x y : e.finite_subspace) : edist x y = e (x - y) := rfl
/-- Normed group instance on `e.finite_subspace`. -/
instance : normed_add_comm_group e.finite_subspace :=
{ norm := λ x, (e x).to_real,
dist_eq := λ x y, rfl,
.. finite_subspace.metric_space e, .. submodule.add_comm_group _ }
lemma finite_norm_eq (x : e.finite_subspace) : ‖x‖ = (e x).to_real := rfl
/-- Normed space instance on `e.finite_subspace`. -/
instance : normed_space 𝕜 e.finite_subspace :=
{ norm_smul_le := λ c x, le_of_eq $ by simp [finite_norm_eq, ennreal.to_real_mul] }
end enorm
|
7e5096d4880bec61022a90830baad8a97aa05727 | 19e80d9dcdc050ba32a44257170460f6eb2f174b | /examples.lean | 294a54cbdefcd6e0fbbc9b750e4eaa5546d2208b | [] | no_license | petersonbill64/lean | d36d7d93d0f1e4e5618f1426d41567e33a0da6fc | 07b7b69e15785c75ebba6629be4fad92799fd7de | refs/heads/master | 1,609,627,927,456 | 1,438,537,533,000 | 1,438,537,533,000 | 40,084,227 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 142 | lean | import theories.number_theory.bezout
import data.nat.gcd
open nat
theorem thm2 (a b : ℕ) : a + b = b + a := add.comm _ _
|
236040fdb5b55db5cd202425fa25ab17c862e8ff | 7282d49021d38dacd06c4ce45a48d09627687fe0 | /tests/lean/simp20.lean | f400ea93ce26dcb67c936a1f6dcdf3ac5201c005 | [
"Apache-2.0"
] | permissive | steveluc/lean | 5a0b4431acefaf77f15b25bbb49294c2449923ad | 92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496 | refs/heads/master | 1,611,332,256,930 | 1,391,013,244,000 | 1,391,013,244,000 | 16,361,079 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 332 | lean | import cast
rewrite_set simple
set_option pp::implicit true
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))
*) |
7a5c16f3fb555af0069e39d30b2b38e6f81eb4c8 | ea916b7f42baf59c02ca82e274a87b3e45397968 | /src/super/prover.lean | 58321ef881afc561adcab4946ffd0959c4c20cf6 | [] | no_license | robertylewis/super2 | 2926383b166e43ebd815b81ae8fba976393a160c | 8ba522fd609d25752cd3d9b478bc48b6453e3c1e | refs/heads/master | 1,670,062,676,962 | 1,597,795,530,000 | 1,597,795,530,000 | 289,744,671 | 0 | 0 | null | 1,598,207,476,000 | 1,598,207,476,000 | null | UTF-8 | Lean | false | false | 7,650 | lean | import super.prover_state super.selection
super.inferences.distinct super.inferences.resolution
super.inferences.clausify super.inferences.empty_clause
super.inferences.subsumption super.inferences.superposition
super.inferences.factoring super.inferences.inhabited
super.inferences.demod
super.eqn_lemmas
namespace super
open native tactic
meta def default_preprocessing_rules : list preprocessing_rule :=
[ preprocessing.empty_clause,
preprocessing.clausify,
preprocessing.distinct,
preprocessing.inhabited,
preprocessing.pos_refl,
preprocessing.neg_refl,
preprocessing.flip_eq,
preprocessing.distinct,
preprocessing.subsumption_interreduction
-- preprocessing.forward_subsumption,
]
meta def default_simplification_rules : list simplification_rule :=
[ simplification.forward_demod,
simplification.pos_refl,
simplification.neg_refl,
simplification.forward_subsumption ]
meta def default_inference_rules : list inference_rule :=
[ inference.backward_subsumption,
inference.backward_demod,
inference.resolution,
inference.factoring,
inference.forward_superposition,
inference.backward_superposition,
inference.unify_eq ]
meta structure options :=
(literal_selection : literal_selection_strategy := selection21)
(clause_selection : clause_selection_strategy := age_weight_clause_selection 3 4)
(simpl_rules : list simplification_rule := default_simplification_rules)
(inf_rules : list inference_rule := default_inference_rules)
(preproc_rules : list preprocessing_rule := default_preprocessing_rules)
meta def do_simplification (opts : options)
(given : derived_clause) : prover (option derived_clause) := do
cls : option clause ← opts.simpl_rules.mfoldl (λ cls sr,
match (cls : option clause) with
| some cls := sr cls
| none := pure none
end) (some given.cls),
pure $ cls.map $ λ cls, { cls := cls, ..given }
meta def do_preprocessing (opts : options) : list clause → prover (list clause) | newly_derived := do
newly_derived ← opts.preproc_rules.mfoldl (λ cls pr, pr cls) newly_derived,
if ¬ newly_derived.existsb (λ c : clause, c.ty.literals = []) then
pure newly_derived
else do
newly_derived ← preprocessing.empty_clause newly_derived,
if ¬ newly_derived.existsb (λ c : clause, c.ty.literals = []) then
do_preprocessing newly_derived
else
pure newly_derived
declare_trace super
meta def main_loop (opts : options) : list clause → ℕ → prover (option expr) | newly_derived n := do
newly_derived ← do_preprocessing opts newly_derived,
let derived_empty_clauses := newly_derived.filter (λ c, c.ty.literals = []),
match derived_empty_clauses with
| (c::_) := do
c ← c.instantiate_mvars,
c.check,
prf ← unfold_defs c.prf,
type_check prf,
state_t.lift $ infer_type prf >>= is_def_eq `(false),
pure prf
| _ := do
newly_derived.mmap' (add_passive opts.literal_selection),
passive_size ← rb_map.size <$> get_passive,
if passive_size = 0 then
do act ← get_active, tactic.trace act.values,
pure none -- saturation
else do
given_id ← opts.clause_selection n,
given ← consume_passive given_id,
given ← do_simplification opts given,
match given with
| none := main_loop [] (n+1)
| some given := do
if given.cls.literals = [] then main_loop [given.cls] (n+1) else do
when (is_trace_enabled_for `super)
(do act ← get_active,
given ← pp given,
trace $ "[a=" ++ to_string act.size ++
",p=" ++ to_string passive_size ++
"] " ++ to_string given),
given.cls.check,
given ← intern_derived given,
add_active given,
given' ← given.clone,
newly_derived ← list.join <$> opts.inf_rules.mmap (λ ir, ir given'),
main_loop newly_derived (n+1)
end
end
meta def main (opts : options) (initial : list clause) : tactic (option expr) := do
initial ← initial.mmap clause.clone, -- work around local context restriction
prod.fst <$> state_t.run (main_loop opts initial 0) prover_state.initial
meta def with_ground_mvars {α} (tac : tactic α) : tactic α := do
reverted_goal ← tactic.retrieve (unfreeze_local_instances >> revert_all >> target),
reverted_goal ← instantiate_mvars reverted_goal,
mvars ← reverted_goal.sorted_mvars,
lcs ← mk_locals_core mvars,
let univ_mvars := (reverted_goal.mk_app lcs).univ_meta_vars.to_list,
ups ← univ_mvars.mmap (λ _, mk_fresh_name),
(goal::goals) ← get_goals,
(res, proof) ← tactic.retrieve (do
(mvars.zip lcs).mmap' (λ ⟨m, lc⟩, unify m lc),
(univ_mvars.zip ups).mmap (λ ⟨m, up⟩, unify_level (level.mvar m) (level.param up)),
set_goals [goal],
instantiate_mvars_in_target,
res ← tac,
done,
proof ← instantiate_mvars goal,
pure (res, proof)),
let proof := (proof.abstract_locals (lcs.map expr.local_uniq_name)).instantiate_vars mvars,
let proof := proof.instantiate_univ_params
((ups.zip univ_mvars).map (λ ⟨up, m⟩, (up, level.mvar m))),
exact proof,
pure res
meta def solve (opts : options) (initial : list clause) : tactic unit := do
some empty_clause ← main opts initial | fail "saturation",
(target >>= is_def_eq `(false)) <|> exfalso,
exact empty_clause
meta def intros' : tactic (list expr) :=
(do x ← intro_core `_, xs ← intros', pure (x::xs)) <|> pure []
noncomputable lemma {u} super_contradiction {α : Sort u} (h : (α → false) → false) : α :=
match classical.type_decidable α with
| psum.inl a := a
| psum.inr nota := @false.rec _ (h nota)
end
meta def better_contradiction : tactic expr :=
tactic.by_contradiction <|>
(applyc ``super_contradiction >> intro1)
meta def solve_with_goal (opts : options) (initial : list clause) : tactic unit := do
classical,
hs ← intros',
tgt ← target,
hs ← if tgt = `(false) then pure hs else
(::) <$> better_contradiction <*> pure hs,
initial ← (++ initial) <$> hs.mmap clause.of_proof,
-- FIXME: happens e.g. with eq.mpr
initial ← initial.mfilter (λ c, do
is_ok ← succeeds c.check,
if is_ok then pure tt else do
trace "discarding clause, invalid type",
pure ff),
some empty_clause ← main opts initial | fail "saturation",
exact empty_clause
meta def aux_lemma_clauses_of_pexpr_name (n : name) : tactic (list clause) := do
p ← resolve_name n,
let e := p.erase_annotations.get_app_fn.erase_annotations,
match e with
| expr.const n _ := get_aux_lemma_clauses n
| _ := pure []
end
meta def aux_lemma_clauses_of_pexpr : pexpr → tactic (list clause)
| (expr.const n _) := aux_lemma_clauses_of_pexpr_name n
| (expr.local_const n _ _ _) := aux_lemma_clauses_of_pexpr_name n
| _ := pure []
meta def clauses_of_simp_arg_type : simp_arg_type → tactic (list clause)
| simp_arg_type.all_hyps := do lctx ← local_context, lctx.mmap clause.of_proof
| (simp_arg_type.except _) := fail "super [-foo] not supported"
| (simp_arg_type.symm_expr e) := clauses_of_simp_arg_type (simp_arg_type.expr e)
| (simp_arg_type.expr e) := do
eqn_lems ← aux_lemma_clauses_of_pexpr e,
cls ← tactic.retrieve (to_expr e >>= clause.of_proof >>= clause.pack) >>= packed_clause.unpack,
pure (cls :: eqn_lems)
meta def clauses_of_simp_arg_type_list (simp_args : list simp_arg_type) : tactic (list clause) :=
list.join <$> simp_args.mmap clauses_of_simp_arg_type
end super
namespace tactic.interactive
open lean.parser
open interactive
open interactive.types
open tactic
-- TODO: show unused arguments
meta def super (args : parse simp_arg_list)
(opts : super.options := {}) : tactic unit :=
_root_.super.with_ground_mvars $ do
cs ← _root_.super.clauses_of_simp_arg_type_list args,
_root_.super.solve_with_goal opts cs
end tactic.interactive
|
68eb762c9e8a25696ca30f8ba044272b8669cf38 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /hott/init/axioms/funext_of_ua.hlean | ab14fca08722bf57182a5747b2b7b2975702a45c | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,856 | hlean | /-
Copyright (c) 2014 Jakob von Raumer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: init.axioms.funext_of_ua
Author: Jakob von Raumer
Ported from Coq HoTT
-/
prelude
import ..equiv ..datatypes ..types.prod
import .funext_varieties .ua
open eq function prod is_trunc sigma equiv is_equiv unit
section
universe variables l
private theorem ua_isequiv_postcompose {A B : Type.{l}} {C : Type}
{w : A → B} [H0 : is_equiv w] : is_equiv (@compose C A B w) :=
let w' := equiv.mk w H0 in
let eqinv : A = B := ((@is_equiv.inv _ _ _ (univalence A B)) w') in
let eq' := equiv_of_eq eqinv in
is_equiv.adjointify (@compose C A B w)
(@compose C B A (is_equiv.inv w))
(λ (x : C → B),
have eqretr : eq' = w',
from (@retr _ _ (@equiv_of_eq A B) (univalence A B) w'),
have invs_eq : (to_fun eq')⁻¹ = (to_fun w')⁻¹,
from inv_eq eq' w' eqretr,
have eqfin : (to_fun eq') ∘ ((to_fun eq')⁻¹ ∘ x) = x,
from (λ p,
(@eq.rec_on Type.{l} A
(λ B' p', Π (x' : C → B'), (to_fun (equiv_of_eq p'))
∘ ((to_fun (equiv_of_eq p'))⁻¹ ∘ x') = x')
B p (λ x', idp))
) eqinv x,
have eqfin' : (to_fun w') ∘ ((to_fun eq')⁻¹ ∘ x) = x,
from eqretr ▹ eqfin,
have eqfin'' : (to_fun w') ∘ ((to_fun w')⁻¹ ∘ x) = x,
from invs_eq ▹ eqfin',
eqfin''
)
(λ (x : C → A),
have eqretr : eq' = w',
from (@retr _ _ (@equiv_of_eq A B) (univalence A B) w'),
have invs_eq : (to_fun eq')⁻¹ = (to_fun w')⁻¹,
from inv_eq eq' w' eqretr,
have eqfin : (to_fun eq')⁻¹ ∘ ((to_fun eq') ∘ x) = x,
from (λ p, eq.rec_on p idp) eqinv,
have eqfin' : (to_fun eq')⁻¹ ∘ ((to_fun w') ∘ x) = x,
from eqretr ▹ eqfin,
have eqfin'' : (to_fun w')⁻¹ ∘ ((to_fun w') ∘ x) = x,
from invs_eq ▹ eqfin',
eqfin''
)
-- We are ready to prove functional extensionality,
-- starting with the naive non-dependent version.
private definition diagonal [reducible] (B : Type) : Type
:= Σ xy : B × B, pr₁ xy = pr₂ xy
private definition isequiv_src_compose {A B : Type}
: @is_equiv (A → diagonal B)
(A → B)
(compose (pr₁ ∘ pr1)) :=
@ua_isequiv_postcompose _ _ _ (pr₁ ∘ pr1)
(is_equiv.adjointify (pr₁ ∘ pr1)
(λ x, sigma.mk (x , x) idp) (λx, idp)
(λ x, sigma.rec_on x
(λ xy, prod.rec_on xy
(λ b c p, eq.rec_on p idp))))
private definition isequiv_tgt_compose {A B : Type}
: @is_equiv (A → diagonal B)
(A → B)
(compose (pr₂ ∘ pr1)) :=
@ua_isequiv_postcompose _ _ _ (pr2 ∘ pr1)
(is_equiv.adjointify (pr2 ∘ pr1)
(λ x, sigma.mk (x , x) idp) (λx, idp)
(λ x, sigma.rec_on x
(λ xy, prod.rec_on xy
(λ b c p, eq.rec_on p idp))))
set_option class.conservative false
theorem nondep_funext_from_ua {A : Type} {B : Type}
: Π {f g : A → B}, f ∼ g → f = g :=
(λ (f g : A → B) (p : f ∼ g),
let d := λ (x : A), sigma.mk (f x , f x) idp in
let e := λ (x : A), sigma.mk (f x , g x) (p x) in
let precomp1 := compose (pr₁ ∘ pr1) in
have equiv1 [visible] : is_equiv precomp1,
from @isequiv_src_compose A B,
have equiv2 [visible] : Π x y, is_equiv (ap precomp1),
from is_equiv.is_equiv_ap precomp1,
have H' : Π (x y : A → diagonal B),
pr₁ ∘ pr1 ∘ x = pr₁ ∘ pr1 ∘ y → x = y,
from (λ x y, is_equiv.inv (ap precomp1)),
have eq2 : pr₁ ∘ pr1 ∘ d = pr₁ ∘ pr1 ∘ e,
from idp,
have eq0 : d = e,
from H' d e eq2,
have eq1 : (pr₂ ∘ pr1) ∘ d = (pr₂ ∘ pr1) ∘ e,
from ap _ eq0,
eq1
)
end
-- Now we use this to prove weak funext, which as we know
-- implies (with dependent eta) also the strong dependent funext.
theorem weak_funext_of_ua : weak_funext :=
(λ (A : Type) (P : A → Type) allcontr,
let U := (λ (x : A), unit) in
have pequiv : Π (x : A), P x ≃ U x,
from (λ x, @equiv_unit_of_is_contr (P x) (allcontr x)),
have psim : Π (x : A), P x = U x,
from (λ x, @is_equiv.inv _ _
equiv_of_eq (univalence _ _) (pequiv x)),
have p : P = U,
from @nondep_funext_from_ua A Type P U psim,
have tU' : is_contr (A → unit),
from is_contr.mk (λ x, ⋆)
(λ f, @nondep_funext_from_ua A unit (λ x, ⋆) f
(λ x, unit.rec_on (f x) idp)),
have tU : is_contr (Π x, U x),
from tU',
have tlast : is_contr (Πx, P x),
from eq.transport _ p⁻¹ tU,
tlast
)
-- In the following we will proof function extensionality using the univalence axiom
definition funext_of_ua : funext :=
funext_of_weak_funext (@weak_funext_of_ua)
variables {A : Type} {P : A → Type} {f g : Π x, P x}
namespace funext
definition is_equiv_apD [instance] (f g : Π x, P x) : is_equiv (@apD10 A P f g) :=
funext_of_ua f g
end funext
open funext
definition eq_equiv_homotopy : (f = g) ≃ (f ∼ g) :=
equiv.mk apD10 _
definition eq_of_homotopy [reducible] : f ∼ g → f = g :=
(@apD10 A P f g)⁻¹
--TODO: rename to eq_of_homotopy_idp
definition eq_of_homotopy_id (f : Π x, P x) : eq_of_homotopy (λx : A, idpath (f x)) = idpath f :=
is_equiv.sect apD10 idp
definition naive_funext_of_ua : naive_funext :=
λ A P f g h, eq_of_homotopy h
protected definition homotopy.rec_on {Q : (f ∼ g) → Type} (p : f ∼ g)
(H : Π(q : f = g), Q (apD10 q)) : Q p :=
retr apD10 p ▹ H (eq_of_homotopy p)
|
4f5fc5ffa1db8701ecf15cac524c0e99dbf12d5e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1900.lean | 8717912f2306cf1f61f33a4606e494c901c87d3c | [
"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 | 215 | lean | @[elab_as_elim]
def strongSubRecursion {P : Nat → Nat → Sort _} (H : ∀ a b, (∀ x y, x < a → y < b → P x y) → P a b) :
∀ n m : Nat, P n m
| n, m => H n m fun x y _ _ => strongSubRecursion H x y
|
dfc81379ac662f60d838e241e74406c1dc6c77d1 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/noetherian.lean | 32b36a1d65eddd2e08ad63437886e890392d7a02 | [
"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 | 37,228 | lean | /-
Copyright (c) 2018 Mario Carneiro, Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kevin Buzzard
-/
import algebraic_geometry.prime_spectrum
import data.multiset.finset_ops
import linear_algebra.linear_independent
import order.order_iso_nat
import order.compactly_generated
import ring_theory.ideal.operations
import group_theory.finiteness
/-!
# Noetherian rings and modules
The following are equivalent for a module M over a ring R:
1. Every increasing chain of submodules M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises.
2. Every submodule is finitely generated.
A module satisfying these equivalent conditions is said to be a *Noetherian* R-module.
A ring is a *Noetherian ring* if it is Noetherian as a module over itself.
(Note that we do not assume yet that our rings are commutative,
so perhaps this should be called "left Noetherian".
To avoid cumbersome names once we specialize to the commutative case,
we don't make this explicit in the declaration names.)
## Main definitions
Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`.
* `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module.
* `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class,
implemented as the predicate that all `R`-submodules of `M` are finitely generated.
## Main statements
* `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form:
if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R
such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0.
* `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff
`>` is well-founded on `submodule R M`.
Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X],
is proved in `ring_theory.polynomial`.
## References
* [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald]
* [samuel]
## Tags
Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module
-/
open set
open_locale big_operators pointwise
namespace submodule
variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M]
/-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/
def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N
theorem fg_def {N : submodule R M} :
N.fg ↔ ∃ S : set M, finite S ∧ span R S = N :=
⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin
rintro ⟨t', h, rfl⟩,
rcases finite.exists_finset_coe h with ⟨t, rfl⟩,
exact ⟨t, rfl⟩
end⟩
lemma fg_iff_add_submonoid_fg (P : submodule ℕ M) :
P.fg ↔ P.to_add_submonoid.fg :=
⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩,
λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩⟩
lemma fg_iff_add_subgroup_fg {G : Type*} [add_comm_group G] (P : submodule ℤ G) :
P.fg ↔ P.to_add_subgroup.fg :=
⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩,
λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩⟩
lemma fg_iff_exists_fin_generating_family {N : submodule R M} :
N.fg ↔ ∃ (n : ℕ) (s : fin n → M), span R (range s) = N :=
begin
rw fg_def,
split,
{ rintros ⟨S, Sfin, hS⟩,
obtain ⟨n, f, rfl⟩ := Sfin.fin_embedding,
exact ⟨n, f, hS⟩, },
{ rintros ⟨n, s, hs⟩,
refine ⟨range s, finite_range s, hs⟩ },
end
/-- **Nakayama's Lemma**. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2,
[Stacks 00DV](https://stacks.math.columbia.edu/tag/00DV) -/
theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R]
{M : Type*} [add_comm_group M] [module R M]
(I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) :
∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) :=
begin
rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩,
have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N,
{ refine ⟨1, _, _, _⟩,
{ rw sub_self, exact I.zero_mem },
{ rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn },
{ rw [← span_le, hs], exact le_refl N } },
clear hin hs, revert this,
refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _),
{ rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn,
rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn },
apply ih, rcases H with ⟨r, hr1, hrn, hs⟩,
rw [← set.singleton_union, span_union, smul_sup] at hrn,
rw [set.insert_subset] at hs,
have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s,
{ specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn,
rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz,
rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩,
use r-c, split,
{ rw [sub_right_comm], exact I.sub_mem hr1 hci },
{ rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } },
rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩,
{ rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢,
rw [ring_hom.map_mul, hc1, hr1, mul_one] },
{ intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn,
rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz,
rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩,
change _ • _ ∈ I • span R s,
rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul],
exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) }
end
theorem fg_bot : (⊥ : submodule R M).fg :=
⟨∅, by rw [finset.coe_empty, span_empty]⟩
theorem fg_span {s : set M} (hs : finite s) : fg (span R s) :=
⟨hs.to_finset, by rw [hs.coe_to_finset]⟩
theorem fg_span_singleton (x : M) : fg (R ∙ x) :=
fg_span (finite_singleton x)
theorem fg_sup {N₁ N₂ : submodule R M}
(hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg :=
let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in
fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩
variables {P : Type*} [add_comm_monoid P] [module R P]
variables {f : M →ₗ[R] P}
theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg :=
let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩
lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M]
[add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M}
(hfn : (N.map f).fg) : N.fg :=
let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, linear_map.ker_eq_bot.1 hf h,
linear_map.map_injective hf $ by { rw [f.map_span, finset.coe_preimage,
set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht],
rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩
lemma fg_top {R M : Type*} [ring R] [add_comm_group M] [module R M]
(N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg :=
⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ fg_map h,
λ h, fg_of_fg_map N.subtype N.ker_subtype $ by rwa [map_top, range_subtype]⟩
lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) :
(⊤ : submodule R M).fg :=
e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ fg_map h
theorem fg_prod {sb : submodule R M} {sc : submodule R P}
(hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg :=
let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in
fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc,
(htb.1.image _).union (htc.1.image _),
by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩
/-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are
finitely generated then so is M. -/
theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M]
[add_comm_group P] [module R P] (f : M →ₗ[R] P)
{s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg :=
begin
haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P,
cases hs1 with t1 ht1, cases hs2 with t2 ht2,
have : ∀ y ∈ t1, ∃ x ∈ s, f x = y,
{ intros y hy,
have : y ∈ map f s, { rw ← ht1, exact subset_span hy },
rcases mem_map.1 this with ⟨x, hx1, hx2⟩,
exact ⟨x, hx1, hx2⟩ },
have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y,
{ choose g hg1 hg2,
existsi λ y, if H : y ∈ t1 then g y H else 0,
intros y H, split,
{ simp only [dif_pos H], apply hg1 },
{ simp only [dif_pos H], apply hg2 } },
cases this with g hg, clear this,
existsi t1.image g ∪ t2,
rw [finset.coe_union, span_union, finset.coe_image],
apply le_antisymm,
{ refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _),
{ intros y hy, exact (hg y hy).1 },
{ intros x hx, have := subset_span hx,
rw ht2 at this,
exact this.1 } },
intros x hx,
have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ },
rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_image_iff_total] at this,
rcases this with ⟨l, hl1, hl2⟩,
refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun
((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _,
x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l),
_, add_sub_cancel'_right _ _⟩,
{ rw [← set.image_id (g '' ↑t1), finsupp.mem_span_image_iff_total], refine ⟨_, _, rfl⟩,
haveI : inhabited P := ⟨0⟩,
rw [← finsupp.lmap_domain_supported _ _ g, mem_map],
refine ⟨l, hl1, _⟩,
refl, },
rw [ht2, mem_inf], split,
{ apply s.sub_mem hx,
rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index],
refine s.sum_mem _,
{ intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 },
{ exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } },
{ rw [linear_map.mem_ker, f.map_sub, ← hl2],
rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply],
rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum],
rw sub_eq_zero,
refine finset.sum_congr rfl (λ y hy, _),
unfold id,
rw [f.map_smul, (hg y (hl1 hy)).2],
{ exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }
end
/-- The image of a finitely generated ideal is finitely generated. -/
lemma map_fg_of_fg {R S : Type*} [comm_ring R] [comm_ring S] (I : ideal R) (h : I.fg) (f : R →+* S)
: (I.map f).fg :=
begin
obtain ⟨X, hXfin, hXgen⟩ := fg_def.1 h,
apply fg_def.2,
refine ⟨set.image f X, finite.image ⇑f hXfin, _⟩,
rw [ideal.map, ideal.span, ← hXgen],
refine le_antisymm (submodule.span_mono (image_subset _ ideal.subset_span)) _,
rw [submodule.span_le, image_subset_iff],
intros i hi,
refine submodule.span_induction hi (λ x hx, _) _ (λ x y hx hy, _) (λ r x hx, _),
{ simp only [set_like.mem_coe, mem_preimage],
suffices : f x ∈ f '' X, { exact ideal.subset_span this },
exact mem_image_of_mem ⇑f hx },
{ simp only [set_like.mem_coe, ring_hom.map_zero, mem_preimage, zero_mem] },
{ simp only [set_like.mem_coe, mem_preimage] at hx hy,
simp only [ring_hom.map_add, set_like.mem_coe, mem_preimage],
exact submodule.add_mem _ hx hy },
{ simp only [set_like.mem_coe, mem_preimage] at hx,
simp only [algebra.id.smul_eq_mul, set_like.mem_coe, mem_preimage, ring_hom.map_mul],
exact submodule.smul_mem _ _ hx }
end
/-- The kernel of the composition of two linear maps is finitely generated if both kernels are and
the first morphism is surjective. -/
lemma fg_ker_comp {R M N P : Type*} [ring R] [add_comm_group M] [module R M]
[add_comm_group N] [module R N] [add_comm_group P] [module R P] (f : M →ₗ[R] N)
(g : N →ₗ[R] P) (hf1 : f.ker.fg) (hf2 : g.ker.fg) (hsur : function.surjective f) :
(g.comp f).ker.fg :=
begin
rw linear_map.ker_comp,
apply fg_of_fg_map_of_fg_inf_ker f,
{ rwa [submodule.map_comap_eq, linear_map.range_eq_top.2 hsur, top_inf_eq] },
{ rwa [inf_of_le_right (show f.ker ≤ (comap f g.ker), from comap_mono (@bot_le _ _ g.ker))] }
end
lemma fg_restrict_scalars {R S M : Type*} [comm_ring R] [comm_ring S] [algebra R S]
[add_comm_group M] [module S M] [module R M] [is_scalar_tower R S M] (N : submodule S M)
(hfin : N.fg) (h : function.surjective (algebra_map R S)) : (submodule.restrict_scalars R N).fg :=
begin
obtain ⟨X, rfl⟩ := hfin,
use X,
exact submodule.span_eq_restrict_scalars R S M X h
end
lemma fg_ker_ring_hom_comp {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A]
(f : R →+* S) (g : S →+* A) (hf : f.ker.fg) (hg : g.ker.fg) (hsur : function.surjective f) :
(g.comp f).ker.fg :=
begin
letI : algebra R S := ring_hom.to_algebra f,
letI : algebra R A := ring_hom.to_algebra (g.comp f),
letI : algebra S A := ring_hom.to_algebra g,
letI : is_scalar_tower R S A := is_scalar_tower.of_algebra_map_eq (λ _, rfl),
let f₁ := algebra.linear_map R S,
let g₁ := (is_scalar_tower.to_alg_hom R S A).to_linear_map,
exact fg_ker_comp f₁ g₁ hf (fg_restrict_scalars g.ker hg hsur) hsur
end
/-- Finitely generated submodules are precisely compact elements in the submodule lattice. -/
theorem fg_iff_compact (s : submodule R M) : s.fg ↔ complete_lattice.is_compact_element s :=
begin
classical,
-- Introduce shorthand for span of an element
let sp : M → submodule R M := λ a, span R {a},
-- Trivial rewrite lemma; a small hack since simp (only) & rw can't accomplish this smoothly.
have supr_rw : ∀ t : finset M, (⨆ x ∈ t, sp x) = (⨆ x ∈ (↑t : set M), sp x), from λ t, by refl,
split,
{ rintro ⟨t, rfl⟩,
rw [span_eq_supr_of_singleton_spans, ←supr_rw, ←(finset.sup_eq_supr t sp)],
apply complete_lattice.finset_sup_compact_of_compact,
exact λ n _, singleton_span_is_compact_element n, },
{ intro h,
-- s is the Sup of the spans of its elements.
have sSup : s = Sup (sp '' ↑s),
by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, eq_comm, span_eq],
-- by h, s is then below (and equal to) the sup of the spans of finitely many elements.
obtain ⟨u, ⟨huspan, husup⟩⟩ := h (sp '' ↑s) (le_of_eq sSup),
have ssup : s = u.sup id,
{ suffices : u.sup id ≤ s, from le_antisymm husup this,
rw [sSup, finset.sup_id_eq_Sup], exact Sup_le_Sup huspan, },
obtain ⟨t, ⟨hts, rfl⟩⟩ := finset.subset_image_iff.mp huspan,
rw [finset.sup_finset_image, function.comp.left_id, finset.sup_eq_supr, supr_rw,
←span_eq_supr_of_singleton_spans, eq_comm] at ssup,
exact ⟨t, ssup⟩, },
end
end submodule
/--
`is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module,
implemented as the predicate that all `R`-submodules of `M` are finitely generated.
-/
class is_noetherian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop :=
(noetherian : ∀ (s : submodule R M), s.fg)
section
variables {R : Type*} {M : Type*} {P : Type*}
variables [ring R] [add_comm_group M] [add_comm_group P]
variables [module R M] [module R P]
open is_noetherian
include R
/-- An R-module is Noetherian iff all its submodules are finitely-generated. -/
lemma is_noetherian_def : is_noetherian R M ↔ ∀ (s : submodule R M), s.fg :=
⟨λ h, h.noetherian, is_noetherian.mk⟩
theorem is_noetherian_submodule {N : submodule R M} :
is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg :=
⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs,
submodule.map_comap_eq_self this ▸ submodule.fg_map (hn _),
λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $
by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩
theorem is_noetherian_submodule_left {N : submodule R M} :
is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg :=
is_noetherian_submodule.trans
⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩
theorem is_noetherian_submodule_right {N : submodule R M} :
is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg :=
is_noetherian_submodule.trans
⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩
instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N :=
is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _
lemma is_noetherian_of_le {s t : submodule R M} [ht : is_noetherian R t]
(h : s ≤ t) : is_noetherian R s :=
is_noetherian_submodule.mpr (λ s' hs', is_noetherian_submodule.mp ht _ (le_trans hs' h))
variable (M)
theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤)
[is_noetherian R M] : is_noetherian R P :=
⟨λ s, have (s.comap f).map f = s, from submodule.map_comap_eq_self $ hf.symm ▸ le_top,
this ▸ submodule.fg_map $ noetherian _⟩
variable {M}
theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P)
[is_noetherian R M] : is_noetherian R P :=
is_noetherian_of_surjective _ f.to_linear_map f.range
lemma is_noetherian_top_iff :
is_noetherian R (⊤ : submodule R M) ↔ is_noetherian R M :=
begin
unfreezingI { split; assume h },
{ exact is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) },
{ exact is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl).symm },
end
lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) :
is_noetherian R M :=
is_noetherian_of_linear_equiv (linear_equiv.of_injective f $ linear_map.ker_eq_bot.mp hf).symm
lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) :
N.fg :=
@@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N
instance is_noetherian_prod [is_noetherian R M]
[is_noetherian R P] : is_noetherian R (M × P) :=
⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $
have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P),
from λ x ⟨hx1, hx2⟩, ⟨x.1, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩,
submodule.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩
instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R]
[Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι]
[∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) :=
begin
haveI := classical.dec_eq ι,
suffices on_finset : ∀ s : finset ι, is_noetherian R (Π i : s, M i),
{ let coe_e := equiv.subtype_univ_equiv finset.mem_univ,
letI : is_noetherian R (Π i : finset.univ, M (coe_e i)) := on_finset finset.univ,
exact is_noetherian_of_linear_equiv (linear_equiv.Pi_congr_left R M coe_e), },
intro s,
induction s using finset.induction with a s has ih,
{ split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2,
intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 },
refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _
_ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih),
fconstructor,
{ exact λ f i, or.by_cases (finset.mem_insert.1 i.2)
(λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1))
(λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) },
{ intros f g, ext i, unfold or.by_cases, cases i with i hi,
rcases finset.mem_insert.1 hi with rfl | h,
{ change _ = _ + _, simp only [dif_pos], refl },
{ change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h },
simp only [dif_neg this, dif_pos h], refl } },
{ intros c f, ext i, unfold or.by_cases, cases i with i hi,
rcases finset.mem_insert.1 hi with rfl | h,
{ change _ = c • _, simp only [dif_pos], refl },
{ change _ = c • _, have : ¬i = a, { rintro rfl, exact has h },
simp only [dif_neg this, dif_pos h], refl } },
{ exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) },
{ intro f, apply prod.ext,
{ simp only [or.by_cases, dif_pos] },
{ ext ⟨i, his⟩,
have : ¬i = a, { rintro rfl, exact has his },
dsimp only [or.by_cases], change i ∈ s at his,
rw [dif_neg this, dif_pos his] } },
{ intro f, ext ⟨i, hi⟩,
rcases finset.mem_insert.1 hi with rfl | h,
{ simp only [or.by_cases, dif_pos], },
{ have : ¬i = a, { rintro rfl, exact has h },
simp only [or.by_cases, dif_neg this, dif_pos h], } }
end
/-- A version of `is_noetherian_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_noetherian_pi' {R ι M : Type*} [ring R] [add_comm_group M] [module R M] [fintype ι]
[is_noetherian R M] : is_noetherian R (ι → M) :=
is_noetherian_pi
end
open is_noetherian submodule function
section
universe w
variables {R M P : Type*} {N : Type w} [ring R] [add_comm_group M] [module R M]
[add_comm_group N] [module R N] [add_comm_group P] [module R P]
theorem is_noetherian_iff_well_founded :
is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) :=
begin
rw (complete_lattice.well_founded_characterisations $ submodule R M).out 0 3,
exact ⟨λ ⟨h⟩, λ k, (fg_iff_compact k).mp (h k), λ h, ⟨λ k, (fg_iff_compact k).mpr (h k)⟩⟩,
end
variables (R M)
lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] :
∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) :=
is_noetherian_iff_well_founded.mp
variables {R M}
lemma finite_of_linear_independent [nontrivial R] [is_noetherian 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_gt R M)).elim' _),
have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩,
have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s,
{ rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 },
have : ∀ a b : ℕ, a ≤ b ↔
span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}),
{ assume a b,
rw [span_le_span_iff hs (this a) (this b),
set.image_subset_image_iff (subtype.coe_injective.comp f.injective),
set.subset_def],
exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ },
exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}),
λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩,
by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩
end
/-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them.
-/
theorem set_has_maximal_iff_noetherian :
(∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔
is_noetherian R M :=
by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max']
/-- A module is Noetherian iff every increasing chain of submodules stabilizes. -/
theorem monotone_stabilizes_iff_noetherian :
(∀ (f : ℕ →ₘ submodule R M), ∃ n, ∀ m, n ≤ m → f n = f m)
↔ is_noetherian R M :=
by rw [is_noetherian_iff_well_founded, well_founded.monotone_chain_condition]
/-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/
lemma is_noetherian.induction [is_noetherian R M] {P : submodule R M → Prop}
(hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I :=
well_founded.recursion (well_founded_submodule_gt R M) I hgt
/-- If the first and final modules in a short exact sequence are noetherian,
then the middle module is also noetherian. -/
theorem is_noetherian_of_range_eq_ker
[is_noetherian R M] [is_noetherian R P]
(f : M →ₗ[R] N) (g : N →ₗ[R] P)
(hf : function.injective f)
(hg : function.surjective g)
(h : f.range = g.ker) :
is_noetherian R N :=
is_noetherian_iff_well_founded.2 $
well_founded_gt_exact_sequence
(well_founded_submodule_gt R M)
(well_founded_submodule_gt R P)
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])
/--
For any endomorphism of a Noetherian module, there is some nontrivial iterate
with disjoint kernel and range.
-/
theorem is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot
[I : is_noetherian R M] (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊓ (f ^ n).range = ⊥ :=
begin
obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I
(f.iterate_ker.comp ⟨λ n, n+1, λ n m w, by linarith⟩),
specialize w (2 * n + 1) (by linarith),
dsimp at w,
refine ⟨n+1, nat.succ_ne_zero _, _⟩,
rw eq_bot_iff,
rintros - ⟨h, ⟨y, rfl⟩⟩,
rw [mem_bot, ←linear_map.mem_ker, w],
erw linear_map.mem_ker at h ⊢,
change ((f ^ (n + 1)) * (f ^ (n + 1))) y = 0 at h,
rw ←pow_add at h,
convert h using 3,
linarith,
end
/-- Any surjective endomorphism of a Noetherian module is injective. -/
theorem is_noetherian.injective_of_surjective_endomorphism [is_noetherian R M]
(f : M →ₗ[R] M) (s : surjective f) : injective f :=
begin
obtain ⟨n, ne, w⟩ := is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot f,
rw [linear_map.range_eq_top.mpr (linear_map.iterate_surjective s n), inf_top_eq,
linear_map.ker_eq_bot] at w,
exact linear_map.injective_of_iterate_injective ne w,
end
/-- Any surjective endomorphism of a Noetherian module is bijective. -/
theorem is_noetherian.bijective_of_surjective_endomorphism [is_noetherian R M]
(f : M →ₗ[R] M) (s : surjective f) : bijective f :=
⟨is_noetherian.injective_of_surjective_endomorphism f s, s⟩
/--
A sequence `f` of submodules of a noetherian module,
with `f (n+1)` disjoint from the supremum of `f 0`, ..., `f n`,
is eventually zero.
-/
lemma is_noetherian.disjoint_partial_sups_eventually_bot [I : is_noetherian R M]
(f : ℕ → submodule R M) (h : ∀ n, disjoint (partial_sups f n) (f (n+1))) :
∃ n : ℕ, ∀ m, n ≤ m → f m = ⊥ :=
begin
-- A little off-by-one cleanup first:
suffices t : ∃ n : ℕ, ∀ m, n ≤ m → f (m+1) = ⊥,
{ obtain ⟨n, w⟩ := t,
use n+1,
rintros (_|m) p,
{ cases p, },
{ apply w,
exact nat.succ_le_succ_iff.mp p }, },
obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (partial_sups f),
exact ⟨n, (λ m p,
eq_bot_of_disjoint_absorbs (h m) ((eq.symm (w (m + 1) (le_add_right p))).trans (w m p)))⟩
end
/--
If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial.
-/
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 ≪≫ₗ _,
rw w,
exact submodule.bot_equiv_punit,
end
end
/--
A ring is Noetherian if it is Noetherian as a module over itself,
i.e. all its ideals are finitely generated.
-/
class is_noetherian_ring (R) [ring R] extends is_noetherian R R : Prop
theorem is_noetherian_ring_iff {R} [ring R] : is_noetherian_ring R ↔ is_noetherian R R :=
⟨λ h, h.1, @is_noetherian_ring.mk _ _⟩
/-- A commutative ring is Noetherian if and only if all its ideals are finitely-generated. -/
lemma is_noetherian_ring_iff_ideal_fg (R : Type*) [comm_ring R] :
is_noetherian_ring R ↔ ∀ I : ideal R, I.fg :=
is_noetherian_ring_iff.trans is_noetherian_def
@[priority 80] -- see Note [lower instance priority]
instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] :
is_noetherian R M :=
by letI := classical.dec; exact
⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩
theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R :=
by haveI := subsingleton_of_zero_eq_one h01;
haveI := fintype.of_subsingleton (0:R);
exact is_noetherian_ring_iff.2 (ring.is_noetherian_of_fintype R R)
theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M]
(N : submodule R M) (h : is_noetherian R M) : is_noetherian R N :=
begin
rw is_noetherian_iff_well_founded at h ⊢,
exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h,
end
instance submodule.quotient.is_noetherian {R} [ring R] {M} [add_comm_group M] [module R M]
(N : submodule R M) [h : is_noetherian R M] : is_noetherian R N.quotient :=
begin
rw is_noetherian_iff_well_founded at h ⊢,
exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h,
end
/-- If `M / S / R` is a scalar tower, and `M / R` is Noetherian, then `M / S` is
also noetherian. -/
theorem is_noetherian_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_noetherian R M) : is_noetherian S M :=
begin
rw is_noetherian_iff_well_founded at h ⊢,
refine (submodule.restrict_scalars_embedding R S M).dual.well_founded h
end
instance ideal.quotient.is_noetherian_ring {R : Type*} [comm_ring R] [h : is_noetherian_ring R]
(I : ideal R) : is_noetherian_ring I.quotient :=
is_noetherian_ring_iff.mpr $ is_noetherian_of_tower R $ submodule.quotient.is_noetherian _
theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M]
(N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N :=
let ⟨s, hs⟩ := hN in
begin
haveI := classical.dec_eq M,
haveI := classical.dec_eq R,
letI : is_noetherian R R := by apply_instance,
have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx,
refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _)
_ _ _ is_noetherian_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 } },
rw linear_map.range_eq_top,
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_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M]
[is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M :=
have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h,
by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl)
/-- In a module over a noetherian ring, the submodule generated by finitely many vectors is
noetherian. -/
theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M]
[is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) :=
is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩)
theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S]
(f : R →+* S) (hf : function.surjective f)
[H : is_noetherian_ring R] : is_noetherian_ring S :=
begin
rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at H ⊢,
exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H,
end
instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S)
[is_noetherian_ring R] : is_noetherian_ring f.range :=
is_noetherian_ring_of_surjective R f.range f.range_restrict
f.range_restrict_surjective
theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S]
(f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S :=
is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective
namespace submodule
variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A]
variables (M N : submodule R A)
theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg :=
let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in
fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩
lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg :=
nat.rec_on n
(⟨{1}, by simp [one_eq_span]⟩)
(λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih)
end submodule
section primes
variables {R : Type*} [comm_ring R] [is_noetherian_ring R]
/--In a noetherian ring, every ideal contains a product of prime ideals
([samuel, § 3.3, Lemma 3])-/
lemma exists_prime_spectrum_prod_le (I : ideal R) :
∃ (Z : multiset (prime_spectrum R)), multiset.prod (Z.map (coe : subtype _ → ideal R)) ≤ I :=
begin
refine is_noetherian.induction (λ (M : ideal R) hgt, _) I,
by_cases h_prM : M.is_prime,
{ use {⟨M, h_prM⟩},
rw [multiset.map_singleton, multiset.prod_singleton, subtype.coe_mk],
exact le_rfl },
by_cases htop : M = ⊤,
{ rw htop,
exact ⟨0, le_top⟩ },
have lt_add : ∀ z ∉ M, M < M + span R {z},
{ intros z hz,
refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _),
rw m_eq,
exact mem_sup_right (mem_span_singleton_self z) },
obtain ⟨x, hx, y, hy, hxy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left htop,
obtain ⟨Wx, h_Wx⟩ := hgt (M + span R {x}) (lt_add _ hx),
obtain ⟨Wy, h_Wy⟩ := hgt (M + span R {y}) (lt_add _ hy),
use Wx + Wy,
rw [multiset.map_add, multiset.prod_add],
apply le_trans (submodule.mul_le_mul h_Wx h_Wy),
rw add_mul,
apply sup_le (show M * (M + span R {y}) ≤ M, from ideal.mul_le_right),
rw mul_add,
apply sup_le (show span R {x} * M ≤ M, from ideal.mul_le_left),
rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem],
end
variables {A : Type*} [comm_ring A] [integral_domain A] [is_noetherian_ring A]
/--In a noetherian integral domain which is not a field, every non-zero ideal contains a non-zero
product of prime ideals; in a field, the whole ring is a non-zero ideal containing only 0 as
product or prime ideals ([samuel, § 3.3, Lemma 3])
-/
lemma exists_prime_spectrum_prod_le_and_ne_bot_of_domain (h_fA : ¬ is_field A) {I : ideal A}
(h_nzI: I ≠ ⊥) :
∃ (Z : multiset (prime_spectrum A)), multiset.prod (Z.map (coe : subtype _ → ideal A)) ≤ I ∧
multiset.prod (Z.map (coe : subtype _ → ideal A)) ≠ ⊥ :=
begin
revert h_nzI,
refine is_noetherian.induction (λ (M : ideal A) hgt, _) I,
intro h_nzM,
have hA_nont : nontrivial A,
apply is_integral_domain.to_nontrivial (integral_domain.to_is_integral_domain A),
by_cases h_topM : M = ⊤,
{ rcases h_topM with rfl,
obtain ⟨p_id, h_nzp, h_pp⟩ : ∃ (p : ideal A), p ≠ ⊥ ∧ p.is_prime,
{ apply ring.not_is_field_iff_exists_prime.mp h_fA },
use [({⟨p_id, h_pp⟩} : multiset (prime_spectrum A)), le_top],
rwa [multiset.map_singleton, multiset.prod_singleton, subtype.coe_mk] },
by_cases h_prM : M.is_prime,
{ use ({⟨M, h_prM⟩} : multiset (prime_spectrum A)),
rw [multiset.map_singleton, multiset.prod_singleton, subtype.coe_mk],
exact ⟨le_rfl, h_nzM⟩ },
obtain ⟨x, hx, y, hy, h_xy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left h_topM,
have lt_add : ∀ z ∉ M, M < M + span A {z},
{ intros z hz,
refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _),
rw m_eq,
exact mem_sup_right (mem_span_singleton_self z) },
obtain ⟨Wx, h_Wx_le, h_Wx_ne⟩ := hgt (M + span A {x}) (lt_add _ hx) (ne_bot_of_gt (lt_add _ hx)),
obtain ⟨Wy, h_Wy_le, h_Wx_ne⟩ := hgt (M + span A {y}) (lt_add _ hy) (ne_bot_of_gt (lt_add _ hy)),
use Wx + Wy,
rw [multiset.map_add, multiset.prod_add],
refine ⟨le_trans (submodule.mul_le_mul h_Wx_le h_Wy_le) _, mt ideal.mul_eq_bot.mp _⟩,
{ rw add_mul,
apply sup_le (show M * (M + span A {y}) ≤ M, from ideal.mul_le_right),
rw mul_add,
apply sup_le (show span A {x} * M ≤ M, from ideal.mul_le_left),
rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem] },
{ rintro (hx | hy); contradiction },
end
end primes
|
4c88383199c590e2bbc4ee2e17de1bc96afbb90b | 6e41ee3ac9b96e8980a16295cc21f131e731884f | /library/data/int/order.lean | abe08e05f77406927bece2dfb2a195e53e17a60e | [
"Apache-2.0"
] | permissive | EgbertRijke/lean | 3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3 | 4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183 | refs/heads/master | 1,610,834,871,476 | 1,422,159,801,000 | 1,422,159,801,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 29,218 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.int.order
Authors: Floris van Doorn, Jeremy Avigad
The order relation on the integers. We show that int is an instance of linear_comm_ordered_ring
and transfer the results.
-/
import .basic algebra.ordered_ring
open nat
open decidable
open fake_simplifier
open int eq.ops
namespace int
private definition nonneg (a : ℤ) : Prop := cases_on a (take n, true) (take n, false)
definition le (a b : ℤ) : Prop := nonneg (sub b a)
definition lt (a b : ℤ) : Prop := le (add a 1) b
infix - := int.sub
infix <= := int.le
infix ≤ := int.le
infix < := int.lt
private definition decidable_nonneg [instance] (a : ℤ) : decidable (nonneg a) := cases_on a _ _
definition decidable_le [instance] (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _
definition decidable_lt [instance] (a b : ℤ) : decidable (a < b) := decidable_nonneg _
private theorem nonneg.elim {a : ℤ} : nonneg a → ∃n : ℕ, a = n :=
cases_on a (take n H, exists.intro n rfl) (take n' H, false.elim H)
private theorem nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) :=
cases_on a (take n, or.inl trivial) (take n, or.inr trivial)
theorem le.intro {a b : ℤ} {n : ℕ} (H : a + n = b) : a ≤ b :=
have H1 : b - a = n, from (eq_add_neg_of_add_eq (!add.comm ▸ H))⁻¹,
have H2 : nonneg n, from true.intro,
show nonneg (b - a), from H1⁻¹ ▸ H2
theorem le.elim {a b : ℤ} (H : a ≤ b) : ∃n : ℕ, a + n = b :=
obtain (n : ℕ) (H1 : b - a = n), from nonneg.elim H,
exists.intro n (!add.comm ▸ iff.mp' !add_eq_iff_eq_add_neg (H1⁻¹))
theorem le.total (a b : ℤ) : a ≤ b ∨ b ≤ a :=
or.elim (nonneg_or_nonneg_neg (b - a))
(assume H, or.inl H)
(assume H : nonneg (-(b - a)),
have H0 : -(b - a) = a - b, from neg_sub b a,
have H1 : nonneg (a - b), from H0 ▸ H, -- too bad: can't do it in one step
or.inr H1)
theorem of_nat_le_of_nat (n m : ℕ) : of_nat n ≤ of_nat m ↔ n ≤ m :=
iff.intro
(assume H : of_nat n ≤ of_nat m,
obtain (k : ℕ) (Hk : of_nat n + of_nat k = of_nat m), from le.elim H,
have H2 : n + k = m, from of_nat_inj ((add_of_nat n k)⁻¹ ⬝ Hk),
nat.le.intro H2)
(assume H : n ≤ m,
obtain (k : ℕ) (Hk : n + k = m), from nat.le.elim H,
have H2 : of_nat n + of_nat k = of_nat m, from Hk ▸ add_of_nat n k,
le.intro H2)
theorem lt_add_succ (a : ℤ) (n : ℕ) : a < a + succ n :=
le.intro (show a + 1 + n = a + succ n, from
calc
a + 1 + n = a + (1 + n) : add.assoc
... = a + (n + 1) : add.comm
... = a + succ n : rfl)
theorem lt.intro {a b : ℤ} {n : ℕ} (H : a + succ n = b) : a < b :=
H ▸ lt_add_succ a n
theorem lt.elim {a b : ℤ} (H : a < b) : ∃n : ℕ, a + succ n = b :=
obtain (n : ℕ) (Hn : a + 1 + n = b), from le.elim H,
have H2 : a + succ n = b, from
calc
a + succ n = a + 1 + n : by simp
... = b : Hn,
exists.intro n H2
theorem of_nat_lt_of_nat (n m : ℕ) : of_nat n < of_nat m ↔ n < m :=
calc
of_nat n < of_nat m ↔ of_nat n + 1 ≤ of_nat m : iff.refl
... ↔ of_nat (succ n) ≤ of_nat m : of_nat_succ n ▸ !iff.refl
... ↔ succ n ≤ m : of_nat_le_of_nat
... ↔ n < m : iff.symm (lt_iff_succ_le _ _)
/- show that the integers form an ordered additive group -/
theorem le.refl (a : ℤ) : a ≤ a :=
le.intro (add_zero a)
theorem le.trans {a b c : ℤ} (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c :=
obtain (n : ℕ) (Hn : a + n = b), from le.elim H1,
obtain (m : ℕ) (Hm : b + m = c), from le.elim H2,
have H3 : a + of_nat (n + m) = c, from
calc
a + of_nat (n + m) = a + (of_nat n + m) : {(add_of_nat n m)⁻¹}
... = a + n + m : (add.assoc a n m)⁻¹
... = b + m : {Hn}
... = c : Hm,
le.intro H3
theorem le.antisymm {a b : ℤ} (H1 : a ≤ b) (H2 : b ≤ a) : a = b :=
obtain (n : ℕ) (Hn : a + n = b), from le.elim H1,
obtain (m : ℕ) (Hm : b + m = a), from le.elim H2,
have H3 : a + of_nat (n + m) = a + 0, from
calc
a + of_nat (n + m) = a + (of_nat n + m) : {(add_of_nat n m)⁻¹}
... = a + n + m : (add.assoc a n m)⁻¹
... = b + m : {Hn}
... = a : Hm
... = a + 0 : (add_zero a)⁻¹,
have H4 : of_nat (n + m) = of_nat 0, from add.left_cancel H3,
have H5 : n + m = 0, from of_nat_inj H4,
have H6 : n = 0, from nat.eq_zero_of_add_eq_zero_right H5,
show a = b, from
calc
a = a + of_nat 0 : (add_zero a)⁻¹
... = a + n : {H6⁻¹}
... = b : Hn
theorem lt.irrefl (a : ℤ) : ¬ a < a :=
(assume H : a < a,
obtain (n : ℕ) (Hn : a + succ n = a), from lt.elim H,
have H2 : a + succ n = a + 0, from
calc
a + succ n = a : Hn
... = a + 0 : by simp,
have H3 : succ n = 0, from add.left_cancel H2,
have H4 : succ n = 0, from of_nat_inj H3,
absurd H4 !succ_ne_zero)
theorem ne_of_lt {a b : ℤ} (H : a < b) : a ≠ b :=
(assume H2 : a = b, absurd (H2 ▸ H) (lt.irrefl b))
theorem succ_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b := H
theorem lt_of_le_succ {a b : ℤ} (H : a + 1 ≤ b) : a < b := H
theorem le_of_lt {a b : ℤ} (H : a < b) : a ≤ b :=
obtain (n : ℕ) (Hn : a + succ n = b), from lt.elim H,
le.intro Hn
theorem lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) :=
iff.intro
(assume H, and.intro (le_of_lt H) (ne_of_lt H))
(assume H,
have H1 : a ≤ b, from and.elim_left H,
have H2 : a ≠ b, from and.elim_right H,
obtain (n : ℕ) (Hn : a + n = b), from le.elim H1,
have H3 : n ≠ 0, from (assume H' : n = 0, H2 (!add_zero ▸ H' ▸ Hn)),
obtain (k : ℕ) (Hk : n = succ k), from nat.exists_eq_succ_of_ne_zero H3,
lt.intro (Hk ▸ Hn))
theorem le_iff_lt_or_eq (a b : ℤ) : a ≤ b ↔ (a < b ∨ a = b) :=
iff.intro
(assume H,
by_cases
(assume H1 : a = b, or.inr H1)
(assume H1 : a ≠ b,
obtain (n : ℕ) (Hn : a + n = b), from le.elim H,
have H2 : n ≠ 0, from (assume H' : n = 0, H1 (!add_zero ▸ H' ▸ Hn)),
obtain (k : ℕ) (Hk : n = succ k), from nat.exists_eq_succ_of_ne_zero H2,
or.inl (lt.intro (Hk ▸ Hn))))
(assume H,
or.elim H
(assume H1, le_of_lt H1)
(assume H1, H1 ▸ !le.refl))
theorem lt_succ (a : ℤ) : a < a + 1 :=
le.refl (a + 1)
theorem add_le_add_left {a b : ℤ} (H : a ≤ b) (c : ℤ) : c + a ≤ c + b :=
obtain (n : ℕ) (Hn : a + n = b), from le.elim H,
have H2 : c + a + n = c + b, from
calc
c + a + n = c + (a + n) : add.assoc c a n
... = c + b : {Hn},
le.intro H2
theorem mul_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a * b :=
obtain (n : ℕ) (Hn : 0 + n = a), from le.elim Ha,
obtain (m : ℕ) (Hm : 0 + m = b), from le.elim Hb,
le.intro
(eq.symm
(calc
a * b = (0 + n) * b : Hn
... = n * b : zero_add
... = n * (0 + m) : Hm
... = n * m : zero_add
... = 0 + n * m : zero_add))
theorem mul_pos {a b : ℤ} (Ha : 0 < a) (Hb : 0 < b) : 0 < a * b :=
obtain (n : ℕ) (Hn : 0 + succ n = a), from lt.elim Ha,
obtain (m : ℕ) (Hm : 0 + succ m = b), from lt.elim Hb,
lt.intro
(eq.symm
(calc
a * b = (0 + succ n) * b : Hn
... = succ n * b : zero_add
... = succ n * (0 + succ m) : Hm
... = succ n * succ m : zero_add
... = of_nat (succ n * succ m) : mul_of_nat
... = of_nat (succ n * m + succ n) : nat.mul_succ
... = of_nat (succ (succ n * m + n)) : nat.add_succ
... = 0 + succ (succ n * m + n) : zero_add))
section
open [classes] algebra
protected definition linear_ordered_comm_ring [instance] : algebra.linear_ordered_comm_ring int :=
algebra.linear_ordered_comm_ring.mk add add.assoc zero zero_add add_zero neg add.left_inv
add.comm mul mul.assoc (of_num 1) one_mul mul_one mul.left_distrib mul.right_distrib
zero_ne_one le le.refl @le.trans @le.antisymm lt lt_iff_le_and_ne @add_le_add_left
@mul_nonneg @mul_pos le_iff_lt_or_eq le.total mul.comm
protected definition decidable_linear_ordered_comm_ring [instance] :
algebra.decidable_linear_ordered_comm_ring int :=
⦃algebra.decidable_linear_ordered_comm_ring,
int.linear_ordered_comm_ring,
decidable_lt := decidable_lt⦄
end
/- instantiate ordered ring theorems to int -/
section port_algebra
definition ge (a b : ℤ) := algebra.has_le.ge a b
definition gt (a b : ℤ) := algebra.has_lt.gt a b
infix >= := int.ge
infix ≥ := int.ge
infix > := int.gt
definition decidable_ge [instance] (a b : ℤ) : decidable (a ≥ b) := _
definition decidable_gt [instance] (a b : ℤ) : decidable (a > b) := _
theorem le_of_eq_of_le : ∀{a b c : ℤ}, a = b → b ≤ c → a ≤ c := @algebra.le_of_eq_of_le _ _
theorem le_of_le_of_eq : ∀{a b c : ℤ}, a ≤ b → b = c → a ≤ c := @algebra.le_of_le_of_eq _ _
theorem lt_of_eq_of_lt : ∀{a b c : ℤ}, a = b → b < c → a < c := @algebra.lt_of_eq_of_lt _ _
theorem lt_of_lt_of_eq : ∀{a b c : ℤ}, a < b → b = c → a < c := @algebra.lt_of_lt_of_eq _ _
calc_trans int.le_of_eq_of_le
calc_trans int.le_of_le_of_eq
calc_trans int.lt_of_eq_of_lt
calc_trans int.lt_of_lt_of_eq
theorem lt.asymm : ∀{a b : ℤ}, a < b → ¬ b < a := @algebra.lt.asymm _ _
theorem lt_of_le_of_ne : ∀{a b : ℤ}, a ≤ b → a ≠ b → a < b := @algebra.lt_of_le_of_ne _ _
theorem lt_of_lt_of_le : ∀{a b c : ℤ}, a < b → b ≤ c → a < c := @algebra.lt_of_lt_of_le _ _
theorem lt_of_le_of_lt : ∀{a b c : ℤ}, a ≤ b → b < c → a < c := @algebra.lt_of_le_of_lt _ _
theorem not_le_of_lt : ∀{a b : ℤ}, a < b → ¬ b ≤ a := @algebra.not_le_of_lt _ _
theorem not_lt_of_le : ∀{a b : ℤ}, a ≤ b → ¬ b < a := @algebra.not_lt_of_le _ _
theorem lt_or_eq_of_le : ∀{a b : ℤ}, a ≤ b → a < b ∨ a = b := @algebra.lt_or_eq_of_le _ _
theorem lt.trichotomy : ∀a b : ℤ, a < b ∨ a = b ∨ b < a := algebra.lt.trichotomy
theorem lt.by_cases : ∀{a b : ℤ} {P : Prop}, (a < b → P) → (a = b → P) → (b < a → P) → P :=
@algebra.lt.by_cases _ _
theorem le_of_not_lt : ∀{a b : ℤ}, ¬ a < b → b ≤ a := @algebra.le_of_not_lt _ _
theorem lt_of_not_le : ∀{a b : ℤ}, ¬ a ≤ b → b < a := @algebra.lt_of_not_le _ _
theorem lt_or_ge : ∀a b : ℤ, a < b ∨ a ≥ b := @algebra.lt_or_ge _ _
theorem le_or_gt : ∀a b : ℤ, a ≤ b ∨ a > b := @algebra.le_or_gt _ _
theorem lt_or_gt_of_ne : ∀{a b : ℤ}, a ≠ b → a < b ∨ a > b := @algebra.lt_or_gt_of_ne _ _
theorem add_le_add_right : ∀{a b : ℤ}, a ≤ b → ∀c : ℤ, a + c ≤ b + c :=
@algebra.add_le_add_right _ _
theorem add_le_add : ∀{a b c d : ℤ}, a ≤ b → c ≤ d → a + c ≤ b + d := @algebra.add_le_add _ _
theorem add_lt_add_left : ∀{a b : ℤ}, a < b → ∀c : ℤ, c + a < c + b :=
@algebra.add_lt_add_left _ _
theorem add_lt_add_right : ∀{a b : ℤ}, a < b → ∀c : ℤ, a + c < b + c :=
@algebra.add_lt_add_right _ _
theorem le_add_of_nonneg_right : ∀{a b : ℤ}, b ≥ 0 → a ≤ a + b :=
@algebra.le_add_of_nonneg_right _ _
theorem le_add_of_nonneg_left : ∀{a b : ℤ}, b ≥ 0 → a ≤ b + a :=
@algebra.le_add_of_nonneg_left _ _
theorem add_lt_add : ∀{a b c d : ℤ}, a < b → c < d → a + c < b + d := @algebra.add_lt_add _ _
theorem add_lt_add_of_le_of_lt : ∀{a b c d : ℤ}, a ≤ b → c < d → a + c < b + d :=
@algebra.add_lt_add_of_le_of_lt _ _
theorem add_lt_add_of_lt_of_le : ∀{a b c d : ℤ}, a < b → c ≤ d → a + c < b + d :=
@algebra.add_lt_add_of_lt_of_le _ _
theorem lt_add_of_pos_right : ∀{a b : ℤ}, b > 0 → a < a + b := @algebra.lt_add_of_pos_right _ _
theorem lt_add_of_pos_left : ∀{a b : ℤ}, b > 0 → a < b + a := @algebra.lt_add_of_pos_left _ _
theorem le_of_add_le_add_left : ∀{a b c : ℤ}, a + b ≤ a + c → b ≤ c :=
@algebra.le_of_add_le_add_left _ _
theorem le_of_add_le_add_right : ∀{a b c : ℤ}, a + b ≤ c + b → a ≤ c :=
@algebra.le_of_add_le_add_right _ _
theorem lt_of_add_lt_add_left : ∀{a b c : ℤ}, a + b < a + c → b < c :=
@algebra.lt_of_add_lt_add_left _ _
theorem lt_of_add_lt_add_right : ∀{a b c : ℤ}, a + b < c + b → a < c :=
@algebra.lt_of_add_lt_add_right _ _
theorem add_le_add_left_iff : ∀a b c : ℤ, a + b ≤ a + c ↔ b ≤ c := algebra.add_le_add_left_iff
theorem add_le_add_right_iff : ∀a b c : ℤ, a + b ≤ c + b ↔ a ≤ c := algebra.add_le_add_right_iff
theorem add_lt_add_left_iff : ∀a b c : ℤ, a + b < a + c ↔ b < c := algebra.add_lt_add_left_iff
theorem add_lt_add_right_iff : ∀a b c : ℤ, a + b < c + b ↔ a < c := algebra.add_lt_add_right_iff
theorem add_nonneg : ∀{a b : ℤ}, 0 ≤ a → 0 ≤ b → 0 ≤ a + b := @algebra.add_nonneg _ _
theorem add_pos : ∀{a b : ℤ}, 0 < a → 0 < b → 0 < a + b := @algebra.add_pos _ _
theorem add_pos_of_pos_of_nonneg : ∀{a b : ℤ}, 0 < a → 0 ≤ b → 0 < a + b :=
@algebra.add_pos_of_pos_of_nonneg _ _
theorem add_pos_of_nonneg_of_pos : ∀{a b : ℤ}, 0 ≤ a → 0 < b → 0 < a + b :=
@algebra.add_pos_of_nonneg_of_pos _ _
theorem add_nonpos : ∀{a b : ℤ}, a ≤ 0 → b ≤ 0 → a + b ≤ 0 :=
@algebra.add_nonpos _ _
theorem add_neg : ∀{a b : ℤ}, a < 0 → b < 0 → a + b < 0 :=
@algebra.add_neg _ _
theorem add_neg_of_neg_of_nonpos : ∀{a b : ℤ}, a < 0 → b ≤ 0 → a + b < 0 :=
@algebra.add_neg_of_neg_of_nonpos _ _
theorem add_neg_of_nonpos_of_neg : ∀{a b : ℤ}, a ≤ 0 → b < 0 → a + b < 0 :=
@algebra.add_neg_of_nonpos_of_neg _ _
theorem add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg : ∀{a b : ℤ},
0 ≤ a → 0 ≤ b → a + b = 0 ↔ a = 0 ∧ b = 0 :=
@algebra.add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg _ _
theorem le_add_of_nonneg_of_le : ∀{a b c : ℤ}, 0 ≤ a → b ≤ c → b ≤ a + c :=
@algebra.le_add_of_nonneg_of_le _ _
theorem le_add_of_le_of_nonneg : ∀{a b c : ℤ}, b ≤ c → 0 ≤ a → b ≤ c + a :=
@algebra.le_add_of_le_of_nonneg _ _
theorem lt_add_of_pos_of_le : ∀{a b c : ℤ}, 0 < a → b ≤ c → b < a + c :=
@algebra.lt_add_of_pos_of_le _ _
theorem lt_add_of_le_of_pos : ∀{a b c : ℤ}, b ≤ c → 0 < a → b < c + a :=
@algebra.lt_add_of_le_of_pos _ _
theorem add_le_of_nonpos_of_le : ∀{a b c : ℤ}, a ≤ 0 → b ≤ c → a + b ≤ c :=
@algebra.add_le_of_nonpos_of_le _ _
theorem add_le_of_le_of_nonpos : ∀{a b c : ℤ}, b ≤ c → a ≤ 0 → b + a ≤ c :=
@algebra.add_le_of_le_of_nonpos _ _
theorem add_lt_of_neg_of_le : ∀{a b c : ℤ}, a < 0 → b ≤ c → a + b < c :=
@algebra.add_lt_of_neg_of_le _ _
theorem add_lt_of_le_of_neg : ∀{a b c : ℤ}, b ≤ c → a < 0 → b + a < c :=
@algebra.add_lt_of_le_of_neg _ _
theorem lt_add_of_nonneg_of_lt : ∀{a b c : ℤ}, 0 ≤ a → b < c → b < a + c :=
@algebra.lt_add_of_nonneg_of_lt _ _
theorem lt_add_of_lt_of_nonneg : ∀{a b c : ℤ}, b < c → 0 ≤ a → b < c + a :=
@algebra.lt_add_of_lt_of_nonneg _ _
theorem lt_add_of_pos_of_lt : ∀{a b c : ℤ}, 0 < a → b < c → b < a + c :=
@algebra.lt_add_of_pos_of_lt _ _
theorem lt_add_of_lt_of_pos : ∀{a b c : ℤ}, b < c → 0 < a → b < c + a :=
@algebra.lt_add_of_lt_of_pos _ _
theorem add_lt_of_nonpos_of_lt : ∀{a b c : ℤ}, a ≤ 0 → b < c → a + b < c :=
@algebra.add_lt_of_nonpos_of_lt _ _
theorem add_lt_of_lt_of_nonpos : ∀{a b c : ℤ}, b < c → a ≤ 0 → b + a < c :=
@algebra.add_lt_of_lt_of_nonpos _ _
theorem add_lt_of_neg_of_lt : ∀{a b c : ℤ}, a < 0 → b < c → a + b < c :=
@algebra.add_lt_of_neg_of_lt _ _
theorem add_lt_of_lt_of_neg : ∀{a b c : ℤ}, b < c → a < 0 → b + a < c :=
@algebra.add_lt_of_lt_of_neg _ _
theorem neg_le_neg : ∀{a b : ℤ}, a ≤ b → -b ≤ -a := @algebra.neg_le_neg _ _
theorem le_of_neg_le_neg : ∀{a b : ℤ}, -b ≤ -a → a ≤ b := @algebra.le_of_neg_le_neg _ _
theorem neg_le_neg_iff_le : ∀a b : ℤ, -a ≤ -b ↔ b ≤ a := algebra.neg_le_neg_iff_le
theorem nonneg_of_neg_nonpos : ∀{a : ℤ}, -a ≤ 0 → 0 ≤ a := @algebra.nonneg_of_neg_nonpos _ _
theorem neg_nonpos_of_nonneg : ∀{a : ℤ}, 0 ≤ a → -a ≤ 0 := @algebra.neg_nonpos_of_nonneg _ _
theorem neg_nonpos_iff_nonneg : ∀a : ℤ, -a ≤ 0 ↔ 0 ≤ a := algebra.neg_nonpos_iff_nonneg
theorem nonpos_of_neg_nonneg : ∀{a : ℤ}, 0 ≤ -a → a ≤ 0 := @algebra.nonpos_of_neg_nonneg _ _
theorem neg_nonneg_of_nonpos : ∀{a : ℤ}, a ≤ 0 → 0 ≤ -a := @algebra.neg_nonneg_of_nonpos _ _
theorem neg_nonneg_iff_nonpos : ∀a : ℤ, 0 ≤ -a ↔ a ≤ 0 := algebra.neg_nonneg_iff_nonpos
theorem neg_lt_neg : ∀{a b : ℤ}, a < b → -b < -a := @algebra.neg_lt_neg _ _
theorem lt_of_neg_lt_neg : ∀{a b : ℤ}, -b < -a → a < b := @algebra.lt_of_neg_lt_neg _ _
theorem neg_lt_neg_iff_lt : ∀a b : ℤ, -a < -b ↔ b < a := algebra.neg_lt_neg_iff_lt
theorem pos_of_neg_neg : ∀{a : ℤ}, -a < 0 → 0 < a := @algebra.pos_of_neg_neg _ _
theorem neg_neg_of_pos : ∀{a : ℤ}, 0 < a → -a < 0 := @algebra.neg_neg_of_pos _ _
theorem neg_neg_iff_pos : ∀a : ℤ, -a < 0 ↔ 0 < a := algebra.neg_neg_iff_pos
theorem neg_of_neg_pos : ∀{a : ℤ}, 0 < -a → a < 0 := @algebra.neg_of_neg_pos _ _
theorem neg_pos_of_neg : ∀{a : ℤ}, a < 0 → 0 < -a := @algebra.neg_pos_of_neg _ _
theorem neg_pos_iff_neg : ∀a : ℤ, 0 < -a ↔ a < 0 := algebra.neg_pos_iff_neg
theorem le_neg_iff_le_neg : ∀a b : ℤ, a ≤ -b ↔ b ≤ -a := algebra.le_neg_iff_le_neg
theorem neg_le_iff_neg_le : ∀a b : ℤ, -a ≤ b ↔ -b ≤ a := algebra.neg_le_iff_neg_le
theorem lt_neg_iff_lt_neg : ∀a b : ℤ, a < -b ↔ b < -a := algebra.lt_neg_iff_lt_neg
theorem neg_lt_iff_neg_lt : ∀a b : ℤ, -a < b ↔ -b < a := algebra.neg_lt_iff_neg_lt
theorem sub_nonneg_iff_le : ∀a b : ℤ, 0 ≤ a - b ↔ b ≤ a := algebra.sub_nonneg_iff_le
theorem sub_nonpos_iff_le : ∀a b : ℤ, a - b ≤ 0 ↔ a ≤ b := algebra.sub_nonpos_iff_le
theorem sub_pos_iff_lt : ∀a b : ℤ, 0 < a - b ↔ b < a := algebra.sub_pos_iff_lt
theorem sub_neg_iff_lt : ∀a b : ℤ, a - b < 0 ↔ a < b := algebra.sub_neg_iff_lt
theorem add_le_iff_le_neg_add : ∀a b c : ℤ, a + b ≤ c ↔ b ≤ -a + c :=
algebra.add_le_iff_le_neg_add
theorem add_le_iff_le_sub_left : ∀a b c : ℤ, a + b ≤ c ↔ b ≤ c - a :=
algebra.add_le_iff_le_sub_left
theorem add_le_iff_le_sub_right : ∀a b c : ℤ, a + b ≤ c ↔ a ≤ c - b :=
algebra.add_le_iff_le_sub_right
theorem le_add_iff_neg_add_le : ∀a b c : ℤ, a ≤ b + c ↔ -b + a ≤ c :=
algebra.le_add_iff_neg_add_le
theorem le_add_iff_sub_left_le : ∀a b c : ℤ, a ≤ b + c ↔ a - b ≤ c :=
algebra.le_add_iff_sub_left_le
theorem le_add_iff_sub_right_le : ∀a b c : ℤ, a ≤ b + c ↔ a - c ≤ b :=
algebra.le_add_iff_sub_right_le
theorem add_lt_iff_lt_neg_add_left : ∀a b c : ℤ, a + b < c ↔ b < -a + c :=
algebra.add_lt_iff_lt_neg_add_left
theorem add_lt_iff_lt_neg_add_right : ∀a b c : ℤ, a + b < c ↔ a < -b + c :=
algebra.add_lt_iff_lt_neg_add_right
theorem add_lt_iff_lt_sub_left : ∀a b c : ℤ, a + b < c ↔ b < c - a :=
algebra.add_lt_iff_lt_sub_left
theorem add_lt_add_iff_lt_sub_right : ∀a b c : ℤ, a + b < c ↔ a < c - b :=
algebra.add_lt_add_iff_lt_sub_right
theorem lt_add_iff_neg_add_lt_left : ∀a b c : ℤ, a < b + c ↔ -b + a < c :=
algebra.lt_add_iff_neg_add_lt_left
theorem lt_add_iff_neg_add_lt_right : ∀a b c : ℤ, a < b + c ↔ -c + a < b :=
algebra.lt_add_iff_neg_add_lt_right
theorem lt_add_iff_sub_lt_left : ∀a b c : ℤ, a < b + c ↔ a - b < c :=
algebra.lt_add_iff_sub_lt_left
theorem lt_add_iff_sub_lt_right : ∀a b c : ℤ, a < b + c ↔ a - c < b :=
algebra.lt_add_iff_sub_lt_right
theorem le_iff_le_of_sub_eq_sub : ∀{a b c d : ℤ}, a - b = c - d → a ≤ b ↔ c ≤ d :=
@algebra.le_iff_le_of_sub_eq_sub _ _
theorem lt_iff_lt_of_sub_eq_sub : ∀{a b c d : ℤ}, a - b = c - d → a < b ↔ c < d :=
@algebra.lt_iff_lt_of_sub_eq_sub _ _
theorem sub_le_sub_left : ∀{a b : ℤ}, a ≤ b → ∀c : ℤ, c - b ≤ c - a :=
@algebra.sub_le_sub_left _ _
theorem sub_le_sub_right : ∀{a b : ℤ}, a ≤ b → ∀c : ℤ, a - c ≤ b - c :=
@algebra.sub_le_sub_right _ _
theorem sub_le_sub : ∀{a b c d : ℤ}, a ≤ b → c ≤ d → a - d ≤ b - c :=
@algebra.sub_le_sub _ _
theorem sub_lt_sub_left : ∀{a b : ℤ}, a < b → ∀c : ℤ, c - b < c - a :=
@algebra.sub_lt_sub_left _ _
theorem sub_lt_sub_right : ∀{a b : ℤ}, a < b → ∀c : ℤ, a - c < b - c :=
@algebra.sub_lt_sub_right _ _
theorem sub_lt_sub : ∀{a b c d : ℤ}, a < b → c < d → a - d < b - c :=
@algebra.sub_lt_sub _ _
theorem sub_lt_sub_of_le_of_lt : ∀{a b c d : ℤ}, a ≤ b → c < d → a - d < b - c :=
@algebra.sub_lt_sub_of_le_of_lt _ _
theorem sub_lt_sub_of_lt_of_le : ∀{a b c d : ℤ}, a < b → c ≤ d → a - d < b - c :=
@algebra.sub_lt_sub_of_lt_of_le _ _
theorem eq_zero_of_neg_eq : ∀{a : ℤ}, -a = a → a = 0 := @algebra.eq_zero_of_neg_eq _ _
definition abs : ℤ → ℤ := algebra.abs
notation `|` a `|` := abs a
theorem abs_of_nonneg : ∀{a : ℤ}, a ≥ 0 → |a| = a := @algebra.abs_of_nonneg _ _
theorem abs_of_pos : ∀{a : ℤ}, a > 0 → |a| = a := @algebra.abs_of_pos _ _
theorem abs_of_neg : ∀{a : ℤ}, a < 0 → |a| = -a := @algebra.abs_of_neg _ _
theorem abs_zero : |0| = 0 := algebra.abs_zero
theorem abs_of_nonpos : ∀{a : ℤ}, a ≤ 0 → |a| = -a := @algebra.abs_of_nonpos _ _
theorem abs_neg : ∀a : ℤ, |-a| = |a| := algebra.abs_neg
theorem abs_nonneg : ∀a : ℤ, | a | ≥ 0 := algebra.abs_nonneg
theorem abs_abs : ∀a : ℤ, | |a| | = |a| := algebra.abs_abs
theorem le_abs_self : ∀a : ℤ, a ≤ |a| := algebra.le_abs_self
theorem neg_le_abs_self : ∀a : ℤ, -a ≤ |a| := algebra.neg_le_abs_self
theorem eq_zero_of_abs_eq_zero : ∀{a : ℤ}, |a| = 0 → a = 0 := @algebra.eq_zero_of_abs_eq_zero _ _
theorem abs_eq_zero_iff_eq_zero : ∀a : ℤ, |a| = 0 ↔ a = 0 := algebra.abs_eq_zero_iff_eq_zero
theorem abs_pos_of_pos : ∀{a : ℤ}, a > 0 → |a| > 0 := @algebra.abs_pos_of_pos _ _
theorem abs_pos_of_neg : ∀{a : ℤ}, a < 0 → |a| > 0 := @algebra.abs_pos_of_neg _ _
theorem abs_pos_of_ne_zero : ∀a : ℤ, a ≠ 0 → |a| > 0 := @algebra.abs_pos_of_ne_zero _ _
theorem abs_sub : ∀a b : ℤ, |a - b| = |b - a| := algebra.abs_sub
theorem abs.by_cases : ∀{P : ℤ → Prop}, ∀{a : ℤ}, P a → P (-a) → P (|a|) :=
@algebra.abs.by_cases _ _
theorem abs_le_of_le_of_neg_le : ∀{a b : ℤ}, a ≤ b → -a ≤ b → |a| ≤ b :=
@algebra.abs_le_of_le_of_neg_le _ _
theorem abs_lt_of_lt_of_neg_lt : ∀{a b : ℤ}, a < b → -a < b → |a| < b :=
@algebra.abs_lt_of_lt_of_neg_lt _ _
theorem abs_add_le_abs_add_abs : ∀a b : ℤ, |a + b| ≤ |a| + |b| :=
algebra.abs_add_le_abs_add_abs
theorem abs_sub_abs_le_abs_sub : ∀a b : ℤ, |a| - |b| ≤ |a - b| :=
algebra.abs_sub_abs_le_abs_sub
theorem mul_le_mul_of_nonneg_left : ∀{a b c : ℤ}, a ≤ b → 0 ≤ c → c * a ≤ c * b :=
@algebra.mul_le_mul_of_nonneg_left _ _
theorem mul_le_mul_of_nonneg_right : ∀{a b c : ℤ}, a ≤ b → 0 ≤ c → a * c ≤ b * c :=
@algebra.mul_le_mul_of_nonneg_right _ _
theorem mul_le_mul : ∀{a b c d : ℤ}, a ≤ c → b ≤ d → 0 ≤ b → 0 ≤ c → a * b ≤ c * d :=
@algebra.mul_le_mul _ _
theorem mul_nonpos_of_nonneg_of_nonpos : ∀{a b : ℤ}, a ≥ 0 → b ≤ 0 → a * b ≤ 0 :=
@algebra.mul_nonpos_of_nonneg_of_nonpos _ _
theorem mul_nonpos_of_nonpos_of_nonneg : ∀{a b : ℤ}, a ≤ 0 → b ≥ 0 → a * b ≤ 0 :=
@algebra.mul_nonpos_of_nonpos_of_nonneg _ _
theorem mul_lt_mul_of_pos_left : ∀{a b c : ℤ}, a < b → 0 < c → c * a < c * b :=
@algebra.mul_lt_mul_of_pos_left _ _
theorem mul_lt_mul_of_pos_right : ∀{a b c : ℤ}, a < b → 0 < c → a * c < b * c :=
@algebra.mul_lt_mul_of_pos_right _ _
theorem mul_lt_mul : ∀{a b c d : ℤ}, a < c → b ≤ d → 0 < b → 0 ≤ c → a * b < c * d :=
@algebra.mul_lt_mul _ _
theorem mul_neg_of_pos_of_neg : ∀{a b : ℤ}, a > 0 → b < 0 → a * b < 0 :=
@algebra.mul_neg_of_pos_of_neg _ _
theorem mul_neg_of_neg_of_pos : ∀{a b : ℤ}, a < 0 → b > 0 → a * b < 0 :=
@algebra.mul_neg_of_neg_of_pos _ _
theorem lt_of_mul_lt_mul_left : ∀{a b c : ℤ}, c * a < c * b → c ≥ 0 → a < b :=
@algebra.lt_of_mul_lt_mul_left _ _
theorem lt_of_mul_lt_mul_right : ∀{a b c : ℤ}, a * c < b * c → c ≥ 0 → a < b :=
@algebra.lt_of_mul_lt_mul_right _ _
theorem le_of_mul_le_mul_left : ∀{a b c : ℤ}, c * a ≤ c * b → c > 0 → a ≤ b :=
@algebra.le_of_mul_le_mul_left _ _
theorem le_of_mul_le_mul_right : ∀{a b c : ℤ}, a * c ≤ b * c → c > 0 → a ≤ b :=
@algebra.le_of_mul_le_mul_right _ _
theorem pos_of_mul_pos_left : ∀{a b : ℤ}, 0 < a * b → 0 ≤ a → 0 < b :=
@algebra.pos_of_mul_pos_left _ _
theorem pos_of_mul_pos_right : ∀{a b : ℤ}, 0 < a * b → 0 ≤ b → 0 < a :=
@algebra.pos_of_mul_pos_right _ _
theorem mul_le_mul_of_nonpos_left : ∀{a b c : ℤ}, b ≤ a → c ≤ 0 → c * a ≤ c * b :=
@algebra.mul_le_mul_of_nonpos_left _ _
theorem mul_le_mul_of_nonpos_right : ∀{a b c : ℤ}, b ≤ a → c ≤ 0 → a * c ≤ b * c :=
@algebra.mul_le_mul_of_nonpos_right _ _
theorem mul_nonneg_of_nonpos_of_nonpos : ∀{a b : ℤ}, a ≤ 0 → b ≤ 0 → 0 ≤ a * b :=
@algebra.mul_nonneg_of_nonpos_of_nonpos _ _
theorem mul_lt_mul_of_neg_left : ∀{a b c : ℤ}, b < a → c < 0 → c * a < c * b :=
@algebra.mul_lt_mul_of_neg_left _ _
theorem mul_lt_mul_of_neg_right : ∀{a b c : ℤ}, b < a → c < 0 → a * c < b * c :=
@algebra.mul_lt_mul_of_neg_right _ _
theorem mul_pos_of_neg_of_neg : ∀{a b : ℤ}, a < 0 → b < 0 → 0 < a * b :=
@algebra.mul_pos_of_neg_of_neg _ _
theorem mul_self_nonneg : ∀a : ℤ, a * a ≥ 0 := algebra.mul_self_nonneg
theorem zero_le_one : #int 0 ≤ 1 := trivial
theorem zero_lt_one : #int 0 < 1 := trivial
theorem pos_and_pos_or_neg_and_neg_of_mul_pos : ∀{a b : ℤ}, a * b > 0 →
(a > 0 ∧ b > 0) ∨ (a < 0 ∧ b < 0) := @algebra.pos_and_pos_or_neg_and_neg_of_mul_pos _ _
definition sign : ∀a : ℤ, ℤ := algebra.sign
theorem sign_of_neg : ∀{a : ℤ}, a < 0 → sign a = -1 := @algebra.sign_of_neg _ _
theorem sign_zero : sign 0 = 0 := algebra.sign_zero
theorem sign_of_pos : ∀{a : ℤ}, a > 0 → sign a = 1 := @algebra.sign_of_pos _ _
theorem sign_one : sign 1 = 1 := algebra.sign_one
theorem sign_neg_one : sign (-1) = -1 := algebra.sign_neg_one
theorem sign_sign : ∀a : ℤ, sign (sign a) = sign a := algebra.sign_sign
theorem pos_of_sign_eq_one : ∀{a : ℤ}, sign a = 1 → a > 0 := @algebra.pos_of_sign_eq_one _ _
theorem eq_zero_of_sign_eq_zero : ∀{a : ℤ}, sign a = 0 → a = 0 :=
@algebra.eq_zero_of_sign_eq_zero _ _
theorem neg_of_sign_eq_neg_one : ∀{a : ℤ}, sign a = -1 → a < 0 :=
@algebra.neg_of_sign_eq_neg_one _ _
theorem sign_neg : ∀a : ℤ, sign (-a) = -(sign a) := algebra.sign_neg
theorem sign_mul : ∀a b : ℤ, sign (a * b) = sign a * sign b := algebra.sign_mul
theorem abs_eq_sign_mul : ∀a : ℤ, |a| = sign a * a := algebra.abs_eq_sign_mul
theorem eq_sign_mul_abs : ∀a : ℤ, a = sign a * |a| := algebra.eq_sign_mul_abs
theorem abs_dvd_iff_dvd : ∀a b : ℤ, |a| | b ↔ a | b := algebra.abs_dvd_iff_dvd
theorem dvd_abs_iff : ∀a b : ℤ, a | |b| ↔ a | b := algebra.dvd_abs_iff
theorem abs_mul : ∀a b : ℤ, |a * b| = |a| * |b| := algebra.abs_mul
theorem abs_mul_self : ∀a : ℤ, |a| * |a| = a * a := algebra.abs_mul_self
end port_algebra
/- more facts specific to int -/
theorem nonneg_of_nat (n : ℕ) : 0 ≤ of_nat n := trivial
theorem exists_eq_of_nat {a : ℤ} (H : 0 ≤ a) : ∃n : ℕ, a = of_nat n :=
obtain (n : ℕ) (H1 : 0 + of_nat n = a), from le.elim H,
exists.intro n (!zero_add ▸ (H1⁻¹))
theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -(of_nat n) :=
have H2 : -a ≥ 0, from iff.mp' !neg_nonneg_iff_nonpos H,
obtain (n : ℕ) (Hn : -a = of_nat n), from exists_eq_of_nat H2,
exists.intro n (eq_neg_of_eq_neg (Hn⁻¹))
theorem of_nat_nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : of_nat (nat_abs a) = a :=
obtain (n : ℕ) (Hn : a = of_nat n), from exists_eq_of_nat H,
Hn⁻¹ ▸ congr_arg of_nat (nat_abs_of_nat n)
theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : of_nat (nat_abs a) = -a :=
have H1 : (-a) ≥ 0, from iff.mp' !neg_nonneg_iff_nonpos H,
calc
of_nat (nat_abs a) = of_nat (nat_abs (-a)) : nat_abs_neg
... = -a : of_nat_nat_abs_of_nonneg H1
end int
|
64e55d2fd566cc32abaee922c9c9407344bb4dbe | 271e26e338b0c14544a889c31c30b39c989f2e0f | /stage0/src/Init/Lean/Meta/SynthInstance.lean | fa8153a95334fa3f5c49671f740ce55a0c668eb9 | [
"Apache-2.0"
] | permissive | dgorokho/lean4 | 805f99b0b60c545b64ac34ab8237a8504f89d7d4 | e949a052bad59b1c7b54a82d24d516a656487d8a | refs/heads/master | 1,607,061,363,851 | 1,578,006,086,000 | 1,578,006,086,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 22,936 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam, Leonardo de Moura
Type class instance synthesizer using tabled resolution.
-/
import Init.Lean.Meta.Basic
import Init.Lean.Meta.Instances
import Init.Lean.Meta.LevelDefEq
import Init.Lean.Meta.AbstractMVars
namespace Lean
namespace Meta
namespace SynthInstance
structure GeneratorNode :=
(mvar : Expr)
(key : Expr)
(mctx : MetavarContext)
(instances : Array Expr)
(currInstanceIdx : Nat)
instance GeneratorNode.inhabited : Inhabited GeneratorNode := ⟨⟨arbitrary _, arbitrary _, arbitrary _, arbitrary _, 0⟩⟩
structure ConsumerNode :=
(mvar : Expr)
(key : Expr)
(mctx : MetavarContext)
(subgoals : List Expr)
instance Consumernode.inhabited : Inhabited ConsumerNode := ⟨⟨arbitrary _, arbitrary _, arbitrary _, []⟩⟩
inductive Waiter
| consumerNode : ConsumerNode → Waiter
| root : Waiter
def Waiter.isRoot : Waiter → Bool
| Waiter.consumerNode _ => false
| Waiter.root => true
/-
In tabled resolution, we creating a mapping from goals (e.g., `HasCoe Nat ?x`) to
answers and waiters. Waiters are consumer nodes that are waiting for answers for a
particular node.
We implement this mapping using a `HashMap` where the keys are
normalized expressions. That is, we replace assignable metavariables
with auxiliary free variables of the form `_tc.<idx>`. We do
not declare these free variables in any local context, and we should
view them as "normalized names" for metavariables. For example, the
term `f ?m ?m ?n` is normalized as
`f _tc.0 _tc.0 _tc.1`.
This approach is structural, and we may visit the same goal more
than once if the different occurrences are just definitionally
equal, but not structurally equal.
Remark: a metavariable is assignable only if its depth is equal to
the metavar context depth.
-/
namespace MkTableKey
structure State :=
(nextIdx : Nat := 0)
(lmap : HashMap MVarId Level := {})
(emap : HashMap MVarId Expr := {})
abbrev M := ReaderT MetavarContext (StateM State)
partial def normLevel : Level → M Level
| u => if !u.hasMVar then pure u else
match u with
| Level.succ v _ => do v ← normLevel v; pure $ u.updateSucc! v
| Level.max v w _ => do v ← normLevel v; w ← normLevel w; pure $ u.updateMax! v w
| Level.imax v w _ => do v ← normLevel v; w ← normLevel w; pure $ u.updateIMax! v w
| Level.mvar mvarId _ => do
mctx ← read;
if !mctx.isLevelAssignable mvarId then pure u
else do
s ← get;
match s.lmap.find? mvarId with
| some u' => pure u'
| none => do
let u' := mkLevelParam $ mkNameNum `_tc s.nextIdx;
modify $ fun s => { nextIdx := s.nextIdx + 1, lmap := s.lmap.insert mvarId u', .. s };
pure u'
| u => pure u
partial def normExpr : Expr → M Expr
| e => if !e.hasMVar then pure e else
match e with
| Expr.const _ us _ => do us ← us.mapM normLevel; pure $ e.updateConst! us
| Expr.sort u _ => do u ← normLevel u; pure $ e.updateSort! u
| Expr.app f a _ => do f ← normExpr f; a ← normExpr a; pure $ e.updateApp! f a
| Expr.letE _ t v b _ => do t ← normExpr t; v ← normExpr v; b ← normExpr b; pure $ e.updateLet! t v b
| Expr.forallE _ d b _ => do d ← normExpr d; b ← normExpr b; pure $ e.updateForallE! d b
| Expr.lam _ d b _ => do d ← normExpr d; b ← normExpr b; pure $ e.updateLambdaE! d b
| Expr.mdata _ b _ => do b ← normExpr b; pure $ e.updateMData! b
| Expr.proj _ _ b _ => do b ← normExpr b; pure $ e.updateProj! b
| Expr.mvar mvarId _ => do
mctx ← read;
if !mctx.isExprAssignable mvarId then pure e
else do
s ← get;
match s.emap.find? mvarId with
| some e' => pure e'
| none => do
let e' := mkFVar $ mkNameNum `_tc s.nextIdx;
modify $ fun s => { nextIdx := s.nextIdx + 1, emap := s.emap.insert mvarId e', .. s };
pure e'
| _ => pure e
end MkTableKey
/- Remark: `mkTableKey` assumes `e` does not contain assigned metavariables. -/
def mkTableKey (mctx : MetavarContext) (e : Expr) : Expr :=
(MkTableKey.normExpr e mctx).run' {}
abbrev Answer := AbstractMVarsResult
structure TableEntry :=
(waiters : Array Waiter)
(answers : Array Answer := #[])
/-
Remark: the SynthInstance.State is not really an extension of `Meta.State`.
The field `postponed` is not needed, and the field `mctx` is misleading since
`synthInstance` methods operate over different `MetavarContext`s simultaneously.
That being said, we still use `extends` because it makes it simpler to move from
`M` to `MetaM`.
-/
structure State extends Meta.State :=
(result : Option Expr := none)
(generatorStack : Array GeneratorNode := #[])
(resumeStack : Array (ConsumerNode × Answer) := #[])
(tableEntries : HashMap Expr TableEntry := {})
abbrev SynthM := ReaderT Context (EStateM Exception State)
instance SynthM.inhabited {α} : Inhabited (SynthM α) := ⟨throw $ Exception.other ""⟩
def getTraceState : SynthM TraceState := do s ← get; pure s.traceState
def getOptions : SynthM Options := do ctx ← read; pure ctx.config.opts
def addContext (msg : MessageData) : SynthM MessageData := do
ctx ← read;
s ← get;
pure $ MessageData.withContext { env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts } msg
instance tracer : SimpleMonadTracerAdapter SynthM :=
{ getOptions := getOptions,
getTraceState := getTraceState,
addContext := addContext,
modifyTraceState := fun f => modify $ fun s => { traceState := f s.traceState, .. s } }
@[inline] def liftMeta {α} (x : MetaM α) : SynthM α :=
adaptState (fun (s : State) => (s.toState, s)) (fun s' s => { toState := s', .. s }) x
instance meta2Synth {α} : HasCoe (MetaM α) (SynthM α) := ⟨liftMeta⟩
@[inline] def withMCtx {α} (mctx : MetavarContext) (x : SynthM α) : SynthM α := do
mctx' ← getMCtx;
modify $ fun s => { mctx := mctx, .. s };
finally x (modify $ fun s => { mctx := mctx', .. s })
/-- Return globals and locals instances that may unify with `type` -/
def getInstances (type : Expr) : MetaM (Array Expr) :=
forallTelescopeReducing type $ fun _ type => do
className? ← isClass type;
match className? with
| none => throwEx $ Exception.notInstance type
| some className => do
globalInstances ← getGlobalInstances;
result ← globalInstances.getUnify type;
result ← result.mapM $ fun c => match c with
| Expr.const constName us _ => do us ← us.mapM (fun _ => mkFreshLevelMVar); pure $ c.updateConst! us
| _ => panic! "global instance is not a constant";
trace! `Meta.synthInstance.globalInstances (type ++ " " ++ result);
localInstances ← getLocalInstances;
let result := localInstances.foldl
(fun (result : Array Expr) linst => if linst.className == className then result.push linst.fvar else result)
result;
pure result
/-- Create a new generator node for `mvar` and add `waiter` as its waiter.
`key` must be `mkTableKey mctx mvarType`. -/
def newSubgoal (mctx : MetavarContext) (key : Expr) (mvar : Expr) (waiter : Waiter) : SynthM Unit :=
withMCtx mctx $ do
trace! `Meta.synthInstance.newSubgoal key;
mvarType ← inferType mvar;
mvarType ← instantiateMVars mvarType;
instances ← getInstances mvarType;
mctx ← getMCtx;
if instances.isEmpty then pure ()
else do
let node : GeneratorNode := {
mvar := mvar,
key := key,
mctx := mctx,
instances := instances,
currInstanceIdx := instances.size
};
let entry : TableEntry := { waiters := #[waiter] };
modify $ fun s =>
{ generatorStack := s.generatorStack.push node,
tableEntries := s.tableEntries.insert key entry,
.. s }
def findEntry? (key : Expr) : SynthM (Option TableEntry) := do
s ← get;
pure $ s.tableEntries.find? key
def getEntry (key : Expr) : SynthM TableEntry := do
entry? ← findEntry? key;
match entry? with
| none => panic! "invalid key at synthInstance"
| some entry => pure entry
/--
Create a `key` for the goal associated with the given metavariable.
That is, we create a key for the type of the metavariable.
We must instantiate assigned metavariables before we invoke `mkTableKey`. -/
def mkTableKeyFor (mctx : MetavarContext) (mvar : Expr) : SynthM Expr :=
withMCtx mctx $ do
mvarType ← inferType mvar;
mvarType ← instantiateMVars mvarType;
pure $ mkTableKey mctx mvarType
/- See `getSubgoals`
We use the parameter `j` to reduce the number of `instantiate*` invocations.
It is the same approach we use at `forallTelescope` and `lambdaTelescope`.
Given `getSubgoalsAux args j subgoals instVal type`,
we have that `type.instantiateRevRange j args.size args` does not have loose bound variables. -/
private partial def getSubgoalsAux (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr)
: Array Expr → Nat → List Expr → Expr → Expr → MetaM (List Expr × Expr × Expr)
| args, j, subgoals, instVal, Expr.forallE n d b c => do
let d := d.instantiateRevRange j args.size args;
mvarType ← mkForall xs d;
mvar ← mkFreshExprMVarAt lctx localInsts mvarType;
let arg := mkAppN mvar xs;
let instVal := mkApp instVal arg;
let subgoals := if c.binderInfo.isInstImplicit then mvar::subgoals else subgoals;
let args := args.push (mkAppN mvar xs);
getSubgoalsAux args j subgoals instVal b
| args, j, subgoals, instVal, type => do
let type := type.instantiateRevRange j args.size args;
type ← whnf type;
if type.isForall then
getSubgoalsAux args args.size subgoals instVal type
else
pure (subgoals, instVal, type)
/--
`getSubgoals lctx localInsts xs inst` creates the subgoals for the instantiate `inst`.
The subgoals are in the context of the free variables `xs`, and
`(lctx, localInsts)` is the local context and instances before we added the free variables to it.
This extra complication is required because
1- We want all metavariables created by `synthInstance` to share the same local context.
2- We want to ensure that applications such as `mvar xs` are higher order patterns.
The method `getGoals` create a new metavariable for each parameter of `inst`.
For example, suppose the type of `inst` is `forall (x_1 : A_1) ... (x_n : A_n), B x_1 ... x_n`.
Then, we create the metavariables `?m_i : forall xs, A_i`, and return the subset of these
metavariables that are instance implicit arguments, and the expressions:
- `inst (?m_1 xs) ... (?m_n xs)` (aka `instVal`)
- `B (?m_1 xs) ... (?m_n xs)` -/
def getSubgoals (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) (inst : Expr) : MetaM (List Expr × Expr × Expr) := do
instType ← inferType inst;
getSubgoalsAux lctx localInsts xs #[] 0 [] inst instType
def tryResolveCore (mvar : Expr) (inst : Expr) : MetaM (Option (MetavarContext × List Expr)) := do
mvarType ← inferType mvar;
lctx ← getLCtx;
localInsts ← getLocalInstances;
forallTelescopeReducing mvarType $ fun xs mvarTypeBody => do
(subgoals, instVal, instTypeBody) ← getSubgoals lctx localInsts xs inst;
trace! `Meta.synthInstance.tryResolve (mvarTypeBody ++ " =?= " ++ instTypeBody);
condM (isDefEq mvarTypeBody instTypeBody)
(do instVal ← mkLambda xs instVal;
condM (isDefEq mvar instVal)
(do trace! `Meta.synthInstance.tryResolve "success";
mctx ← getMCtx;
pure (some (mctx, subgoals)))
(do trace! `Meta.synthInstance.tryResolve "failure assigning";
pure none))
(do trace! `Meta.synthInstance.tryResolve "failure";
pure none)
/--
Try to synthesize metavariable `mvar` using the instance `inst`.
Remark: `mctx` contains `mvar`.
If it succeeds, the result it a new updated metavariable context and a new list of subgoals.
A subgoal is created for each instance implicit parameter of `inst`. -/
def tryResolve (mctx : MetavarContext) (mvar : Expr) (inst : Expr) : SynthM (Option (MetavarContext × List Expr)) :=
traceCtx `Meta.synthInstance.tryResolve $ withMCtx mctx $ tryResolveCore mvar inst
/--
Assign a precomputed answer to `mvar`.
If it succeeds, the result it a new updated metavariable context and a new list of subgoals. -/
def tryAnswer (mctx : MetavarContext) (mvar : Expr) (answer : Answer) : SynthM (Option MetavarContext) :=
withMCtx mctx $ do
(_, _, val) ← openAbstractMVarsResult answer;
condM (isDefEq mvar val)
(do mctx ← getMCtx; pure $ some mctx)
(pure none)
/-- Move waiters that are waiting for the given answer to the resume stack. -/
def wakeUp (answer : Answer) : Waiter → SynthM Unit
| Waiter.root =>
if answer.paramNames.isEmpty && answer.numMVars == 0 then do
modify $ fun s => { result := answer.expr, .. s }
else do
(_, _, answerExpr) ← openAbstractMVarsResult answer;
trace! `Meta.synthInstance ("skip answer containing metavariables " ++ answerExpr);
pure ()
| Waiter.consumerNode cNode => modify $ fun s => { resumeStack := s.resumeStack.push (cNode, answer), .. s }
/--
Create a new answer after `cNode` resolved all subgoals.
That is, `cNode.subgoals == []`.
And then, store it in the tabled entries map, and wakeup waiters. -/
def addAnswer (cNode : ConsumerNode) : SynthM Unit := do
answer ← withMCtx cNode.mctx $ do {
traceM `Meta.synthInstance.newAnswer $ do { mvarType ← inferType cNode.mvar; pure mvarType };
val ← instantiateMVars cNode.mvar;
abstractMVars val -- assignable metavariables become parameters
};
-- Remark: `answer` does not contain assignable or assigned metavariables.
let key := cNode.key;
entry ← getEntry key;
if entry.answers.contains answer then pure () -- if answer was already found, then do nothing
else
let newEntry := { answers := entry.answers.push answer, .. entry };
modify $ fun s => { tableEntries := s.tableEntries.insert key newEntry, .. s };
entry.waiters.forM (wakeUp answer)
/-- Process the next subgoal in the given consumer node. -/
def consume (cNode : ConsumerNode) : SynthM Unit :=
match cNode.subgoals with
| [] => addAnswer cNode
| mvar::_ => do
let waiter := Waiter.consumerNode cNode;
key ← mkTableKeyFor cNode.mctx mvar;
entry? ← findEntry? key;
match entry? with
| none => newSubgoal cNode.mctx key mvar waiter
| some entry => modify $ fun s =>
{ resumeStack := entry.answers.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack,
tableEntries := s.tableEntries.insert key { waiters := entry.waiters.push waiter, .. entry },
.. s }
def getTop : SynthM GeneratorNode := do
s ← get; pure s.generatorStack.back
@[inline] def modifyTop (f : GeneratorNode → GeneratorNode) : SynthM Unit :=
modify $ fun s => { generatorStack := s.generatorStack.modify (s.generatorStack.size - 1) f, .. s }
/-- Try the next instance in the node on the top of the generator stack. -/
def generate : SynthM Unit := do
gNode ← getTop;
if gNode.currInstanceIdx == 0 then
modify $ fun s => { generatorStack := s.generatorStack.pop, .. s }
else do
let key := gNode.key;
let idx := gNode.currInstanceIdx - 1;
let inst := gNode.instances.get! idx;
let mctx := gNode.mctx;
let mvar := gNode.mvar;
trace! `Meta.synthInstance.generate ("instance " ++ inst);
modifyTop $ fun gNode => { currInstanceIdx := idx, .. gNode };
result? ← tryResolve mctx mvar inst;
match result? with
| none => pure ()
| some (mctx, subgoals) => consume { key := key, mvar := mvar, subgoals := subgoals, mctx := mctx }
def getNextToResume : SynthM (ConsumerNode × Answer) := do
s ← get;
let r := s.resumeStack.back;
modify $ fun s => { resumeStack := s.resumeStack.pop, .. s };
pure r
/--
Given `(cNode, answer)` on the top of the resume stack, continue execution by using `answer` to solve the
next subgoal. -/
def resume : SynthM Unit := do
(cNode, answer) ← getNextToResume;
match cNode.subgoals with
| [] => panic! "resume found no remaining subgoals"
| mvar::rest => do
result? ← tryAnswer cNode.mctx mvar answer;
match result? with
| none => pure ()
| some mctx => do
withMCtx mctx $ traceM `Meta.synthInstance.resume $ do {
goal ← inferType cNode.mvar;
subgoal ← inferType mvar;
pure (goal ++ " <== " ++ subgoal)
};
consume { key := cNode.key, mvar := cNode.mvar, subgoals := rest, mctx := mctx }
def step : SynthM Bool := do
s ← get;
if !s.resumeStack.isEmpty then do resume; pure true
else if !s.generatorStack.isEmpty then do generate; pure true
else pure false
def getResult : SynthM (Option Expr) := do
s ← get; pure s.result
partial def synth : Nat → SynthM (Option Expr)
| 0 => do
trace! `Meta.synthInstance "synthInstance is out of fule";
pure none
| n+1 => do
condM step
(do result? ← getResult;
match result? with
| none => synth n
| some result => pure result)
(do trace! `Meta.synthInstance "failed";
pure none)
def main (type : Expr) (fuel : Nat) : MetaM (Option Expr) :=
traceCtx `Meta.synthInstance $ do
trace! `Meta.synthInstance ("main goal " ++ type);
mvar ← mkFreshExprMVar type;
mctx ← getMCtx;
let key := mkTableKey mctx type;
adaptState' (fun (s : Meta.State) => { State . .. s }) (fun (s : State) => s.toState) $ do {
newSubgoal mctx key mvar Waiter.root;
synth fuel
}
end SynthInstance
/-
Type class parameters can be annotated with `outParam` annotations.
Given `C a_1 ... a_n`, we replace `a_i` with a fresh metavariable `?m_i` IF
`a_i` is an `outParam`.
The result is type correct because we reject type class declarations IF
it contains a regular parameter X that depends on an `out` parameter Y.
Then, we execute type class resolution as usual.
If it succeeds, and metavariables ?m_i have been assigned, we solve the unification
constraints ?m_i =?= a_i. If we succeed, we return the result. Otherwise, we fail.
These pending unification constraints are stored in the `Replacements` structure.
-/
structure Replacements :=
(levelReplacements : Array (Level × Level) := #[])
(exprReplacements : Array (Expr × Expr) := #[])
private def preprocess (type : Expr) : MetaM Expr :=
forallTelescopeReducing type $ fun xs type => do
type ← whnf type;
mkForall xs type
private def preprocessLevels (us : List Level) : MetaM (List Level × Array (Level × Level)) := do
(us, r) ← us.foldlM
(fun (r : List Level × Array (Level × Level)) (u : Level) => do
u ← instantiateLevelMVars u;
if u.hasMVar then do
u' ← mkFreshLevelMVar;
pure (u'::r.1, r.2.push (u, u'))
else
pure (u::r.1, r.2))
([], #[]);
pure (us.reverse, r)
private partial def preprocessArgs (ys : Array Expr) : Nat → Array Expr → Array (Expr × Expr) → MetaM (Array Expr × Array (Expr × Expr))
| i, args, r => do
if h : i < ys.size then do
let y := ys.get ⟨i, h⟩;
yType ← inferType y;
if isOutParam yType then do
if h : i < args.size then do
let arg := args.get ⟨i, h⟩;
arg' ← mkFreshExprMVar yType;
preprocessArgs (i+1) (args.set ⟨i, h⟩ arg') (r.push (arg, arg'))
else
throw $ Exception.other "type class resolution failed, insufficient number of arguments" -- TODO improve error message
else
preprocessArgs (i+1) args r
else
pure (args, r)
private def preprocessOutParam (type : Expr) : MetaM (Expr × Replacements) :=
forallTelescope type $ fun xs typeBody =>
match typeBody.getAppFn with
| c@(Expr.const constName us _) => do
env ← getEnv;
if !hasOutParams env constName then pure (type, {})
else do
let args := typeBody.getAppArgs;
cType ← inferType c;
forallTelescopeReducing cType $ fun ys _ => do
(us, levelReplacements) ← preprocessLevels us;
(args, exprReplacements) ← preprocessArgs ys 0 args #[];
type ← mkForall xs (mkAppN (mkConst constName us) args);
pure (type, { levelReplacements := levelReplacements, exprReplacements := exprReplacements })
| _ => pure (type, {})
private def resolveReplacements (r : Replacements) : MetaM Bool :=
try $
r.levelReplacements.allM (fun ⟨u, u'⟩ => isLevelDefEqAux u u')
<&&>
r.exprReplacements.allM (fun ⟨e, e'⟩ => isExprDefEqAux e e')
def synthInstance? (type : Expr) (fuel : Nat := 10000) : MetaM (Option Expr) :=
withConfig (fun config => { transparency := TransparencyMode.reducible, foApprox := true, ctxApprox := true, .. config }) $ do
type ← instantiateMVars type;
type ← preprocess type;
s ← get;
match s.cache.synthInstance.find? type with
| some result => pure result
| none => do
result ← withNewMCtxDepth $ do {
(normType, replacements) ← preprocessOutParam type;
result? ← SynthInstance.main normType fuel;
match result? with
| none => pure none
| some result => do
condM (resolveReplacements replacements)
(do result ← instantiateMVars result;
condM (hasAssignableMVar result)
(pure none)
(pure (some result)))
(pure none)
};
if type.hasMVar then
pure result
else do
modify $ fun s => { cache := { synthInstance := s.cache.synthInstance.insert type result, .. s.cache }, .. s };
pure result
/--
Return `LOption.some r` if succeeded, `LOption.none` if it failed, and `LOption.undef` if
instance cannot be synthesized right now because `type` contains metavariables. -/
def trySynthInstance (type : Expr) (fuel : Nat := 10000) : MetaM (LOption Expr) :=
adaptReader (fun (ctx : Context) => { config := { isDefEqStuckEx := true, .. ctx.config }, .. ctx }) $
catch
(toLOptionM $ synthInstance? type fuel)
(fun ex => match ex with
| Exception.isExprDefEqStuck _ _ _ => pure LOption.undef
| Exception.isLevelDefEqStuck _ _ _ => pure LOption.undef
| _ => throw ex)
def synthInstance (type : Expr) (fuel : Nat := 10000) : MetaM Expr := do
result? ← synthInstance? type fuel;
match result? with
| some result => pure result
| none => throwEx $ Exception.synthInstance type
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Meta.synthInstance;
registerTraceClass `Meta.synthInstance.globalInstances;
registerTraceClass `Meta.synthInstance.newSubgoal;
registerTraceClass `Meta.synthInstance.tryResolve;
registerTraceClass `Meta.synthInstance.resume;
registerTraceClass `Meta.synthInstance.generate
end Meta
end Lean
|
89ee14b0b9aa9d4c80934dec0342787421539e0e | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/comma.lean | 15215ad7ea483c21c88bd6b3e197d15da86e9783 | [
"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,841 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johan Commelin, Bhavik Mehta
-/
import category_theory.isomorphism
import category_theory.functor.category
import category_theory.eq_to_hom
/-!
# Comma categories
A comma category is a construction in category theory, which builds a category out of two functors
with a common codomain. Specifically, for functors `L : A ⥤ T` and `R : B ⥤ T`, an object in
`comma L R` is a morphism `hom : L.obj left ⟶ R.obj right` for some objects `left : A` and
`right : B`, and a morphism in `comma L R` between `hom : L.obj left ⟶ R.obj right` and
`hom' : L.obj left' ⟶ R.obj right'` is a commutative square
```
L.obj left ⟶ L.obj left'
| |
hom | | hom'
↓ ↓
R.obj right ⟶ R.obj right',
```
where the top and bottom morphism come from morphisms `left ⟶ left'` and `right ⟶ right'`,
respectively.
## Main definitions
* `comma L R`: the comma category of the functors `L` and `R`.
* `over X`: the over category of the object `X` (developed in `over.lean`).
* `under X`: the under category of the object `X` (also developed in `over.lean`).
* `arrow T`: the arrow category of the category `T` (developed in `arrow.lean`).
## References
* <https://ncatlab.org/nlab/show/comma+category>
## Tags
comma, slice, coslice, over, under, arrow
-/
namespace category_theory
-- declare the `v`'s first; see `category_theory.category` for an explanation
universes v₁ v₂ v₃ v₄ v₅ u₁ u₂ u₃ u₄ u₅
variables {A : Type u₁} [category.{v₁} A]
variables {B : Type u₂} [category.{v₂} B]
variables {T : Type u₃} [category.{v₃} T]
/-- The objects of the comma category are triples of an object `left : A`, an object
`right : B` and a morphism `hom : L.obj left ⟶ R.obj right`. -/
structure comma (L : A ⥤ T) (R : B ⥤ T) : Type (max u₁ u₂ v₃) :=
(left : A . obviously)
(right : B . obviously)
(hom : L.obj left ⟶ R.obj right)
-- Satisfying the inhabited linter
instance comma.inhabited [inhabited T] : inhabited (comma (𝟭 T) (𝟭 T)) :=
{ default :=
{ left := default,
right := default,
hom := 𝟙 default } }
variables {L : A ⥤ T} {R : B ⥤ T}
/-- A morphism between two objects in the comma category is a commutative square connecting the
morphisms coming from the two objects using morphisms in the image of the functors `L` and `R`.
-/
@[ext] structure comma_morphism (X Y : comma L R) :=
(left : X.left ⟶ Y.left . obviously)
(right : X.right ⟶ Y.right . obviously)
(w' : L.map left ≫ Y.hom = X.hom ≫ R.map right . obviously)
-- Satisfying the inhabited linter
instance comma_morphism.inhabited [inhabited (comma L R)] :
inhabited (comma_morphism (default : comma L R) default) :=
⟨⟨𝟙 _, 𝟙 _⟩⟩
restate_axiom comma_morphism.w'
attribute [simp, reassoc] comma_morphism.w
instance comma_category : category (comma L R) :=
{ hom := comma_morphism,
id := λ X,
{ left := 𝟙 X.left,
right := 𝟙 X.right },
comp := λ X Y Z f g,
{ left := f.left ≫ g.left,
right := f.right ≫ g.right } }
namespace comma
section
variables {X Y Z : comma L R} {f : X ⟶ Y} {g : Y ⟶ Z}
@[simp] lemma id_left : ((𝟙 X) : comma_morphism X X).left = 𝟙 X.left := rfl
@[simp] lemma id_right : ((𝟙 X) : comma_morphism X X).right = 𝟙 X.right := rfl
@[simp] lemma comp_left : (f ≫ g).left = f.left ≫ g.left := rfl
@[simp] lemma comp_right : (f ≫ g).right = f.right ≫ g.right := rfl
end
variables (L) (R)
/-- The functor sending an object `X` in the comma category to `X.left`. -/
@[simps]
def fst : comma L R ⥤ A :=
{ obj := λ X, X.left,
map := λ _ _ f, f.left }
/-- The functor sending an object `X` in the comma category to `X.right`. -/
@[simps]
def snd : comma L R ⥤ B :=
{ obj := λ X, X.right,
map := λ _ _ f, f.right }
/-- We can interpret the commutative square constituting a morphism in the comma category as a
natural transformation between the functors `fst ⋙ L` and `snd ⋙ R` from the comma category
to `T`, where the components are given by the morphism that constitutes an object of the comma
category. -/
@[simps]
def nat_trans : fst L R ⋙ L ⟶ snd L R ⋙ R :=
{ app := λ X, X.hom }
@[simp] lemma eq_to_hom_left (X Y : comma L R) (H : X = Y) :
comma_morphism.left (eq_to_hom H) = eq_to_hom (by { cases H, refl }) := by { cases H, refl }
@[simp] lemma eq_to_hom_right (X Y : comma L R) (H : X = Y) :
comma_morphism.right (eq_to_hom H) = eq_to_hom (by { cases H, refl }) := by { cases H, refl }
section
variables {L₁ L₂ L₃ : A ⥤ T} {R₁ R₂ R₃ : B ⥤ T}
/--
Construct an isomorphism in the comma category given isomorphisms of the objects whose forward
directions give a commutative square.
-/
@[simps]
def iso_mk {X Y : comma L₁ R₁} (l : X.left ≅ Y.left) (r : X.right ≅ Y.right)
(h : L₁.map l.hom ≫ Y.hom = X.hom ≫ R₁.map r.hom) : X ≅ Y :=
{ hom := { left := l.hom, right := r.hom },
inv :=
{ left := l.inv,
right := r.inv,
w' := begin
rw [←L₁.map_iso_inv l, iso.inv_comp_eq, L₁.map_iso_hom, reassoc_of h, ← R₁.map_comp],
simp
end, } }
/-- A natural transformation `L₁ ⟶ L₂` induces a functor `comma L₂ R ⥤ comma L₁ R`. -/
@[simps]
def map_left (l : L₁ ⟶ L₂) : comma L₂ R ⥤ comma L₁ R :=
{ obj := λ X,
{ left := X.left,
right := X.right,
hom := l.app X.left ≫ X.hom },
map := λ X Y f,
{ left := f.left,
right := f.right } }
/-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `L` is
naturally isomorphic to the identity functor. -/
@[simps]
def map_left_id : map_left R (𝟙 L) ≅ 𝟭 _ :=
{ hom :=
{ app := λ X, { left := 𝟙 _, right := 𝟙 _ } },
inv :=
{ app := λ X, { left := 𝟙 _, right := 𝟙 _ } } }
/-- The functor `comma L₁ R ⥤ comma L₃ R` induced by the composition of two natural transformations
`l : L₁ ⟶ L₂` and `l' : L₂ ⟶ L₃` is naturally isomorphic to the composition of the two functors
induced by these natural transformations. -/
@[simps]
def map_left_comp (l : L₁ ⟶ L₂) (l' : L₂ ⟶ L₃) :
(map_left R (l ≫ l')) ≅ (map_left R l') ⋙ (map_left R l) :=
{ hom :=
{ app := λ X, { left := 𝟙 _, right := 𝟙 _ } },
inv :=
{ app := λ X, { left := 𝟙 _, right := 𝟙 _ } } }
/-- A natural transformation `R₁ ⟶ R₂` induces a functor `comma L R₁ ⥤ comma L R₂`. -/
@[simps]
def map_right (r : R₁ ⟶ R₂) : comma L R₁ ⥤ comma L R₂ :=
{ obj := λ X,
{ left := X.left,
right := X.right,
hom := X.hom ≫ r.app X.right },
map := λ X Y f,
{ left := f.left,
right := f.right } }
/-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `R` is
naturally isomorphic to the identity functor. -/
@[simps]
def map_right_id : map_right L (𝟙 R) ≅ 𝟭 _ :=
{ hom :=
{ app := λ X, { left := 𝟙 _, right := 𝟙 _ } },
inv :=
{ app := λ X, { left := 𝟙 _, right := 𝟙 _ } } }
/-- The functor `comma L R₁ ⥤ comma L R₃` induced by the composition of the natural transformations
`r : R₁ ⟶ R₂` and `r' : R₂ ⟶ R₃` is naturally isomorphic to the composition of the functors
induced by these natural transformations. -/
@[simps]
def map_right_comp (r : R₁ ⟶ R₂) (r' : R₂ ⟶ R₃) :
(map_right L (r ≫ r')) ≅ (map_right L r) ⋙ (map_right L r') :=
{ hom :=
{ app := λ X, { left := 𝟙 _, right := 𝟙 _ } },
inv :=
{ app := λ X, { left := 𝟙 _, right := 𝟙 _ } } }
end
section
variables {C : Type u₄} [category.{v₄} C] {D : Type u₅} [category.{v₅} D]
/-- The functor `(F ⋙ L, R) ⥤ (L, R)` -/
@[simps] def pre_left (F: C ⥤ A) (L : A ⥤ T) (R : B ⥤ T) : comma (F ⋙ L) R ⥤ comma L R :=
{ obj := λ X, { left := F.obj X.left, right := X.right, hom := X.hom },
map := λ X Y f, { left := F.map f.left, right := f.right, w' := by simpa using f.w } }
/-- The functor `(F ⋙ L, R) ⥤ (L, R)` -/
@[simps] def pre_right (L : A ⥤ T) (F: C ⥤ B) (R : B ⥤ T) : comma L (F ⋙ R) ⥤ comma L R :=
{ obj := λ X, { left := X.left, right := F.obj X.right, hom := X.hom },
map := λ X Y f, { left := f.left, right := F.map f.right, w' := by simp } }
/-- The functor `(L, R) ⥤ (L ⋙ F, R ⋙ F)` -/
@[simps] def post (L : A ⥤ T) (R : B ⥤ T) (F: T ⥤ C) : comma L R ⥤ comma (L ⋙ F) (R ⋙ F) :=
{ obj := λ X, { left := X.left, right := X.right, hom := F.map X.hom },
map := λ X Y f, { left := f.left, right := f.right, w' :=
by { simp only [functor.comp_map, ←F.map_comp, f.w] } } }
end
end comma
end category_theory
|
6846b7aef1bda54027b5b3d5cd8553e69f7f85e1 | 90edd5cdcf93124fe15627f7304069fdce3442dd | /stage0/src/Lean/Aesop/Rule.lean | 5264b681b55d0038db5959008b3089733f66a214 | [
"Apache-2.0"
] | permissive | JLimperg/lean4-aesop | 8a9d9cd3ee484a8e67fda2dd9822d76708098712 | 5c4b9a3e05c32f69a4357c3047c274f4b94f9c71 | refs/heads/master | 1,689,415,944,104 | 1,627,383,284,000 | 1,627,383,284,000 | 377,536,770 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,961 | lean | /-
Copyright (c) 2021 Jannis Limperg. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jannis Limperg, Asta Halkjær From
-/
import Lean.Aesop.Percent
import Lean.Aesop.RuleTac
import Lean.Aesop.Util
namespace Lean.Aesop
open Lean
open Lean.Meta
/-! ## Rule Indexing Modes -/
inductive IndexingMode : Type
| unindexed
| indexTarget (targetKeys : Array DiscrTree.Key)
deriving Inhabited, BEq
export IndexingMode (unindexed indexTarget)
/-! ## Rules -/
/- The rules in a rule set should be uniquely identified by their name. -/
structure Rule' (α τ : Type) where
name : Name
indexingMode : IndexingMode
extra : α
tac : τ
deriving Inhabited
namespace Rule'
instance : BEq (Rule' α τ) where
beq r s := r.name == s.name
instance [LT α] : LT (Rule' α τ) where
lt r s := r.extra < s.extra
instance [LT α] [DecidableRel (α := α) (· < ·)] :
DecidableRel (α := Rule' α τ) (· < ·) :=
λ r s => inferInstanceAs $ Decidable (r.extra < s.extra)
@[inline]
def map (f : α → β) (g : τ → ι) (r : Rule' α τ) : Rule' β ι :=
{ r with tac := g r.tac, extra := f r.extra }
@[inline]
def mapExtra (f : α → β) (r : Rule' α τ) : Rule' β τ :=
map f id r
@[inline]
def mapTac (f : τ → ι) (r : Rule' α τ) : Rule' α ι :=
map id f r
@[inline]
def mapM [Monad m] (f : α → m β) (g : τ → m ι) (r : Rule' α τ) : m (Rule' β ι) :=
return { r with tac := (← g r.tac), extra := (← f r.extra) }
@[inline]
def mapExtraM [Monad m] (f : α → m β) (r : Rule' α τ) : m (Rule' β τ) :=
mapM f pure r
@[inline]
def mapTacM [Monad m] (f : τ → m ι) (r : Rule' α τ) : m (Rule' α ι) :=
mapM pure f r
def tacToDescr (r : Rule' α RuleTac) : Rule' α RuleTacDescr :=
r.mapTac (·.descr)
def descrToTac (r : Rule' α RuleTacDescr) : MetaM (Rule' α RuleTac) :=
return { r with tac := (← r.tac.toRuleTac) }
end Rule'
/-! ### Normalisation Rules -/
structure NormRuleInfo where
penalty : Int
deriving Inhabited, DecidableEq
instance : LT NormRuleInfo where
lt i j := i.penalty < j.penalty
instance : DecidableRel (α := NormRuleInfo) (· < ·) :=
λ i j => inferInstanceAs $ Decidable (i.penalty < j.penalty)
abbrev NormRule' := Rule' NormRuleInfo
abbrev NormRule := NormRule' RuleTac
instance : ToFormat (NormRule' τ) where
format r := f!"[{r.extra.penalty}] {r.name}"
def defaultNormPenalty : Int := 1
/-! ### Safe and Almost Safe Rules -/
inductive Safety
| safe
| almostSafe
deriving Inhabited, DecidableEq
namespace Safety
instance : ToFormat Safety where
format
| safe => "safe"
| almostSafe => "almostSafe"
end Safety
structure SafeRuleInfo where
penalty : Int
safety : Safety
deriving Inhabited, DecidableEq
instance : LT SafeRuleInfo where
lt i j := i.penalty < j.penalty
instance : DecidableRel (α := SafeRuleInfo) (· < ·) :=
λ i j => inferInstanceAs $ Decidable (i.penalty < j.penalty)
abbrev SafeRule' := Rule' SafeRuleInfo
abbrev SafeRule := SafeRule' RuleTac
instance : ToFormat (SafeRule' τ) where
format r := f!"[{r.extra.penalty}/{r.extra.safety}] {r.name}"
def defaultSafePenalty : Int := 1
/-! ### Unsafe Rules -/
structure UnsafeRuleInfo where
successProbability : Percent
deriving Inhabited
instance : LT UnsafeRuleInfo where
lt i j := i.successProbability > j.successProbability
instance : DecidableRel (α := UnsafeRuleInfo) (· < ·) :=
λ i j => inferInstanceAs $
Decidable (i.successProbability > j.successProbability)
abbrev UnsafeRule' := Rule' UnsafeRuleInfo
abbrev UnsafeRule := UnsafeRule' RuleTac
instance : ToFormat (UnsafeRule' τ) where
format r := f!"[{r.extra.successProbability.toHumanString}] {r.name}"
/-! ### Regular Rules -/
inductive RegularRule' τ
| safe (r : SafeRule' τ)
| «unsafe» (r : UnsafeRule' τ)
deriving BEq
abbrev RegularRule := RegularRule' RuleTac
instance [Inhabited τ] : Inhabited (RegularRule' τ) where
default := RegularRule'.«safe» arbitrary
namespace RegularRule'
instance : ToFormat (RegularRule' τ) where
format
| (safe r) => format r
| («unsafe» r) => format r
def successProbability : RegularRule' τ → Percent
| (safe r) => Percent.hundred
| («unsafe» r) => r.extra.successProbability
def isSafe : RegularRule' τ → Bool
| (safe _) => true
| («unsafe» _) => false
def isUnsafe : RegularRule' τ → Bool
| (safe _) => false
| («unsafe» _) => true
def tac : RegularRule' τ → τ
| (safe r) => r.tac
| («unsafe» r) => r.tac
def name : RegularRule' τ → Name
| (safe r) => r.name
| («unsafe» r) => r.name
end RegularRule'
/-! ## Rule Indices -/
structure RuleIndex (α : Type) where
byTarget : DiscrTree α
unindexed : Array α
deriving Inhabited
namespace RuleIndex
open MessageData in
instance [ToMessageData α] : ToMessageData (RuleIndex α) where
toMessageData ri := node #[
"indexed by target:" ++ node (ri.byTarget.values.map toMessageData),
"unindexed:" ++ node (ri.unindexed.map toMessageData)
]
def empty : RuleIndex α where
byTarget := DiscrTree.empty
unindexed := #[] -- TODO keep these sorted?
instance : EmptyCollection (RuleIndex α) :=
⟨empty⟩
def add [BEq α] (r : α) (imode : IndexingMode) (ri : RuleIndex α) :
RuleIndex α :=
match imode with
| IndexingMode.unindexed => { ri with unindexed := ri.unindexed.push r }
| IndexingMode.indexTarget targetKeys =>
{ ri with byTarget := ri.byTarget.insertCore targetKeys r }
def applicableByTargetRules (ri : RuleIndex α) (goal : MVarId) :
MetaM (Array α) := do
let target ← instantiateMVarsMVarType goal
ri.byTarget.getMatch target
-- TODO remove Inhabited as soon as qsort doesn't require it any more.
def applicableRules [Inhabited α] [LT α] [DecidableRel (α := α) (· < ·)]
(ri : RuleIndex α) (goal : MVarId) : MetaM (Array α) := do
let rs₁ ← applicableByTargetRules ri goal
let rs₂ := ri.unindexed -- TODO does it help if these are already sorted?
return (rs₁ ++ rs₂).qsort (· < ·)
end RuleIndex
/-! ## Rule Set Members -/
inductive RuleSetMember' τ
| normRule (r : NormRule' τ)
| normSimpEntries (es : Array SimpEntry)
| unsafeRule (r : UnsafeRule' τ)
| safeRule (r : SafeRule' τ)
deriving Inhabited
abbrev RuleSetMember := RuleSetMember' RuleTac
abbrev RuleSetMemberDescr := RuleSetMember' RuleTacDescr
namespace RuleSetMember'
def map (f : τ → ι) : RuleSetMember' τ → RuleSetMember' ι
| normRule r => normRule (r.mapTac f)
| normSimpEntries e => normSimpEntries e
| unsafeRule r => unsafeRule (r.mapTac f)
| safeRule r => safeRule (r.mapTac f)
def mapM [Monad m] (f : τ → m ι) : RuleSetMember' τ → m (RuleSetMember' ι)
| normRule r => return normRule (← r.mapTacM f)
| normSimpEntries e => normSimpEntries e
| unsafeRule r => return unsafeRule (← r.mapTacM f)
| safeRule r => return safeRule (← r.mapTacM f)
def toDescr (r : RuleSetMember) : RuleSetMemberDescr :=
r.map (·.descr)
def ofDescr (r : RuleSetMemberDescr) : MetaM RuleSetMember :=
r.mapM (·.toRuleTac)
end RuleSetMember'
/-! ## Rule Set -/
structure RuleSet where
normRules : RuleIndex NormRule
normSimpLemmas : SimpLemmas
unsafeRules : RuleIndex UnsafeRule
safeRules : RuleIndex SafeRule
deriving Inhabited
namespace RuleSet
open MessageData in
instance : ToMessageData RuleSet where
toMessageData rs :=
"Aesop rule set:" ++ node #[
"Unsafe rules:" ++ toMessageData rs.unsafeRules,
"Safe rules:" ++ toMessageData rs.safeRules,
"Normalisation rules:" ++ toMessageData rs.normRules,
"Normalisation simp lemmas:" ++ rs.normSimpLemmas.toMessageData
]
def empty : RuleSet where
normRules := RuleIndex.empty
normSimpLemmas := {}
unsafeRules := RuleIndex.empty
safeRules := RuleIndex.empty
instance : EmptyCollection RuleSet :=
⟨empty⟩
open RuleSetMember' in
def add (rs : RuleSet) : RuleSetMember → RuleSet
| normRule r =>
return { rs with normRules := (← rs.normRules.add r r.indexingMode) }
| normSimpEntries es =>
return { rs with
normSimpLemmas :=
es.foldl (init := rs.normSimpLemmas) SimpLemmas.addSimpEntry }
| unsafeRule r =>
return { rs with unsafeRules := (← rs.unsafeRules.add r r.indexingMode )}
| safeRule r =>
return { rs with safeRules := (← rs.safeRules.add r r.indexingMode )}
def addArray (rs : RuleSet) (ra : Array RuleSetMember) : RuleSet :=
ra.foldl add rs
def applicableNormalizationRules (rs : RuleSet) (goal : MVarId) :
MetaM (Array NormRule) :=
rs.normRules.applicableRules goal
def applicableUnsafeRules (rs : RuleSet) (goal : MVarId) :
MetaM (Array UnsafeRule) :=
rs.unsafeRules.applicableRules goal
def applicableSafeRules (rs : RuleSet) (goal : MVarId) :
MetaM (Array SafeRule) :=
rs.safeRules.applicableRules goal
end RuleSet
end Lean.Aesop
|
b560c42b53ddb3a31cd5c732f9691a8a5ea5183d | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/category_theory/limits/types.lean | 725f39a44564c965aa9b7f9dce4784848cb5a3c5 | [
"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 | 15,226 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Reid Barton
-/
import category_theory.limits.shapes.images
import category_theory.filtered
import tactic.equiv_rw
universes u
open category_theory
open category_theory.limits
namespace category_theory.limits.types
variables {J : Type u} [small_category J]
/--
(internal implementation) the limit cone of a functor,
implemented as flat sections of a pi type
-/
def limit_cone (F : J ⥤ Type u) : cone F :=
{ X := F.sections,
π := { app := λ j u, u.val j } }
local attribute [elab_simple] congr_fun
/-- (internal implementation) the fact that the proposed limit cone is the limit -/
def limit_cone_is_limit (F : J ⥤ Type u) : is_limit (limit_cone F) :=
{ lift := λ s v, ⟨λ j, s.π.app j v, λ j j' f, congr_fun (cone.w s f) _⟩,
uniq' := by { intros, ext x j, exact congr_fun (w j) x } }
/--
The category of types has all limits.
See https://stacks.math.columbia.edu/tag/002U.
-/
instance : has_limits (Type u) :=
{ has_limits_of_shape := λ J 𝒥, by exactI
{ has_limit := λ F, has_limit.mk
{ cone := limit_cone F, is_limit := limit_cone_is_limit F } } }
/--
The equivalence between a limiting cone of `F` in `Type u` and the "concrete" definition as the
sections of `F`.
-/
def is_limit_equiv_sections {F : J ⥤ Type u} {c : cone F} (t : is_limit c) :
c.X ≃ F.sections :=
(is_limit.cone_point_unique_up_to_iso t (limit_cone_is_limit F)).to_equiv
@[simp]
lemma is_limit_equiv_sections_apply
{F : J ⥤ Type u} {c : cone F} (t : is_limit c) (j : J) (x : c.X) :
(((is_limit_equiv_sections t) x) : Π j, F.obj j) j = c.π.app j x :=
rfl
@[simp]
lemma is_limit_equiv_sections_symm_apply
{F : J ⥤ Type u} {c : cone F} (t : is_limit c) (x : F.sections) (j : J) :
c.π.app j ((is_limit_equiv_sections t).symm x) = (x : Π j, F.obj j) j :=
begin
equiv_rw (is_limit_equiv_sections t).symm at x,
simp,
end
/--
The equivalence between the abstract limit of `F` in `Type u`
and the "concrete" definition as the sections of `F`.
-/
noncomputable
def limit_equiv_sections (F : J ⥤ Type u) : (limit F : Type u) ≃ F.sections :=
is_limit_equiv_sections (limit.is_limit _)
@[simp]
lemma limit_equiv_sections_apply (F : J ⥤ Type u) (x : limit F) (j : J) :
(((limit_equiv_sections F) x) : Π j, F.obj j) j = limit.π F j x :=
rfl
@[simp]
lemma limit_equiv_sections_symm_apply (F : J ⥤ Type u) (x : F.sections) (j : J) :
limit.π F j ((limit_equiv_sections F).symm x) = (x : Π j, F.obj j) j :=
is_limit_equiv_sections_symm_apply _ _ _
/--
Construct a term of `limit F : Type u` from a family of terms `x : Π j, F.obj j`
which are "coherent": `∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j'`.
-/
@[ext]
noncomputable
def limit.mk (F : J ⥤ Type u) (x : Π j, F.obj j) (h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') :
(limit F : Type u) :=
(limit_equiv_sections F).symm ⟨x, h⟩
@[simp]
lemma limit.π_mk
(F : J ⥤ Type u) (x : Π j, F.obj j) (h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') (j) :
limit.π F j (limit.mk F x h) = x j :=
by { dsimp [limit.mk], simp, }
-- PROJECT: prove this for concrete categories where the forgetful functor preserves limits
@[ext]
lemma limit_ext (F : J ⥤ Type u) (x y : limit F) (w : ∀ j, limit.π F j x = limit.π F j y) :
x = y :=
begin
apply (limit_equiv_sections F).injective,
ext j,
simp [w j],
end
lemma limit_ext_iff (F : J ⥤ Type u) (x y : limit F) :
x = y ↔ (∀ j, limit.π F j x = limit.π F j y) :=
⟨λ t _, t ▸ rfl, limit_ext _ _ _⟩
-- TODO: are there other limits lemmas that should have `_apply` versions?
-- Can we generate these like with `@[reassoc]`?
-- PROJECT: prove these for any concrete category where the forgetful functor preserves limits?
@[simp]
lemma limit.w_apply {F : J ⥤ Type u} {j j' : J} {x : limit F} (f : j ⟶ j') :
F.map f (limit.π F j x) = limit.π F j' x :=
congr_fun (limit.w F f) x
@[simp]
lemma limit.lift_π_apply (F : J ⥤ Type u) (s : cone F) (j : J) (x : s.X) :
limit.π F j (limit.lift F s x) = s.π.app j x :=
congr_fun (limit.lift_π s j) x
@[simp]
lemma limit.map_π_apply {F G : J ⥤ Type u} (α : F ⟶ G) (j : J) (x) :
limit.π G j (lim_map α x) = α.app j (limit.π F j x) :=
congr_fun (lim_map_π α j) x
/--
The relation defining the quotient type which implements the colimit of a functor `F : J ⥤ Type u`.
See `category_theory.limits.types.quot`.
-/
def quot.rel (F : J ⥤ Type u) : (Σ j, F.obj j) → (Σ j, F.obj j) → Prop :=
(λ p p', ∃ f : p.1 ⟶ p'.1, p'.2 = F.map f p.2)
/--
A quotient type implementing the colimit of a functor `F : J ⥤ Type u`,
as pairs `⟨j, x⟩` where `x : F.obj j`, modulo the equivalence relation generated by
`⟨j, x⟩ ~ ⟨j', x'⟩` whenever there is a morphism `f : j ⟶ j'` so `F.map f x = x'`.
-/
@[nolint has_inhabited_instance]
def quot (F : J ⥤ Type u) : Type u :=
@quot (Σ j, F.obj j) (quot.rel F)
/--
(internal implementation) the colimit cocone of a functor,
implemented as a quotient of a sigma type
-/
def colimit_cocone (F : J ⥤ Type u) : cocone F :=
{ X := quot F,
ι :=
{ app := λ j x, quot.mk _ ⟨j, x⟩,
naturality' := λ j j' f, funext $ λ x, eq.symm (quot.sound ⟨f, rfl⟩) } }
local attribute [elab_with_expected_type] quot.lift
/-- (internal implementation) the fact that the proposed colimit cocone is the colimit -/
def colimit_cocone_is_colimit (F : J ⥤ Type u) : is_colimit (colimit_cocone F) :=
{ desc := λ s, quot.lift (λ (p : Σ j, F.obj j), s.ι.app p.1 p.2)
(assume ⟨j, x⟩ ⟨j', x'⟩ ⟨f, hf⟩, by rw hf; exact (congr_fun (cocone.w s f) x).symm) }
/--
The category of types has all colimits.
See https://stacks.math.columbia.edu/tag/002U.
-/
instance : has_colimits (Type u) :=
{ has_colimits_of_shape := λ J 𝒥, by exactI
{ has_colimit := λ F, has_colimit.mk
{ cocone := colimit_cocone F, is_colimit := colimit_cocone_is_colimit F } } }
/--
The equivalence between the abstract colimit of `F` in `Type u`
and the "concrete" definition as a quotient.
-/
noncomputable
def colimit_equiv_quot (F : J ⥤ Type u) : (colimit F : Type u) ≃ quot F :=
(is_colimit.cocone_point_unique_up_to_iso
(colimit.is_colimit F)
(colimit_cocone_is_colimit F)).to_equiv
@[simp]
lemma colimit_equiv_quot_symm_apply (F : J ⥤ Type u) (j : J) (x : F.obj j) :
(colimit_equiv_quot F).symm (quot.mk _ ⟨j, x⟩) = colimit.ι F j x :=
rfl
@[simp]
lemma colimit_equiv_quot_apply (F : J ⥤ Type u) (j : J) (x : F.obj j) :
(colimit_equiv_quot F) (colimit.ι F j x) = quot.mk _ ⟨j, x⟩ :=
begin
apply (colimit_equiv_quot F).symm.injective,
simp,
end
@[simp]
lemma colimit.w_apply {F : J ⥤ Type u} {j j' : J} {x : F.obj j} (f : j ⟶ j') :
colimit.ι F j' (F.map f x) = colimit.ι F j x :=
congr_fun (colimit.w F f) x
@[simp]
lemma colimit.ι_desc_apply (F : J ⥤ Type u) (s : cocone F) (j : J) (x : F.obj j) :
colimit.desc F s (colimit.ι F j x) = s.ι.app j x :=
congr_fun (colimit.ι_desc s j) x
@[simp]
lemma colimit.ι_map_apply {F G : J ⥤ Type u} (α : F ⟶ G) (j : J) (x) :
colim.map α (colimit.ι F j x) = colimit.ι G j (α.app j x) :=
congr_fun (colimit.ι_map α j) x
lemma colimit_sound
{F : J ⥤ Type u} {j j' : J} {x : F.obj j} {x' : F.obj j'} (f : j ⟶ j') (w : F.map f x = x') :
colimit.ι F j x = colimit.ι F j' x' :=
begin
rw [←w],
simp,
end
lemma colimit_sound'
{F : J ⥤ Type u} {j j' : J} {x : F.obj j} {x' : F.obj j'} {j'' : J} (f : j ⟶ j'') (f' : j' ⟶ j'')
(w : F.map f x = F.map f' x') :
colimit.ι F j x = colimit.ι F j' x' :=
begin
rw [←colimit.w _ f, ←colimit.w _ f'],
rw [types_comp_apply, types_comp_apply, w],
end
lemma colimit_eq {F : J ⥤ Type u } {j j' : J} {x : F.obj j} {x' : F.obj j'}
(w : colimit.ι F j x = colimit.ι F j' x') : eqv_gen (quot.rel F) ⟨j, x⟩ ⟨j', x'⟩ :=
begin
apply quot.eq.1,
simpa using congr_arg (colimit_equiv_quot F) w,
end
lemma jointly_surjective (F : J ⥤ Type u) {t : cocone F} (h : is_colimit t)
(x : t.X) : ∃ j y, t.ι.app j y = x :=
begin
suffices : (λ (x : t.X), ulift.up (∃ j y, t.ι.app j y = x)) = (λ _, ulift.up true),
{ have := congr_fun this x,
have H := congr_arg ulift.down this,
dsimp at H,
rwa eq_true at H },
refine h.hom_ext _,
intro j, ext y,
erw iff_true,
exact ⟨j, y, rfl⟩
end
/-- A variant of `jointly_surjective` for `x : colimit F`. -/
lemma jointly_surjective' {F : J ⥤ Type u}
(x : colimit F) : ∃ j y, colimit.ι F j y = x :=
jointly_surjective F (colimit.is_colimit _) x
namespace filtered_colimit
/- For filtered colimits of types, we can give an explicit description
of the equivalence relation generated by the relation used to form
the colimit. -/
variables (F : J ⥤ Type u)
/--
An alternative relation on `Σ j, F.obj j`,
which generates the same equivalence relation as we use to define the colimit in `Type` above,
but that is more convenient when working with filtered colimits.
Elements in `F.obj j` and `F.obj j'` are equivalent if there is some `k : J` to the right
where their images are equal.
-/
protected def rel (x y : Σ j, F.obj j) : Prop :=
∃ k (f : x.1 ⟶ k) (g : y.1 ⟶ k), F.map f x.2 = F.map g y.2
lemma rel_of_quot_rel (x y : Σ j, F.obj j) : quot.rel F x y → filtered_colimit.rel F x y :=
λ ⟨f, h⟩, ⟨y.1, f, 𝟙 y.1, by rw [← h, functor_to_types.map_id_apply]⟩
lemma eqv_gen_quot_rel_of_rel (x y : Σ j, F.obj j) :
filtered_colimit.rel F x y → eqv_gen (quot.rel F) x y :=
λ ⟨k, f, g, h⟩, eqv_gen.trans _ ⟨k, F.map f x.2⟩ _ (eqv_gen.rel _ _ ⟨f, rfl⟩)
(eqv_gen.symm _ _ (eqv_gen.rel _ _ ⟨g, h⟩))
local attribute [elab_simple] nat_trans.app
/-- Recognizing filtered colimits of types. -/
noncomputable def is_colimit_of (t : cocone F) (hsurj : ∀ (x : t.X), ∃ i xi, x = t.ι.app i xi)
(hinj : ∀ i j xi xj, t.ι.app i xi = t.ι.app j xj →
∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj) : is_colimit t :=
-- Strategy: Prove that the map from "the" colimit of F (defined above) to t.X
-- is a bijection.
begin
apply is_colimit.of_iso_colimit (colimit.is_colimit F),
refine cocones.ext (equiv.to_iso (equiv.of_bijective _ _)) _,
{ exact colimit.desc F t },
{ split,
{ show function.injective _,
intros a b h,
rcases jointly_surjective F (colimit.is_colimit F) a with ⟨i, xi, rfl⟩,
rcases jointly_surjective F (colimit.is_colimit F) b with ⟨j, xj, rfl⟩,
change (colimit.ι F i ≫ colimit.desc F t) xi = (colimit.ι F j ≫ colimit.desc F t) xj at h,
rw [colimit.ι_desc, colimit.ι_desc] at h,
rcases hinj i j xi xj h with ⟨k, f, g, h'⟩,
change colimit.ι F i xi = colimit.ι F j xj,
rw [←colimit.w F f, ←colimit.w F g],
change colimit.ι F k (F.map f xi) = colimit.ι F k (F.map g xj),
rw h' },
{ show function.surjective _,
intro x,
rcases hsurj x with ⟨i, xi, rfl⟩,
use colimit.ι F i xi,
simp } },
{ intro j, apply colimit.ι_desc }
end
variables [is_filtered_or_empty J]
protected lemma rel_equiv : equivalence (filtered_colimit.rel F) :=
⟨λ x, ⟨x.1, 𝟙 x.1, 𝟙 x.1, rfl⟩,
λ x y ⟨k, f, g, h⟩, ⟨k, g, f, h.symm⟩,
λ x y z ⟨k, f, g, h⟩ ⟨k', f', g', h'⟩,
let ⟨l, fl, gl, _⟩ := is_filtered_or_empty.cocone_objs k k',
⟨m, n, hn⟩ := is_filtered_or_empty.cocone_maps (g ≫ fl) (f' ≫ gl) in
⟨m, f ≫ fl ≫ n, g' ≫ gl ≫ n, calc
F.map (f ≫ fl ≫ n) x.2
= F.map (fl ≫ n) (F.map f x.2) : by simp
... = F.map (fl ≫ n) (F.map g y.2) : by rw h
... = F.map ((g ≫ fl) ≫ n) y.2 : by simp
... = F.map ((f' ≫ gl) ≫ n) y.2 : by rw hn
... = F.map (gl ≫ n) (F.map f' y.2) : by simp
... = F.map (gl ≫ n) (F.map g' z.2) : by rw h'
... = F.map (g' ≫ gl ≫ n) z.2 : by simp⟩⟩
protected lemma rel_eq_eqv_gen_quot_rel :
filtered_colimit.rel F = eqv_gen (quot.rel F) :=
begin
ext ⟨j, x⟩ ⟨j', y⟩,
split,
{ apply eqv_gen_quot_rel_of_rel },
{ rw ← relation.eqv_gen_iff_of_equivalence (filtered_colimit.rel_equiv F),
exact relation.eqv_gen_mono (rel_of_quot_rel F) }
end
lemma colimit_eq_iff_aux {i j : J} {xi : F.obj i} {xj : F.obj j} :
(colimit_cocone F).ι.app i xi = (colimit_cocone F).ι.app j xj ↔
filtered_colimit.rel F ⟨i, xi⟩ ⟨j, xj⟩ :=
begin
change quot.mk _ _ = quot.mk _ _ ↔ _,
rw [quot.eq, filtered_colimit.rel_eq_eqv_gen_quot_rel],
end
lemma is_colimit_eq_iff {t : cocone F} (ht : is_colimit t) {i j : J} {xi : F.obj i} {xj : F.obj j} :
t.ι.app i xi = t.ι.app j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj :=
let t' := colimit_cocone F,
e : t' ≅ t := is_colimit.unique_up_to_iso (colimit_cocone_is_colimit F) ht,
e' : t'.X ≅ t.X := (cocones.forget _).map_iso e in
begin
refine iff.trans _ (colimit_eq_iff_aux F),
convert e'.to_equiv.apply_eq_iff_eq; rw ←e.hom.w; refl
end
lemma colimit_eq_iff {i j : J} {xi : F.obj i} {xj : F.obj j} :
colimit.ι F i xi = colimit.ι F j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj :=
is_colimit_eq_iff _ (colimit.is_colimit F)
end filtered_colimit
variables {α β : Type u} (f : α ⟶ β)
section -- implementation of `has_image`
/-- the image of a morphism in Type is just `set.range f` -/
def image : Type u := set.range f
instance [inhabited α] : inhabited (image f) :=
{ default := ⟨f (default α), ⟨_, rfl⟩⟩ }
/-- the inclusion of `image f` into the target -/
def image.ι : image f ⟶ β := subtype.val
instance : mono (image.ι f) :=
(mono_iff_injective _).2 subtype.val_injective
variables {f}
/-- the universal property for the image factorisation -/
noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I :=
(λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I)
lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f :=
begin
ext x,
change (F'.e ≫ F'.m) _ = _,
rw [F'.fac, (classical.indefinite_description _ x.2).2],
refl,
end
end
/-- the factorisation of any morphism in Type through a mono. -/
def mono_factorisation : mono_factorisation f :=
{ I := image f,
m := image.ι f,
e := set.range_factorization f }
/-- the facorisation through a mono has the universal property of the image. -/
noncomputable def is_image : is_image (mono_factorisation f) :=
{ lift := image.lift,
lift_fac' := image.lift_fac }
instance : has_image f :=
has_image.mk ⟨_, is_image f⟩
instance : has_images (Type u) :=
{ has_image := by apply_instance }
instance : has_image_maps (Type u) :=
{ has_image_map := λ f g st, has_image_map.transport st (mono_factorisation f.hom) (is_image g.hom)
(λ x, ⟨st.right x.1, ⟨st.left (classical.some x.2),
begin
have p := st.w,
replace p := congr_fun p (classical.some x.2),
simp only [functor.id_map, types_comp_apply, subtype.val_eq_coe] at p,
erw [p, classical.some_spec x.2],
end⟩⟩) rfl }
end category_theory.limits.types
|
aea378c94df2d9aca41452bc9a2b32128c211285 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/calculus/extend_deriv.lean | ab93efeadaf14998816480ad2c8f5b05b8d7266d | [
"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,551 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.calculus.mean_value
/-!
# Extending differentiability to the boundary
We investigate how differentiable functions inside a set extend to differentiable functions
on the boundary. For this, it suffices that the function and its derivative admit limits there.
A general version of this statement is given in `has_fderiv_at_boundary_of_tendsto_fderiv`.
One-dimensional versions, in which one wants to obtain differentiability at the left endpoint or
the right endpoint of an interval, are given in
`has_deriv_at_interval_left_endpoint_of_tendsto_deriv` and
`has_deriv_at_interval_right_endpoint_of_tendsto_deriv`. These versions are formulated in terms
of the one-dimensional derivative `deriv ℝ f`.
-/
variables {E : Type*} [normed_group E] [normed_space ℝ E]
{F : Type*} [normed_group F] [normed_space ℝ F]
open filter set metric continuous_linear_map
open_locale topological_space
local attribute [mono] prod_mono
/-- If a function `f` is differentiable in a convex open set and continuous on its closure, and its
derivative converges to a limit `f'` at a point on the boundary, then `f` is differentiable there
with derivative `f'`. -/
theorem has_fderiv_at_boundary_of_tendsto_fderiv {f : E → F} {s : set E} {x : E} {f' : E →L[ℝ] F}
(f_diff : differentiable_on ℝ f s) (s_conv : convex ℝ s) (s_open : is_open s)
(f_cont : ∀y ∈ closure s, continuous_within_at f s y)
(h : tendsto (λy, fderiv ℝ f y) (𝓝[s] x) (𝓝 f')) :
has_fderiv_within_at f f' (closure s) x :=
begin
classical,
-- one can assume without loss of generality that `x` belongs to the closure of `s`, as the
-- statement is empty otherwise
by_cases hx : x ∉ closure s,
{ rw ← closure_closure at hx, exact has_fderiv_within_at_of_not_mem_closure hx },
push_neg at hx,
rw [has_fderiv_within_at, has_fderiv_at_filter, asymptotics.is_o_iff],
/- One needs to show that `∥f y - f x - f' (y - x)∥ ≤ ε ∥y - x∥` for `y` close to `x` in `closure
s`, where `ε` is an arbitrary positive constant. By continuity of the functions, it suffices to
prove this for nearby points inside `s`. In a neighborhood of `x`, the derivative of `f` is
arbitrarily close to `f'` by assumption. The mean value inequality completes the proof. -/
assume ε ε_pos,
obtain ⟨δ, δ_pos, hδ⟩ : ∃ δ > 0, ∀ y ∈ s, dist y x < δ → ∥fderiv ℝ f y - f'∥ < ε,
by simpa [dist_zero_right] using tendsto_nhds_within_nhds.1 h ε ε_pos,
set B := ball x δ,
suffices : ∀ y ∈ B ∩ (closure s), ∥f y - f x - (f' y - f' x)∥ ≤ ε * ∥y - x∥,
from mem_nhds_within_iff.2 ⟨δ, δ_pos, λy hy, by simpa using this y hy⟩,
suffices : ∀ p : E × E, p ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) → ∥f p.2 - f p.1 - (f' p.2 - f' p.1)∥
≤ ε * ∥p.2 - p.1∥,
{ rw closure_prod_eq at this,
intros y y_in,
apply this ⟨x, y⟩,
have : B ∩ closure s ⊆ closure (B ∩ s), from closure_inter_open is_open_ball,
exact ⟨this ⟨mem_ball_self δ_pos, hx⟩, this y_in⟩ },
have key : ∀ p : E × E, p ∈ (B ∩ s) ×ˢ (B ∩ s) → ∥f p.2 - f p.1 - (f' p.2 - f' p.1)∥
≤ ε * ∥p.2 - p.1∥,
{ rintros ⟨u, v⟩ ⟨u_in, v_in⟩,
have conv : convex ℝ (B ∩ s) := (convex_ball _ _).inter s_conv,
have diff : differentiable_on ℝ f (B ∩ s) := f_diff.mono (inter_subset_right _ _),
have bound : ∀ z ∈ (B ∩ s), ∥fderiv_within ℝ f (B ∩ s) z - f'∥ ≤ ε,
{ intros z z_in,
convert le_of_lt (hδ _ z_in.2 z_in.1),
have op : is_open (B ∩ s) := is_open_ball.inter s_open,
rw differentiable_at.fderiv_within _ (op.unique_diff_on z z_in),
exact (diff z z_in).differentiable_at (is_open.mem_nhds op z_in) },
simpa using conv.norm_image_sub_le_of_norm_fderiv_within_le' diff bound u_in v_in },
rintros ⟨u, v⟩ uv_in,
refine continuous_within_at.closure_le uv_in _ _ key,
have f_cont' : ∀y ∈ closure s, continuous_within_at (f - f') s y,
{ intros y y_in,
exact tendsto.sub (f_cont y y_in) (f'.cont.continuous_within_at) },
all_goals { -- common start for both continuity proofs
have : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s, by mono ; exact inter_subset_right _ _,
obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s,
by simpa [closure_prod_eq] using closure_mono this uv_in,
apply continuous_within_at.mono _ this,
simp only [continuous_within_at] },
rw nhds_within_prod_eq,
{ have : ∀ u v, f v - f u - (f' v - f' u) = f v - f' v - (f u - f' u) := by { intros, abel },
simp only [this],
exact tendsto.comp continuous_norm.continuous_at
((tendsto.comp (f_cont' v v_in) tendsto_snd).sub $
tendsto.comp (f_cont' u u_in) tendsto_fst) },
{ apply tendsto_nhds_within_of_tendsto_nhds,
rw nhds_prod_eq,
exact tendsto_const_nhds.mul
(tendsto.comp continuous_norm.continuous_at $ tendsto_snd.sub tendsto_fst) },
end
/-- If a function is differentiable on the right of a point `a : ℝ`, continuous at `a`, and
its derivative also converges at `a`, then `f` is differentiable on the right at `a`. -/
lemma has_deriv_at_interval_left_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E}
(f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a)
(hs : s ∈ 𝓝[>] a)
(f_lim' : tendsto (λx, deriv f x) (𝓝[>] a) (𝓝 e)) :
has_deriv_within_at f e (Ici a) a :=
begin
/- This is a specialization of `has_fderiv_at_boundary_of_tendsto_fderiv`. To be in the setting of
this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we
call `t = (a, b)`. Then, we check all the assumptions of this theorem and we apply it. -/
obtain ⟨b, ab : a < b, sab : Ioc a b ⊆ s⟩ :=
mem_nhds_within_Ioi_iff_exists_Ioc_subset.1 hs,
let t := Ioo a b,
have ts : t ⊆ s := subset.trans Ioo_subset_Ioc_self sab,
have t_diff : differentiable_on ℝ f t := f_diff.mono ts,
have t_conv : convex ℝ t := convex_Ioo a b,
have t_open : is_open t := is_open_Ioo,
have t_closure : closure t = Icc a b := closure_Ioo ab.ne,
have t_cont : ∀y ∈ closure t, continuous_within_at f t y,
{ rw t_closure,
assume y hy,
by_cases h : y = a,
{ rw h, exact f_lim.mono ts },
{ have : y ∈ s := sab ⟨lt_of_le_of_ne hy.1 (ne.symm h), hy.2⟩,
exact (f_diff.continuous_on y this).mono ts } },
have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)),
{ simp [deriv_fderiv.symm],
refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _,
exact tendsto_nhds_within_mono_left Ioo_subset_Ioi_self f_lim' },
-- now we can apply `has_fderiv_at_boundary_of_differentiable`
have : has_deriv_within_at f e (Icc a b) a,
{ rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure],
exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' },
exact this.nhds_within (mem_nhds_within_Ici_iff_exists_Icc_subset.2 ⟨b, ab, subset.refl _⟩)
end
/-- If a function is differentiable on the left of a point `a : ℝ`, continuous at `a`, and
its derivative also converges at `a`, then `f` is differentiable on the left at `a`. -/
lemma has_deriv_at_interval_right_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E}
(f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a)
(hs : s ∈ 𝓝[<] a)
(f_lim' : tendsto (λx, deriv f x) (𝓝[<] a) (𝓝 e)) :
has_deriv_within_at f e (Iic a) a :=
begin
/- This is a specialization of `has_fderiv_at_boundary_of_differentiable`. To be in the setting of
this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we
call `t = (b, a)`. Then, we check all the assumptions of this theorem and we apply it. -/
obtain ⟨b, ba, sab⟩ : ∃ b ∈ Iio a, Ico b a ⊆ s :=
mem_nhds_within_Iio_iff_exists_Ico_subset.1 hs,
let t := Ioo b a,
have ts : t ⊆ s := subset.trans Ioo_subset_Ico_self sab,
have t_diff : differentiable_on ℝ f t := f_diff.mono ts,
have t_conv : convex ℝ t := convex_Ioo b a,
have t_open : is_open t := is_open_Ioo,
have t_closure : closure t = Icc b a := closure_Ioo (ne_of_lt ba),
have t_cont : ∀y ∈ closure t, continuous_within_at f t y,
{ rw t_closure,
assume y hy,
by_cases h : y = a,
{ rw h, exact f_lim.mono ts },
{ have : y ∈ s := sab ⟨hy.1, lt_of_le_of_ne hy.2 h⟩,
exact (f_diff.continuous_on y this).mono ts } },
have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)),
{ simp [deriv_fderiv.symm],
refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _,
exact tendsto_nhds_within_mono_left Ioo_subset_Iio_self f_lim' },
-- now we can apply `has_fderiv_at_boundary_of_differentiable`
have : has_deriv_within_at f e (Icc b a) a,
{ rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure],
exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' },
exact this.nhds_within (mem_nhds_within_Iic_iff_exists_Icc_subset.2 ⟨b, ba, subset.refl _⟩)
end
/-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are
continuous at this point, then `g` is also the derivative of `f` at this point. -/
lemma has_deriv_at_of_has_deriv_at_of_ne {f g : ℝ → E} {x : ℝ}
(f_diff : ∀ y ≠ x, has_deriv_at f (g y) y)
(hf : continuous_at f x) (hg : continuous_at g x) :
has_deriv_at f (g x) x :=
begin
have A : has_deriv_within_at f (g x) (Ici x) x,
{ have diff : differentiable_on ℝ f (Ioi x) :=
λy hy, (f_diff y (ne_of_gt hy)).differentiable_at.differentiable_within_at,
-- next line is the nontrivial bit of this proof, appealing to differentiability
-- extension results.
apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff hf.continuous_within_at
self_mem_nhds_within,
have : tendsto g (𝓝[>] x) (𝓝 (g x)) := tendsto_inf_left hg,
apply this.congr' _,
apply mem_of_superset self_mem_nhds_within (λy hy, _),
exact (f_diff y (ne_of_gt hy)).deriv.symm },
have B : has_deriv_within_at f (g x) (Iic x) x,
{ have diff : differentiable_on ℝ f (Iio x) :=
λy hy, (f_diff y (ne_of_lt hy)).differentiable_at.differentiable_within_at,
-- next line is the nontrivial bit of this proof, appealing to differentiability
-- extension results.
apply has_deriv_at_interval_right_endpoint_of_tendsto_deriv diff hf.continuous_within_at
self_mem_nhds_within,
have : tendsto g (𝓝[<] x) (𝓝 (g x)) := tendsto_inf_left hg,
apply this.congr' _,
apply mem_of_superset self_mem_nhds_within (λy hy, _),
exact (f_diff y (ne_of_lt hy)).deriv.symm },
simpa using B.union A
end
/-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are
continuous at this point, then `g` is the derivative of `f` everywhere. -/
lemma has_deriv_at_of_has_deriv_at_of_ne' {f g : ℝ → E} {x : ℝ}
(f_diff : ∀ y ≠ x, has_deriv_at f (g y) y)
(hf : continuous_at f x) (hg : continuous_at g x) (y : ℝ) :
has_deriv_at f (g y) y :=
begin
rcases eq_or_ne y x with rfl|hne,
{ exact has_deriv_at_of_has_deriv_at_of_ne f_diff hf hg },
{ exact f_diff y hne }
end
|
cde218e0603efed723f08f7d1cf713d7ff784e57 | 680b0d1592ce164979dab866b232f6fa743f2cc8 | /library/init/logic.lean | b4bdf7e26b0deafe9f266af92e1525f8b5810963 | [
"Apache-2.0"
] | permissive | syohex/lean | 657428ab520f8277fc18cf04bea2ad200dbae782 | 081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc | refs/heads/master | 1,611,274,838,635 | 1,452,668,188,000 | 1,452,668,188,000 | 49,562,028 | 0 | 0 | null | 1,452,675,604,000 | 1,452,675,602,000 | null | UTF-8 | Lean | false | false | 33,575 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn
-/
prelude
import init.datatypes init.reserved_notation init.tactic
definition id [reducible] [unfold_full] {A : Type} (a : A) : A :=
a
/- implication -/
definition implies (a b : Prop) := a → b
lemma implies.trans [trans] {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r :=
assume hp, h₂ (h₁ hp)
definition trivial := true.intro
definition not (a : Prop) := a → false
prefix `¬` := not
definition absurd {a : Prop} {b : Type} (H1 : a) (H2 : ¬a) : b :=
false.rec b (H2 H1)
lemma not.intro [intro!] {a : Prop} (H : a → false) : ¬ a :=
H
theorem mt {a b : Prop} (H1 : a → b) (H2 : ¬b) : ¬a :=
assume Ha : a, absurd (H1 Ha) H2
definition implies.resolve {a b : Prop} (H : a → b) (nb : ¬ b) : ¬ a := assume Ha, nb (H Ha)
/- not -/
theorem not_false : ¬false :=
assume H : false, H
definition non_contradictory (a : Prop) : Prop := ¬¬a
theorem non_contradictory_intro {a : Prop} (Ha : a) : ¬¬a :=
assume Hna : ¬a, absurd Ha Hna
/- false -/
theorem false.elim {c : Prop} (H : false) : c :=
false.rec c H
/- eq -/
notation a = b := eq a b
definition rfl {A : Type} {a : A} : a = a := eq.refl a
-- proof irrelevance is built in
theorem proof_irrel {a : Prop} (H₁ H₂ : a) : H₁ = H₂ :=
rfl
-- Remark: we provide the universe levels explicitly to make sure `eq.drec` has the same type of `eq.rec` in the HoTT library
protected theorem eq.drec.{l₁ l₂} {A : Type.{l₂}} {a : A} {C : Π (x : A), a = x → Type.{l₁}} (h₁ : C a (eq.refl a)) {b : A} (h₂ : a = b) : C b h₂ :=
eq.rec (λh₂ : a = a, show C a h₂, from h₁) h₂ h₂
namespace eq
variables {A : Type}
variables {a b c a': A}
protected theorem drec_on {a : A} {C : Π (x : A), a = x → Type} {b : A} (h₂ : a = b) (h₁ : C a (refl a)) : C b h₂ :=
eq.drec h₁ h₂
theorem subst {P : A → Prop} (H₁ : a = b) (H₂ : P a) : P b :=
eq.rec H₂ H₁
theorem trans (H₁ : a = b) (H₂ : b = c) : a = c :=
subst H₂ H₁
theorem symm : a = b → b = a :=
eq.rec (refl a)
theorem substr {P : A → Prop} (H₁ : b = a) : P a → P b :=
subst (symm H₁)
theorem mp {a b : Type} : (a = b) → a → b :=
eq.rec_on
theorem mpr {a b : Type} : (a = b) → b → a :=
assume H₁ H₂, eq.rec_on (eq.symm H₁) H₂
namespace ops
notation H `⁻¹` := symm H --input with \sy or \-1 or \inv
notation H1 ⬝ H2 := trans H1 H2
notation H1 ▸ H2 := subst H1 H2
notation H1 ▹ H2 := eq.rec H2 H1
end ops
end eq
theorem congr {A B : Type} {f₁ f₂ : A → B} {a₁ a₂ : A} (H₁ : f₁ = f₂) (H₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ :=
eq.subst H₁ (eq.subst H₂ rfl)
theorem congr_fun {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) (a : A) : f a = g a :=
eq.subst H (eq.refl (f a))
theorem congr_arg {A B : Type} {a₁ a₂ : A} (f : A → B) : a₁ = a₂ → f a₁ = f a₂ :=
congr rfl
section
variables {A : Type} {a b c: A}
open eq.ops
theorem trans_rel_left (R : A → A → Prop) (H₁ : R a b) (H₂ : b = c) : R a c :=
H₂ ▸ H₁
theorem trans_rel_right (R : A → A → Prop) (H₁ : a = b) (H₂ : R b c) : R a c :=
H₁⁻¹ ▸ H₂
end
section
variable {p : Prop}
open eq.ops
theorem of_eq_true (H : p = true) : p :=
H⁻¹ ▸ trivial
theorem not_of_eq_false (H : p = false) : ¬p :=
assume Hp, H ▸ Hp
end
attribute eq.subst [subst]
attribute eq.refl [refl]
attribute eq.trans [trans]
attribute eq.symm [symm]
/- ne -/
definition ne [reducible] {A : Type} (a b : A) := ¬(a = b)
notation a ≠ b := ne a b
namespace ne
open eq.ops
variable {A : Type}
variables {a b : A}
theorem intro (H : a = b → false) : a ≠ b := H
theorem elim (H : a ≠ b) : a = b → false := H
theorem irrefl (H : a ≠ a) : false := H rfl
theorem symm (H : a ≠ b) : b ≠ a :=
assume (H₁ : b = a), H (H₁⁻¹)
end ne
theorem false_of_ne {A : Type} {a : A} : a ≠ a → false := ne.irrefl
section
open eq.ops
variables {p : Prop}
theorem ne_false_of_self : p → p ≠ false :=
assume (Hp : p) (Heq : p = false), Heq ▸ Hp
theorem ne_true_of_not : ¬p → p ≠ true :=
assume (Hnp : ¬p) (Heq : p = true), (Heq ▸ Hnp) trivial
theorem true_ne_false : ¬true = false :=
ne_false_of_self trivial
end
infixl ` == `:50 := heq
section
universe variable u
variables {A B C : Type.{u}} {a a' : A} {b b' : B} {c : C}
theorem eq_of_heq (H : a == a') : a = a' :=
have H₁ : ∀ (Ht : A = A), eq.rec a Ht = a, from
λ Ht, eq.refl a,
heq.rec H₁ H (eq.refl A)
theorem heq.elim {A : Type} {a : A} {P : A → Type} {b : A} (H₁ : a == b)
: P a → P b := eq.rec_on (eq_of_heq H₁)
theorem heq.subst {P : ∀T : Type, T → Prop} : a == b → P A a → P B b :=
heq.rec_on
theorem heq.symm (H : a == b) : b == a :=
heq.rec_on H (heq.refl a)
theorem heq_of_eq (H : a = a') : a == a' :=
eq.subst H (heq.refl a)
theorem heq.trans (H₁ : a == b) (H₂ : b == c) : a == c :=
heq.subst H₂ H₁
theorem heq_of_heq_of_eq (H₁ : a == b) (H₂ : b = b') : a == b' :=
heq.trans H₁ (heq_of_eq H₂)
theorem heq_of_eq_of_heq (H₁ : a = a') (H₂ : a' == b) : a == b :=
heq.trans (heq_of_eq H₁) H₂
definition type_eq_of_heq (H : a == b) : A = B :=
heq.rec_on H (eq.refl A)
end
open eq.ops
theorem eq_rec_heq {A : Type} {P : A → Type} {a a' : A} (H : a = a') (p : P a) : H ▹ p == p :=
eq.drec_on H !heq.refl
theorem heq_of_eq_rec_left {A : Type} {P : A → Type} : ∀ {a a' : A} {p₁ : P a} {p₂ : P a'} (e : a = a') (h₂ : e ▹ p₁ = p₂), p₁ == p₂
| a a p₁ p₂ (eq.refl a) h := eq.rec_on h !heq.refl
theorem heq_of_eq_rec_right {A : Type} {P : A → Type} : ∀ {a a' : A} {p₁ : P a} {p₂ : P a'} (e : a' = a) (h₂ : p₁ = e ▹ p₂), p₁ == p₂
| a a p₁ p₂ (eq.refl a) h := eq.rec_on h !heq.refl
theorem of_heq_true {a : Prop} (H : a == true) : a :=
of_eq_true (eq_of_heq H)
theorem eq_rec_compose : ∀ {A B C : Type} (p₁ : B = C) (p₂ : A = B) (a : A), p₁ ▹ (p₂ ▹ a : B) = (p₂ ⬝ p₁) ▹ a
| A A A (eq.refl A) (eq.refl A) a := calc
eq.refl A ▹ eq.refl A ▹ a = eq.refl A ▹ a : rfl
... = (eq.refl A ⬝ eq.refl A) ▹ a : {proof_irrel (eq.refl A) (eq.refl A ⬝ eq.refl A)}
theorem eq_rec_eq_eq_rec {A₁ A₂ : Type} {p : A₁ = A₂} : ∀ {a₁ : A₁} {a₂ : A₂}, p ▹ a₁ = a₂ → a₁ = p⁻¹ ▹ a₂ :=
eq.drec_on p (λ a₁ a₂ h, eq.drec_on h rfl)
theorem eq_rec_of_heq_left : ∀ {A₁ A₂ : Type} {a₁ : A₁} {a₂ : A₂} (h : a₁ == a₂), type_eq_of_heq h ▹ a₁ = a₂
| A A a a (heq.refl a) := rfl
theorem eq_rec_of_heq_right {A₁ A₂ : Type} {a₁ : A₁} {a₂ : A₂} (h : a₁ == a₂) : a₁ = (type_eq_of_heq h)⁻¹ ▹ a₂ :=
eq_rec_eq_eq_rec (eq_rec_of_heq_left h)
attribute heq.refl [refl]
attribute heq.trans [trans]
attribute heq_of_heq_of_eq [trans]
attribute heq_of_eq_of_heq [trans]
attribute heq.symm [symm]
/- and -/
notation a /\ b := and a b
notation a ∧ b := and a b
variables {a b c d : Prop}
attribute and.rec [elim]
attribute and.intro [intro!]
theorem and.elim (H₁ : a ∧ b) (H₂ : a → b → c) : c :=
and.rec H₂ H₁
theorem and.swap : a ∧ b → b ∧ a :=
and.rec (λHa Hb, and.intro Hb Ha)
/- or -/
notation a \/ b := or a b
notation a ∨ b := or a b
attribute or.rec [elim]
namespace or
theorem elim (H₁ : a ∨ b) (H₂ : a → c) (H₃ : b → c) : c :=
or.rec H₂ H₃ H₁
end or
theorem non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) :=
assume not_em : ¬(a ∨ ¬a),
have neg_a : ¬a, from
assume pos_a : a, absurd (or.inl pos_a) not_em,
absurd (or.inr neg_a) not_em
theorem or.swap : a ∨ b → b ∨ a := or.rec or.inr or.inl
/- iff -/
definition iff (a b : Prop) := (a → b) ∧ (b → a)
notation a <-> b := iff a b
notation a ↔ b := iff a b
theorem iff.intro : (a → b) → (b → a) → (a ↔ b) := and.intro
attribute iff.intro [intro!]
theorem iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := and.rec
attribute iff.elim [recursor 5] [elim]
theorem iff.elim_left : (a ↔ b) → a → b := and.left
definition iff.mp := @iff.elim_left
theorem iff.elim_right : (a ↔ b) → b → a := and.right
definition iff.mpr := @iff.elim_right
theorem iff.refl [refl] (a : Prop) : a ↔ a :=
iff.intro (assume H, H) (assume H, H)
theorem iff.rfl {a : Prop} : a ↔ a :=
iff.refl a
theorem iff.trans [trans] (H₁ : a ↔ b) (H₂ : b ↔ c) : a ↔ c :=
iff.intro
(assume Ha, iff.mp H₂ (iff.mp H₁ Ha))
(assume Hc, iff.mpr H₁ (iff.mpr H₂ Hc))
theorem iff.symm [symm] (H : a ↔ b) : b ↔ a :=
iff.intro (iff.elim_right H) (iff.elim_left H)
theorem iff.comm : (a ↔ b) ↔ (b ↔ a) :=
iff.intro iff.symm iff.symm
theorem iff.of_eq {a b : Prop} (H : a = b) : a ↔ b :=
eq.rec_on H iff.rfl
theorem not_iff_not_of_iff (H₁ : a ↔ b) : ¬a ↔ ¬b :=
iff.intro
(assume (Hna : ¬ a) (Hb : b), Hna (iff.elim_right H₁ Hb))
(assume (Hnb : ¬ b) (Ha : a), Hnb (iff.elim_left H₁ Ha))
theorem of_iff_true (H : a ↔ true) : a :=
iff.mp (iff.symm H) trivial
theorem not_of_iff_false : (a ↔ false) → ¬a := iff.mp
theorem iff_true_intro (H : a) : a ↔ true :=
iff.intro
(λ Hl, trivial)
(λ Hr, H)
theorem iff_false_intro (H : ¬a) : a ↔ false :=
iff.intro H !false.rec
theorem not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a :=
iff.intro
(λ (Hl : ¬¬¬a) (Ha : a), Hl (non_contradictory_intro Ha))
absurd
theorem imp_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a → b) ↔ (c → d) :=
iff.intro
(λHab Hc, iff.mp H2 (Hab (iff.mpr H1 Hc)))
(λHcd Ha, iff.mpr H2 (Hcd (iff.mp H1 Ha)))
theorem imp_congr_right (H : a → (b ↔ c)) : (a → b) ↔ (a → c) :=
iff.intro
(take Hab Ha, iff.elim_left (H Ha) (Hab Ha))
(take Hab Ha, iff.elim_right (H Ha) (Hab Ha))
theorem not_not_intro (Ha : a) : ¬¬a :=
assume Hna : ¬a, Hna Ha
theorem not_of_not_not_not (H : ¬¬¬a) : ¬a :=
λ Ha, absurd (not_not_intro Ha) H
theorem not_true [simp] : (¬ true) ↔ false :=
iff_false_intro (not_not_intro trivial)
theorem not_false_iff [simp] : (¬ false) ↔ true :=
iff_true_intro not_false
theorem not_congr [congr] (H : a ↔ b) : ¬a ↔ ¬b :=
iff.intro (λ H₁ H₂, H₁ (iff.mpr H H₂)) (λ H₁ H₂, H₁ (iff.mp H H₂))
theorem ne_self_iff_false [simp] {A : Type} (a : A) : (not (a = a)) ↔ false :=
iff.intro false_of_ne false.elim
theorem eq_self_iff_true [simp] {A : Type} (a : A) : (a = a) ↔ true :=
iff_true_intro rfl
theorem heq_self_iff_true [simp] {A : Type} (a : A) : (a == a) ↔ true :=
iff_true_intro (heq.refl a)
theorem iff_not_self [simp] (a : Prop) : (a ↔ ¬a) ↔ false :=
iff_false_intro (λ H,
have H' : ¬a, from (λ Ha, (iff.mp H Ha) Ha),
H' (iff.mpr H H'))
theorem not_iff_self [simp] (a : Prop) : (¬a ↔ a) ↔ false :=
iff_false_intro (λ H,
have H' : ¬a, from (λ Ha, (iff.mpr H Ha) Ha),
H' (iff.mp H H'))
theorem true_iff_false [simp] : (true ↔ false) ↔ false :=
iff_false_intro (λ H, iff.mp H trivial)
theorem false_iff_true [simp] : (false ↔ true) ↔ false :=
iff_false_intro (λ H, iff.mpr H trivial)
theorem false_of_true_iff_false : (true ↔ false) → false :=
assume H, iff.mp H trivial
/- and simp rules -/
theorem and.imp (H₂ : a → c) (H₃ : b → d) : a ∧ b → c ∧ d :=
and.rec (λHa Hb, and.intro (H₂ Ha) (H₃ Hb))
theorem and_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ∧ b) ↔ (c ∧ d) :=
iff.intro (and.imp (iff.mp H1) (iff.mp H2)) (and.imp (iff.mpr H1) (iff.mpr H2))
theorem and_congr_right (H : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) :=
iff.intro
(take Hab, obtain `a` `b`, from Hab, and.intro `a` (iff.elim_left (H `a`) `b`))
(take Hac, obtain `a` `c`, from Hac, and.intro `a` (iff.elim_right (H `a`) `c`))
theorem and.comm [simp] : a ∧ b ↔ b ∧ a :=
iff.intro and.swap and.swap
theorem and.assoc [simp] : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) :=
iff.intro
(and.rec (λ H' Hc, and.rec (λ Ha Hb, and.intro Ha (and.intro Hb Hc)) H'))
(and.rec (λ Ha, and.rec (λ Hb Hc, and.intro (and.intro Ha Hb) Hc)))
theorem and.left_comm [simp] : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) :=
iff.trans (iff.symm !and.assoc) (iff.trans (and_congr !and.comm !iff.refl) !and.assoc)
theorem and_iff_left {a b : Prop} (Hb : b) : (a ∧ b) ↔ a :=
iff.intro and.left (λHa, and.intro Ha Hb)
theorem and_iff_right {a b : Prop} (Ha : a) : (a ∧ b) ↔ b :=
iff.intro and.right (and.intro Ha)
theorem and_true [simp] (a : Prop) : a ∧ true ↔ a :=
and_iff_left trivial
theorem true_and [simp] (a : Prop) : true ∧ a ↔ a :=
and_iff_right trivial
theorem and_false [simp] (a : Prop) : a ∧ false ↔ false :=
iff_false_intro and.right
theorem false_and [simp] (a : Prop) : false ∧ a ↔ false :=
iff_false_intro and.left
theorem not_and_self [simp] (a : Prop) : (¬a ∧ a) ↔ false :=
iff_false_intro (λ H, and.elim H (λ H₁ H₂, absurd H₂ H₁))
theorem and_not_self [simp] (a : Prop) : (a ∧ ¬a) ↔ false :=
iff_false_intro (λ H, and.elim H (λ H₁ H₂, absurd H₁ H₂))
theorem and_self [simp] (a : Prop) : a ∧ a ↔ a :=
iff.intro and.left (assume H, and.intro H H)
/- or simp rules -/
theorem or.imp (H₂ : a → c) (H₃ : b → d) : a ∨ b → c ∨ d :=
or.rec (λ H, or.inl (H₂ H)) (λ H, or.inr (H₃ H))
theorem or.imp_left (H : a → b) : a ∨ c → b ∨ c :=
or.imp H id
theorem or.imp_right (H : a → b) : c ∨ a → c ∨ b :=
or.imp id H
theorem or_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ∨ b) ↔ (c ∨ d) :=
iff.intro (or.imp (iff.mp H1) (iff.mp H2)) (or.imp (iff.mpr H1) (iff.mpr H2))
theorem or.comm [simp] : a ∨ b ↔ b ∨ a := iff.intro or.swap or.swap
theorem or.assoc [simp] : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) :=
iff.intro
(or.rec (or.imp_right or.inl) (λ H, or.inr (or.inr H)))
(or.rec (λ H, or.inl (or.inl H)) (or.imp_left or.inr))
theorem or.left_comm [simp] : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) :=
iff.trans (iff.symm !or.assoc) (iff.trans (or_congr !or.comm !iff.refl) !or.assoc)
theorem or_true [simp] (a : Prop) : a ∨ true ↔ true :=
iff_true_intro (or.inr trivial)
theorem true_or [simp] (a : Prop) : true ∨ a ↔ true :=
iff_true_intro (or.inl trivial)
theorem or_false [simp] (a : Prop) : a ∨ false ↔ a :=
iff.intro (or.rec id false.elim) or.inl
theorem false_or [simp] (a : Prop) : false ∨ a ↔ a :=
iff.trans or.comm !or_false
theorem or_self [simp] (a : Prop) : a ∨ a ↔ a :=
iff.intro (or.rec id id) or.inl
/- or resolution rulse -/
definition or.resolve_left {a b : Prop} (H : a ∨ b) (na : ¬ a) : b :=
or.elim H (λ Ha, absurd Ha na) id
definition or.neg_resolve_left {a b : Prop} (H : ¬ a ∨ b) (Ha : a) : b :=
or.elim H (λ na, absurd Ha na) id
definition or.resolve_right {a b : Prop} (H : a ∨ b) (nb : ¬ b) : a :=
or.elim H id (λ Hb, absurd Hb nb)
definition or.neg_resolve_right {a b : Prop} (H : a ∨ ¬ b) (Hb : b) : a :=
or.elim H id (λ nb, absurd Hb nb)
/- iff simp rules -/
theorem iff_true [simp] (a : Prop) : (a ↔ true) ↔ a :=
iff.intro (assume H, iff.mpr H trivial) iff_true_intro
theorem true_iff [simp] (a : Prop) : (true ↔ a) ↔ a :=
iff.trans iff.comm !iff_true
theorem iff_false [simp] (a : Prop) : (a ↔ false) ↔ ¬ a :=
iff.intro and.left iff_false_intro
theorem false_iff [simp] (a : Prop) : (false ↔ a) ↔ ¬ a :=
iff.trans iff.comm !iff_false
theorem iff_self [simp] (a : Prop) : (a ↔ a) ↔ true :=
iff_true_intro iff.rfl
theorem iff_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ↔ b) ↔ (c ↔ d) :=
and_congr (imp_congr H1 H2) (imp_congr H2 H1)
/- exists -/
inductive Exists {A : Type} (P : A → Prop) : Prop :=
intro : ∀ (a : A), P a → Exists P
attribute Exists.intro [intro]
definition exists.intro := @Exists.intro
notation `exists` binders `, ` r:(scoped P, Exists P) := r
notation `∃` binders `, ` r:(scoped P, Exists P) := r
attribute Exists.rec [elim]
theorem exists.elim {A : Type} {p : A → Prop} {B : Prop}
(H1 : ∃x, p x) (H2 : ∀ (a : A), p a → B) : B :=
Exists.rec H2 H1
/- exists unique -/
definition exists_unique {A : Type} (p : A → Prop) :=
∃x, p x ∧ ∀y, p y → y = x
notation `∃!` binders `, ` r:(scoped P, exists_unique P) := r
theorem exists_unique.intro [intro] {A : Type} {p : A → Prop} (w : A) (H1 : p w) (H2 : ∀y, p y → y = w) :
∃!x, p x :=
exists.intro w (and.intro H1 H2)
theorem exists_unique.elim [recursor 4] [elim] {A : Type} {p : A → Prop} {b : Prop}
(H2 : ∃!x, p x) (H1 : ∀x, p x → (∀y, p y → y = x) → b) : b :=
exists.elim H2 (λ w Hw, H1 w (and.left Hw) (and.right Hw))
theorem exists_unique_of_exists_of_unique {A : Type} {p : A → Prop}
(Hex : ∃ x, p x) (Hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x :=
exists.elim Hex (λ x px, exists_unique.intro x px (take y, suppose p y, Hunique y x this px))
theorem exists_of_exists_unique {A : Type} {p : A → Prop} (H : ∃! x, p x) : ∃ x, p x :=
exists.elim H (λ x Hx, exists.intro x (and.left Hx))
theorem unique_of_exists_unique {A : Type} {p : A → Prop}
(H : ∃! x, p x) {y₁ y₂ : A} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ :=
exists_unique.elim H
(take x, suppose p x,
assume unique : ∀ y, p y → y = x,
show y₁ = y₂, from eq.trans (unique _ py₁) (eq.symm (unique _ py₂)))
/- exists, forall, exists unique congruences -/
section
variables {A : Type} {p₁ p₂ : A → Prop}
theorem forall_congr [congr] {A : Type} {P Q : A → Prop} (H : ∀a, (P a ↔ Q a)) : (∀a, P a) ↔ ∀a, Q a :=
iff.intro (λp a, iff.mp (H a) (p a)) (λq a, iff.mpr (H a) (q a))
theorem exists_imp_exists {A : Type} {P Q : A → Prop} (H : ∀a, (P a → Q a)) (p : ∃a, P a) : ∃a, Q a :=
exists.elim p (λa Hp, exists.intro a (H a Hp))
theorem exists_congr [congr] {A : Type} {P Q : A → Prop} (H : ∀a, (P a ↔ Q a)) : (∃a, P a) ↔ ∃a, Q a :=
iff.intro
(exists_imp_exists (λa, iff.mp (H a)))
(exists_imp_exists (λa, iff.mpr (H a)))
theorem exists_unique_congr [congr] (H : ∀ x, p₁ x ↔ p₂ x) : (∃! x, p₁ x) ↔ (∃! x, p₂ x) :=
exists_congr (λx, and_congr (H x) (forall_congr (λy, imp_congr (H y) iff.rfl)))
end
/- decidable -/
inductive decidable [class] (p : Prop) : Type :=
| inl : p → decidable p
| inr : ¬p → decidable p
definition decidable_true [instance] : decidable true :=
decidable.inl trivial
definition decidable_false [instance] : decidable false :=
decidable.inr not_false
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
definition dite (c : Prop) [H : decidable c] {A : Type} : (c → A) → (¬ c → A) → A :=
decidable.rec_on H
/- if-then-else -/
definition ite (c : Prop) [H : decidable c] {A : Type} (t e : A) : A :=
decidable.rec_on H (λ Hc, t) (λ Hnc, e)
namespace decidable
variables {p q : Prop}
definition rec_on_true [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : p) (H4 : H1 H3)
: decidable.rec_on H H1 H2 :=
decidable.rec_on H (λh, H4) (λh, !false.rec (h H3))
definition rec_on_false [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : ¬p) (H4 : H2 H3)
: decidable.rec_on H H1 H2 :=
decidable.rec_on H (λh, false.rec _ (H3 h)) (λh, H4)
definition by_cases {q : Type} [C : decidable p] : (p → q) → (¬p → q) → q := !dite
theorem em (p : Prop) [decidable p] : p ∨ ¬p := by_cases or.inl or.inr
theorem by_contradiction [decidable p] (H : ¬p → false) : p :=
if H1 : p then H1 else false.rec _ (H H1)
end decidable
section
variables {p q : Prop}
open decidable
definition decidable_of_decidable_of_iff (Hp : decidable p) (H : p ↔ q) : decidable q :=
if Hp : p then inl (iff.mp H Hp)
else inr (iff.mp (not_iff_not_of_iff H) Hp)
definition decidable_of_decidable_of_eq (Hp : decidable p) (H : p = q) : decidable q :=
decidable_of_decidable_of_iff Hp (iff.of_eq H)
protected definition or.by_cases [decidable p] [decidable q] {A : Type}
(h : p ∨ q) (h₁ : p → A) (h₂ : q → A) : A :=
if hp : p then h₁ hp else
if hq : q then h₂ hq else
false.rec _ (or.elim h hp hq)
end
section
variables {p q : Prop}
open decidable (rec_on inl inr)
definition decidable_and [instance] [decidable p] [decidable q] : decidable (p ∧ q) :=
if hp : p then
if hq : q then inl (and.intro hp hq)
else inr (assume H : p ∧ q, hq (and.right H))
else inr (assume H : p ∧ q, hp (and.left H))
definition decidable_or [instance] [decidable p] [decidable q] : decidable (p ∨ q) :=
if hp : p then inl (or.inl hp) else
if hq : q then inl (or.inr hq) else
inr (or.rec hp hq)
definition decidable_not [instance] [decidable p] : decidable (¬p) :=
if hp : p then inr (absurd hp) else inl hp
definition decidable_implies [instance] [decidable p] [decidable q] : decidable (p → q) :=
if hp : p then
if hq : q then inl (assume H, hq)
else inr (assume H : p → q, absurd (H hp) hq)
else inl (assume Hp, absurd Hp hp)
definition decidable_iff [instance] [decidable p] [decidable q] : decidable (p ↔ q) :=
decidable_and
end
definition decidable_pred [reducible] {A : Type} (R : A → Prop) := Π (a : A), decidable (R a)
definition decidable_rel [reducible] {A : Type} (R : A → A → Prop) := Π (a b : A), decidable (R a b)
definition decidable_eq [reducible] (A : Type) := decidable_rel (@eq A)
definition decidable_ne [instance] {A : Type} [decidable_eq A] (a b : A) : decidable (a ≠ b) :=
decidable_implies
namespace bool
theorem ff_ne_tt : ff = tt → false
| [none]
end bool
open bool
definition is_dec_eq {A : Type} (p : A → A → bool) : Prop := ∀ ⦃x y : A⦄, p x y = tt → x = y
definition is_dec_refl {A : Type} (p : A → A → bool) : Prop := ∀x, p x x = tt
open decidable
protected definition bool.has_decidable_eq [instance] : ∀a b : bool, decidable (a = b)
| ff ff := inl rfl
| ff tt := inr ff_ne_tt
| tt ff := inr (ne.symm ff_ne_tt)
| tt tt := inl rfl
definition decidable_eq_of_bool_pred {A : Type} {p : A → A → bool} (H₁ : is_dec_eq p) (H₂ : is_dec_refl p) : decidable_eq A :=
take x y : A, if Hp : p x y = tt then inl (H₁ Hp)
else inr (assume Hxy : x = y, (eq.subst Hxy Hp) (H₂ y))
theorem decidable_eq_inl_refl {A : Type} [H : decidable_eq A] (a : A) : H a a = inl (eq.refl a) :=
match H a a with
| inl e := rfl
| inr n := absurd rfl n
end
open eq.ops
theorem decidable_eq_inr_neg {A : Type} [H : decidable_eq A] {a b : A} : Π n : a ≠ b, H a b = inr n :=
assume n,
match H a b with
| inl e := absurd e n
| inr n₁ := proof_irrel n n₁ ▸ rfl
end
/- inhabited -/
inductive inhabited [class] (A : Type) : Type :=
mk : A → inhabited A
protected definition inhabited.value {A : Type} : inhabited A → A :=
inhabited.rec (λa, a)
protected definition inhabited.destruct {A : Type} {B : Type} (H1 : inhabited A) (H2 : A → B) : B :=
inhabited.rec H2 H1
definition default (A : Type) [H : inhabited A] : A :=
inhabited.value H
definition arbitrary [irreducible] (A : Type) [H : inhabited A] : A :=
inhabited.value H
definition Prop.is_inhabited [instance] : inhabited Prop :=
inhabited.mk true
definition inhabited_fun [instance] (A : Type) {B : Type} [H : inhabited B] : inhabited (A → B) :=
inhabited.rec_on H (λb, inhabited.mk (λa, b))
definition inhabited_Pi [instance] (A : Type) {B : A → Type} [Πx, inhabited (B x)] :
inhabited (Πx, B x) :=
inhabited.mk (λa, !default)
protected definition bool.is_inhabited [instance] : inhabited bool :=
inhabited.mk ff
protected definition pos_num.is_inhabited [instance] : inhabited pos_num :=
inhabited.mk pos_num.one
protected definition num.is_inhabited [instance] : inhabited num :=
inhabited.mk num.zero
inductive nonempty [class] (A : Type) : Prop :=
intro : A → nonempty A
protected definition nonempty.elim {A : Type} {B : Prop} (H1 : nonempty A) (H2 : A → B) : B :=
nonempty.rec H2 H1
theorem nonempty_of_inhabited [instance] {A : Type} [inhabited A] : nonempty A :=
nonempty.intro !default
theorem nonempty_of_exists {A : Type} {P : A → Prop} : (∃x, P x) → nonempty A :=
Exists.rec (λw H, nonempty.intro w)
/- subsingleton -/
inductive subsingleton [class] (A : Type) : Prop :=
intro : (∀ a b : A, a = b) → subsingleton A
protected definition subsingleton.elim {A : Type} [H : subsingleton A] : ∀(a b : A), a = b :=
subsingleton.rec (λp, p) H
protected definition subsingleton.helim {A B : Type} [H : subsingleton A] (h : A = B) (a : A) (b : B) : a == b :=
by induction h; apply heq_of_eq; apply subsingleton.elim
definition subsingleton_prop [instance] (p : Prop) : subsingleton p :=
subsingleton.intro (λa b, !proof_irrel)
definition subsingleton_decidable [instance] (p : Prop) : subsingleton (decidable p) :=
subsingleton.intro (λ d₁,
match d₁ with
| inl t₁ := (λ d₂,
match d₂ with
| inl t₂ := eq.rec_on (proof_irrel t₁ t₂) rfl
| inr f₂ := absurd t₁ f₂
end)
| inr f₁ := (λ d₂,
match d₂ with
| inl t₂ := absurd t₂ f₁
| inr f₂ := eq.rec_on (proof_irrel f₁ f₂) rfl
end)
end)
protected theorem rec_subsingleton {p : Prop} [H : decidable p]
{H1 : p → Type} {H2 : ¬p → Type}
[H3 : Π(h : p), subsingleton (H1 h)] [H4 : Π(h : ¬p), subsingleton (H2 h)]
: subsingleton (decidable.rec_on H H1 H2) :=
decidable.rec_on H (λh, H3 h) (λh, H4 h) --this can be proven using dependent version of "by_cases"
theorem if_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t e : A} : (ite c t e) = t :=
decidable.rec
(λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e))
(λ Hnc : ¬c, absurd Hc Hnc)
H
theorem if_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t e : A} : (ite c t e) = e :=
decidable.rec
(λ Hc : c, absurd Hc Hnc)
(λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t e))
H
theorem if_t_t [simp] (c : Prop) [H : decidable c] {A : Type} (t : A) : (ite c t t) = t :=
decidable.rec
(λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t t))
(λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t t))
H
theorem implies_of_if_pos {c t e : Prop} [decidable c] (h : ite c t e) : c → t :=
assume Hc, eq.rec_on (if_pos Hc) h
theorem implies_of_if_neg {c t e : Prop} [decidable c] (h : ite c t e) : ¬c → e :=
assume Hnc, eq.rec_on (if_neg Hnc) h
theorem if_ctx_congr {A : Type} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c]
{x y u v : A}
(h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) :
ite b x y = ite c u v :=
decidable.rec_on dec_b
(λ hp : b, calc
ite b x y = x : if_pos hp
... = u : h_t (iff.mp h_c hp)
... = ite c u v : if_pos (iff.mp h_c hp))
(λ hn : ¬b, calc
ite b x y = y : if_neg hn
... = v : h_e (iff.mp (not_iff_not_of_iff h_c) hn)
... = ite c u v : if_neg (iff.mp (not_iff_not_of_iff h_c) hn))
theorem if_congr [congr] {A : Type} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c]
{x y u v : A}
(h_c : b ↔ c) (h_t : x = u) (h_e : y = v) :
ite b x y = ite c u v :=
@if_ctx_congr A b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e)
theorem if_ctx_simp_congr {A : Type} {b c : Prop} [dec_b : decidable b] {x y u v : A}
(h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) :
ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) :=
@if_ctx_congr A b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x y u v h_c h_t h_e
theorem if_simp_congr [congr] {A : Type} {b c : Prop} [dec_b : decidable b] {x y u v : A}
(h_c : b ↔ c) (h_t : x = u) (h_e : y = v) :
ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) :=
@if_ctx_simp_congr A b c dec_b x y u v h_c (λ h, h_t) (λ h, h_e)
definition if_true [simp] {A : Type} (t e : A) : (if true then t else e) = t :=
if_pos trivial
definition if_false [simp] {A : Type} (t e : A) : (if false then t else e) = e :=
if_neg not_false
theorem if_ctx_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c]
(h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) :
ite b x y ↔ ite c u v :=
decidable.rec_on dec_b
(λ hp : b, calc
ite b x y ↔ x : iff.of_eq (if_pos hp)
... ↔ u : h_t (iff.mp h_c hp)
... ↔ ite c u v : iff.of_eq (if_pos (iff.mp h_c hp)))
(λ hn : ¬b, calc
ite b x y ↔ y : iff.of_eq (if_neg hn)
... ↔ v : h_e (iff.mp (not_iff_not_of_iff h_c) hn)
... ↔ ite c u v : iff.of_eq (if_neg (iff.mp (not_iff_not_of_iff h_c) hn)))
theorem if_congr_prop [congr] {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c]
(h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) :
ite b x y ↔ ite c u v :=
if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e)
theorem if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b]
(h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) :
ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) :=
@if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e
theorem if_simp_congr_prop [congr] {b c x y u v : Prop} [dec_b : decidable b]
(h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) :
ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) :=
@if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e)
theorem dif_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t : c → A} {e : ¬ c → A} : dite c t e = t Hc :=
decidable.rec
(λ Hc : c, eq.refl (@dite c (decidable.inl Hc) A t e))
(λ Hnc : ¬c, absurd Hc Hnc)
H
theorem dif_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t : c → A} {e : ¬ c → A} : dite c t e = e Hnc :=
decidable.rec
(λ Hc : c, absurd Hc Hnc)
(λ Hnc : ¬c, eq.refl (@dite c (decidable.inr Hnc) A t e))
H
theorem dif_ctx_congr {A : Type} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c]
{x : b → A} {u : c → A} {y : ¬b → A} {v : ¬c → A}
(h_c : b ↔ c)
(h_t : ∀ (h : c), x (iff.mpr h_c h) = u h)
(h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) :
(@dite b dec_b A x y) = (@dite c dec_c A u v) :=
decidable.rec_on dec_b
(λ hp : b, calc
dite b x y = x hp : dif_pos hp
... = x (iff.mpr h_c (iff.mp h_c hp)) : proof_irrel
... = u (iff.mp h_c hp) : h_t
... = dite c u v : dif_pos (iff.mp h_c hp))
(λ hn : ¬b, let h_nc : ¬b ↔ ¬c := not_iff_not_of_iff h_c in calc
dite b x y = y hn : dif_neg hn
... = y (iff.mpr h_nc (iff.mp h_nc hn)) : proof_irrel
... = v (iff.mp h_nc hn) : h_e
... = dite c u v : dif_neg (iff.mp h_nc hn))
theorem dif_ctx_simp_congr {A : Type} {b c : Prop} [dec_b : decidable b]
{x : b → A} {u : c → A} {y : ¬b → A} {v : ¬c → A}
(h_c : b ↔ c)
(h_t : ∀ (h : c), x (iff.mpr h_c h) = u h)
(h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) :
(@dite b dec_b A x y) = (@dite c (decidable_of_decidable_of_iff dec_b h_c) A u v) :=
@dif_ctx_congr A b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e
-- Remark: dite and ite are "definitionally equal" when we ignore the proofs.
theorem dite_ite_eq (c : Prop) [decidable c] {A : Type} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e :=
rfl
definition is_true (c : Prop) [decidable c] : Prop :=
if c then true else false
definition is_false (c : Prop) [decidable c] : Prop :=
if c then false else true
definition of_is_true {c : Prop} [H₁ : decidable c] (H₂ : is_true c) : c :=
decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, !false.rec (if_neg Hnc ▸ H₂))
notation `dec_trivial` := of_is_true trivial
theorem not_of_not_is_true {c : Prop} [decidable c] (H : ¬ is_true c) : ¬ c :=
if Hc : c then absurd trivial (if_pos Hc ▸ H) else Hc
theorem not_of_is_false {c : Prop} [decidable c] (H : is_false c) : ¬ c :=
if Hc : c then !false.rec (if_pos Hc ▸ H) else Hc
theorem of_not_is_false {c : Prop} [decidable c] (H : ¬ is_false c) : c :=
if Hc : c then Hc else absurd trivial (if_neg Hc ▸ H)
-- The following symbols should not be considered in the pattern inference procedure used by
-- heuristic instantiation.
attribute and or not iff ite dite eq ne heq [no_pattern]
-- namespace used to collect congruence rules for "contextual simplification"
namespace contextual
attribute if_ctx_simp_congr [congr]
attribute if_ctx_simp_congr_prop [congr]
attribute dif_ctx_simp_congr [congr]
end contextual
|
d59800f603da3eba5de3573b85763a05eaa8d3e4 | 33340b3a23ca62ef3c8a7f6a2d4e14c07c6d3354 | /dlo/formula.lean | 235f778c1d9ec36e61ad29aa954dd7f3293b549d | [] | 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 | 9,496 | lean | import ..list ..logic data.rat
instance rat.inhabited : inhabited rat := ⟨0⟩
inductive term_dlo : Type
| var : nat → term_dlo
| cst : rat → term_dlo
notation `V'` := term_dlo.var
notation `C'` r := term_dlo.cst r
instance term_dlo.decidable_eq : decidable_eq term_dlo := by tactic.mk_dec_eq_instance
-- def term_dlo.decr_idx : term_dlo rat → term_dlo rat
-- | (term_dlo.var rat m) := term_dlo.var rat (m-1)
-- | (term_dlo.cst b) := term_dlo.cst b
--
def term_dlo.incr_idx : term_dlo → term_dlo
| (term_dlo.var m) := term_dlo.var (m+1)
| (term_dlo.cst b) := term_dlo.cst b
def term_dlo.eval (bs : list rat) : term_dlo → rat
| (term_dlo.var n) := list.inth bs n
| (term_dlo.cst r) := r
-- meta def term_dlo.to_format : term_dlo → format
-- | (term_dlo.var m) := "#" ++ to_fmt m
-- | (term_dlo.cst b) := "@" ++ to_fmt b
-- meta instance term_dlo.has_to_format : has_to_format term_dlo :=
-- ⟨term_dlo.to_format⟩
lemma term_dlo.eval_incr_idx_eq {t : term_dlo} {b : rat} {bs} :
t.incr_idx.eval (b::bs) = t.eval bs :=
begin cases t with n b; simp [term_dlo.incr_idx, term_dlo.eval] end
instance dec_eq_term_dlo : decidable_eq term_dlo :=
by tactic.mk_dec_eq_instance
inductive atom_dlo : Type
| lt : term_dlo → term_dlo → atom_dlo
| eq : term_dlo → term_dlo → atom_dlo
def atom_dlo.eval (bs : list rat) : atom_dlo → Prop
| (atom_dlo.lt t1 t2) := term_dlo.eval bs t1 < term_dlo.eval bs t2
| (atom_dlo.eq t1 t2) := term_dlo.eval bs t1 = term_dlo.eval bs t2
-- | (x <' y) := sorry
-- | (x =' y) := sorry
-- meta def atom_dlo.to_format : atom_dlo → format
-- | (atom_dlo.lt t s) := to_fmt t ++ " < " ++ to_fmt s
-- | (atom_dlo.eq t s) := to_fmt t ++ " = " ++ to_fmt s
inductive formula_dlo : Type
| true : formula_dlo
| false : formula_dlo
| atom : atom_dlo → formula_dlo
| and : formula_dlo → formula_dlo → formula_dlo
| or : formula_dlo → formula_dlo → formula_dlo
| not : formula_dlo → formula_dlo
| ex : formula_dlo → formula_dlo
-- | formula_dlo.true := sorry
-- | formula_dlo.false := sorry
-- | (formula_dlo.atom a) := sorry
-- | (formula_dlo.and p q) := sorry
-- | (p ∨' q) := sorry
-- | (¬' p) := sorry
-- | (formula_dlo.ex p) := sorry
notation `⊤'` := formula_dlo.true
notation `⊥'` := formula_dlo.false
notation `A'` a := formula_dlo.atom a
notation `¬'` p := formula_dlo.not p
notation p `∧'` q := formula_dlo.and p q
notation p `∨'` q := formula_dlo.or p q
notation `∃'` p := formula_dlo.ex p
notation x `<'` y := atom_dlo.lt x y
notation x `='` y := atom_dlo.eq x y
def formula_dlo.eval : list rat → formula_dlo → Prop
| as formula_dlo.true := _root_.true
| as formula_dlo.false := _root_.false
| as (formula_dlo.atom a) := a.eval as
| as (formula_dlo.not φ) := ¬ (formula_dlo.eval as φ)
| as (formula_dlo.or φ ψ) := (formula_dlo.eval as φ) ∨ (formula_dlo.eval as ψ)
| as (formula_dlo.and φ ψ) := (formula_dlo.eval as φ) ∧ (formula_dlo.eval as ψ)
| as (formula_dlo.ex φ) := ∃ d, formula_dlo.eval (d::as) φ
lemma eval_true {xs : list rat} : formula_dlo.true.eval xs ↔ _root_.true :=
by simp [formula_dlo.eval]
lemma eval_not {p : formula_dlo} (xs : list rat) :
(p.not).eval xs ↔ ¬ (p.eval xs) := iff.refl _
lemma eval_not_false {p : formula_dlo} (xs : list rat) :
(formula_dlo.false.not).eval xs ↔ _root_.true :=
begin simp [formula_dlo.eval] end
lemma eval_not_or {p q : formula_dlo} {xs : list rat} :
((formula_dlo.or p q).not).eval xs ↔ ((p.not).eval xs ∧ (q.not).eval xs) :=
begin simp [formula_dlo.eval, eval_not, not_or_distrib] end
lemma eval_not_and {p q : formula_dlo} {xs : list rat} :
((formula_dlo.and p q).not).eval xs ↔ ((p.not).eval xs ∨ (q.not).eval xs) :=
begin
simp only [formula_dlo.eval, eval_not ],
rw (@not_and_distrib _ _ (classical.dec _))
end
lemma eval_or {p q : formula_dlo} (xs : list rat) :
(formula_dlo.or p q).eval xs = (p.eval xs ∨ q.eval xs) := eq.refl _
lemma eval_and {p q : formula_dlo} {xs : list rat} :
(formula_dlo.and p q).eval xs = (p.eval xs ∧ q.eval xs) := eq.refl _
lemma eval_le {t s : term_dlo} {rs : list rat} :
(atom_dlo.lt t s).eval rs ↔ (t.eval rs < s.eval rs) := iff.refl _
lemma eval_false {xs : list rat} : formula_dlo.false.eval xs ↔ _root_.false :=
by simp [formula_dlo.eval]
lemma eval_ex {p : formula_dlo} (xs) : p.ex.eval xs = ∃ x, (p.eval (x::xs)) :=
begin simp [formula_dlo.eval] end
open rat
def not_o : formula_dlo → formula_dlo
| formula_dlo.true := formula_dlo.false
| formula_dlo.false := formula_dlo.true
| p := p.not
def and_o : formula_dlo → formula_dlo → formula_dlo
| (formula_dlo.true) q' := q'
| p' (formula_dlo.true) := p'
| (formula_dlo.false) q' := formula_dlo.false
| p' (formula_dlo.false) := formula_dlo.false
| p' q' := formula_dlo.and p' q'
def or_o : formula_dlo → formula_dlo → formula_dlo
| (formula_dlo.true ) _ := formula_dlo.true
| _ (formula_dlo.true ) := formula_dlo.true
| (formula_dlo.false ) q := q
| p (formula_dlo.false ) := p
| p q := formula_dlo.or p q
lemma eval_not_o {p : formula_dlo} (xs : list rat) :
(not_o p).eval xs ↔ ¬(p.eval xs) :=
begin cases p; simp [not_o, formula_dlo.eval] end
lemma eval_or_o {p q : formula_dlo} (xs : list rat) :
(or_o p q).eval xs ↔ (p.eval xs ∨ q.eval xs) :=
begin cases p; cases q; simp [or_o, formula_dlo.eval] end
lemma eval_and_o {p q : formula_dlo} (xs : list rat) :
(and_o p q).eval xs ↔ (p.eval xs ∧ q.eval xs) :=
begin cases p; cases q; simp [and_o, formula_dlo.eval] end
-- Requires : qfree arg-0
def formula_dlo.map (f : atom_dlo → atom_dlo) : formula_dlo → formula_dlo
| formula_dlo.true := formula_dlo.true
| formula_dlo.false := formula_dlo.false
| (formula_dlo.atom a) := formula_dlo.atom (f a)
| (formula_dlo.not p) := p.map.not
| (formula_dlo.or p q) := formula_dlo.or p.map q.map
| (formula_dlo.and p q) := formula_dlo.and p.map q.map
| (formula_dlo.ex p) := formula_dlo.false
def conj : list (formula_dlo) → formula_dlo
| [] := formula_dlo.true
| (p::ps) := and_o p $ conj ps
def conj_atom : list (atom_dlo) → formula_dlo
| [] := formula_dlo.true
| (a::as) := and_o (formula_dlo.atom a) $ conj_atom as
def disj : list (formula_dlo) → formula_dlo
| [] := formula_dlo.false
| (p::ps) := or_o p $ disj ps
lemma eval_disj {xs : list rat} :
∀ {ps : list (formula_dlo)}, (disj ps).eval xs ↔ (∃ p : formula_dlo, p ∈ ps ∧ p.eval xs)
| [] := begin simp [disj, formula_dlo.eval] end
| (p::ps) :=
begin
rw [list.forsome_mem_cons], simp [disj, eval_or_o],
apply or_iff_or iff.rfl eval_disj
end
def disj_map {β : Type} (bs : list β) (p : β → formula_dlo) := disj (list.map p bs)
lemma eval_disj_map {β : Type} (as : list β)
(p : β → formula_dlo) {ds : list rat} :
(disj_map as p).eval ds ↔ ∃ a, a ∈ as ∧ (p a).eval ds :=
begin
simp [disj_map, eval_disj],
constructor; intro h; cases h with x hx; cases hx with hx1 hx2,
{ cases hx1 with a ha, cases ha with ha1 ha2, subst ha2,
existsi a, constructor; assumption },
{ existsi (p x), constructor, existsi x,
constructor, assumption, refl, assumption }
end
lemma cases_not_o (P : formula_dlo → Prop) (p : formula_dlo)
(HT : P formula_dlo.true) (Hp : P formula_dlo.false) (Hq : P (p.not)) : P (not_o p) :=
begin cases p; try {simp [not_o], assumption} end
lemma cases_or_o (P : formula_dlo → Prop) (p q : formula_dlo)
(HT : P formula_dlo.true) (Hp : P p) (Hq : P q) (Hpq : P (formula_dlo.or p q)) : P (or_o p q) :=
begin cases p; cases q; try {simp [or_o], assumption} end
lemma cases_and_o (P : formula_dlo → Prop) (p q : formula_dlo)
(HB : P formula_dlo.false) (Hp : P p) (Hq : P q) (Hpq : P (formula_dlo.and p q)) : P (and_o p q) :=
begin cases p; cases q; try {simp [and_o], assumption} end
-- meta def formula_dlo.to_format : formula_dlo → format
-- | (formula_dlo.true) := "⊤"
-- | (formula_dlo.false) := "⊥"
-- | (formula_dlo.atom a) := a.to_format
-- | (formula_dlo.and p q) := "(" ++ (formula_dlo.to_format p) ++ " ∧ " ++ (formula_dlo.to_format q) ++ ")"
-- | (formula_dlo.or p q) := "(" ++ (formula_dlo.to_format p) ++ " ∨ " ++ (formula_dlo.to_format q) ++ ")"
-- | (formula_dlo.not p) := "¬(" ++ (formula_dlo.to_format p) ++ ")"
-- | (formula_dlo.ex p) := "∃(" ++ (formula_dlo.to_format p) ++ ")"
-- meta instance formula_dlo.has_to_format : has_to_format (formula_dlo) := ⟨formula_dlo.to_format⟩
--
-- meta instance formula_dlo.has_to_tactic_format : has_to_tactic_format (formula_dlo) :=
-- has_to_format_to_has_to_tactic_format _
instance atom_dlo.decidable_eq : decidable_eq atom_dlo := by tactic.mk_dec_eq_instance
instance dec_aval {as a} : decidable (atom_dlo.eval as a) :=
begin cases a; {simp [atom_dlo.eval], apply_instance} end
def avals (bs : list rat) (as : list atom_dlo) : Prop :=
∀ a ∈ as, atom_dlo.eval bs a
lemma eval_conj {xs : list rat} :
∀ {ps : list formula_dlo}, formula_dlo.eval xs (conj ps) ↔ (∀ p ∈ ps, formula_dlo.eval xs p)
| [] := begin simp [conj, formula_dlo.eval] end
| (p::ps) :=
begin
simp [conj, eval_and_o],
apply and_iff_and iff.rfl eval_conj
end
lemma eval_conj_atom {xs : list rat} :
∀ {as : list atom_dlo}, (conj_atom as).eval xs ↔ (∀ a ∈ as, atom_dlo.eval xs a)
| [] := begin simp [conj_atom] end
| (a::as) :=
begin simp [conj_atom, eval_and_o, atom_dlo.eval,
eval_conj_atom, formula_dlo.eval] end |
1014d0960e74148e96601730c1812e78b68667c7 | d9ed0fce1c218297bcba93e046cb4e79c83c3af8 | /library/tools/super/inhabited.lean | d9d45131cef7cf39a55d9f2fe77dd2c46f71d16a | [
"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 | 2,318 | lean | /-
Copyright (c) 2016 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause_ops .prover_state
open expr tactic monad
namespace super
meta def try_nonempty_lookup_left (c : clause) : tactic (list clause) :=
on_first_left_dn c $ λhnx,
match is_local_not c^.local_false hnx^.local_type with
| some type := do
univ ← infer_univ type,
lf_univ ← infer_univ c^.local_false,
guard $ lf_univ = level.zero,
inst ← mk_instance (app (const ``nonempty [univ]) type),
instt ← infer_type inst,
return [([], app_of_list (const ``nonempty.elim [univ])
[type, c^.local_false, inst, hnx])]
| _ := failed
end
meta def try_nonempty_left (c : clause) : tactic (list clause) :=
on_first_left c $ λprop,
match prop with
| (app (const ``nonempty [u]) type) := do
x ← mk_local_def `x type,
return [([x], app_of_list (const ``nonempty.intro [u]) [type, x])]
| _ := failed
end
meta def try_nonempty_right (c : clause) : tactic (list clause) :=
on_first_right c $ λhnonempty,
match hnonempty^.local_type with
| (app (const ``nonempty [u]) type) := do
lf_univ ← infer_univ c^.local_false,
guard $ lf_univ = level.zero,
hnx ← mk_local_def `nx (imp type c^.local_false),
return [([hnx], app_of_list (const ``nonempty.elim [u])
[type, c^.local_false, hnonempty, hnx])]
| _ := failed
end
meta def try_inhabited_left (c : clause) : tactic (list clause) :=
on_first_left c $ λprop,
match prop with
| (app (const ``inhabited [u]) type) := do
x ← mk_local_def `x type,
return [([x], app_of_list (const ``inhabited.mk [u]) [type, x])]
| _ := failed
end
meta def try_inhabited_right (c : clause) : tactic (list clause) :=
on_first_right' c $ λhinh,
match hinh^.local_type with
| (app (const ``inhabited [u]) type) :=
return [([], app_of_list (const ``inhabited.default [u]) [type, hinh])]
| _ := failed
end
@[super.inf]
meta def inhabited_infs : inf_decl := inf_decl.mk 10 $ take given, do
for' [try_nonempty_lookup_left,
try_nonempty_left, try_nonempty_right,
try_inhabited_left, try_inhabited_right] $ λr,
simp_if_successful given (r given^.c)
end super
|
77ccd820031925ca088602fb6c70667d0cbdc966 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/ring_theory/power_series/well_known.lean | 1e18ca42288ed19945a9e32f02f6a89129a3690d | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,958 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import ring_theory.power_series.basic
import data.nat.parity
import algebra.big_operators.nat_antidiagonal
/-!
# Definition of well-known power series
In this file we define the following power series:
* `power_series.inv_units_sub`: given `u : units R`, this is the series for `1 / (u - x)`.
It is given by `∑ n, x ^ n /ₚ u ^ (n + 1)`.
* `power_series.sin`, `power_series.cos`, `power_series.exp` : power series for sin, cosine, and
exponential functions.
-/
namespace power_series
section ring
variables {R S : Type*} [ring R] [ring S]
/-- The power series for `1 / (u - x)`. -/
def inv_units_sub (u : units R) : power_series R := mk $ λ n, 1 /ₚ u ^ (n + 1)
@[simp] lemma coeff_inv_units_sub (u : units R) (n : ℕ) :
coeff R n (inv_units_sub u) = 1 /ₚ u ^ (n + 1) :=
coeff_mk _ _
@[simp] lemma constant_coeff_inv_units_sub (u : units R) :
constant_coeff R (inv_units_sub u) = 1 /ₚ u :=
by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_units_sub, zero_add, pow_one]
@[simp] lemma inv_units_sub_mul_X (u : units R) :
inv_units_sub u * X = inv_units_sub u * C R u - 1 :=
begin
ext (_|n),
{ simp },
{ simp [n.succ_ne_zero, pow_succ] }
end
@[simp] lemma inv_units_sub_mul_sub (u : units R) : inv_units_sub u * (C R u - X) = 1 :=
by simp [mul_sub, sub_sub_cancel]
lemma map_inv_units_sub (f : R →+* S) (u : units R) :
map f (inv_units_sub u) = inv_units_sub (units.map (f : R →* S) u) :=
by { ext, simp [← monoid_hom.map_pow] }
end ring
section field
variables (A A' : Type*) [ring A] [ring A'] [algebra ℚ A] [algebra ℚ A']
open_locale nat
/-- Power series for the exponential function at zero. -/
def exp : power_series A := mk $ λ n, algebra_map ℚ A (1 / n!)
/-- Power series for the sine function at zero. -/
def sin : power_series A :=
mk $ λ n, if even n then 0 else algebra_map ℚ A ((-1) ^ (n / 2) / n!)
/-- Power series for the cosine function at zero. -/
def cos : power_series A :=
mk $ λ n, if even n then algebra_map ℚ A ((-1) ^ (n / 2) / n!) else 0
variables {A A'} (n : ℕ) (f : A →+* A')
@[simp] lemma coeff_exp : coeff A n (exp A) = algebra_map ℚ A (1 / n!) := coeff_mk _ _
@[simp] lemma constant_coeff_exp : constant_coeff A (exp A) = 1 := ring_hom.map_one _
@[simp] lemma map_exp : map (f : A →+* A') (exp A) = exp A' := by { ext, simp }
@[simp] lemma map_sin : map f (sin A) = sin A' := by { ext, simp [sin, apply_ite f] }
@[simp] lemma map_cos : map f (cos A) = cos A' := by { ext, simp [cos, apply_ite f] }
end field
open ring_hom
open finset nat
variables {A : Type*} [comm_ring A]
/-- Shows that $e^{aX} * e^{bX} = e^{(a + b)X}$ -/
theorem exp_mul_exp_eq_exp_add [algebra ℚ A] (a b : A) :
rescale a (exp A) * rescale b (exp A) = rescale (a + b) (exp A) :=
begin
ext,
simp only [coeff_mul, exp, rescale, coeff_mk, coe_mk, factorial,
nat.sum_antidiagonal_eq_sum_range_succ_mk, add_pow, sum_mul],
apply sum_congr rfl,
rintros x hx,
suffices : a^x * b^(n - x) * (algebra_map ℚ A (1 / ↑(x.factorial)) * algebra_map ℚ A
(1 / ↑((n - x).factorial))) =
a^x * b^(n - x) * ((↑(n.choose x) * (algebra_map ℚ A) (1 / ↑(n.factorial)))),
{ convert this using 1; ring },
congr' 1,
rw [←map_nat_cast (algebra_map ℚ A) (n.choose x), ←map_mul, ←map_mul],
refine ring_hom.congr_arg _ _,
rw [mul_one_div ↑(n.choose x) _, one_div_mul_one_div],
symmetry,
rw [div_eq_iff, div_mul_eq_mul_div, one_mul, choose_eq_factorial_div_factorial],
norm_cast,
rw cast_dvd_char_zero,
{ apply factorial_mul_factorial_dvd_factorial (mem_range_succ_iff.1 hx), },
{ apply mem_range_succ_iff.1 hx, },
{ rintros h, apply factorial_ne_zero n, rw cast_eq_zero.1 h, },
end
/-- Shows that $e^{x} * e^{-x} = 1$ -/
theorem exp_mul_exp_neg_eq_one [algebra ℚ A] : exp A * eval_neg_hom (exp A) = 1 :=
by convert exp_mul_exp_eq_exp_add (1 : A) (-1); simp
/-- Shows that $(e^{X})^k = e^{kX}$. -/
theorem exp_pow_eq_rescale_exp [algebra ℚ A] (k : ℕ) : (exp A)^k = rescale (k : A) (exp A) :=
begin
induction k with k h,
{ simp only [rescale_zero, constant_coeff_exp, function.comp_app, map_one, cast_zero,
pow_zero, coe_comp], },
simpa only [succ_eq_add_one, cast_add, ←exp_mul_exp_eq_exp_add (k : A), ←h, cast_one,
id_apply, rescale_one] using pow_succ' (exp A) k,
end
/-- Shows that
$\sum_{k = 0}^{n - 1} (e^{X})^k = \sum_{p = 0}^{\infty} \sum_{k = 0}^{n - 1} \frac{k^p}{p!}X^p$. -/
theorem exp_pow_sum [algebra ℚ A] (n : ℕ) : (finset.range n).sum (λ k, (exp A)^k) =
power_series.mk (λ p, (finset.range n).sum (λ k, k^p * algebra_map ℚ A p.factorial⁻¹)) :=
begin
simp only [exp_pow_eq_rescale_exp, rescale],
ext,
simp only [one_div, coeff_mk, coe_mk, coeff_exp, factorial, linear_map.map_sum],
end
end power_series
|
a36acb77e42941f75756e92e70667da144809aab | c8af905dcd8475f414868d303b2eb0e9d3eb32f9 | /examples/common.lean | 97afafe1605b55a43905b6438455a2d931131b50 | [
"BSD-3-Clause"
] | permissive | continuouspi/lean-cpi | 81480a13842d67ff5f3698643210d8ed5dd08de4 | 443bf2cb236feadc45a01387099c236ab2b78237 | refs/heads/master | 1,650,307,316,582 | 1,587,033,364,000 | 1,587,033,364,000 | 207,499,661 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 397 | lean | import data.cpi.semantics.with_normalise data.cpi.semantics.ode
def ℍ : Type := fin_poly raw_string ℚ
instance : half_ring ℍ := fin_poly.half_ring string ℚ
instance : has_repr ℍ := fin_poly.has_repr string ℚ
def ℂ : Type := ℍ
instance : half_ring ℂ := fin_poly.half_ring _ _
instance : has_repr ℂ := fin_poly.has_repr _ _
def conc : ℍ ↪ ℂ := function.embedding.refl _
|
dfc561c15820e497fb3926de3c973cfdbc7ccd8c | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/analysis/complex/polynomial.lean | 99f5c713bd234f86f70e1f80edc298764591c0d3 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 5,995 | lean | /-
Copyright (c) 2019 Chris Hughes All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.polynomial topology.algebra.polynomial analysis.complex.exponential
open complex polynomial metric filter is_absolute_value set lattice
namespace complex
lemma exists_forall_abs_polynomial_eval_le (p : polynomial ℂ) :
∃ x, ∀ y, (p.eval x).abs ≤ (p.eval y).abs :=
if hp0 : 0 < degree p
then let ⟨r, hr0, hr⟩ := polynomial.tendsto_infinity complex.abs hp0 ((p.eval 0).abs) in
let ⟨x, hx₁, hx₂⟩ := (proper_space.compact_ball (0:ℂ) r).exists_forall_le
(set.ne_empty_iff_exists_mem.2 ⟨0, by simp [le_of_lt hr0]⟩)
(λ z, abs (p.eval z)) (continuous_abs.comp p.continuous_eval).continuous_on in
⟨x, λ y, if hy : y.abs ≤ r then hx₂ y $ by simpa [complex.dist_eq] using hy
else le_trans (hx₂ _ (by simp [le_of_lt hr0])) (le_of_lt (hr y (lt_of_not_ge hy)))⟩
else ⟨p.coeff 0, by rw [eq_C_of_degree_le_zero (le_of_not_gt hp0)]; simp⟩
/- The following proof uses the method given at
<https://ncatlab.org/nlab/show/fundamental+theorem+of+algebra#classical_fta_via_advanced_calculus> -/
/-- The fundamental theorem of algebra. Every non constant complex polynomial
has a root -/
lemma exists_root {f : polynomial ℂ} (hf : 0 < degree f) : ∃ z : ℂ, is_root f z :=
let ⟨z₀, hz₀⟩ := exists_forall_abs_polynomial_eval_le f in
exists.intro z₀ $ by_contradiction $ λ hf0,
have hfX : f - C (f.eval z₀) ≠ 0,
from mt sub_eq_zero.1 (λ h, not_le_of_gt hf (h.symm ▸ degree_C_le)),
let n := root_multiplicity z₀ (f - C (f.eval z₀)) in
let g := (f - C (f.eval z₀)) /ₘ ((X - C z₀) ^ n) in
have hg0 : g.eval z₀ ≠ 0, from eval_div_by_monic_pow_root_multiplicity_ne_zero _ hfX,
have hg : g * (X - C z₀) ^ n = f - C (f.eval z₀),
from div_by_monic_mul_pow_root_multiplicity_eq _ _,
have hn0 : 0 < n, from nat.pos_of_ne_zero $ λ hn0, by simpa [g, hn0] using hg0,
let ⟨δ', hδ'₁, hδ'₂⟩ := continuous_iff.1 (polynomial.continuous_eval g) z₀
((g.eval z₀).abs) (complex.abs_pos.2 hg0) in
let δ := min (min (δ' / 2) 1) (((f.eval z₀).abs / (g.eval z₀).abs) / 2) in
have hf0' : 0 < (f.eval z₀).abs, from complex.abs_pos.2 hf0,
have hfg0 : 0 < abs (eval z₀ f) * (abs (eval z₀ g))⁻¹, from div_pos hf0' (complex.abs_pos.2 hg0),
have hδ0 : 0 < δ, from lt_min (lt_min (half_pos hδ'₁) (by norm_num)) (half_pos hfg0),
have hδ : ∀ z : ℂ, abs (z - z₀) = δ → abs (g.eval z - g.eval z₀) < (g.eval z₀).abs,
from λ z hz, hδ'₂ z (by rw [complex.dist_eq, hz];
exact lt_of_le_of_lt (le_trans (min_le_left _ _) (min_le_left _ _))
(half_lt_self hδ'₁)),
have hδ1 : δ ≤ 1, from le_trans (min_le_left _ _) (min_le_right _ _),
let F : polynomial ℂ := C (f.eval z₀) + C (g.eval z₀) * (X - C z₀) ^ n in
let z' := (-f.eval z₀ * (g.eval z₀).abs * δ ^ n /
((f.eval z₀).abs * g.eval z₀)) ^ (n⁻¹ : ℂ) + z₀ in
have hF₁ : F.eval z' = f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs,
by simp only [F, cpow_nat_inv_pow _ hn0, div_eq_mul_inv, eval_pow, mul_assoc, mul_comm (g.eval z₀),
mul_left_comm (g.eval z₀), mul_left_comm (g.eval z₀)⁻¹, mul_inv', inv_mul_cancel hg0,
eval_C, eval_add, eval_neg, sub_eq_add_neg, eval_mul, eval_X, add_neg_cancel_right,
neg_mul_eq_neg_mul_symm, mul_one, div_eq_mul_inv];
simp only [mul_comm, mul_left_comm, mul_assoc],
have hδs : (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs < 1,
by rw [div_eq_mul_inv, mul_right_comm, mul_comm, ← inv_inv' (complex.abs _ * _), mul_inv',
inv_inv', ← div_eq_mul_inv, div_lt_iff hfg0, one_mul];
calc δ ^ n ≤ δ ^ 1 : pow_le_pow_of_le_one (le_of_lt hδ0) hδ1 hn0
... = δ : pow_one _
... ≤ ((f.eval z₀).abs / (g.eval z₀).abs) / 2 : min_le_right _ _
... < _ : half_lt_self hfg0,
have hF₂ : (F.eval z').abs = (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n,
from calc (F.eval z').abs = (f.eval z₀ - f.eval z₀ * (g.eval z₀).abs
* δ ^ n / (f.eval z₀).abs).abs : congr_arg abs hF₁
... = abs (f.eval z₀) * complex.abs (1 - (g.eval z₀).abs * δ ^ n /
(f.eval z₀).abs : ℝ) : by rw [← complex.abs_mul];
exact congr_arg complex.abs
(by simp [mul_add, add_mul, mul_assoc, div_eq_mul_inv])
... = _ : by rw [complex.abs_of_nonneg (sub_nonneg.2 (le_of_lt hδs)),
mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt hf0')), mul_one],
have hef0 : abs (eval z₀ g) * (eval z₀ f).abs ≠ 0,
from mul_ne_zero (mt complex.abs_eq_zero.1 hg0) (mt complex.abs_eq_zero.1 hf0),
have hz'z₀ : abs (z' - z₀) = δ,
by simp [z', mul_assoc, mul_left_comm _ (_ ^ n), mul_comm _ (_ ^ n),
mul_comm (eval z₀ f).abs, _root_.mul_div_cancel _ hef0, of_real_mul,
neg_mul_eq_neg_mul_symm, neg_div, is_absolute_value.abv_pow complex.abs,
complex.abs_of_nonneg (le_of_lt hδ0), real.pow_nat_rpow_nat_inv (le_of_lt hδ0) hn0],
have hF₃ : (f.eval z' - F.eval z').abs < (g.eval z₀).abs * δ ^ n,
from calc (f.eval z' - F.eval z').abs
= (g.eval z' - g.eval z₀).abs * (z' - z₀).abs ^ n :
by rw [← eq_sub_iff_add_eq.1 hg, ← is_absolute_value.abv_pow complex.abs,
← complex.abs_mul, sub_mul];
simp [F, eval_pow, eval_add, eval_mul, eval_sub, eval_C, eval_X, eval_neg, add_sub_cancel]
... = (g.eval z' - g.eval z₀).abs * δ ^ n : by rw hz'z₀
... < _ : (mul_lt_mul_right (pow_pos hδ0 _)).2 (hδ _ hz'z₀),
lt_irrefl (f.eval z₀).abs $
calc (f.eval z₀).abs ≤ (f.eval z').abs : hz₀ _
... = (F.eval z' + (f.eval z' - F.eval z')).abs : by simp
... ≤ (F.eval z').abs + (f.eval z' - F.eval z').abs : complex.abs_add _ _
... < (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n + (g.eval z₀).abs * δ ^ n :
add_lt_add_of_le_of_lt (by rw hF₂) hF₃
... = (f.eval z₀).abs : sub_add_cancel _ _
end complex
|
5090843d1f0092f721b4544d64baa716ef377fa7 | 54ce0561cebde424526f41d45f490ed56be2bd0c | /src/game/ch3_Set_Theory/4_Images_and_Inverse_Images.lean | 12a3bcb38cd42a75a68e6a54248a6033aeae8a3e | [] | no_license | melembroucarlitos/Tao_Analysis-LEAN | cf7b3298d317891a09e4bf21cfe7c7ffcb57b9a9 | 3f4fc7e090d96b6cef64896492fba4bef124794b | refs/heads/master | 1,692,952,385,694 | 1,636,287,522,000 | 1,636,287,522,000 | 400,630,166 | 3 | 0 | null | 1,635,910,807,000 | 1,630,096,823,000 | Lean | UTF-8 | Lean | false | false | 176 | lean | -- Level name : Images and Inverse Images
/-
# Hey yall
## This is just to a placeholder to make sure all is working
these are some words
and these are some other words
-/
|
e1fd0db9d41fd1fb547102f53fd4c55b2b63a0ca | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/function/continuous_map_dense.lean | c7c511cfef3a1e298f488cf266cd8765c25cafa3 | [
"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,713 | lean | /-
Copyright (c) 2021 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth
-/
import measure_theory.measure.regular
import measure_theory.function.simple_func_dense_lp
import topology.urysohns_lemma
import measure_theory.integral.bochner
/-!
# Approximation in Lᵖ by continuous functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file proves that bounded continuous functions are dense in `Lp E p μ`, for `p < ∞`, if the
domain `α` of the functions is a normal topological space and the measure `μ` is weakly regular.
It also proves the same results for approximation by continuous functions with compact support
when the space is locally compact and `μ` is regular.
The result is presented in several versions. First concrete versions giving an approximation
up to `ε` in these various contexts, and then abstract versions stating that the topological
closure of the relevant subgroups of `Lp` are the whole space.
* `mem_ℒp.exists_has_compact_support_snorm_sub_le` states that, in a locally compact space,
an `ℒp` function can be approximated by continuous functions with compact support,
in the sense that `snorm (f - g) p μ` is small.
* `mem_ℒp.exists_has_compact_support_integral_rpow_sub_le`: same result, but expressed in
terms of `∫ ‖f - g‖^p`.
Versions with `integrable` instead of `mem_ℒp` are specialized to the case `p = 1`.
Versions with `bounded_continuous` instead of `has_compact_support` drop the locally
compact assumption and give only approximation by a bounded continuous function.
* `measure_theory.Lp.bounded_continuous_function_dense`: The subgroup
`measure_theory.Lp.bounded_continuous_function` of `Lp E p μ`, the additive subgroup of
`Lp E p μ` consisting of equivalence classes containing a continuous representative, is dense in
`Lp E p μ`.
* `bounded_continuous_function.to_Lp_dense_range`: For finite-measure `μ`, the continuous linear
map `bounded_continuous_function.to_Lp p μ 𝕜` from `α →ᵇ E` to `Lp E p μ` has dense range.
* `continuous_map.to_Lp_dense_range`: For compact `α` and finite-measure `μ`, the continuous linear
map `continuous_map.to_Lp p μ 𝕜` from `C(α, E)` to `Lp E p μ` has dense range.
Note that for `p = ∞` this result is not true: the characteristic function of the set `[0, ∞)` in
`ℝ` cannot be continuously approximated in `L∞`.
The proof is in three steps. First, since simple functions are dense in `Lp`, it suffices to prove
the result for a scalar multiple of a characteristic function of a measurable set `s`. Secondly,
since the measure `μ` is weakly regular, the set `s` can be approximated above by an open set and
below by a closed set. Finally, since the domain `α` is normal, we use Urysohn's lemma to find a
continuous function interpolating between these two sets.
## Related results
Are you looking for a result on "directional" approximation (above or below with respect to an
order) of functions whose codomain is `ℝ≥0∞` or `ℝ`, by semicontinuous functions? See the
Vitali-Carathéodory theorem, in the file `measure_theory.vitali_caratheodory`.
-/
open_locale ennreal nnreal topology bounded_continuous_function
open measure_theory topological_space continuous_map set
variables {α : Type*} [measurable_space α] [topological_space α] [normal_space α] [borel_space α]
variables {E : Type*} [normed_add_comm_group E] {μ : measure α} {p : ℝ≥0∞}
namespace measure_theory
variables [normed_space ℝ E]
/-- A variant of Urysohn's lemma, `ℒ^p` version, for an outer regular measure `μ`:
consider two sets `s ⊆ u` which are respectively closed and open with `μ s < ∞`, and a vector `c`.
Then one may find a continuous function `f` equal to `c` on `s` and to `0` outside of `u`,
bounded by `‖c‖` everywhere, and such that the `ℒ^p` norm of `f - s.indicator (λ y, c)` is
arbitrarily small. Additionally, this function `f` belongs to `ℒ^p`. -/
lemma exists_continuous_snorm_sub_le_of_closed [μ.outer_regular]
(hp : p ≠ ∞) {s u : set α} (s_closed : is_closed s) (u_open : is_open u) (hsu : s ⊆ u)
(hs : μ s ≠ ∞) (c : E) {ε : ℝ≥0∞} (hε : ε ≠ 0) :
∃ (f : α → E), continuous f ∧ snorm (λ x, f x - s.indicator (λ y, c) x) p μ ≤ ε ∧
(∀ x, ‖f x‖ ≤ ‖c‖) ∧ function.support f ⊆ u ∧ mem_ℒp f p μ :=
begin
obtain ⟨η, η_pos, hη⟩ : ∃ (η : ℝ≥0), 0 < η ∧ ∀ (s : set α), μ s ≤ η →
snorm (s.indicator (λ x, c)) p μ ≤ ε, from exists_snorm_indicator_le hp c hε,
have ηpos : (0 : ℝ≥0∞) < η := ennreal.coe_lt_coe.2 η_pos,
obtain ⟨V, sV, V_open, h'V, hV⟩ : ∃ (V : set α) (H : V ⊇ s), is_open V ∧ μ V < ∞ ∧ μ (V \ s) < η,
from s_closed.measurable_set.exists_is_open_diff_lt hs ηpos.ne',
let v := u ∩ V,
have hsv : s ⊆ v := subset_inter hsu sV,
have hμv : μ v < ∞ := (measure_mono (inter_subset_right _ _)).trans_lt h'V,
obtain ⟨g, hgv, hgs, hg_range⟩ := exists_continuous_zero_one_of_closed
(u_open.inter V_open).is_closed_compl s_closed (disjoint_compl_left_iff.2 hsv),
-- Multiply this by `c` to get a continuous approximation to the function `f`; the key point is
-- that this is pointwise bounded by the indicator of the set `v \ s`, which has small measure.
have g_norm : ∀ x, ‖g x‖ = g x := λ x, by rw [real.norm_eq_abs, abs_of_nonneg (hg_range x).1],
have gc_bd0 : ∀ x, ‖g x • c‖ ≤ ‖c‖,
{ assume x,
simp only [norm_smul, g_norm x],
apply mul_le_of_le_one_left (norm_nonneg _),
exact (hg_range x).2 },
have gc_bd : ∀ x, ‖g x • c - s.indicator (λ x, c) x‖ ≤ ‖(v \ s).indicator (λ x, c) x‖,
{ intros x,
by_cases hv : x ∈ v,
{ rw ← set.diff_union_of_subset hsv at hv,
cases hv with hsv hs,
{ simpa only [hsv.2, set.indicator_of_not_mem, not_false_iff, sub_zero, hsv,
set.indicator_of_mem] using gc_bd0 x},
{ simp [hgs hs, hs] } },
{ simp [hgv hv, (λ h, hv (hsv h) : x ∉ s)], } },
have gc_support : function.support (λ (x : α), g x • c) ⊆ v,
{ refine function.support_subset_iff'.2 (λ x hx, _),
simp only [hgv hx, pi.zero_apply, zero_smul] },
have gc_mem : mem_ℒp (λ x, g x • c) p μ,
{ refine mem_ℒp.smul_of_top_left (mem_ℒp_top_const _) _,
refine ⟨g.continuous.ae_strongly_measurable, _⟩,
have : snorm (v.indicator (λ x, (1 : ℝ))) p μ < ⊤,
{ refine (snorm_indicator_const_le _ _).trans_lt _,
simp only [lt_top_iff_ne_top, hμv.ne, nnnorm_one, ennreal.coe_one, one_div, one_mul, ne.def,
ennreal.rpow_eq_top_iff, inv_lt_zero, false_and, or_false, not_and, not_lt,
ennreal.to_real_nonneg, implies_true_iff] },
refine (snorm_mono (λ x, _)).trans_lt this,
by_cases hx : x ∈ v,
{ simp only [hx, abs_of_nonneg (hg_range x).1, (hg_range x).2, real.norm_eq_abs,
indicator_of_mem, cstar_ring.norm_one] },
{ simp only [hgv hx, pi.zero_apply, real.norm_eq_abs, abs_zero, abs_nonneg] } },
refine ⟨λ x, g x • c, g.continuous.smul continuous_const, (snorm_mono gc_bd).trans _, gc_bd0,
gc_support.trans (inter_subset_left _ _), gc_mem⟩,
exact hη _ ((measure_mono (diff_subset_diff (inter_subset_right _ _) subset.rfl)).trans hV.le),
end
/-- In a locally compact space, any function in `ℒp` can be approximated by compactly supported
continuous functions when `p < ∞`, version in terms of `snorm`. -/
lemma mem_ℒp.exists_has_compact_support_snorm_sub_le
[locally_compact_space α] [μ.regular] (hp : p ≠ ∞)
{f : α → E} (hf : mem_ℒp f p μ) {ε : ℝ≥0∞} (hε : ε ≠ 0) :
∃ (g : α → E), has_compact_support g ∧ snorm (f - g) p μ ≤ ε ∧ continuous g ∧ mem_ℒp g p μ :=
begin
suffices H : ∃ (g : α → E), snorm (f - g) p μ ≤ ε ∧ continuous g ∧ mem_ℒp g p μ ∧
has_compact_support g,
{ rcases H with ⟨g, hg, g_cont, g_mem, g_support⟩,
exact ⟨g, g_support, hg, g_cont, g_mem⟩ },
-- It suffices to check that the set of functions we consider approximates characteristic
-- functions, is stable under addition and consists of ae strongly measurable functions.
-- First check the latter easy facts.
apply hf.induction_dense hp _ _ _ _ hε, rotate,
-- stability under addition
{ rintros f g ⟨f_cont, f_mem, hf⟩ ⟨g_cont, g_mem, hg⟩,
exact ⟨f_cont.add g_cont, f_mem.add g_mem, hf.add hg⟩ },
-- ae strong measurability
{ rintros f ⟨f_cont, f_mem, hf⟩,
exact f_mem.ae_strongly_measurable },
-- We are left with approximating characteristic functions.
-- This follows from `exists_continuous_snorm_sub_le_of_closed`.
assume c t ht htμ ε hε,
rcases exists_Lp_half E μ p hε with ⟨δ, δpos, hδ⟩,
obtain ⟨η, ηpos, hη⟩ : ∃ (η : ℝ≥0), 0 < η ∧ ∀ (s : set α), μ s ≤ η →
snorm (s.indicator (λ x, c)) p μ ≤ δ, from exists_snorm_indicator_le hp c δpos.ne',
have hη_pos' : (0 : ℝ≥0∞) < η, from ennreal.coe_pos.2 ηpos,
obtain ⟨s, st, s_compact, μs⟩ : ∃ s ⊆ t, is_compact s ∧ μ (t \ s) < η,
from ht.exists_is_compact_diff_lt htμ.ne hη_pos'.ne',
have hsμ : μ s < ∞, from (measure_mono st).trans_lt htμ,
have I1 : snorm (s.indicator (λ y, c) - t.indicator (λ y, c)) p μ ≤ δ,
{ rw [← snorm_neg, neg_sub, ← indicator_diff st],
exact (hη _ μs.le) },
obtain ⟨k, k_compact, sk, -⟩ : ∃ (k : set α), is_compact k ∧ s ⊆ interior k ∧ k ⊆ univ,
from exists_compact_between s_compact is_open_univ (subset_univ _),
rcases exists_continuous_snorm_sub_le_of_closed hp s_compact.is_closed is_open_interior sk
hsμ.ne c δpos.ne' with ⟨f, f_cont, I2, f_bound, f_support, f_mem⟩,
have I3 : snorm (f - t.indicator (λ y, c)) p μ ≤ ε,
{ convert (hδ _ _ (f_mem.ae_strongly_measurable.sub
(ae_strongly_measurable_const.indicator s_compact.measurable_set))
((ae_strongly_measurable_const.indicator s_compact.measurable_set).sub
(ae_strongly_measurable_const.indicator ht)) I2 I1).le,
simp only [sub_add_sub_cancel] },
refine ⟨f, I3, f_cont, f_mem, has_compact_support.intro k_compact (λ x hx, _)⟩,
rw ← function.nmem_support,
contrapose! hx,
exact interior_subset (f_support hx)
end
/-- In a locally compact space, any function in `ℒp` can be approximated by compactly supported
continuous functions when `0 < p < ∞`, version in terms of `∫`. -/
lemma mem_ℒp.exists_has_compact_support_integral_rpow_sub_le
[locally_compact_space α] [μ.regular] {p : ℝ} (hp : 0 < p)
{f : α → E} (hf : mem_ℒp f (ennreal.of_real p) μ) {ε : ℝ} (hε : 0 < ε) :
∃ (g : α → E), has_compact_support g ∧ ∫ x, ‖f x - g x‖^p ∂μ ≤ ε ∧ continuous g
∧ mem_ℒp g (ennreal.of_real p) μ :=
begin
have I : 0 < ε ^ (1/p) := real.rpow_pos_of_pos hε _,
have A : ennreal.of_real (ε ^ (1/p)) ≠ 0,
by simp only [ne.def, ennreal.of_real_eq_zero, not_le, I],
have B : ennreal.of_real p ≠ 0, by simpa only [ne.def, ennreal.of_real_eq_zero, not_le] using hp,
rcases hf.exists_has_compact_support_snorm_sub_le ennreal.coe_ne_top A
with ⟨g, g_support, hg, g_cont, g_mem⟩,
change snorm _ (ennreal.of_real p) _ ≤ _ at hg,
refine ⟨g, g_support, _, g_cont, g_mem⟩,
rwa [(hf.sub g_mem).snorm_eq_integral_rpow_norm B ennreal.coe_ne_top,
ennreal.of_real_le_of_real_iff I.le, one_div,
ennreal.to_real_of_real hp.le, real.rpow_le_rpow_iff _ hε.le (inv_pos.2 hp)] at hg,
exact integral_nonneg (λ x, real.rpow_nonneg_of_nonneg (norm_nonneg _) _),
end
/-- In a locally compact space, any integrable function can be approximated by compactly supported
continuous functions, version in terms of `∫⁻`. -/
lemma integrable.exists_has_compact_support_lintegral_sub_le [locally_compact_space α] [μ.regular]
{f : α → E} (hf : integrable f μ) {ε : ℝ≥0∞} (hε : ε ≠ 0) :
∃ (g : α → E), has_compact_support g ∧ ∫⁻ x, ‖f x - g x‖₊ ∂μ ≤ ε ∧ continuous g
∧ integrable g μ :=
begin
simp only [← mem_ℒp_one_iff_integrable, ← snorm_one_eq_lintegral_nnnorm] at hf ⊢,
exact hf.exists_has_compact_support_snorm_sub_le ennreal.one_ne_top hε,
end
/-- In a locally compact space, any integrable function can be approximated by compactly supported
continuous functions, version in terms of `∫`. -/
lemma integrable.exists_has_compact_support_integral_sub_le [locally_compact_space α] [μ.regular]
{f : α → E} (hf : integrable f μ) {ε : ℝ} (hε : 0 < ε) :
∃ (g : α → E), has_compact_support g ∧ ∫ x, ‖f x - g x‖ ∂μ ≤ ε ∧ continuous g
∧ integrable g μ :=
begin
simp only [← mem_ℒp_one_iff_integrable, ← snorm_one_eq_lintegral_nnnorm,
← ennreal.of_real_one] at hf ⊢,
simpa using hf.exists_has_compact_support_integral_rpow_sub_le zero_lt_one hε,
end
/-- Any function in `ℒp` can be approximated by bounded continuous functions when `p < ∞`,
version in terms of `snorm`. -/
lemma mem_ℒp.exists_bounded_continuous_snorm_sub_le [μ.weakly_regular] (hp : p ≠ ∞)
{f : α → E} (hf : mem_ℒp f p μ) {ε : ℝ≥0∞} (hε : ε ≠ 0) :
∃ (g : α →ᵇ E), snorm (f - g) p μ ≤ ε ∧ mem_ℒp g p μ :=
begin
suffices H : ∃ (g : α → E), snorm (f - g) p μ ≤ ε ∧ continuous g ∧ mem_ℒp g p μ ∧
metric.bounded (range g),
{ rcases H with ⟨g, hg, g_cont, g_mem, g_bd⟩,
exact ⟨⟨⟨g, g_cont⟩, metric.bounded_range_iff.1 g_bd⟩, hg, g_mem⟩ },
-- It suffices to check that the set of functions we consider approximates characteristic
-- functions, is stable under addition and made of ae strongly measurable functions.
-- First check the latter easy facts.
apply hf.induction_dense hp _ _ _ _ hε, rotate,
-- stability under addition
{ rintros f g ⟨f_cont, f_mem, f_bd⟩ ⟨g_cont, g_mem, g_bd⟩,
refine ⟨f_cont.add g_cont, f_mem.add g_mem, _⟩,
let f' : α →ᵇ E := ⟨⟨f, f_cont⟩, metric.bounded_range_iff.1 f_bd⟩,
let g' : α →ᵇ E := ⟨⟨g, g_cont⟩, metric.bounded_range_iff.1 g_bd⟩,
exact (f' + g').bounded_range },
-- ae strong measurability
{ exact λ f ⟨_, h, _⟩, h.ae_strongly_measurable },
-- We are left with approximating characteristic functions.
-- This follows from `exists_continuous_snorm_sub_le_of_closed`.
assume c t ht htμ ε hε,
rcases exists_Lp_half E μ p hε with ⟨δ, δpos, hδ⟩,
obtain ⟨η, ηpos, hη⟩ : ∃ (η : ℝ≥0), 0 < η ∧ ∀ (s : set α), μ s ≤ η →
snorm (s.indicator (λ x, c)) p μ ≤ δ, from exists_snorm_indicator_le hp c δpos.ne',
have hη_pos' : (0 : ℝ≥0∞) < η, from ennreal.coe_pos.2 ηpos,
obtain ⟨s, st, s_closed, μs⟩ : ∃ s ⊆ t, is_closed s ∧ μ (t \ s) < η,
from ht.exists_is_closed_diff_lt htμ.ne hη_pos'.ne',
have hsμ : μ s < ∞, from (measure_mono st).trans_lt htμ,
have I1 : snorm (s.indicator (λ y, c) - t.indicator (λ y, c)) p μ ≤ δ,
{ rw [← snorm_neg, neg_sub, ← indicator_diff st],
exact (hη _ μs.le) },
rcases exists_continuous_snorm_sub_le_of_closed hp s_closed is_open_univ (subset_univ _)
hsμ.ne c δpos.ne' with ⟨f, f_cont, I2, f_bound, -, f_mem⟩,
have I3 : snorm (f - t.indicator (λ y, c)) p μ ≤ ε,
{ convert (hδ _ _ (f_mem.ae_strongly_measurable.sub
(ae_strongly_measurable_const.indicator s_closed.measurable_set))
((ae_strongly_measurable_const.indicator s_closed.measurable_set).sub
(ae_strongly_measurable_const.indicator ht)) I2 I1).le,
simp only [sub_add_sub_cancel] },
refine ⟨f, I3, f_cont, f_mem, _⟩,
exact (bounded_continuous_function.of_normed_add_comm_group f f_cont _ f_bound).bounded_range,
end
/-- Any function in `ℒp` can be approximated by bounded continuous functions when `0 < p < ∞`,
version in terms of `∫`. -/
lemma mem_ℒp.exists_bounded_continuous_integral_rpow_sub_le
[μ.weakly_regular] {p : ℝ} (hp : 0 < p)
{f : α → E} (hf : mem_ℒp f (ennreal.of_real p) μ) {ε : ℝ} (hε : 0 < ε) :
∃ (g : α →ᵇ E), ∫ x, ‖f x - g x‖^p ∂μ ≤ ε ∧ mem_ℒp g (ennreal.of_real p) μ :=
begin
have I : 0 < ε ^ (1/p) := real.rpow_pos_of_pos hε _,
have A : ennreal.of_real (ε ^ (1/p)) ≠ 0,
by simp only [ne.def, ennreal.of_real_eq_zero, not_le, I],
have B : ennreal.of_real p ≠ 0, by simpa only [ne.def, ennreal.of_real_eq_zero, not_le] using hp,
rcases hf.exists_bounded_continuous_snorm_sub_le ennreal.coe_ne_top A with ⟨g, hg, g_mem⟩,
change snorm _ (ennreal.of_real p) _ ≤ _ at hg,
refine ⟨g, _, g_mem⟩,
rwa [(hf.sub g_mem).snorm_eq_integral_rpow_norm B ennreal.coe_ne_top,
ennreal.of_real_le_of_real_iff I.le, one_div,
ennreal.to_real_of_real hp.le, real.rpow_le_rpow_iff _ hε.le (inv_pos.2 hp)] at hg,
exact integral_nonneg (λ x, real.rpow_nonneg_of_nonneg (norm_nonneg _) _),
end
/-- Any integrable function can be approximated by bounded continuous functions,
version in terms of `∫⁻`. -/
lemma integrable.exists_bounded_continuous_lintegral_sub_le [μ.weakly_regular]
{f : α → E} (hf : integrable f μ) {ε : ℝ≥0∞} (hε : ε ≠ 0) :
∃ (g : α →ᵇ E), ∫⁻ x, ‖f x - g x‖₊ ∂μ ≤ ε ∧ integrable g μ :=
begin
simp only [← mem_ℒp_one_iff_integrable, ← snorm_one_eq_lintegral_nnnorm] at hf ⊢,
exact hf.exists_bounded_continuous_snorm_sub_le ennreal.one_ne_top hε,
end
/-- Any integrable function can be approximated by bounded continuous functions,
version in terms of `∫`. -/
lemma integrable.exists_bounded_continuous_integral_sub_le [μ.weakly_regular]
{f : α → E} (hf : integrable f μ) {ε : ℝ} (hε : 0 < ε) :
∃ (g : α →ᵇ E), ∫ x, ‖f x - g x‖ ∂μ ≤ ε ∧ integrable g μ :=
begin
simp only [← mem_ℒp_one_iff_integrable, ← snorm_one_eq_lintegral_nnnorm,
← ennreal.of_real_one] at hf ⊢,
simpa using hf.exists_bounded_continuous_integral_rpow_sub_le zero_lt_one hε,
end
namespace Lp
variables (E)
/-- A function in `Lp` can be approximated in `Lp` by continuous functions. -/
lemma bounded_continuous_function_dense
[second_countable_topology_either α E] [_i : fact (1 ≤ p)] (hp : p ≠ ∞) [μ.weakly_regular] :
(bounded_continuous_function E p μ).topological_closure = ⊤ :=
begin
rw add_subgroup.eq_top_iff',
assume f,
refine mem_closure_iff_frequently.mpr _,
rw metric.nhds_basis_closed_ball.frequently_iff,
intros ε hε,
have A : ennreal.of_real ε ≠ 0, by simp only [ne.def, ennreal.of_real_eq_zero, not_le, hε],
obtain ⟨g, hg, g_mem⟩ : ∃ (g : α →ᵇ E), snorm (f - g) p μ ≤ ennreal.of_real ε ∧ mem_ℒp g p μ,
from (Lp.mem_ℒp f).exists_bounded_continuous_snorm_sub_le hp A,
refine ⟨g_mem.to_Lp _, _, ⟨g, rfl⟩⟩,
simp only [dist_eq_norm, metric.mem_closed_ball'],
rw Lp.norm_def,
convert ennreal.to_real_le_of_le_of_real hε.le hg using 2,
apply snorm_congr_ae,
filter_upwards [coe_fn_sub f (g_mem.to_Lp g), g_mem.coe_fn_to_Lp] with x hx h'x,
simp only [hx, pi.sub_apply, sub_right_inj, h'x],
end
end Lp
end measure_theory
variables [second_countable_topology_either α E] [_i : fact (1 ≤ p)] (hp : p ≠ ∞)
variables (𝕜 : Type*) [normed_field 𝕜] [normed_algebra ℝ 𝕜] [normed_space 𝕜 E]
include _i hp
variables (E) (μ)
namespace bounded_continuous_function
lemma to_Lp_dense_range [μ.weakly_regular] [is_finite_measure μ] :
dense_range ⇑(to_Lp p μ 𝕜 : (α →ᵇ E) →L[𝕜] Lp E p μ) :=
begin
haveI : normed_space ℝ E := restrict_scalars.normed_space ℝ 𝕜 E,
rw dense_range_iff_closure_range,
suffices : (linear_map.range (to_Lp p μ 𝕜 : _ →L[𝕜] Lp E p μ))
.to_add_subgroup.topological_closure = ⊤,
{ exact congr_arg coe this },
simp [range_to_Lp p μ, measure_theory.Lp.bounded_continuous_function_dense E hp],
end
end bounded_continuous_function
namespace continuous_map
lemma to_Lp_dense_range [compact_space α] [μ.weakly_regular] [is_finite_measure μ] :
dense_range ⇑(to_Lp p μ 𝕜 : C(α, E) →L[𝕜] Lp E p μ) :=
begin
haveI : normed_space ℝ E := restrict_scalars.normed_space ℝ 𝕜 E,
rw dense_range_iff_closure_range,
suffices : (linear_map.range (to_Lp p μ 𝕜 : _ →L[𝕜] Lp E p μ))
.to_add_subgroup.topological_closure = ⊤,
{ exact congr_arg coe this },
simp [range_to_Lp p μ, measure_theory.Lp.bounded_continuous_function_dense E hp]
end
end continuous_map
|
864c4ed1cf036105ddeafc418c6e666b97749930 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/topology/metric_space/completion.lean | de30bb6d260ed19e099faac6d012ca050a2b69e3 | [
"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 | 8,582 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sébastien Gouëzel
-/
import topology.uniform_space.completion topology.metric_space.isometry
/-!
# The completion of a metric space
Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show
here that the uniform space completion of a metric space inherits a metric space structure,
by extending the distance to the completion and checking that it is indeed a distance, and that
it defines the same uniformity as the already defined uniform structure on the completion
-/
open lattice set filter uniform_space uniform_space.completion
noncomputable theory
universes u
variables {α : Type u} [metric_space α]
namespace metric
/-- The distance on the completion is obtained by extending the distance on the original space,
by uniform continuity. -/
instance : has_dist (completion α) :=
⟨completion.extension₂ dist⟩
/-- The new distance is uniformly continuous. -/
protected lemma completion.uniform_continuous_dist :
uniform_continuous (λp:completion α × completion α, dist p.1 p.2) :=
uniform_continuous_extension₂ dist
/-- The new distance is an extension of the original distance. -/
protected lemma completion.dist_eq (x y : α) : dist (x : completion α) y = dist x y :=
completion.extension₂_coe_coe uniform_continuous_dist' _ _
/- Let us check that the new distance satisfies the axioms of a distance, by starting from the
properties on α and extending them to `completion α` by continuity. -/
protected lemma completion.dist_self (x : completion α) : dist x x = 0 :=
begin
apply induction_on x,
{ refine is_closed_eq _ continuous_const,
exact (completion.uniform_continuous_dist.continuous.comp
(continuous.prod_mk continuous_id continuous_id) : _) },
{ assume a,
rw [completion.dist_eq, dist_self] }
end
protected lemma completion.dist_comm (x y : completion α) : dist x y = dist y x :=
begin
apply induction_on₂ x y,
{ refine is_closed_eq completion.uniform_continuous_dist.continuous _,
exact (completion.uniform_continuous_dist.continuous.comp continuous_swap : _) },
{ assume a b,
rw [completion.dist_eq, completion.dist_eq, dist_comm] }
end
protected lemma completion.dist_triangle (x y z : completion α) : dist x z ≤ dist x y + dist y z :=
begin
apply induction_on₃ x y z,
{ refine is_closed_le _ (continuous.add _ _),
{ have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.2)) :=
continuous.prod_mk continuous_fst (continuous.comp continuous_snd continuous_snd),
exact (completion.uniform_continuous_dist.continuous.comp this : _) },
{ have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.1)) :=
continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd),
exact (completion.uniform_continuous_dist.continuous.comp this : _) },
{ have : continuous (λp : completion α × completion α × completion α, (p.2.1, p.2.2)) :=
continuous.prod_mk (continuous_fst.comp continuous_snd)
(continuous.comp continuous_snd continuous_snd),
exact (continuous.comp completion.uniform_continuous_dist.continuous this : _) } },
{ assume a b c,
rw [completion.dist_eq, completion.dist_eq, completion.dist_eq],
exact dist_triangle a b c }
end
/-- Elements of the uniformity (defined generally for completions) can be characterized in terms
of the distance. -/
protected lemma completion.mem_uniformity_dist (s : set (completion α × completion α)) :
s ∈ uniformity (completion α) ↔ (∃ε>0, ∀{a b}, dist a b < ε → (a, b) ∈ s) :=
begin
split,
{ /- Start from an entourage `s`. It contains a closed entourage `t`. Its pullback in α is an
entourage, so it contains an ε-neighborhood of the diagonal by definition of the entourages
in metric spaces. Then `t` contains an ε-neighborhood of the diagonal in `completion α`, as
closed properties pass to the completion. -/
assume hs,
rcases mem_uniformity_is_closed hs with ⟨t, ht, ⟨tclosed, ts⟩⟩,
have A : {x : α × α | (coe (x.1), coe (x.2)) ∈ t} ∈ uniformity α :=
uniform_continuous_def.1 (uniform_continuous_coe α) t ht,
rcases mem_uniformity_dist.1 A with ⟨ε, εpos, hε⟩,
refine ⟨ε, εpos, λx y hxy, _⟩,
have : ε ≤ dist x y ∨ (x, y) ∈ t,
{ apply induction_on₂ x y,
{ have : {x : completion α × completion α | ε ≤ dist (x.fst) (x.snd) ∨ (x.fst, x.snd) ∈ t}
= {p : completion α × completion α | ε ≤ dist p.1 p.2} ∪ t, by ext; simp,
rw this,
apply is_closed_union _ tclosed,
exact is_closed_le continuous_const completion.uniform_continuous_dist.continuous },
{ assume x y,
rw completion.dist_eq,
by_cases h : ε ≤ dist x y,
{ exact or.inl h },
{ have Z := hε (not_le.1 h),
simp only [set.mem_set_of_eq] at Z,
exact or.inr Z }}},
simp only [not_le.mpr hxy, false_or, not_le] at this,
exact ts this },
{ /- Start from a set `s` containing an ε-neighborhood of the diagonal in `completion α`. To show
that it is an entourage, we use the fact that `dist` is uniformly continuous on
`completion α × completion α` (this is a general property of the extension of uniformly
continuous functions). Therefore, the preimage of the ε-neighborhood of the diagonal in ℝ
is an entourage in `completion α × completion α`. Massaging this property, it follows that
the ε-neighborhood of the diagonal is an entourage in `completion α`, and therefore this is
also the case of `s`. -/
rintros ⟨ε, εpos, hε⟩,
let r : set (ℝ × ℝ) := {p | dist p.1 p.2 < ε},
have : r ∈ uniformity ℝ := metric.dist_mem_uniformity εpos,
have T := uniform_continuous_def.1 (@completion.uniform_continuous_dist α _) r this,
simp only [uniformity_prod_eq_prod, mem_prod_iff, exists_prop,
filter.mem_map, set.mem_set_of_eq] at T,
rcases T with ⟨t1, ht1, t2, ht2, ht⟩,
refine mem_sets_of_superset ht1 _,
have A : ∀a b : completion α, (a, b) ∈ t1 → dist a b < ε,
{ assume a b hab,
have : ((a, b), (a, a)) ∈ set.prod t1 t2 := ⟨hab, refl_mem_uniformity ht2⟩,
have I := ht this,
simp [completion.dist_self, real.dist_eq, completion.dist_comm] at I,
exact lt_of_le_of_lt (le_abs_self _) I },
show t1 ⊆ s,
{ rintros ⟨a, b⟩ hp,
have : dist a b < ε := A a b hp,
exact hε this }}
end
/-- If two points are at distance 0, then they coincide. -/
protected lemma completion.eq_of_dist_eq_zero (x y : completion α) (h : dist x y = 0) : x = y :=
begin
/- This follows from the separation of `completion α` and from the description of
entourages in terms of the distance. -/
have : separated (completion α) := by apply_instance,
refine separated_def.1 this x y (λs hs, _),
rcases (completion.mem_uniformity_dist s).1 hs with ⟨ε, εpos, hε⟩,
rw ← h at εpos,
exact hε εpos
end
/- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition
of the metric space structure. -/
protected lemma completion.uniformity_dist' :
uniformity (completion α) = (⨅ε:{ε:ℝ // ε>0}, principal {p | dist p.1 p.2 < ε.val}) :=
begin
ext s, rw mem_infi,
{ simp [completion.mem_uniformity_dist, subset_def] },
{ rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩,
simp [lt_min_iff, (≥)] {contextual := tt} },
{ exact ⟨⟨1, zero_lt_one⟩⟩ }
end
protected lemma completion.uniformity_dist :
uniformity (completion α) = (⨅ ε>0, principal {p | dist p.1 p.2 < ε}) :=
by simpa [infi_subtype] using @completion.uniformity_dist' α _
/-- Metric space structure on the completion of a metric space. -/
instance completion.metric_space : metric_space (completion α) :=
{ dist_self := completion.dist_self,
eq_of_dist_eq_zero := completion.eq_of_dist_eq_zero,
dist_comm := completion.dist_comm,
dist_triangle := completion.dist_triangle,
to_uniform_space := by apply_instance,
uniformity_dist := completion.uniformity_dist }
/-- The embedding of a metric space in its completion is an isometry. -/
lemma completion.coe_isometry : isometry (coe : α → completion α) :=
isometry_emetric_iff_metric.2 completion.dist_eq
end metric
|
e05685ff9d604a94bcaf48b4a2a73258127eb2ca | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/direct_sum/tensor_product.lean | 174207abfb52c693dea04c513cdf2cb625e9a2c8 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,160 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Eric Wieser
-/
import linear_algebra.tensor_product
import algebra.direct_sum.module
/-!
# Tensor products of direct sums
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file shows that taking `tensor_product`s commutes with taking `direct_sum`s in both arguments.
## Main results
* `tensor_product.direct_sum`
* `tensor_product.direct_sum_left`
* `tensor_product.direct_sum_right`
-/
section ring
namespace tensor_product
open_locale tensor_product
open_locale direct_sum
open linear_map
local attribute [ext] tensor_product.ext
variables (R : Type*) [comm_ring R]
variables {ι₁ : Type*} {ι₂ : Type*}
variables [decidable_eq ι₁] [decidable_eq ι₂]
variables (M₁ : ι₁ → Type*) (M₁' : Type*) (M₂ : ι₂ → Type*) (M₂' : Type*)
variables [Π i₁, add_comm_group (M₁ i₁)] [add_comm_group M₁']
variables [Π i₂, add_comm_group (M₂ i₂)] [add_comm_group M₂']
variables [Π i₁, module R (M₁ i₁)] [module R M₁'] [Π i₂, module R (M₂ i₂)] [module R M₂']
/-- The linear equivalence `(⨁ i₁, M₁ i₁) ⊗ (⨁ i₂, M₂ i₂) ≃ (⨁ i₁, ⨁ i₂, M₁ i₁ ⊗ M₂ i₂)`, i.e.
"tensor product distributes over direct sum". -/
protected def direct_sum :
(⨁ i₁, M₁ i₁) ⊗[R] (⨁ i₂, M₂ i₂) ≃ₗ[R] (⨁ (i : ι₁ × ι₂), M₁ i.1 ⊗[R] M₂ i.2) :=
begin
refine linear_equiv.of_linear
(lift $ direct_sum.to_module R _ _ $ λ i₁, flip $ direct_sum.to_module R _ _ $ λ i₂,
flip $ curry $ direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂))
(direct_sum.to_module R _ _ $ λ i, map (direct_sum.lof R _ _ _) (direct_sum.lof R _ _ _))
_ _; [ext ⟨i₁, i₂⟩ x₁ x₂ : 4, ext i₁ i₂ x₁ x₂ : 5],
repeat { rw compr₂_apply <|> rw comp_apply <|> rw id_apply <|> rw mk_apply <|>
rw direct_sum.to_module_lof <|> rw map_tmul <|> rw lift.tmul <|> rw flip_apply <|>
rw curry_apply },
end
/-- Tensor products distribute over a direct sum on the left . -/
def direct_sum_left : (⨁ i₁, M₁ i₁) ⊗[R] M₂' ≃ₗ[R] (⨁ i, M₁ i ⊗[R] M₂') :=
linear_equiv.of_linear
(lift $ direct_sum.to_module R _ _ $ λ i, (mk R _ _).compr₂ $
(direct_sum.lof R ι₁ (λ i, M₁ i ⊗[R] M₂') _))
(direct_sum.to_module R _ _ $ λ i, rtensor _ (direct_sum.lof R ι₁ _ _))
(direct_sum.linear_map_ext R $ λ i, tensor_product.ext $ linear_map.ext₂ $ λ m₁ m₂, begin
dsimp only [comp_apply, compr₂_apply, id_apply, mk_apply],
simp_rw [direct_sum.to_module_lof, rtensor_tmul, lift.tmul, direct_sum.to_module_lof,
compr₂_apply, mk_apply],
end)
(tensor_product.ext $ direct_sum.linear_map_ext R $ λ i, linear_map.ext₂ $ λ m₁ m₂, begin
dsimp only [comp_apply, compr₂_apply, id_apply, mk_apply],
simp_rw [direct_sum.to_module_lof, lift.tmul, direct_sum.to_module_lof, compr₂_apply, mk_apply,
direct_sum.to_module_lof, rtensor_tmul],
end)
/-- Tensor products distribute over a direct sum on the right. -/
def direct_sum_right : M₁' ⊗[R] (⨁ i, M₂ i) ≃ₗ[R] (⨁ i, M₁' ⊗[R] M₂ i) :=
(tensor_product.comm R _ _) ≪≫ₗ (direct_sum_left R M₂ M₁') ≪≫ₗ
(dfinsupp.map_range.linear_equiv $ λ i, (tensor_product.comm R _ _))
variables {M₁ M₁' M₂ M₂'}
@[simp] theorem direct_sum_lof_tmul_lof (i₁ : ι₁) (m₁ : M₁ i₁) (i₂ : ι₂) (m₂ : M₂ i₂) :
tensor_product.direct_sum R M₁ M₂ (direct_sum.lof R ι₁ M₁ i₁ m₁ ⊗ₜ direct_sum.lof R ι₂ M₂ i₂ m₂) =
direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂) (m₁ ⊗ₜ m₂) :=
by simp [tensor_product.direct_sum]
@[simp] lemma direct_sum_left_tmul_lof (i : ι₁) (x : M₁ i) (y : M₂') :
direct_sum_left R M₁ M₂' (direct_sum.lof R _ _ i x ⊗ₜ[R] y)
= direct_sum.lof R _ _ i (x ⊗ₜ[R] y) :=
begin
dsimp only [direct_sum_left, linear_equiv.of_linear_apply, lift.tmul],
rw direct_sum.to_module_lof R i,
refl,
end
@[simp] lemma direct_sum_left_symm_lof_tmul (i : ι₁) (x : M₁ i) (y : M₂') :
(direct_sum_left R M₁ M₂').symm (direct_sum.lof R _ _ i (x ⊗ₜ[R] y))
= direct_sum.lof R _ _ i x ⊗ₜ[R] y :=
by rw [linear_equiv.symm_apply_eq, direct_sum_left_tmul_lof]
@[simp] lemma direct_sum_right_tmul_lof (x : M₁') (i : ι₂) (y : M₂ i) :
direct_sum_right R M₁' M₂ (x ⊗ₜ[R] direct_sum.lof R _ _ i y)
= direct_sum.lof R _ _ i (x ⊗ₜ[R] y) :=
begin
dsimp only [direct_sum_right, linear_equiv.trans_apply, tensor_product.comm_tmul],
rw direct_sum_left_tmul_lof,
exact dfinsupp.map_range_single,
end
@[simp] lemma direct_sum_right_symm_lof_tmul (x : M₁') (i : ι₂) (y : M₂ i):
(direct_sum_right R M₁' M₂).symm (direct_sum.lof R _ _ i (x ⊗ₜ[R] y))
= x ⊗ₜ[R] direct_sum.lof R _ _ i y :=
by rw [linear_equiv.symm_apply_eq, direct_sum_right_tmul_lof]
end tensor_product
end ring
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.