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
a632b9e013da41e91e37fac23c48d52831c7178a
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebraic_topology/simplicial_object.lean
252791c6d885eba2cde8e73bc55e5328117cf13f
[ "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
19,258
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison, Adam Topaz -/ import algebraic_topology.simplex_category import category_theory.arrow import category_theory.limits.functor_category import category_theory.opposites /-! # Simplicial objects in a category. A simplicial object in a category `C` is a `C`-valued presheaf on `simplex_category`. (Similarly a cosimplicial object is functor `simplex_category ⥤ C`.) Use the notation `X _[n]` in the `simplicial` locale to obtain the `n`-th term of a (co)simplicial object `X`, where `n` is a natural number. -/ open opposite open category_theory open category_theory.limits universes v u v' u' namespace category_theory variables (C : Type u) [category.{v} C] /-- The category of simplicial objects valued in a category `C`. This is the category of contravariant functors from `simplex_category` to `C`. -/ @[derive category, nolint has_inhabited_instance] def simplicial_object := simplex_categoryᵒᵖ ⥤ C namespace simplicial_object localized "notation X `_[`:1000 n `]` := (X : category_theory.simplicial_object _).obj (opposite.op (simplex_category.mk n))" in simplicial instance {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (simplicial_object C) := by {dsimp [simplicial_object], apply_instance} instance [has_limits C] : has_limits (simplicial_object C) := ⟨infer_instance⟩ instance {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (simplicial_object C) := by {dsimp [simplicial_object], apply_instance} instance [has_colimits C] : has_colimits (simplicial_object C) := ⟨infer_instance⟩ variables {C} (X : simplicial_object C) /-- Face maps for a simplicial object. -/ def δ {n} (i : fin (n+2)) : X _[n+1] ⟶ X _[n] := X.map (simplex_category.δ i).op /-- Degeneracy maps for a simplicial object. -/ def σ {n} (i : fin (n+1)) : X _[n] ⟶ X _[n+1] := X.map (simplex_category.σ i).op /-- Isomorphisms from identities in ℕ. -/ def eq_to_iso {n m : ℕ} (h : n = m) : X _[n] ≅ X _[m] := X.map_iso (eq_to_iso (by rw h)) @[simp] lemma eq_to_iso_refl {n : ℕ} (h : n = n) : X.eq_to_iso h = iso.refl _ := by { ext, simp [eq_to_iso], } /-- The generic case of the first simplicial identity -/ lemma δ_comp_δ {n} {i j : fin (n+2)} (H : i ≤ j) : X.δ j.succ ≫ X.δ i = X.δ i.cast_succ ≫ X.δ j := by { dsimp [δ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_δ H] } /-- The special case of the first simplicial identity -/ lemma δ_comp_δ_self {n} {i : fin (n+2)} : X.δ i.cast_succ ≫ X.δ i = X.δ i.succ ≫ X.δ i := by { dsimp [δ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_δ_self] } /-- The second simplicial identity -/ lemma δ_comp_σ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≤ j.cast_succ) : X.σ j.succ ≫ X.δ i.cast_succ = X.δ i ≫ X.σ j := by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_of_le H] } /-- The first part of the third simplicial identity -/ lemma δ_comp_σ_self {n} {i : fin (n+1)} : X.σ i ≫ X.δ i.cast_succ = 𝟙 _ := begin dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_self, op_id, X.map_id], end /-- The second part of the third simplicial identity -/ lemma δ_comp_σ_succ {n} {i : fin (n+1)} : X.σ i ≫ X.δ i.succ = 𝟙 _ := begin dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_succ, op_id, X.map_id], end /-- The fourth simplicial identity -/ lemma δ_comp_σ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) : X.σ j.cast_succ ≫ X.δ i.succ = X.δ i ≫ X.σ j := by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_of_gt H] } /-- The fifth simplicial identity -/ lemma σ_comp_σ {n} {i j : fin (n+1)} (H : i ≤ j) : X.σ j ≫ X.σ i.cast_succ = X.σ i ≫ X.σ j.succ := by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.σ_comp_σ H] } variable (C) /-- Functor composition induces a functor on simplicial objects. -/ @[simps] def whiskering (D : Type*) [category D] : (C ⥤ D) ⥤ simplicial_object C ⥤ simplicial_object D := whiskering_right _ _ _ /-- Truncated simplicial objects. -/ @[derive category, nolint has_inhabited_instance] def truncated (n : ℕ) := (simplex_category.truncated n)ᵒᵖ ⥤ C variable {C} namespace truncated instance {n} {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (simplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_limits C] : has_limits (simplicial_object.truncated C n) := ⟨infer_instance⟩ instance {n} {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (simplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_colimits C] : has_colimits (simplicial_object.truncated C n) := ⟨infer_instance⟩ variable (C) /-- Functor composition induces a functor on truncated simplicial objects. -/ @[simps] def whiskering {n} (D : Type*) [category D] : (C ⥤ D) ⥤ truncated C n ⥤ truncated D n := whiskering_right _ _ _ variable {C} end truncated section skeleton /-- The skeleton functor from simplicial objects to truncated simplicial objects. -/ def sk (n : ℕ) : simplicial_object C ⥤ simplicial_object.truncated C n := (whiskering_left _ _ _).obj simplex_category.truncated.inclusion.op end skeleton variable (C) /-- The constant simplicial object is the constant functor. -/ abbreviation const : C ⥤ simplicial_object C := category_theory.functor.const _ /-- The category of augmented simplicial objects, defined as a comma category. -/ @[derive category, nolint has_inhabited_instance] def augmented := comma (𝟭 (simplicial_object C)) (const C) variable {C} namespace augmented /-- Drop the augmentation. -/ @[simps] def drop : augmented C ⥤ simplicial_object C := comma.fst _ _ /-- The point of the augmentation. -/ @[simps] def point : augmented C ⥤ C := comma.snd _ _ /-- The functor from augmented objects to arrows. -/ @[simps] def to_arrow : augmented C ⥤ arrow C := { obj := λ X, { left := (drop.obj X) _[0], right := (point.obj X), hom := X.hom.app _ }, map := λ X Y η, { left := (drop.map η).app _, right := (point.map η), w' := begin dsimp, rw ← nat_trans.comp_app, erw η.w, refl, end } } variable (C) /-- Functor composition induces a functor on augmented simplicial objects. -/ @[simp] def whiskering_obj (D : Type*) [category D] (F : C ⥤ D) : augmented C ⥤ augmented D := { obj := λ X, { left := ((whiskering _ _).obj F).obj (drop.obj X), right := F.obj (point.obj X), hom := whisker_right X.hom F ≫ (functor.const_comp _ _ _).hom }, map := λ X Y η, { left := whisker_right η.left _, right := F.map η.right, w' := begin ext, dsimp, rw [category.comp_id, category.comp_id, ← F.map_comp, ← F.map_comp, ← nat_trans.comp_app], erw η.w, refl, end } } /-- Functor composition induces a functor on augmented simplicial objects. -/ @[simps] def whiskering (D : Type u') [category.{v'} D] : (C ⥤ D) ⥤ augmented C ⥤ augmented D := { obj := whiskering_obj _ _, map := λ X Y η, { app := λ A, { left := whisker_left _ η, right := η.app _, w' := begin ext n, dsimp, rw [category.comp_id, category.comp_id, η.naturality], end }, }, } variable {C} end augmented open_locale simplicial /-- Aaugment a simplicial object with an object. -/ @[simps] def augment (X : simplicial_object C) (X₀ : C) (f : X _[0] ⟶ X₀) (w : ∀ (i : simplex_category) (g₁ g₂ : [0] ⟶ i), X.map g₁.op ≫ f = X.map g₂.op ≫ f) : simplicial_object.augmented C := { left := X, right := X₀, hom := { app := λ i, X.map (simplex_category.const i.unop 0).op ≫ f, naturality' := begin intros i j g, dsimp, rw ← g.op_unop, simpa only [← X.map_comp, ← category.assoc, category.comp_id, ← op_comp] using w _ _ _, end } } @[simp] lemma augment_hom_zero (X : simplicial_object C) (X₀ : C) (f : X _[0] ⟶ X₀) (w) : (X.augment X₀ f w).hom.app (op [0]) = f := by { dsimp, rw [simplex_category.hom_zero_zero ([0].const 0), op_id, X.map_id, category.id_comp] } end simplicial_object /-- Cosimplicial objects. -/ @[derive category, nolint has_inhabited_instance] def cosimplicial_object := simplex_category ⥤ C namespace cosimplicial_object localized "notation X `_[`:1000 n `]` := (X : category_theory.cosimplicial_object _).obj (simplex_category.mk n)" in simplicial instance {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (cosimplicial_object C) := by {dsimp [cosimplicial_object], apply_instance} instance [has_limits C] : has_limits (cosimplicial_object C) := ⟨infer_instance⟩ instance {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (cosimplicial_object C) := by {dsimp [cosimplicial_object], apply_instance} instance [has_colimits C] : has_colimits (cosimplicial_object C) := ⟨infer_instance⟩ variables {C} (X : cosimplicial_object C) /-- Coface maps for a cosimplicial object. -/ def δ {n} (i : fin (n+2)) : X _[n] ⟶ X _[n+1] := X.map (simplex_category.δ i) /-- Codegeneracy maps for a cosimplicial object. -/ def σ {n} (i : fin (n+1)) : X _[n+1] ⟶ X _[n] := X.map (simplex_category.σ i) /-- Isomorphisms from identities in ℕ. -/ def eq_to_iso {n m : ℕ} (h : n = m) : X _[n] ≅ X _[m] := X.map_iso (eq_to_iso (by rw h)) @[simp] lemma eq_to_iso_refl {n : ℕ} (h : n = n) : X.eq_to_iso h = iso.refl _ := by { ext, simp [eq_to_iso], } /-- The generic case of the first cosimplicial identity -/ lemma δ_comp_δ {n} {i j : fin (n+2)} (H : i ≤ j) : X.δ i ≫ X.δ j.succ = X.δ j ≫ X.δ i.cast_succ := by { dsimp [δ], simp only [←X.map_comp, simplex_category.δ_comp_δ H], } /-- The special case of the first cosimplicial identity -/ lemma δ_comp_δ_self {n} {i : fin (n+2)} : X.δ i ≫ X.δ i.cast_succ = X.δ i ≫ X.δ i.succ := by { dsimp [δ], simp only [←X.map_comp, simplex_category.δ_comp_δ_self] } /-- The second cosimplicial identity -/ lemma δ_comp_σ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≤ j.cast_succ) : X.δ i.cast_succ ≫ X.σ j.succ = X.σ j ≫ X.δ i := by { dsimp [δ, σ], simp only [←X.map_comp, simplex_category.δ_comp_σ_of_le H] } /-- The first part of the third cosimplicial identity -/ lemma δ_comp_σ_self {n} {i : fin (n+1)} : X.δ i.cast_succ ≫ X.σ i = 𝟙 _ := begin dsimp [δ, σ], simp only [←X.map_comp, simplex_category.δ_comp_σ_self, X.map_id], end /-- The second part of the third cosimplicial identity -/ lemma δ_comp_σ_succ {n} {i : fin (n+1)} : X.δ i.succ ≫ X.σ i = 𝟙 _ := begin dsimp [δ, σ], simp only [←X.map_comp, simplex_category.δ_comp_σ_succ, X.map_id], end /-- The fourth cosimplicial identity -/ lemma δ_comp_σ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) : X.δ i.succ ≫ X.σ j.cast_succ = X.σ j ≫ X.δ i := by { dsimp [δ, σ], simp only [←X.map_comp, simplex_category.δ_comp_σ_of_gt H] } /-- The fifth cosimplicial identity -/ lemma σ_comp_σ {n} {i j : fin (n+1)} (H : i ≤ j) : X.σ i.cast_succ ≫ X.σ j = X.σ j.succ ≫ X.σ i := by { dsimp [δ, σ], simp only [←X.map_comp, simplex_category.σ_comp_σ H] } variable (C) /-- Functor composition induces a functor on cosimplicial objects. -/ @[simps] def whiskering (D : Type*) [category D] : (C ⥤ D) ⥤ cosimplicial_object C ⥤ cosimplicial_object D := whiskering_right _ _ _ /-- Truncated cosimplicial objects. -/ @[derive category, nolint has_inhabited_instance] def truncated (n : ℕ) := simplex_category.truncated n ⥤ C variable {C} namespace truncated instance {n} {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (cosimplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_limits C] : has_limits (cosimplicial_object.truncated C n) := ⟨infer_instance⟩ instance {n} {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (cosimplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_colimits C] : has_colimits (cosimplicial_object.truncated C n) := ⟨infer_instance⟩ variable (C) /-- Functor composition induces a functor on truncated cosimplicial objects. -/ @[simps] def whiskering {n} (D : Type*) [category D] : (C ⥤ D) ⥤ truncated C n ⥤ truncated D n := whiskering_right _ _ _ variable {C} end truncated section skeleton /-- The skeleton functor from cosimplicial objects to truncated cosimplicial objects. -/ def sk (n : ℕ) : cosimplicial_object C ⥤ cosimplicial_object.truncated C n := (whiskering_left _ _ _).obj simplex_category.truncated.inclusion end skeleton variable (C) /-- The constant cosimplicial object. -/ abbreviation const : C ⥤ cosimplicial_object C := category_theory.functor.const _ /-- Augmented cosimplicial objects. -/ @[derive category, nolint has_inhabited_instance] def augmented := comma (const C) (𝟭 (cosimplicial_object C)) variable {C} namespace augmented /-- Drop the augmentation. -/ @[simps] def drop : augmented C ⥤ cosimplicial_object C := comma.snd _ _ /-- The point of the augmentation. -/ @[simps] def point : augmented C ⥤ C := comma.fst _ _ /-- The functor from augmented objects to arrows. -/ @[simps] def to_arrow : augmented C ⥤ arrow C := { obj := λ X, { left := (point.obj X), right := (drop.obj X) _[0], hom := X.hom.app _ }, map := λ X Y η, { left := (point.map η), right := (drop.map η).app _, w' := begin dsimp, rw ← nat_trans.comp_app, erw ← η.w, refl, end } } variable (C) /-- Functor composition induces a functor on augmented cosimplicial objects. -/ @[simp] def whiskering_obj (D : Type*) [category D] (F : C ⥤ D) : augmented C ⥤ augmented D := { obj := λ X, { left := F.obj (point.obj X), right := ((whiskering _ _).obj F).obj (drop.obj X), hom := (functor.const_comp _ _ _).inv ≫ whisker_right X.hom F }, map := λ X Y η, { left := F.map η.left, right := whisker_right η.right _, w' := begin ext, dsimp, rw [category.id_comp, category.id_comp, ← F.map_comp, ← F.map_comp, ← nat_trans.comp_app], erw ← η.w, refl, end } } /-- Functor composition induces a functor on augmented cosimplicial objects. -/ @[simps] def whiskering (D : Type u') [category.{v'} D] : (C ⥤ D) ⥤ augmented C ⥤ augmented D := { obj := whiskering_obj _ _, map := λ X Y η, { app := λ A, { left := η.app _, right := whisker_left _ η, w' := begin ext n, dsimp, rw [category.id_comp, category.id_comp, η.naturality], end }, }, } variable {C} end augmented open_locale simplicial /-- Augment a cosimplicial object with an object. -/ @[simps] def augment (X : cosimplicial_object C) (X₀ : C) (f : X₀ ⟶ X.obj [0]) (w : ∀ (i : simplex_category) (g₁ g₂ : [0] ⟶ i), f ≫ X.map g₁ = f ≫ X.map g₂) : cosimplicial_object.augmented C := { left := X₀, right := X, hom := { app := λ i, f ≫ X.map (simplex_category.const i 0), naturality' := begin intros i j g, dsimp, simpa [← X.map_comp] using w _ _ _, end } } @[simp] lemma augment_hom_zero (X : cosimplicial_object C) (X₀ : C) (f : X₀ ⟶ X.obj [0]) (w) : (X.augment X₀ f w).hom.app [0] = f := by { dsimp, rw [simplex_category.hom_zero_zero ([0].const 0), X.map_id, category.comp_id] } end cosimplicial_object /-- The anti-equivalence between simplicial objects and cosimplicial objects. -/ @[simps] def simplicial_cosimplicial_equiv : (simplicial_object C)ᵒᵖ ≌ (cosimplicial_object Cᵒᵖ) := functor.left_op_right_op_equiv _ _ variable {C} /-- Construct an augmented cosimplicial object in the opposite category from an augmented simplicial object. -/ @[simps] def simplicial_object.augmented.right_op (X : simplicial_object.augmented C) : cosimplicial_object.augmented Cᵒᵖ := { left := opposite.op X.right, right := X.left.right_op, hom := X.hom.right_op } /-- Construct an augmented simplicial object from an augmented cosimplicial object in the opposite category. -/ @[simps] def cosimplicial_object.augmented.left_op (X : cosimplicial_object.augmented Cᵒᵖ) : simplicial_object.augmented C := { left := X.right.left_op, right := X.left.unop, hom := X.hom.left_op } /-- Converting an augmented simplicial object to an augmented cosimplicial object and back is isomorphic to the given object. -/ @[simps] def simplicial_object.augmented.right_op_left_op_iso (X : simplicial_object.augmented C) : X.right_op.left_op ≅ X := comma.iso_mk X.left.right_op_left_op_iso (eq_to_iso $ by simp) (by tidy) /-- Converting an augmented cosimplicial object to an augmented simplicial object and back is isomorphic to the given object. -/ @[simps] def cosimplicial_object.augmented.left_op_right_op_iso (X : cosimplicial_object.augmented Cᵒᵖ) : X.left_op.right_op ≅ X := comma.iso_mk (eq_to_iso $ by simp) X.right.left_op_right_op_iso (by tidy) variable (C) /-- A functorial version of `simplicial_object.augmented.right_op`. -/ @[simps] def simplicial_to_cosimplicial_augmented : (simplicial_object.augmented C)ᵒᵖ ⥤ cosimplicial_object.augmented Cᵒᵖ := { obj := λ X, X.unop.right_op, map := λ X Y f, { left := f.unop.right.op, right := f.unop.left.right_op, w' := begin ext x, dsimp, simp_rw ← op_comp, congr' 1, exact (congr_app f.unop.w (op x)).symm, end } } /-- A functorial version of `cosimplicial_object.augmented.left_op`. -/ @[simps] def cosimplicial_to_simplicial_augmented : cosimplicial_object.augmented Cᵒᵖ ⥤ (simplicial_object.augmented C)ᵒᵖ := { obj := λ X, opposite.op X.left_op, map := λ X Y f, quiver.hom.op $ { left := f.right.left_op, right := f.left.unop, w' := begin ext x, dsimp, simp_rw ← unop_comp, congr' 1, exact (congr_app f.w x.unop).symm, end} } /-- The contravariant categorical equivalence between augmented simplicial objects and augmented cosimplicial objects in the opposite category. -/ @[simps] def simplicial_cosimplicial_augmented_equiv : (simplicial_object.augmented C)ᵒᵖ ≌ cosimplicial_object.augmented Cᵒᵖ := { functor := simplicial_to_cosimplicial_augmented _, inverse := cosimplicial_to_simplicial_augmented _, unit_iso := nat_iso.of_components (λ X, X.unop.right_op_left_op_iso.op) begin intros X Y f, dsimp, rw (show f = f.unop.op, by simp), simp_rw ← op_comp, congr' 1, tidy, end, counit_iso := nat_iso.of_components (λ X, X.left_op_right_op_iso) (by tidy) } end category_theory
3b55d0f20e7a8dffb9167fdce22b1ff00c5712d2
b815abf92ce063fe0d1fabf5b42da483552aa3e8
/library/init/data/list/basic.lean
9587497578e247cd8589f5775c31b089bddefc23
[ "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
3,785
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 open decidable list notation h :: t := cons h t notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l universe variables u v instance (α : Type u) : inhabited (list α) := ⟨list.nil⟩ variables {α : Type u} {β : Type v} namespace list 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 def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a instance : has_emptyc (list α) := ⟨list.nil⟩ protected def insert [decidable_eq α] (a : α) (l : list α) : list α := if a ∈ l then l else concat l a instance [decidable_eq α] : has_insert α list := ⟨list.insert⟩ protected def union [decidable_eq α] : list α → list α → list α | l₁ [] := l₁ | l₁ (a::l₂) := union (insert a l₁) l₂ instance [decidable_eq α] : has_union (list α) := ⟨list.union⟩ protected def inter [decidable_eq α] : list α → list α → list α | [] l₂ := [] | (a::l₁) l₂ := if a ∈ l₂ then a :: inter l₁ l₂ else inter l₁ l₂ instance [decidable_eq α] : has_inter (list α) := ⟨list.inter⟩ def length : list α → nat | [] := 0 | (a :: l) := length l + 1 open option nat def nth : list α → nat → option α | [] n := none | (a :: l) 0 := some a | (a :: l) (n+1) := nth l n def head [inhabited α] : list α → α | [] := default α | (a :: l) := a 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 [] def map (f : α → β) : list α → list β | [] := [] | (a :: l) := f a :: map l def for : list α → (α → β) → list β := flip map def join : list (list α) → list α | [] := [] | (l :: ls) := append l (join ls) def filter (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: filter l else filter l def dropn : ℕ → list α → list α | 0 a := a | (succ n) [] := [] | (succ n) (x::r) := dropn n r def taken : ℕ → list α → list α | 0 a := [] | (succ n) [] := [] | (succ n) (x :: r) := x :: taken n r definition foldl (f : α → β → α) : α → list β → α | a [] := a | a (b :: l) := foldl (f a b) l definition foldr (f : α → β → β) : β → list α → β | b [] := b | b (a :: l) := f a (foldr b l) definition any (l : list α) (p : α → bool) : bool := foldr (λ a r, p a || r) ff l definition all (l : list α) (p : α → bool) : bool := foldr (λ a r, p a && r) tt l def zip : list α → list β → list (prod α β) | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := (prod.mk x y) :: zip xs ys def repeat (a : α) : ℕ → list α | 0 := [] | (succ n) := a :: repeat n def iota_core : ℕ → list ℕ → list ℕ | 0 l := reverse l | (succ n) l := iota_core n (succ n :: l) def iota : ℕ → list ℕ := λ n, iota_core n [] end list
3735d0b725a2231a8930511aa93e2cd3ad84fdb9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/frobenius_number.lean
2a9c1f7a36f1ec35e6d4e1efcf9e328c9702e757
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,309
lean
/- Copyright (c) 2021 Alex Zhao. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex Zhao -/ import data.nat.modeq import group_theory.submonoid.basic import group_theory.submonoid.membership import tactic.ring import tactic.zify /-! # Frobenius Number in Two Variables > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we first define a predicate for Frobenius numbers, then solve the 2-variable variant of this problem. ## Theorem Statement Given a finite set of relatively prime integers all greater than 1, their Frobenius number is the largest positive integer that cannot be expressed as a sum of nonnegative multiples of these integers. Here we show the Frobenius number of two relatively prime integers `m` and `n` greater than 1 is `m * n - m - n`. This result is also known as the Chicken McNugget Theorem. ## Implementation Notes First we define Frobenius numbers in general using `is_greatest` and `add_submonoid.closure`. Then we proceed to compute the Frobenius number of `m` and `n`. For the upper bound, we begin with an auxiliary lemma showing `m * n` is not attainable, then show `m * n - m - n` is not attainable. Then for the construction, we create a `k_1` which is `k mod n` and `0 mod m`, then show it is at most `k`. Then `k_1` is a multiple of `m`, so `(k-k_1)` is a multiple of n, and we're done. ## Tags frobenius number, chicken mcnugget, chinese remainder theorem, add_submonoid.closure -/ open nat /-- A natural number `n` is the **Frobenius number** of a set of natural numbers `s` if it is an upper bound on the complement of the additive submonoid generated by `s`. In other words, it is the largest number that can not be expressed as a sum of numbers in `s`. -/ def is_frobenius_number (n : ℕ) (s : set ℕ) : Prop := is_greatest {k | k ∉ add_submonoid.closure (s)} n variables {m n : ℕ} /-- The **Chicken Mcnugget theorem** stating that the Frobenius number of positive numbers `m` and `n` is `m * n - m - n`. -/ theorem is_frobenius_number_pair (cop : coprime m n) (hm : 1 < m) (hn : 1 < n) : is_frobenius_number (m * n - m - n) {m, n} := begin simp_rw [is_frobenius_number, add_submonoid.mem_closure_pair], have hmn : m + n ≤ m * n := add_le_mul hm hn, split, { push_neg, intros a b h, apply cop.mul_add_mul_ne_mul (add_one_ne_zero a) (add_one_ne_zero b), simp only [nat.sub_sub, smul_eq_mul] at h, zify at h ⊢, rw [← sub_eq_zero] at h ⊢, rw ← h, ring, }, { intros k hk, dsimp at hk, contrapose! hk, let x := chinese_remainder cop 0 k, have hx : x.val < m * n := chinese_remainder_lt_mul cop 0 k (ne_bot_of_gt hm) (ne_bot_of_gt hn), suffices key : x.1 ≤ k, { obtain ⟨a, ha⟩ := modeq_zero_iff_dvd.mp x.2.1, obtain ⟨b, hb⟩ := (modeq_iff_dvd' key).mp x.2.2, exact ⟨a, b, by rw [mul_comm, ←ha, mul_comm, ←hb, nat.add_sub_of_le key]⟩, }, refine modeq.le_of_lt_add x.2.2 (lt_of_le_of_lt _ (add_lt_add_right hk n)), rw nat.sub_add_cancel (le_tsub_of_add_le_left hmn), exact modeq.le_of_lt_add (x.2.1.trans (modeq_zero_iff_dvd.mpr (nat.dvd_sub' (dvd_mul_right m n) dvd_rfl)).symm) (lt_of_lt_of_le hx le_tsub_add), }, end
d24b62c1d59d5dfc045fe5eb69a97140934ce664
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/reflect_isomorphisms.lean
2e1ade604a67ab4ee24789611400d8efd6b97377
[ "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
2,654
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.cones open category_theory category_theory.limits namespace category_theory universes v₁ v₂ u₁ u₂ variables {C : Type u₁} [category.{v₁} C] section reflects_iso variables {D : Type u₂} [category.{v₂} D] /-- Define what it means for a functor `F : C ⥤ D` to reflect isomorphisms: for any morphism `f : A ⟶ B`, if `F.map f` is an isomorphism then `f` is as well. Note that we do not assume or require that `F` is faithful. -/ class reflects_isomorphisms (F : C ⥤ D) := (reflects : Π {A B : C} (f : A ⟶ B) [is_iso (F.map f)], is_iso f) /-- If `F` reflects isos and `F.map f` is an iso, then `f` is an iso. -/ def is_iso_of_reflects_iso {A B : C} (f : A ⟶ B) (F : C ⥤ D) [is_iso (F.map f)] [reflects_isomorphisms F] : is_iso f := reflects_isomorphisms.reflects F f end reflects_iso variables {J : Type v₁} [small_category J] {K : J ⥤ C} /-- Given a cone morphism whose object part is an isomorphism, produce an isomorphism of cones. -/ def cone_iso_of_hom_iso {K : J ⥤ C} {c d : cone K} (f : c ⟶ d) [i : is_iso f.hom] : is_iso f := { inv := { hom := i.inv, w' := λ j, (as_iso f.hom).inv_comp_eq.2 (f.w j).symm } } /-- Given a cocone morphism whose object part is an isomorphism, produce an isomorphism of cocones. -/ def cocone_iso_of_hom_iso {K : J ⥤ C} {c d : cocone K} (f : c ⟶ d) [i : is_iso f.hom] : is_iso f := { inv := { hom := i.inv, w' := λ j, (as_iso f.hom).comp_inv_eq.2 (f.w j).symm } } variables {D : Type u₂} [category.{v₁} D] /-- 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 /-- 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 category_theory
3176e7614b8f49ce9d80f4add055ab0f9900bee8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/elements.lean
7059f1f66c837c022f890e33c133c0625960aaa4
[]
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
6,074
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.comma import Mathlib.category_theory.groupoid import Mathlib.category_theory.punit import Mathlib.PostPort universes w v u namespace Mathlib /-! # The category of elements This file defines the category of elements, also known as (a special case of) the Grothendieck construction. Given a functor `F : C ⥤ Type`, an object of `F.elements` is a pair `(X : C, x : F.obj X)`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. ## Implementation notes This construction is equivalent to a special case of a comma construction, so this is mostly just a more convenient API. We prove the equivalence in `category_theory.category_of_elements.comma_equivalence`. ## References * [Emily Riehl, *Category Theory in Context*, Section 2.4][riehl2017] * <https://en.wikipedia.org/wiki/Category_of_elements> * <https://ncatlab.org/nlab/show/category+of+elements> ## Tags category of elements, Grothendieck construction, comma category -/ namespace category_theory /-- The type of objects for the category of elements of a functor `F : C ⥤ Type` is a pair `(X : C, x : F.obj X)`. -/ def functor.elements {C : Type u} [category C] (F : C ⥤ Type w) := sigma fun (c : C) => functor.obj F c /-- The category structure on `F.elements`, for `F : C ⥤ Type`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. -/ protected instance category_of_elements {C : Type u} [category C] (F : C ⥤ Type w) : category (functor.elements F) := category.mk namespace category_of_elements theorem ext {C : Type u} [category C] (F : C ⥤ Type w) {x : functor.elements F} {y : functor.elements F} (f : x ⟶ y) (g : x ⟶ y) (w : subtype.val f = subtype.val g) : f = g := subtype.ext_val w @[simp] theorem comp_val {C : Type u} [category C] {F : C ⥤ Type w} {p : functor.elements F} {q : functor.elements F} {r : functor.elements F} {f : p ⟶ q} {g : q ⟶ r} : subtype.val (f ≫ g) = subtype.val f ≫ subtype.val g := rfl @[simp] theorem id_val {C : Type u} [category C] {F : C ⥤ Type w} {p : functor.elements F} : subtype.val 𝟙 = 𝟙 := rfl end category_of_elements protected instance groupoid_of_elements {G : Type u} [groupoid G] (F : G ⥤ Type w) : groupoid (functor.elements F) := groupoid.mk fun (p q : functor.elements F) (f : p ⟶ q) => { val := inv (subtype.val f), property := sorry } namespace category_of_elements /-- The functor out of the category of elements which forgets the element. -/ @[simp] theorem π_map {C : Type u} [category C] (F : C ⥤ Type w) (X : functor.elements F) (Y : functor.elements F) (f : X ⟶ Y) : functor.map (π F) f = subtype.val f := Eq.refl (functor.map (π F) f) /-- A natural transformation between functors induces a functor between the categories of elements. -/ @[simp] theorem map_obj_fst {C : Type u} [category C] {F₁ : C ⥤ Type w} {F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) (t : functor.elements F₁) : sigma.fst (functor.obj (map α) t) = sigma.fst t := Eq.refl (sigma.fst (functor.obj (map α) t)) @[simp] theorem map_π {C : Type u} [category C] {F₁ : C ⥤ Type w} {F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) : map α ⋙ π F₂ = π F₁ := rfl /-- The forward direction of the equivalence `F.elements ≅ (*, F)`. -/ def to_comma {C : Type u} [category C] (F : C ⥤ Type w) : functor.elements F ⥤ comma (functor.from_punit PUnit) F := functor.mk (fun (X : functor.elements F) => comma.mk fun (_x : functor.obj (functor.from_punit PUnit) PUnit.unit) => sigma.snd X) fun (X Y : functor.elements F) (f : X ⟶ Y) => comma_morphism.mk @[simp] theorem to_comma_obj {C : Type u} [category C] (F : C ⥤ Type w) (X : functor.elements F) : functor.obj (to_comma F) X = comma.mk fun (_x : functor.obj (functor.from_punit PUnit) PUnit.unit) => sigma.snd X := rfl @[simp] theorem to_comma_map {C : Type u} [category C] (F : C ⥤ Type w) {X : functor.elements F} {Y : functor.elements F} (f : X ⟶ Y) : functor.map (to_comma F) f = comma_morphism.mk := rfl /-- The reverse direction of the equivalence `F.elements ≅ (*, F)`. -/ def from_comma {C : Type u} [category C] (F : C ⥤ Type w) : comma (functor.from_punit PUnit) F ⥤ functor.elements F := functor.mk (fun (X : comma (functor.from_punit PUnit) F) => sigma.mk (comma.right X) (comma.hom X PUnit.unit)) fun (X Y : comma (functor.from_punit PUnit) F) (f : X ⟶ Y) => { val := comma_morphism.right f, property := sorry } @[simp] theorem from_comma_obj {C : Type u} [category C] (F : C ⥤ Type w) (X : comma (functor.from_punit PUnit) F) : functor.obj (from_comma F) X = sigma.mk (comma.right X) (comma.hom X PUnit.unit) := rfl @[simp] theorem from_comma_map {C : Type u} [category C] (F : C ⥤ Type w) {X : comma (functor.from_punit PUnit) F} {Y : comma (functor.from_punit PUnit) F} (f : X ⟶ Y) : functor.map (from_comma F) f = { val := comma_morphism.right f, property := congr_fun (Eq.symm (comma_morphism.w' f)) PUnit.unit } := rfl /-- The equivalence between the category of elements `F.elements` and the comma category `(*, F)`. -/ def comma_equivalence {C : Type u} [category C] (F : C ⥤ Type w) : functor.elements F ≌ comma (functor.from_punit PUnit) F := equivalence.mk (to_comma F) (from_comma F) (nat_iso.of_components (fun (X : functor.elements F) => eq_to_iso sorry) sorry) (nat_iso.of_components (fun (X : comma (functor.from_punit PUnit) F) => iso.mk comma_morphism.mk comma_morphism.mk) sorry) @[simp] theorem comma_equivalence_functor {C : Type u} [category C] (F : C ⥤ Type w) : equivalence.functor (comma_equivalence F) = to_comma F := rfl @[simp] theorem comma_equivalence_inverse {C : Type u} [category C] (F : C ⥤ Type w) : equivalence.inverse (comma_equivalence F) = from_comma F := rfl
2c3e635b47593c3452eee8dd97951e88e5d56940
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/option/basic.lean
f97e2de65222d32d52188ad65e8b5a27877ec066
[ "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
7,410
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.basic namespace option variables {α : Type*} {β : Type*} {γ : Type*} lemma some_ne_none (x : α) : some x ≠ none := λ h, option.no_confusion h @[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o | (some a) _ := rfl theorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a | _ _ rfl := rfl @[simp] lemma not_mem_none (a : α) : a ∉ (none : option α) := λ h, option.no_confusion h @[simp] lemma some_get : ∀ {x : option α} (h : is_some x), some (option.get h) = x | (some x) hx := rfl @[simp] lemma get_some (x : α) (h : is_some (some x)) : option.get h = x := rfl @[simp] lemma get_or_else_some (x y : α) : option.get_or_else (some x) y = x := rfl lemma get_or_else_of_ne_none {x : option α} (hx : x ≠ none) (y : α) : some (x.get_or_else y) = x := by cases x; [contradiction, rw get_or_else_some] theorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b := option.some.inj $ ha.symm.trans hb theorem injective_some (α : Type*) : function.injective (@some α) := λ _ _, some_inj.mp /-- `option.map f` is injective if `f` is injective. -/ theorem injective_map {f : α → β} (Hf : function.injective f) : function.injective (option.map f) | none none H := rfl | (some a₁) (some a₂) H := by rw Hf (option.some.inj H) @[ext] theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ | none none H := rfl | (some a) o H := ((H _).1 rfl).symm | o (some b) H := (H _).2 rfl theorem eq_none_iff_forall_not_mem {o : option α} : o = none ↔ (∀ a, a ∉ o) := ⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩ @[simp] theorem none_bind {α β} (f : α → option β) : none >>= f = none := rfl @[simp] theorem some_bind {α β} (a : α) (f : α → option β) : some a >>= f = f a := rfl @[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl @[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl @[simp] theorem bind_some : ∀ x : option α, x >>= some = x := @bind_pure α option _ _ @[simp] theorem bind_eq_some {α β} {x : option α} {f : α → option β} {b : β} : x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} : x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_none' {o : option α} {f : α → option β} : o.bind f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := by simp only [eq_none_iff_forall_not_mem, not_exists, not_and, mem_def, bind_eq_some'] @[simp] theorem bind_eq_none {α β} {o : option α} {f : α → option β} : o >>= f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := bind_eq_none' lemma bind_comm {α β γ} {f : α → β → option γ} (a : option α) (b : option β) : a.bind (λx, b.bind (f x)) = b.bind (λy, a.bind (λx, f x y)) := by cases a; cases b; refl lemma bind_assoc (x : option α) (f : α → option β) (g : β → option γ) : (x.bind f).bind g = x.bind (λ y, (f y).bind g) := by cases x; refl @[simp] theorem map_none {α β} {f : α → β} : f <$> none = none := rfl @[simp] theorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl @[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl @[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl @[simp] theorem map_eq_some {α β} {x : option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} : x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_id' : option.map (@id α) = id := map_id @[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl @[simp] theorem some_orelse' (a : α) (x : option α) : (some a).orelse x = some a := rfl @[simp] theorem some_orelse (a : α) (x : option α) : (some a <|> x) = some a := rfl @[simp] theorem none_orelse' (x : option α) : none.orelse x = x := by cases x; refl @[simp] theorem none_orelse (x : option α) : (none <|> x) = x := none_orelse' x @[simp] theorem orelse_none' (x : option α) : x.orelse none = x := by cases x; refl @[simp] theorem orelse_none (x : option α) : (x <|> none) = x := orelse_none' x @[simp] theorem is_some_none : @is_some α none = ff := rfl @[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl theorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a := by cases x; simp [is_some]; exact ⟨_, rfl⟩ @[simp] theorem is_none_none : @is_none α none = tt := rfl @[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl @[simp] theorem not_is_some {a : option α} : is_some a = ff ↔ a.is_none = tt := by cases a; simp lemma eq_some_iff_get_eq {o : option α} {a : α} : o = some a ↔ ∃ h : o.is_some, option.get h = a := by cases o; simp lemma not_is_some_iff_eq_none {o : option α} : ¬o.is_some ↔ o = none := by cases o; simp lemma ne_none_iff_is_some {o : option α} : o ≠ none ↔ o.is_some := by cases o; simp lemma bex_ne_none {p : option α → Prop} : (∃ x ≠ none, p x) ↔ ∃ x, p (some x) := ⟨λ ⟨x, hx, hp⟩, ⟨get $ ne_none_iff_is_some.1 hx, by rwa [some_get]⟩, λ ⟨x, hx⟩, ⟨some x, some_ne_none x, hx⟩⟩ lemma ball_ne_none {p : option α → Prop} : (∀ x ≠ none, p x) ↔ ∀ x, p (some x) := ⟨λ h x, h (some x) (some_ne_none x), λ h x hx, by simpa only [some_get] using h (get $ ne_none_iff_is_some.1 hx)⟩ theorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o | (some a) _ := rfl theorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a | _ rfl := rfl @[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} : guard p a = some b ↔ a = b ∧ p a := by by_cases p a; simp [option.guard, h]; intro; contradiction @[simp] theorem guard_eq_some' {p : Prop} [decidable p] : ∀ u, _root_.guard p = some u ↔ p | () := by by_cases p; simp [guard, h, pure]; intro; contradiction theorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) : ∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ | none none := or.inl rfl | (some a) none := or.inl rfl | none (some b) := or.inr rfl | (some a) (some b) := by simpa [lift_or_get] using h a b @[simp] lemma lift_or_get_none_left {f} {b : option α} : lift_or_get f none b = b := by cases b; refl @[simp] lemma lift_or_get_none_right {f} {a : option α} : lift_or_get f a none = a := by cases a; refl @[simp] lemma lift_or_get_some_some {f} {a b : α} : lift_or_get f (some a) (some b) = f a b := rfl /-- given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this function to `a` if it comes from `α`, and return `b` otherwise. -/ def cases_on' : option α → β → (α → β) → β | none n s := n | (some a) n s := s a end option
685c110bfe5f326f80f6519124deb98c9ed2d3d9
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/perm/support.lean
8d2e19a333fc1880b1a2a409292727baeb042923
[ "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
20,226
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Aaron Anderson, Yakov Pechersky -/ import data.finset.card import data.fintype.basic import group_theory.perm.basic /-! # Support of a permutation ## Main definitions In the following, `f g : equiv.perm α`. * `equiv.perm.disjoint`: two permutations `f` and `g` are `disjoint` if every element is fixed either by `f`, or by `g`. Equivalently, `f` and `g` are `disjoint` iff their `support` are disjoint. * `equiv.perm.is_swap`: `f = swap x y` for `x ≠ y`. * `equiv.perm.support`: the elements `x : α` that are not fixed by `f`. -/ open equiv finset namespace equiv.perm variables {α : Type*} section disjoint /-- Two permutations `f` and `g` are `disjoint` if their supports are disjoint, i.e., every element is fixed either by `f`, or by `g`. -/ def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x variables {f g h : perm α} @[symm] lemma disjoint.symm : disjoint f g → disjoint g f := by simp only [disjoint, or.comm, imp_self] lemma disjoint.symmetric : symmetric (@disjoint α) := λ _ _, disjoint.symm lemma disjoint_comm : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint.commute (h : disjoint f g) : commute f g := equiv.ext $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_iff_eq_or_eq : disjoint f g ↔ ∀ (x : α), f x = x ∨ g x = x := iff.rfl @[simp] lemma disjoint_refl_iff : disjoint f f ↔ f = 1 := begin refine ⟨λ h, _, λ h, h.symm ▸ disjoint_one_left 1⟩, ext x, cases h x with hx hx; simp [hx] end lemma disjoint.inv_left (h : disjoint f g) : disjoint f⁻¹ g := begin intro x, rw [inv_eq_iff_eq, eq_comm], exact h x end lemma disjoint.inv_right (h : disjoint f g) : disjoint f g⁻¹ := h.symm.inv_left.symm @[simp] lemma disjoint_inv_left_iff : disjoint f⁻¹ g ↔ disjoint f g := begin refine ⟨λ h, _, disjoint.inv_left⟩, convert h.inv_left, exact (inv_inv _).symm end @[simp] lemma disjoint_inv_right_iff : disjoint f g⁻¹ ↔ disjoint f g := by rw [disjoint_comm, disjoint_inv_left_iff, disjoint_comm] lemma disjoint.mul_left (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint.mul_right (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by { rw disjoint_comm, exact H1.symm.mul_left H2.symm } lemma disjoint_prod_right (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons, exact (h _ (list.mem_cons_self _ _)).mul_right (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := hp.prod_eq' $ hl.imp $ λ f g, disjoint.commute lemma nodup_of_pairwise_disjoint {l : list (perm α)} (h1 : (1 : perm α) ∉ l) (h2 : l.pairwise disjoint) : l.nodup := begin refine list.pairwise.imp_of_mem _ h2, rintros σ - h_mem - h_disjoint rfl, suffices : σ = 1, { rw this at h_mem, exact h1 h_mem }, exact ext (λ a, (or_self _).mp (h_disjoint a)), end lemma pow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma zpow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [zpow_neg_succ_of_nat, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma zpow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by { rw [zpow_neg_succ_of_nat, inv_eq_iff_eq, ← f.injective.eq_iff, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm], exact pow_apply_eq_of_apply_apply_eq_self hffx _ } lemma disjoint.mul_apply_eq_iff {σ τ : perm α} (hστ : disjoint σ τ) {a : α} : (σ * τ) a = a ↔ σ a = a ∧ τ a = a := begin refine ⟨λ h, _, λ h, by rw [mul_apply, h.2, h.1]⟩, cases hστ a with hσ hτ, { exact ⟨hσ, σ.injective (h.trans hσ.symm)⟩ }, { exact ⟨(congr_arg σ hτ).symm.trans h, hτ⟩ }, end lemma disjoint.mul_eq_one_iff {σ τ : perm α} (hστ : disjoint σ τ) : σ * τ = 1 ↔ σ = 1 ∧ τ = 1 := by simp_rw [ext_iff, one_apply, hστ.mul_apply_eq_iff, forall_and_distrib] lemma disjoint.zpow_disjoint_zpow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℤ) : disjoint (σ ^ m) (τ ^ n) := λ x, or.imp (λ h, zpow_apply_eq_self_of_apply_eq_self h m) (λ h, zpow_apply_eq_self_of_apply_eq_self h n) (hστ x) lemma disjoint.pow_disjoint_pow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℕ) : disjoint (σ ^ m) (τ ^ n) := hστ.zpow_disjoint_zpow m n end disjoint section is_swap variable [decidable_eq α] /-- `f.is_swap` indicates that the permutation `f` is a transposition of two elements. -/ def is_swap (f : perm α) : Prop := ∃ x y, x ≠ y ∧ f = swap x y lemma is_swap.of_subtype_is_swap {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : f.is_swap) : (of_subtype f).is_swap := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by { simp only [ne.def] at hxy, exact hxy.1 }, equiv.ext $ λ z, begin rw [hxy.2, of_subtype], simp only [swap_apply_def, coe_fn_mk, swap_inv, subtype.mk_eq_mk, monoid_hom.coe_mk], split_ifs; rw subtype.coe_mk <|> cc, end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, f.injective.eq_iff] at *, by_cases h : f y = x, { split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * }, { split_ifs at hy; cc } end end is_swap section support section set variables (p q : perm α) lemma set_support_inv_eq : {x | p⁻¹ x ≠ x} = {x | p x ≠ x} := begin ext x, simp only [set.mem_set_of_eq, ne.def], rw [inv_def, symm_apply_eq, eq_comm] end lemma set_support_apply_mem {p : perm α} {a : α} : p a ∈ {x | p x ≠ x} ↔ a ∈ {x | p x ≠ x} := by simp lemma set_support_zpow_subset (n : ℤ) : {x | (p ^ n) x ≠ x} ⊆ {x | p x ≠ x} := begin intros x, simp only [set.mem_set_of_eq, ne.def], intros hx H, simpa [zpow_apply_eq_self_of_apply_eq_self H] using hx end lemma set_support_mul_subset : {x | (p * q) x ≠ x} ⊆ {x | p x ≠ x} ∪ {x | q x ≠ x} := begin intro x, simp only [perm.coe_mul, function.comp_app, ne.def, set.mem_union_eq, set.mem_set_of_eq], by_cases hq : q x = x; simp [hq] end end set variables [decidable_eq α] [fintype α] {f g : perm α} /-- The `finset` of nonfixed points of a permutation. -/ def support (f : perm α) : finset α := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support {x : α} : x ∈ f.support ↔ f x ≠ x := by rw [support, mem_filter, and_iff_right (mem_univ x)] lemma not_mem_support {x : α} : x ∉ f.support ↔ f x = x := by simp lemma coe_support_eq_set_support (f : perm α) : (f.support : set α) = {x | f x ≠ x} := by { ext, simp } @[simp] lemma support_eq_empty_iff {σ : perm α} : σ.support = ∅ ↔ σ = 1 := by simp_rw [finset.ext_iff, mem_support, finset.not_mem_empty, iff_false, not_not, equiv.perm.ext_iff, one_apply] @[simp] lemma support_one : (1 : perm α).support = ∅ := by rw support_eq_empty_iff @[simp] lemma support_refl : support (equiv.refl α) = ∅ := support_one lemma support_congr (h : f.support ⊆ g.support) (h' : ∀ x ∈ g.support, f x = g x) : f = g := begin ext x, by_cases hx : x ∈ g.support, { exact h' x hx }, { rw [not_mem_support.mp hx, ←not_mem_support], exact λ H, hx (h H) } end lemma support_mul_le (f g : perm α) : (f * g).support ≤ f.support ⊔ g.support := λ x, begin rw [sup_eq_union, mem_union, mem_support, mem_support, mem_support, mul_apply, ←not_and_distrib, not_imp_not], rintro ⟨hf, hg⟩, rw [hg, hf] end lemma exists_mem_support_of_mem_support_prod {l : list (perm α)} {x : α} (hx : x ∈ l.prod.support) : ∃ f : perm α, f ∈ l ∧ x ∈ f.support := begin contrapose! hx, simp_rw [mem_support, not_not] at hx ⊢, induction l with f l ih generalizing hx, { refl }, { rw [list.prod_cons, mul_apply, ih (λ g hg, hx g (or.inr hg)), hx f (or.inl rfl)] }, end lemma support_pow_le (σ : perm α) (n : ℕ) : (σ ^ n).support ≤ σ.support := λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (pow_apply_eq_self_of_apply_eq_self h2 n)) @[simp] lemma support_inv (σ : perm α) : support (σ⁻¹) = σ.support := by simp_rw [finset.ext_iff, mem_support, not_iff_not, (inv_eq_iff_eq).trans eq_comm, iff_self, imp_true_iff] @[simp] lemma apply_mem_support {x : α} : f x ∈ f.support ↔ x ∈ f.support := by rw [mem_support, mem_support, ne.def, ne.def, not_iff_not, apply_eq_iff_eq] @[simp] lemma pow_apply_mem_support {n : ℕ} {x : α} : (f ^ n) x ∈ f.support ↔ x ∈ f.support := begin induction n with n ih, { refl }, rw [pow_succ, perm.mul_apply, apply_mem_support, ih] end @[simp] lemma zpow_apply_mem_support {n : ℤ} {x : α} : (f ^ n) x ∈ f.support ↔ x ∈ f.support := begin cases n, { rw [int.of_nat_eq_coe, zpow_coe_nat, pow_apply_mem_support] }, { rw [zpow_neg_succ_of_nat, ← support_inv, ← inv_pow, pow_apply_mem_support] } end lemma pow_eq_on_of_mem_support (h : ∀ (x ∈ f.support ∩ g.support), f x = g x) (k : ℕ) : ∀ (x ∈ f.support ∩ g.support), (f ^ k) x = (g ^ k) x := begin induction k with k hk, { simp }, { intros x hx, rw [pow_succ', mul_apply, pow_succ', mul_apply, h _ hx, hk], rwa [mem_inter, apply_mem_support, ←h _ hx, apply_mem_support, ←mem_inter] } end lemma disjoint_iff_disjoint_support : disjoint f g ↔ _root_.disjoint f.support g.support := by simp [disjoint_iff_eq_or_eq, disjoint_iff, finset.ext_iff, not_and_distrib] lemma disjoint.disjoint_support (h : disjoint f g) : _root_.disjoint f.support g.support := disjoint_iff_disjoint_support.1 h lemma disjoint.support_mul (h : disjoint f g) : (f * g).support = f.support ∪ g.support := begin refine le_antisymm (support_mul_le _ _) (λ a, _), rw [mem_union, mem_support, mem_support, mem_support, mul_apply, ←not_and_distrib, not_imp_not], exact (h a).elim (λ hf h, ⟨hf, f.apply_eq_iff_eq.mp (h.trans hf.symm)⟩) (λ hg h, ⟨(congr_arg f hg).symm.trans h, hg⟩), end lemma support_prod_of_pairwise_disjoint (l : list (perm α)) (h : l.pairwise disjoint) : l.prod.support = (l.map support).foldr (⊔) ⊥ := begin induction l with hd tl hl, { simp }, { rw [list.pairwise_cons] at h, have : disjoint hd tl.prod := disjoint_prod_right _ h.left, simp [this.support_mul, hl h.right] } end lemma support_prod_le (l : list (perm α)) : l.prod.support ≤ (l.map support).foldr (⊔) ⊥ := begin induction l with hd tl hl, { simp }, { rw [list.prod_cons, list.map_cons, list.foldr_cons], refine (support_mul_le hd tl.prod).trans _, exact sup_le_sup le_rfl hl } end lemma support_zpow_le (σ : perm α) (n : ℤ) : (σ ^ n).support ≤ σ.support := λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (zpow_apply_eq_self_of_apply_eq_self h2 n)) @[simp] lemma support_swap {x y : α} (h : x ≠ y) : support (swap x y) = {x, y} := begin ext z, by_cases hx : z = x, any_goals { simpa [hx] using h.symm }, by_cases hy : z = y; { simp [swap_apply_of_ne_of_ne, hx, hy]; cc } end lemma support_swap_iff (x y : α) : support (swap x y) = {x, y} ↔ x ≠ y := begin refine ⟨λ h H, _, support_swap⟩, subst H, simp only [swap_self, support_refl, insert_singleton_self_eq] at h, have : x ∈ ∅, { rw h, exact mem_singleton.mpr rfl }, simpa end lemma support_swap_mul_swap {x y z : α} (h : list.nodup [x, y, z]) : support (swap x y * swap y z) = {x, y, z} := begin simp only [list.not_mem_nil, and_true, list.mem_cons_iff, not_false_iff, list.nodup_cons, list.mem_singleton, and_self, list.nodup_nil] at h, push_neg at h, apply le_antisymm, { convert support_mul_le _ _, rw [support_swap h.left.left, support_swap h.right], ext, simp [or.comm, or.left_comm] }, { intro, simp only [mem_insert, mem_singleton], rintro (rfl | rfl | rfl | _); simp [swap_apply_of_ne_of_ne, h.left.left, h.left.left.symm, h.left.right, h.left.right.symm, h.right.symm] } end lemma support_swap_mul_ge_support_diff (f : perm α) (x y : α) : f.support \ {x, y} ≤ (swap x y * f).support := begin intro, simp only [and_imp, perm.coe_mul, function.comp_app, ne.def, mem_support, mem_insert, mem_sdiff, mem_singleton], push_neg, rintro ha ⟨hx, hy⟩ H, rw [swap_apply_eq_iff, swap_apply_of_ne_of_ne hx hy] at H, exact ha H end lemma support_swap_mul_eq (f : perm α) (x : α) (h : f (f x) ≠ x) : (swap x (f x) * f).support = f.support \ {x} := begin by_cases hx : f x = x, { simp [hx, sdiff_singleton_eq_erase, not_mem_support.mpr hx, erase_eq_of_not_mem] }, ext z, by_cases hzx : z = x, { simp [hzx] }, by_cases hzf : z = f x, { simp [hzf, hx, h, swap_apply_of_ne_of_ne], }, by_cases hzfx : f z = x, { simp [ne.symm hzx, hzx, ne.symm hzf, hzfx] }, { simp [ne.symm hzx, hzx, ne.symm hzf, hzfx, f.injective.ne hzx, swap_apply_of_ne_of_ne] } end lemma mem_support_swap_mul_imp_mem_support_ne {x y : α} (hy : y ∈ support (swap x (f x) * f)) : y ∈ support f ∧ y ≠ x := begin simp only [mem_support, swap_apply_def, mul_apply, f.injective.eq_iff] at *, by_cases h : f y = x, { split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * }, { split_ifs at hy; cc } end lemma disjoint.mem_imp (h : disjoint f g) {x : α} (hx : x ∈ f.support) : x ∉ g.support := λ H, h.disjoint_support (mem_inter_of_mem hx H) lemma eq_on_support_mem_disjoint {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) : ∀ (x ∈ f.support), f x = l.prod x := begin induction l with hd tl IH, { simpa using h }, { intros x hx, rw list.pairwise_cons at hl, rw list.mem_cons_iff at h, rcases h with rfl|h, { rw [list.prod_cons, mul_apply, not_mem_support.mp ((disjoint_prod_right tl hl.left).mem_imp hx)] }, { rw [list.prod_cons, mul_apply, ←IH h hl.right _ hx, eq_comm, ←not_mem_support], refine (hl.left _ h).symm.mem_imp _, simpa using hx } } end lemma disjoint.mono {x y : perm α} (h : disjoint f g) (hf : x.support ≤ f.support) (hg : y.support ≤ g.support) : disjoint x y := begin rw disjoint_iff_disjoint_support at h ⊢, intros a ha, exact h (mem_inter_of_mem (hf (mem_of_mem_inter_left ha)) (hg (mem_of_mem_inter_right ha))) end lemma support_le_prod_of_mem {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) : f.support ≤ l.prod.support := begin intros x hx, rwa [mem_support, ←eq_on_support_mem_disjoint h hl _ hx, ←mem_support], end section extend_domain variables {β : Type*} [decidable_eq β] [fintype β] {p : β → Prop} [decidable_pred p] @[simp] lemma support_extend_domain (f : α ≃ subtype p) {g : perm α} : support (g.extend_domain f) = g.support.map f.as_embedding := begin ext b, simp only [exists_prop, function.embedding.coe_fn_mk, to_embedding_apply, mem_map, ne.def, function.embedding.trans_apply, mem_support], by_cases pb : p b, { rw [extend_domain_apply_subtype _ _ pb], split, { rintro h, refine ⟨f.symm ⟨b, pb⟩, _, by simp⟩, contrapose! h, simp [h] }, { rintro ⟨a, ha, hb⟩, contrapose! ha, obtain rfl : a = f.symm ⟨b, pb⟩, { rw eq_symm_apply, exact subtype.coe_injective hb }, rw eq_symm_apply, exact subtype.coe_injective ha } }, { rw [extend_domain_apply_not_subtype _ _ pb], simp only [not_exists, false_iff, not_and, eq_self_iff_true, not_true], rintros a ha rfl, exact pb (subtype.prop _) } end lemma card_support_extend_domain (f : α ≃ subtype p) {g : perm α} : (g.extend_domain f).support.card = g.support.card := by simp end extend_domain section card @[simp] lemma card_support_eq_zero {f : perm α} : f.support.card = 0 ↔ f = 1 := by rw [finset.card_eq_zero, support_eq_empty_iff] lemma one_lt_card_support_of_ne_one {f : perm α} (h : f ≠ 1) : 1 < f.support.card := begin simp_rw [one_lt_card_iff, mem_support, ←not_or_distrib], contrapose! h, ext a, specialize h (f a) a, rwa [apply_eq_iff_eq, or_self, or_self] at h, end lemma card_support_ne_one (f : perm α) : f.support.card ≠ 1 := begin by_cases h : f = 1, { exact ne_of_eq_of_ne (card_support_eq_zero.mpr h) zero_ne_one }, { exact ne_of_gt (one_lt_card_support_of_ne_one h) }, end @[simp] lemma card_support_le_one {f : perm α} : f.support.card ≤ 1 ↔ f = 1 := by rw [le_iff_lt_or_eq, nat.lt_succ_iff, nat.le_zero_iff, card_support_eq_zero, or_iff_not_imp_right, imp_iff_right f.card_support_ne_one] lemma two_le_card_support_of_ne_one {f : perm α} (h : f ≠ 1) : 2 ≤ f.support.card := one_lt_card_support_of_ne_one h lemma card_support_swap_mul {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, (mem_support_swap_mul_imp_mem_support_ne hz).left, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ lemma card_support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x ::ₘ y ::ₘ 0, by simp [hxy]⟩, from congr_arg card $ by simp [support_swap hxy, *, finset.ext_iff] @[simp] lemma card_support_eq_two {f : perm α} : f.support.card = 2 ↔ is_swap f := begin split; intro h, { obtain ⟨x, t, hmem, hins, ht⟩ := card_eq_succ.1 h, obtain ⟨y, rfl⟩ := card_eq_one.1 ht, rw mem_singleton at hmem, refine ⟨x, y, hmem, _⟩, ext a, have key : ∀ b, f b ≠ b ↔ _ := λ b, by rw [←mem_support, ←hins, mem_insert, mem_singleton], by_cases ha : f a = a, { have ha' := not_or_distrib.mp (mt (key a).mpr (not_not.mpr ha)), rw [ha, swap_apply_of_ne_of_ne ha'.1 ha'.2] }, { have ha' := (key (f a)).mp (mt f.apply_eq_iff_eq.mp ha), obtain rfl | rfl := ((key a).mp ha), { rw [or.resolve_left ha' ha, swap_apply_left] }, { rw [or.resolve_right ha' ha, swap_apply_right] } } }, { obtain ⟨x, y, hxy, rfl⟩ := h, exact card_support_swap hxy } end lemma disjoint.card_support_mul (h : disjoint f g) : (f * g).support.card = f.support.card + g.support.card := begin rw ←finset.card_disjoint_union, { congr, ext, simp [h.support_mul] }, { simpa using h.disjoint_support } end lemma card_support_prod_list_of_pairwise_disjoint {l : list (perm α)} (h : l.pairwise disjoint) : l.prod.support.card = (l.map (finset.card ∘ support)).sum := begin induction l with a t ih, { exact card_support_eq_zero.mpr rfl, }, { obtain ⟨ha, ht⟩ := list.pairwise_cons.1 h, rw [list.prod_cons, list.map_cons, list.sum_cons, ←ih ht], exact (disjoint_prod_right _ ha).card_support_mul } end end card end support end equiv.perm
d76130c85a2d9f4c624c859db0f2b46c33b9ca07
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/algebra/category/Group/images.lean
0181db5cfc92e5ab947b58f996621320bf0bd73a
[ "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
3,865
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Group.basic import category_theory.limits.shapes.images import category_theory.limits.types /-! # The category of commutative additive groups has images. -/ open category_theory open category_theory.limits universe u namespace AddCommGroup -- Note that because `injective_of_mono` is currently only proved in `Type 0`, -- we restrict to the lowest universe here for now. variables {G H : AddCommGroup.{0}} (f : G ⟶ H) local attribute [ext] subtype.ext_val section -- implementation details of `has_image` for AddCommGroup; use the API, not these /-- the image of a morphism in AddCommGroup is just the bundling of `add_monoid_hom.range f` -/ def image : AddCommGroup := AddCommGroup.of (add_monoid_hom.range f) /-- the inclusion of `image f` into the target -/ def image.ι : image f ⟶ H := f.range.subtype instance : mono (image.ι f) := concrete_category.mono_of_injective (image.ι f) subtype.val_injective /-- the corestriction map to the image -/ def factor_thru_image : G ⟶ image f := f.to_range lemma image.fac : factor_thru_image f ≫ image.ι f = f := by { ext, refl, } local attribute [simp] image.fac variables {f} /-- the universal property for the image factorisation -/ noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := { to_fun := (λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I), map_zero' := begin haveI := F'.m_mono, apply injective_of_mono F'.m, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, add_monoid_hom.map_zero], convert (classical.indefinite_description (λ y, f y = 0) _).2, end, map_add' := begin intros x y, haveI := F'.m_mono, apply injective_of_mono F'.m, rw [add_monoid_hom.map_add], change (F'.e ≫ F'.m) _ = (F'.e ≫ F'.m) _ + (F'.e ≫ F'.m) _, rw [F'.fac], rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, refl, end, } 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 AddCommGroup through a mono. -/ def mono_factorisation : mono_factorisation f := { I := image f, m := image.ι f, e := factor_thru_image f } noncomputable instance : has_image f := { F := mono_factorisation f, is_image := { lift := image.lift, lift_fac' := image.lift_fac } } noncomputable instance : has_images AddCommGroup.{0} := { has_image := infer_instance } -- We'll later get this as a consequence of `[abelian AddCommGroup]`. -- Nevertheless this instance has the desired definitional behaviour, -- and is useful in the meantime for doing cohomology. -- When the `[abelian AddCommGroup]` instance is available -- this instance should be reviewed, and ideally removed if the `[abelian]` instance -- provides something definitionally equivalent. noncomputable instance : has_image_maps AddCommGroup.{0} := { has_image_map := λ f g st, { map := { to_fun := image.map ((forget AddCommGroup).map_arrow.map st), map_zero' := by { ext, simp, }, map_add' := λ x y, by { ext, simp, refl, } } } } @[simp] lemma image_map {f g : arrow AddCommGroup.{0}} (st : f ⟶ g) (x : image f.hom): (image.map st x).val = st.right x.1 := rfl /-- The categorical image of a morphism in `AddCommGroup` agrees with the usual group-theoretical range. -/ def image_iso_range {G H : AddCommGroup} (f : G ⟶ H) : image f ≅ AddCommGroup.of f.range := iso.refl _ end AddCommGroup
32e8df03b544b93cbc694346bacaab337e26f3a5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group/prod_auto.lean
ac7f07bf97fe5f52b4619b915e30b0794473d3f3
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
13,307
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group.hom import Mathlib.data.equiv.mul_add import Mathlib.data.prod import Mathlib.PostPort universes u_5 u_6 u_3 u_4 u_1 u_2 u_7 u_8 u_9 namespace Mathlib /-! # Monoid, group etc structures on `M × N` In this file we define one-binop (`monoid`, `group` etc) structures on `M × N`. We also prove trivial `simp` lemmas, and define the following operations on `monoid_hom`s: * `fst M N : M × N →* M`, `snd M N : M × N →* N`: projections `prod.fst` and `prod.snd` as `monoid_hom`s; * `inl M N : M →* M × N`, `inr M N : N →* M × N`: inclusions of first/second monoid into the product; * `f.prod g : `M →* N × P`: sends `x` to `(f x, g x)`; * `f.coprod g : M × N →* P`: sends `(x, y)` to `f x * g y`; * `f.prod_map g : M × N → M' × N'`: `prod.map f g` as a `monoid_hom`, sends `(x, y)` to `(f x, g y)`. -/ namespace prod protected instance has_add {M : Type u_5} {N : Type u_6} [Add M] [Add N] : Add (M × N) := { add := fun (p q : M × N) => (fst p + fst q, snd p + snd q) } @[simp] theorem fst_add {M : Type u_5} {N : Type u_6} [Add M] [Add N] (p : M × N) (q : M × N) : fst (p + q) = fst p + fst q := rfl @[simp] theorem snd_add {M : Type u_5} {N : Type u_6} [Add M] [Add N] (p : M × N) (q : M × N) : snd (p + q) = snd p + snd q := rfl @[simp] theorem mk_add_mk {M : Type u_5} {N : Type u_6} [Add M] [Add N] (a₁ : M) (a₂ : M) (b₁ : N) (b₂ : N) : (a₁, b₁) + (a₂, b₂) = (a₁ + a₂, b₁ + b₂) := rfl protected instance has_one {M : Type u_5} {N : Type u_6} [HasOne M] [HasOne N] : HasOne (M × N) := { one := (1, 1) } @[simp] theorem fst_zero {M : Type u_5} {N : Type u_6} [HasZero M] [HasZero N] : fst 0 = 0 := rfl @[simp] theorem snd_one {M : Type u_5} {N : Type u_6} [HasOne M] [HasOne N] : snd 1 = 1 := rfl theorem zero_eq_mk {M : Type u_5} {N : Type u_6} [HasZero M] [HasZero N] : 0 = (0, 0) := rfl @[simp] theorem mk_eq_zero {M : Type u_5} {N : Type u_6} [HasZero M] [HasZero N] {x : M} {y : N} : (x, y) = 0 ↔ x = 0 ∧ y = 0 := mk.inj_iff theorem fst_mul_snd {M : Type u_5} {N : Type u_6} [monoid M] [monoid N] (p : M × N) : (fst p, 1) * (1, snd p) = p := ext (mul_one (fst p)) (one_mul (snd p)) protected instance has_inv {M : Type u_5} {N : Type u_6} [has_inv M] [has_inv N] : has_inv (M × N) := has_inv.mk fun (p : M × N) => (fst p⁻¹, snd p⁻¹) @[simp] theorem fst_inv {G : Type u_3} {H : Type u_4} [has_inv G] [has_inv H] (p : G × H) : fst (p⁻¹) = (fst p⁻¹) := rfl @[simp] theorem snd_neg {G : Type u_3} {H : Type u_4} [Neg G] [Neg H] (p : G × H) : snd (-p) = -snd p := rfl @[simp] theorem inv_mk {G : Type u_3} {H : Type u_4} [has_inv G] [has_inv H] (a : G) (b : H) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl protected instance has_sub {M : Type u_5} {N : Type u_6} [Sub M] [Sub N] : Sub (M × N) := { sub := fun (p q : M × N) => (fst p - fst q, snd p - snd q) } @[simp] theorem fst_sub {A : Type u_1} {B : Type u_2} [add_group A] [add_group B] (a : A × B) (b : A × B) : fst (a - b) = fst a - fst b := rfl @[simp] theorem snd_sub {A : Type u_1} {B : Type u_2} [add_group A] [add_group B] (a : A × B) (b : A × B) : snd (a - b) = snd a - snd b := rfl @[simp] theorem mk_sub_mk {A : Type u_1} {B : Type u_2} [add_group A] [add_group B] (x₁ : A) (x₂ : A) (y₁ : B) (y₂ : B) : (x₁, y₁) - (x₂, y₂) = (x₁ - x₂, y₁ - y₂) := rfl protected instance semigroup {M : Type u_5} {N : Type u_6} [semigroup M] [semigroup N] : semigroup (M × N) := semigroup.mk Mul.mul sorry protected instance add_monoid {M : Type u_5} {N : Type u_6} [add_monoid M] [add_monoid N] : add_monoid (M × N) := add_monoid.mk add_semigroup.add sorry 0 sorry sorry protected instance group {G : Type u_3} {H : Type u_4} [group G] [group H] : group (G × H) := group.mk monoid.mul sorry monoid.one sorry sorry has_inv.inv Div.div sorry protected instance add_comm_semigroup {G : Type u_3} {H : Type u_4} [add_comm_semigroup G] [add_comm_semigroup H] : add_comm_semigroup (G × H) := add_comm_semigroup.mk add_semigroup.add sorry sorry protected instance left_cancel_semigroup {G : Type u_3} {H : Type u_4} [left_cancel_semigroup G] [left_cancel_semigroup H] : left_cancel_semigroup (G × H) := left_cancel_semigroup.mk semigroup.mul sorry sorry protected instance right_cancel_semigroup {G : Type u_3} {H : Type u_4} [right_cancel_semigroup G] [right_cancel_semigroup H] : right_cancel_semigroup (G × H) := right_cancel_semigroup.mk semigroup.mul sorry sorry protected instance add_comm_monoid {M : Type u_5} {N : Type u_6} [add_comm_monoid M] [add_comm_monoid N] : add_comm_monoid (M × N) := add_comm_monoid.mk add_comm_semigroup.add sorry add_monoid.zero sorry sorry sorry protected instance comm_group {G : Type u_3} {H : Type u_4} [comm_group G] [comm_group H] : comm_group (G × H) := comm_group.mk comm_semigroup.mul sorry group.one sorry sorry group.inv group.div sorry sorry end prod namespace monoid_hom /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `M`.-/ def fst (M : Type u_5) (N : Type u_6) [monoid M] [monoid N] : M × N →* M := mk prod.fst sorry sorry /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `N`.-/ def Mathlib.add_monoid_hom.snd (M : Type u_5) (N : Type u_6) [add_monoid M] [add_monoid N] : M × N →+ N := add_monoid_hom.mk prod.snd sorry sorry /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `M` to `M × N`. -/ def Mathlib.add_monoid_hom.inl (M : Type u_5) (N : Type u_6) [add_monoid M] [add_monoid N] : M →+ M × N := add_monoid_hom.mk (fun (x : M) => (x, 0)) sorry sorry /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `N` to `M × N`. -/ def Mathlib.add_monoid_hom.inr (M : Type u_5) (N : Type u_6) [add_monoid M] [add_monoid N] : N →+ M × N := add_monoid_hom.mk (fun (y : N) => (0, y)) sorry sorry @[simp] theorem Mathlib.add_monoid_hom.coe_fst {M : Type u_5} {N : Type u_6} [add_monoid M] [add_monoid N] : ⇑(add_monoid_hom.fst M N) = prod.fst := rfl @[simp] theorem Mathlib.add_monoid_hom.coe_snd {M : Type u_5} {N : Type u_6} [add_monoid M] [add_monoid N] : ⇑(add_monoid_hom.snd M N) = prod.snd := rfl @[simp] theorem inl_apply {M : Type u_5} {N : Type u_6} [monoid M] [monoid N] (x : M) : coe_fn (inl M N) x = (x, 1) := rfl @[simp] theorem inr_apply {M : Type u_5} {N : Type u_6} [monoid M] [monoid N] (y : N) : coe_fn (inr M N) y = (1, y) := rfl @[simp] theorem Mathlib.add_monoid_hom.fst_comp_inl {M : Type u_5} {N : Type u_6} [add_monoid M] [add_monoid N] : add_monoid_hom.comp (add_monoid_hom.fst M N) (add_monoid_hom.inl M N) = add_monoid_hom.id M := rfl @[simp] theorem Mathlib.add_monoid_hom.snd_comp_inl {M : Type u_5} {N : Type u_6} [add_monoid M] [add_monoid N] : add_monoid_hom.comp (add_monoid_hom.snd M N) (add_monoid_hom.inl M N) = 0 := rfl @[simp] theorem Mathlib.add_monoid_hom.fst_comp_inr {M : Type u_5} {N : Type u_6} [add_monoid M] [add_monoid N] : add_monoid_hom.comp (add_monoid_hom.fst M N) (add_monoid_hom.inr M N) = 0 := rfl @[simp] theorem Mathlib.add_monoid_hom.snd_comp_inr {M : Type u_5} {N : Type u_6} [add_monoid M] [add_monoid N] : add_monoid_hom.comp (add_monoid_hom.snd M N) (add_monoid_hom.inr M N) = add_monoid_hom.id N := rfl /-- Combine two `monoid_hom`s `f : M →* N`, `g : M →* P` into `f.prod g : M →* N × P` given by `(f.prod g) x = (f x, g x)` -/ protected def prod {M : Type u_5} {N : Type u_6} {P : Type u_7} [monoid M] [monoid N] [monoid P] (f : M →* N) (g : M →* P) : M →* N × P := mk (fun (x : M) => (coe_fn f x, coe_fn g x)) sorry sorry @[simp] theorem prod_apply {M : Type u_5} {N : Type u_6} {P : Type u_7} [monoid M] [monoid N] [monoid P] (f : M →* N) (g : M →* P) (x : M) : coe_fn (monoid_hom.prod f g) x = (coe_fn f x, coe_fn g x) := rfl @[simp] theorem fst_comp_prod {M : Type u_5} {N : Type u_6} {P : Type u_7} [monoid M] [monoid N] [monoid P] (f : M →* N) (g : M →* P) : comp (fst N P) (monoid_hom.prod f g) = f := ext fun (x : M) => rfl @[simp] theorem snd_comp_prod {M : Type u_5} {N : Type u_6} {P : Type u_7} [monoid M] [monoid N] [monoid P] (f : M →* N) (g : M →* P) : comp (snd N P) (monoid_hom.prod f g) = g := ext fun (x : M) => rfl @[simp] theorem Mathlib.add_monoid_hom.prod_unique {M : Type u_5} {N : Type u_6} {P : Type u_7} [add_monoid M] [add_monoid N] [add_monoid P] (f : M →+ N × P) : add_monoid_hom.prod (add_monoid_hom.comp (add_monoid_hom.fst N P) f) (add_monoid_hom.comp (add_monoid_hom.snd N P) f) = f := sorry /-- `prod.map` as a `monoid_hom`. -/ def Mathlib.add_monoid_hom.prod_map {M : Type u_5} {N : Type u_6} [add_monoid M] [add_monoid N] {M' : Type u_8} {N' : Type u_9} [add_monoid M'] [add_monoid N'] (f : M →+ M') (g : N →+ N') : M × N →+ M' × N' := add_monoid_hom.prod (add_monoid_hom.comp f (add_monoid_hom.fst M N)) (add_monoid_hom.comp g (add_monoid_hom.snd M N)) theorem Mathlib.add_monoid_hom.prod_map_def {M : Type u_5} {N : Type u_6} [add_monoid M] [add_monoid N] {M' : Type u_8} {N' : Type u_9} [add_monoid M'] [add_monoid N'] (f : M →+ M') (g : N →+ N') : add_monoid_hom.prod_map f g = add_monoid_hom.prod (add_monoid_hom.comp f (add_monoid_hom.fst M N)) (add_monoid_hom.comp g (add_monoid_hom.snd M N)) := rfl @[simp] theorem coe_prod_map {M : Type u_5} {N : Type u_6} [monoid M] [monoid N] {M' : Type u_8} {N' : Type u_9} [monoid M'] [monoid N'] (f : M →* M') (g : N →* N') : ⇑(prod_map f g) = prod.map ⇑f ⇑g := rfl theorem prod_comp_prod_map {M : Type u_5} {N : Type u_6} {P : Type u_7} [monoid M] [monoid N] {M' : Type u_8} {N' : Type u_9} [monoid M'] [monoid N'] [monoid P] (f : P →* M) (g : P →* N) (f' : M →* M') (g' : N →* N') : comp (prod_map f' g') (monoid_hom.prod f g) = monoid_hom.prod (comp f' f) (comp g' g) := rfl /-- Coproduct of two `monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 * g p.2`. -/ def coprod {M : Type u_5} {N : Type u_6} {P : Type u_7} [monoid M] [monoid N] [comm_monoid P] (f : M →* P) (g : N →* P) : M × N →* P := comp f (fst M N) * comp g (snd M N) @[simp] theorem coprod_apply {M : Type u_5} {N : Type u_6} {P : Type u_7} [monoid M] [monoid N] [comm_monoid P] (f : M →* P) (g : N →* P) (p : M × N) : coe_fn (coprod f g) p = coe_fn f (prod.fst p) * coe_fn g (prod.snd p) := rfl @[simp] theorem Mathlib.add_monoid_hom.coprod_comp_inl {M : Type u_5} {N : Type u_6} {P : Type u_7} [add_monoid M] [add_monoid N] [add_comm_monoid P] (f : M →+ P) (g : N →+ P) : add_monoid_hom.comp (add_monoid_hom.coprod f g) (add_monoid_hom.inl M N) = f := sorry @[simp] theorem Mathlib.add_monoid_hom.coprod_comp_inr {M : Type u_5} {N : Type u_6} {P : Type u_7} [add_monoid M] [add_monoid N] [add_comm_monoid P] (f : M →+ P) (g : N →+ P) : add_monoid_hom.comp (add_monoid_hom.coprod f g) (add_monoid_hom.inr M N) = g := sorry @[simp] theorem Mathlib.add_monoid_hom.coprod_unique {M : Type u_5} {N : Type u_6} {P : Type u_7} [add_monoid M] [add_monoid N] [add_comm_monoid P] (f : M × N →+ P) : add_monoid_hom.coprod (add_monoid_hom.comp f (add_monoid_hom.inl M N)) (add_monoid_hom.comp f (add_monoid_hom.inr M N)) = f := sorry @[simp] theorem coprod_inl_inr {M : Type u_1} {N : Type u_2} [comm_monoid M] [comm_monoid N] : coprod (inl M N) (inr M N) = id (M × N) := coprod_unique (id (M × N)) theorem comp_coprod {M : Type u_5} {N : Type u_6} {P : Type u_7} [monoid M] [monoid N] [comm_monoid P] {Q : Type u_1} [comm_monoid Q] (h : P →* Q) (f : M →* P) (g : N →* P) : comp h (coprod f g) = coprod (comp h f) (comp h g) := sorry end monoid_hom namespace mul_equiv /-- The equivalence between `M × N` and `N × M` given by swapping the components is multiplicative. -/ def prod_comm {M : Type u_5} {N : Type u_6} [monoid M] [monoid N] : M × N ≃* N × M := mk (equiv.to_fun (equiv.prod_comm M N)) (equiv.inv_fun (equiv.prod_comm M N)) sorry sorry sorry @[simp] theorem coe_prod_comm {M : Type u_5} {N : Type u_6} [monoid M] [monoid N] : ⇑prod_comm = prod.swap := rfl @[simp] theorem coe_prod_comm_symm {M : Type u_5} {N : Type u_6} [monoid M] [monoid N] : ⇑(symm prod_comm) = prod.swap := rfl /-- The monoid equivalence between units of a product of two monoids, and the product of the units of each monoid. -/ def prod_units {M : Type u_5} {N : Type u_6} [monoid M] [monoid N] : units (M × N) ≃* units M × units N := mk (⇑(monoid_hom.prod (units.map (monoid_hom.fst M N)) (units.map (monoid_hom.snd M N)))) (fun (u : units M × units N) => units.mk (↑(prod.fst u), ↑(prod.snd u)) (↑(prod.fst u⁻¹), ↑(prod.snd u⁻¹)) sorry sorry) sorry sorry sorry end Mathlib
e608faf2954c0c0c306cfd6feed7de63a75b67d7
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Init/Meta.lean
c08d16df56e66b276763d28c6c00a2bbde30be47
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
46,629
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 and Sebastian Ullrich Additional goodies for writing macros -/ prelude import Init.Data.Array.Basic import Init.Data.Option.BasicAux namespace Lean @[extern c inline "lean_box(LEAN_VERSION_MAJOR)"] private opaque version.getMajor (u : Unit) : Nat def version.major : Nat := version.getMajor () @[extern c inline "lean_box(LEAN_VERSION_MINOR)"] private opaque version.getMinor (u : Unit) : Nat def version.minor : Nat := version.getMinor () @[extern c inline "lean_box(LEAN_VERSION_PATCH)"] private opaque version.getPatch (u : Unit) : Nat def version.patch : Nat := version.getPatch () @[extern "lean_get_githash"] opaque getGithash (u : Unit) : String def githash : String := getGithash () @[extern c inline "LEAN_VERSION_IS_RELEASE"] opaque version.getIsRelease (u : Unit) : Bool def version.isRelease : Bool := version.getIsRelease () /-- Additional version description like "nightly-2018-03-11" -/ @[extern c inline "lean_mk_string(LEAN_SPECIAL_VERSION_DESC)"] opaque version.getSpecialDesc (u : Unit) : String def version.specialDesc : String := version.getSpecialDesc () def versionStringCore := toString version.major ++ "." ++ toString version.minor ++ "." ++ toString version.patch def versionString := if version.specialDesc ≠ "" then versionStringCore ++ "-" ++ version.specialDesc else if version.isRelease then versionStringCore else versionStringCore ++ ", commit " ++ githash def origin := "leanprover/lean4" def toolchain := if version.specialDesc ≠ "" then if version.isRelease then origin ++ ":" ++ versionStringCore ++ "-" ++ version.specialDesc else origin ++ ":" ++ version.specialDesc else if version.isRelease then origin ++ ":" ++ versionStringCore else "" @[extern c inline "LEAN_IS_STAGE0"] opaque Internal.isStage0 (u : Unit) : Bool /-- Valid identifier names -/ def isGreek (c : Char) : Bool := 0x391 ≤ c.val && c.val ≤ 0x3dd def isLetterLike (c : Char) : Bool := (0x3b1 ≤ c.val && c.val ≤ 0x3c9 && c.val ≠ 0x3bb) || -- Lower greek, but lambda (0x391 ≤ c.val && c.val ≤ 0x3A9 && c.val ≠ 0x3A0 && c.val ≠ 0x3A3) || -- Upper greek, but Pi and Sigma (0x3ca ≤ c.val && c.val ≤ 0x3fb) || -- Coptic letters (0x1f00 ≤ c.val && c.val ≤ 0x1ffe) || -- Polytonic Greek Extended Character Set (0x2100 ≤ c.val && c.val ≤ 0x214f) || -- Letter like block (0x1d49c ≤ c.val && c.val ≤ 0x1d59f) -- Latin letters, Script, Double-struck, Fractur def isNumericSubscript (c : Char) : Bool := 0x2080 ≤ c.val && c.val ≤ 0x2089 def isSubScriptAlnum (c : Char) : Bool := isNumericSubscript c || (0x2090 ≤ c.val && c.val ≤ 0x209c) || (0x1d62 ≤ c.val && c.val ≤ 0x1d6a) def isIdFirst (c : Char) : Bool := c.isAlpha || c = '_' || isLetterLike c def isIdRest (c : Char) : Bool := c.isAlphanum || c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c def idBeginEscape := '«' def idEndEscape := '»' def isIdBeginEscape (c : Char) : Bool := c = idBeginEscape def isIdEndEscape (c : Char) : Bool := c = idEndEscape namespace Name def getRoot : Name → Name | anonymous => anonymous | n@(str anonymous _) => n | n@(num anonymous _) => n | str n _ => getRoot n | num n _ => getRoot n @[export lean_is_inaccessible_user_name] def isInaccessibleUserName : Name → Bool | Name.str _ s => s.contains '✝' || s == "_inaccessible" | Name.num p _ => isInaccessibleUserName p | _ => false def escapePart (s : String) : Option String := if s.length > 0 && isIdFirst (s.get 0) && (s.toSubstring.drop 1).all isIdRest then s else if s.any isIdEndEscape then none else some <| idBeginEscape.toString ++ s ++ idEndEscape.toString -- NOTE: does not roundtrip even with `escape = true` if name is anonymous or contains numeric part or `idEndEscape` variable (sep : String) (escape : Bool) def toStringWithSep : Name → String | anonymous => "[anonymous]" | str anonymous s => maybeEscape s | num anonymous v => toString v | str n s => toStringWithSep n ++ sep ++ maybeEscape s | num n v => toStringWithSep n ++ sep ++ Nat.repr v where maybeEscape s := if escape then escapePart s |>.getD s else s protected def toString (n : Name) (escape := true) : String := -- never escape "prettified" inaccessible names or macro scopes or pseudo-syntax introduced by the delaborator toStringWithSep "." (escape && !n.isInaccessibleUserName && !n.hasMacroScopes && !maybePseudoSyntax) n where maybePseudoSyntax := if let .str _ s := n.getRoot then -- could be pseudo-syntax for loose bvar or universe mvar, output as is "#".isPrefixOf s || "?".isPrefixOf s else false instance : ToString Name where toString n := n.toString private def hasNum : Name → Bool | anonymous => false | num .. => true | str p .. => hasNum p protected def reprPrec (n : Name) (prec : Nat) : Std.Format := match n with | anonymous => Std.Format.text "Lean.Name.anonymous" | num p i => Repr.addAppParen ("Lean.Name.mkNum " ++ Name.reprPrec p max_prec ++ " " ++ repr i) prec | str p s => if p.hasNum then Repr.addAppParen ("Lean.Name.mkStr " ++ Name.reprPrec p max_prec ++ " " ++ repr s) prec else Std.Format.text "`" ++ n.toString instance : Repr Name where reprPrec := Name.reprPrec def capitalize : Name → Name | .str p s => .str p s.capitalize | n => n def replacePrefix : Name → Name → Name → Name | anonymous, anonymous, newP => newP | anonymous, _, _ => anonymous | n@(str p s), queryP, newP => if n == queryP then newP else Name.mkStr (p.replacePrefix queryP newP) s | n@(num p s), queryP, newP => if n == queryP then newP else Name.mkNum (p.replacePrefix queryP newP) s /-- `eraseSuffix? n s` return `n'` if `n` is of the form `n == n' ++ s`. -/ def eraseSuffix? : Name → Name → Option Name | n, anonymous => some n | str p s, str p' s' => if s == s' then eraseSuffix? p p' else none | num p s, num p' s' => if s == s' then eraseSuffix? p p' else none | _, _ => none /-- Remove macros scopes, apply `f`, and put them back -/ @[inline] def modifyBase (n : Name) (f : Name → Name) : Name := if n.hasMacroScopes then let view := extractMacroScopes n { view with name := f view.name }.review else f n @[export lean_name_append_after] def appendAfter (n : Name) (suffix : String) : Name := n.modifyBase fun | str p s => Name.mkStr p (s ++ suffix) | n => Name.mkStr n suffix @[export lean_name_append_index_after] def appendIndexAfter (n : Name) (idx : Nat) : Name := n.modifyBase fun | str p s => Name.mkStr p (s ++ "_" ++ toString idx) | n => Name.mkStr n ("_" ++ toString idx) @[export lean_name_append_before] def appendBefore (n : Name) (pre : String) : Name := n.modifyBase fun | anonymous => Name.mkStr anonymous pre | str p s => Name.mkStr p (pre ++ s) | num p n => Name.mkNum (Name.mkStr p pre) n protected theorem beq_iff_eq {m n : Name} : m == n ↔ m = n := by show m.beq n ↔ _ induction m generalizing n <;> cases n <;> simp_all [Name.beq, And.comm] instance : LawfulBEq Name where eq_of_beq := Name.beq_iff_eq.1 rfl := Name.beq_iff_eq.2 rfl instance : DecidableEq Name := fun a b => if h : a == b then .isTrue (by simp_all) else .isFalse (by simp_all) end Name structure NameGenerator where namePrefix : Name := `_uniq idx : Nat := 1 deriving Inhabited namespace NameGenerator @[inline] def curr (g : NameGenerator) : Name := Name.mkNum g.namePrefix g.idx @[inline] def next (g : NameGenerator) : NameGenerator := { g with idx := g.idx + 1 } @[inline] def mkChild (g : NameGenerator) : NameGenerator × NameGenerator := ({ namePrefix := Name.mkNum g.namePrefix g.idx, idx := 1 }, { g with idx := g.idx + 1 }) end NameGenerator class MonadNameGenerator (m : Type → Type) where getNGen : m NameGenerator setNGen : NameGenerator → m Unit export MonadNameGenerator (getNGen setNGen) def mkFreshId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m Name := do let ngen ← getNGen let r := ngen.curr setNGen ngen.next pure r instance monadNameGeneratorLift (m n : Type → Type) [MonadLift m n] [MonadNameGenerator m] : MonadNameGenerator n := { getNGen := liftM (getNGen : m _), setNGen := fun ngen => liftM (setNGen ngen : m _) } namespace Syntax deriving instance Repr for Syntax.Preresolved deriving instance Repr for Syntax deriving instance Repr for TSyntax abbrev Term := TSyntax `term abbrev Command := TSyntax `command protected abbrev Level := TSyntax `level protected abbrev Tactic := TSyntax `tactic abbrev Prec := TSyntax `prec abbrev Prio := TSyntax `prio abbrev Ident := TSyntax identKind abbrev StrLit := TSyntax strLitKind abbrev CharLit := TSyntax charLitKind abbrev NameLit := TSyntax nameLitKind abbrev ScientificLit := TSyntax scientificLitKind abbrev NumLit := TSyntax numLitKind end Syntax export Syntax (Term Command Prec Prio Ident StrLit CharLit NameLit ScientificLit NumLit) namespace TSyntax instance : Coe (TSyntax [k]) (TSyntax (k :: ks)) where coe stx := ⟨stx⟩ instance : Coe (TSyntax ks) (TSyntax (k' :: ks)) where coe stx := ⟨stx⟩ instance : Coe Ident Term where coe s := ⟨s.raw⟩ instance : CoeDep Term ⟨Syntax.ident info ss n res⟩ Ident where coe := ⟨Syntax.ident info ss n res⟩ instance : Coe StrLit Term where coe s := ⟨s.raw⟩ instance : Coe NameLit Term where coe s := ⟨s.raw⟩ instance : Coe ScientificLit Term where coe s := ⟨s.raw⟩ instance : Coe NumLit Term where coe s := ⟨s.raw⟩ instance : Coe CharLit Term where coe s := ⟨s.raw⟩ instance : Coe Ident Syntax.Level where coe s := ⟨s.raw⟩ instance : Coe NumLit Prio where coe s := ⟨s.raw⟩ instance : Coe NumLit Prec where coe s := ⟨s.raw⟩ namespace Compat scoped instance : CoeTail Syntax (TSyntax k) where coe s := ⟨s⟩ scoped instance : CoeTail (Array Syntax) (TSyntaxArray k) where coe := .mk end Compat end TSyntax namespace Syntax deriving instance BEq for Syntax.Preresolved /-- Compare syntax structures modulo source info. -/ partial def structEq : Syntax → Syntax → Bool | Syntax.missing, Syntax.missing => true | Syntax.node _ k args, Syntax.node _ k' args' => k == k' && args.isEqv args' structEq | Syntax.atom _ val, Syntax.atom _ val' => val == val' | Syntax.ident _ rawVal val preresolved, Syntax.ident _ rawVal' val' preresolved' => rawVal == rawVal' && val == val' && preresolved == preresolved' | _, _ => false instance : BEq Lean.Syntax := ⟨structEq⟩ instance : BEq (Lean.TSyntax k) := ⟨(·.raw == ·.raw)⟩ partial def getTailInfo? : Syntax → Option SourceInfo | atom info _ => info | ident info .. => info | node SourceInfo.none _ args => args.findSomeRev? getTailInfo? | node info _ _ => info | _ => none def getTailInfo (stx : Syntax) : SourceInfo := stx.getTailInfo?.getD SourceInfo.none def getTrailingSize (stx : Syntax) : Nat := match stx.getTailInfo? with | some (SourceInfo.original (trailing := trailing) ..) => trailing.bsize | _ => 0 /-- Return substring of original input covering `stx`. Result is meaningful only if all involved `SourceInfo.original`s refer to the same string (as is the case after parsing). -/ def getSubstring? (stx : Syntax) (withLeading := true) (withTrailing := true) : Option Substring := match stx.getHeadInfo, stx.getTailInfo with | SourceInfo.original lead startPos _ _, SourceInfo.original _ _ trail stopPos => some { str := lead.str startPos := if withLeading then lead.startPos else startPos stopPos := if withTrailing then trail.stopPos else stopPos } | _, _ => none @[specialize] private partial def updateLast {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if i == 0 then none else let i := i - 1 let v := a[i]! match f v with | some v => some <| a.set! i v | none => updateLast a f i partial def setTailInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node info k args => match updateLast args (setTailInfoAux info) args.size with | some args => some <| node info k args | none => none | _ => none def setTailInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setTailInfoAux info stx with | some stx => stx | none => stx def unsetTrailing (stx : Syntax) : Syntax := match stx.getTailInfo with | SourceInfo.original lead pos _ endPos => stx.setTailInfo (SourceInfo.original lead pos "".toSubstring endPos) | _ => stx @[specialize] private partial def updateFirst {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if h : i < a.size then let v := a[i] match f v with | some v => some <| a.set ⟨i, h⟩ v | none => updateFirst a f (i+1) else none partial def setHeadInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node i k args => match updateFirst args (setHeadInfoAux info) 0 with | some args => some <| node i k args | _ => none | _ => none def setHeadInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setHeadInfoAux info stx with | some stx => stx | none => stx def setInfo (info : SourceInfo) : Syntax → Syntax | atom _ val => atom info val | ident _ rawVal val pre => ident info rawVal val pre | node _ kind args => node info kind args | missing => missing /-- Return the first atom/identifier that has position information -/ partial def getHead? : Syntax → Option Syntax | stx@(atom info ..) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node SourceInfo.none _ args => args.findSome? getHead? | stx@(node ..) => stx | _ => none def copyHeadTailInfoFrom (target source : Syntax) : Syntax := target.setHeadInfo source.getHeadInfo |>.setTailInfo source.getTailInfo /-- Ensure head position is synthetic. The server regards syntax as "original" only if both head and tail info are `original`. -/ def mkSynthetic (stx : Syntax) : Syntax := stx.setHeadInfo (SourceInfo.fromRef stx) end Syntax /-- Use the head atom/identifier of the current `ref` as the `ref` -/ @[inline] def withHeadRefOnly {m : Type → Type} [Monad m] [MonadRef m] {α} (x : m α) : m α := do match (← getRef).getHead? with | none => x | some ref => withRef ref x @[inline] def mkNode (k : SyntaxNodeKind) (args : Array Syntax) : TSyntax k := ⟨Syntax.node SourceInfo.none k args⟩ /-- Syntax objects for a Lean module. -/ structure Module where header : Syntax commands : Array Syntax /-- Expand macros in the given syntax. A node with kind `k` is visited only if `p k` is true. Note that the default value for `p` returns false for `by ...` nodes. This is a "hack". The tactic framework abuses the macro system to implement extensible tactics. For example, one can define ```lean syntax "my_trivial" : tactic -- extensible tactic macro_rules | `(tactic| my_trivial) => `(tactic| decide) macro_rules | `(tactic| my_trivial) => `(tactic| assumption) ``` When the tactic evaluator finds the tactic `my_trivial`, it tries to evaluate the `macro_rule` expansions until one "works", i.e., the macro expansion is evaluated without producing an exception. We say this solution is a bit hackish because the term elaborator may invoke `expandMacros` with `(p := fun _ => true)`, and expand the tactic macros as just macros. In the example above, `my_trivial` would be replaced with `assumption`, `decide` would not be tried if `assumption` fails at tactic evaluation time. We are considering two possible solutions for this issue: 1- A proper extensible tactic feature that does not rely on the macro system. 2- Typed macros that know the syntax categories they're working in. Then, we would be able to select which syntatic categories are expanded by `expandMacros`. -/ partial def expandMacros (stx : Syntax) (p : SyntaxNodeKind → Bool := fun k => k != `Lean.Parser.Term.byTactic) : MacroM Syntax := withRef stx do match stx with | .node info k args => do if p k then match (← expandMacro? stx) with | some stxNew => expandMacros stxNew | none => do let args ← Macro.withIncRecDepth stx <| args.mapM expandMacros return .node info k args else return stx | stx => return stx /-! # Helper functions for processing Syntax programmatically -/ /-- Create an identifier copying the position from `src`. To refer to a specific constant, use `mkCIdentFrom` instead. -/ def mkIdentFrom (src : Syntax) (val : Name) (canonical := false) : Ident := ⟨Syntax.ident (SourceInfo.fromRef src canonical) (toString val).toSubstring val []⟩ def mkIdentFromRef [Monad m] [MonadRef m] (val : Name) (canonical := false) : m Ident := do return mkIdentFrom (← getRef) val canonical /-- Create an identifier referring to a constant `c` copying the position from `src`. This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally be captured. -/ def mkCIdentFrom (src : Syntax) (c : Name) (canonical := false) : Ident := -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend let id := addMacroScope `_internal c reservedMacroScope ⟨Syntax.ident (SourceInfo.fromRef src canonical) (toString id).toSubstring id [.decl c []]⟩ def mkCIdentFromRef [Monad m] [MonadRef m] (c : Name) (canonical := false) : m Syntax := do return mkCIdentFrom (← getRef) c canonical def mkCIdent (c : Name) : Ident := mkCIdentFrom Syntax.missing c @[export lean_mk_syntax_ident] def mkIdent (val : Name) : Ident := ⟨Syntax.ident SourceInfo.none (toString val).toSubstring val []⟩ @[inline] def mkNullNode (args : Array Syntax := #[]) : Syntax := mkNode nullKind args @[inline] def mkGroupNode (args : Array Syntax := #[]) : Syntax := mkNode groupKind args def mkSepArray (as : Array Syntax) (sep : Syntax) : Array Syntax := Id.run do let mut i := 0 let mut r := #[] for a in as do if i > 0 then r := r.push sep |>.push a else r := r.push a i := i + 1 return r def mkOptionalNode (arg : Option Syntax) : Syntax := match arg with | some arg => mkNullNode #[arg] | none => mkNullNode #[] def mkHole (ref : Syntax) (canonical := false) : Syntax := mkNode `Lean.Parser.Term.hole #[mkAtomFrom ref "_" canonical] namespace Syntax def mkSep (a : Array Syntax) (sep : Syntax) : Syntax := mkNullNode <| mkSepArray a sep def SepArray.ofElems {sep} (elems : Array Syntax) : SepArray sep := ⟨mkSepArray elems (if sep.isEmpty then mkNullNode else mkAtom sep)⟩ def SepArray.ofElemsUsingRef [Monad m] [MonadRef m] {sep} (elems : Array Syntax) : m (SepArray sep) := do let ref ← getRef; return ⟨mkSepArray elems (if sep.isEmpty then mkNullNode else mkAtomFrom ref sep)⟩ instance : Coe (Array Syntax) (SepArray sep) where coe := SepArray.ofElems instance : Coe (TSyntaxArray k) (TSepArray k sep) where coe a := ⟨mkSepArray a.raw (mkAtom sep)⟩ /-- Create syntax representing a Lean term application, but avoid degenerate empty applications. -/ def mkApp (fn : Term) : (args : TSyntaxArray `term) → Term | #[] => fn | args => ⟨mkNode `Lean.Parser.Term.app #[fn, mkNullNode args.raw]⟩ def mkCApp (fn : Name) (args : TSyntaxArray `term) : Term := mkApp (mkCIdent fn) args def mkLit (kind : SyntaxNodeKind) (val : String) (info := SourceInfo.none) : TSyntax kind := let atom : Syntax := Syntax.atom info val mkNode kind #[atom] def mkStrLit (val : String) (info := SourceInfo.none) : StrLit := mkLit strLitKind (String.quote val) info def mkNumLit (val : String) (info := SourceInfo.none) : NumLit := mkLit numLitKind val info def mkScientificLit (val : String) (info := SourceInfo.none) : TSyntax scientificLitKind := mkLit scientificLitKind val info def mkNameLit (val : String) (info := SourceInfo.none) : NameLit := mkLit nameLitKind val info /-! Recall that we don't have special Syntax constructors for storing numeric and string atoms. The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or different ways of representing them. So, our atoms contain just the parsed string. The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded in binary, octal, decimal and hexadecimal format. `isNatLit` implements a "decoder" for Syntax objects representing these numerals. -/ private partial def decodeBinLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if c == '0' then decodeBinLitAux s (s.next i) (2*val) else if c == '1' then decodeBinLitAux s (s.next i) (2*val + 1) else none private partial def decodeOctalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '7' then decodeOctalLitAux s (s.next i) (8*val + c.toNat - '0'.toNat) else none private def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat × String.Pos) := let c := s.get i let i := s.next i if '0' ≤ c && c ≤ '9' then some (c.toNat - '0'.toNat, i) else if 'a' ≤ c && c ≤ 'f' then some (10 + c.toNat - 'a'.toNat, i) else if 'A' ≤ c && c ≤ 'F' then some (10 + c.toNat - 'A'.toNat, i) else none private partial def decodeHexLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else match decodeHexDigit s i with | some (d, i) => decodeHexLitAux s i (16*val + d) | none => none private partial def decodeDecimalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeDecimalLitAux s (s.next i) (10*val + c.toNat - '0'.toNat) else none def decodeNatLitVal? (s : String) : Option Nat := let len := s.length if len == 0 then none else let c := s.get 0 if c == '0' then if len == 1 then some 0 else let c := s.get ⟨1⟩ if c == 'x' || c == 'X' then decodeHexLitAux s ⟨2⟩ 0 else if c == 'b' || c == 'B' then decodeBinLitAux s ⟨2⟩ 0 else if c == 'o' || c == 'O' then decodeOctalLitAux s ⟨2⟩ 0 else if c.isDigit then decodeDecimalLitAux s 0 0 else none else if c.isDigit then decodeDecimalLitAux s 0 0 else none def isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String := match stx with | Syntax.node _ k args => if k == litKind && args.size == 1 then match args.get! 0 with | (Syntax.atom _ val) => some val | _ => none else none | _ => none private def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat := match isLit? litKind stx with | some val => decodeNatLitVal? val | _ => none def isNatLit? (s : Syntax) : Option Nat := isNatLitAux numLitKind s def isFieldIdx? (s : Syntax) : Option Nat := isNatLitAux fieldIdxKind s /-- Decodes a 'scientific number' string which is consumed by the `OfScientific` class. Takes as input a string such as `123`, `123.456e7` and returns a triple `(n, sign, e)` with value given by `n * 10^-e` if `sign` else `n * 10^e`. -/ partial def decodeScientificLitVal? (s : String) : Option (Nat × Bool × Nat) := let len := s.length if len == 0 then none else let c := s.get 0 if c.isDigit then decode 0 0 else none where decodeAfterExp (i : String.Pos) (val : Nat) (e : Nat) (sign : Bool) (exp : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then if sign then some (val, sign, exp + e) else if exp >= e then some (val, sign, exp - e) else some (val, true, e - exp) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterExp (s.next i) val e sign (10*exp + c.toNat - '0'.toNat) else none decodeExp (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if c == '-' then decodeAfterExp (s.next i) val e true 0 else if c == '+' then decodeAfterExp (s.next i) val e false 0 else decodeAfterExp i val e false 0 decodeAfterDot (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then some (val, true, e) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterDot (s.next i) (10*val + c.toNat - '0'.toNat) (e+1) else if c == 'e' || c == 'E' then decodeExp (s.next i) val e else none decode (i : String.Pos) (val : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if '0' ≤ c && c ≤ '9' then decode (s.next i) (10*val + c.toNat - '0'.toNat) else if c == '.' then decodeAfterDot (s.next i) val 0 else if c == 'e' || c == 'E' then decodeExp (s.next i) val 0 else none def isScientificLit? (stx : Syntax) : Option (Nat × Bool × Nat) := match isLit? scientificLitKind stx with | some val => decodeScientificLitVal? val | _ => none def isIdOrAtom? : Syntax → Option String | Syntax.atom _ val => some val | Syntax.ident _ rawVal _ _ => some rawVal.toString | _ => none def toNat (stx : Syntax) : Nat := match stx.isNatLit? with | some val => val | none => 0 def decodeQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := do let c := s.get i let i := s.next i if c == '\\' then pure ('\\', i) else if c = '\"' then pure ('\"', i) else if c = '\'' then pure ('\'', i) else if c = 'r' then pure ('\r', i) else if c = 'n' then pure ('\n', i) else if c = 't' then pure ('\t', i) else if c = 'x' then let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i pure (Char.ofNat (16*d₁ + d₂), i) else if c = 'u' then do let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i let (d₃, i) ← decodeHexDigit s i let (d₄, i) ← decodeHexDigit s i pure (Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄), i) else none partial def decodeStrLitAux (s : String) (i : String.Pos) (acc : String) : Option String := do let c := s.get i let i := s.next i if c == '\"' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeQuotedChar s i decodeStrLitAux s i (acc.push c) else decodeStrLitAux s i (acc.push c) def decodeStrLit (s : String) : Option String := decodeStrLitAux s ⟨1⟩ "" def isStrLit? (stx : Syntax) : Option String := match isLit? strLitKind stx with | some val => decodeStrLit val | _ => none def decodeCharLit (s : String) : Option Char := do let c := s.get ⟨1⟩ if c == '\\' then do let (c, _) ← decodeQuotedChar s ⟨2⟩ pure c else pure c def isCharLit? (stx : Syntax) : Option Char := match isLit? charLitKind stx with | some val => decodeCharLit val | _ => none private partial def splitNameLitAux (ss : Substring) (acc : List Substring) : List Substring := let splitRest (ss : Substring) (acc : List Substring) : List Substring := if ss.front == '.' then splitNameLitAux (ss.drop 1) acc else if ss.isEmpty then acc else [] if ss.isEmpty then [] else let curr := ss.front if isIdBeginEscape curr then let escapedPart := ss.takeWhile (!isIdEndEscape ·) let escapedPart := { escapedPart with stopPos := ss.stopPos.min (escapedPart.str.next escapedPart.stopPos) } if !isIdEndEscape (escapedPart.get <| escapedPart.prev ⟨escapedPart.bsize⟩) then [] else splitRest (ss.extract ⟨escapedPart.bsize⟩ ⟨ss.bsize⟩) (escapedPart :: acc) else if isIdFirst curr then let idPart := ss.takeWhile isIdRest splitRest (ss.extract ⟨idPart.bsize⟩ ⟨ss.bsize⟩) (idPart :: acc) else if curr.isDigit then let idPart := ss.takeWhile Char.isDigit splitRest (ss.extract ⟨idPart.bsize⟩ ⟨ss.bsize⟩) (idPart :: acc) else [] /-- Split a name literal (without the backtick) into its dot-separated components. For example, `foo.bla.«bo.o»` ↦ `["foo", "bla", "«bo.o»"]`. If the literal cannot be parsed, return `[]`. -/ def splitNameLit (ss : Substring) : List Substring := splitNameLitAux ss [] |>.reverse def decodeNameLit (s : String) : Option Name := if s.get 0 == '`' then match splitNameLitAux (s.toSubstring.drop 1) [] with | [] => none | comps => some <| comps.foldr (init := Name.anonymous) fun comp n => let comp := comp.toString if isIdBeginEscape comp.front then Name.mkStr n (comp.drop 1 |>.dropRight 1) else if comp.front.isDigit then if let some k := decodeNatLitVal? comp then Name.mkNum n k else unreachable! else Name.mkStr n comp else none def isNameLit? (stx : Syntax) : Option Name := match isLit? nameLitKind stx with | some val => decodeNameLit val | _ => none def hasArgs : Syntax → Bool | Syntax.node _ _ args => args.size > 0 | _ => false def isAtom : Syntax → Bool | atom _ _ => true | _ => false def isToken (token : String) : Syntax → Bool | atom _ val => val.trim == token.trim | _ => false def isNone (stx : Syntax) : Bool := match stx with | Syntax.node _ k args => k == nullKind && args.size == 0 -- when elaborating partial syntax trees, it's reasonable to interpret missing parts as `none` | Syntax.missing => true | _ => false def getOptionalIdent? (stx : Syntax) : Option Name := match stx.getOptional? with | some stx => some stx.getId | none => none partial def findAux (p : Syntax → Bool) : Syntax → Option Syntax | stx@(Syntax.node _ _ args) => if p stx then some stx else args.findSome? (findAux p) | stx => if p stx then some stx else none def find? (stx : Syntax) (p : Syntax → Bool) : Option Syntax := findAux p stx end Syntax namespace TSyntax def getNat (s : NumLit) : Nat := s.raw.isNatLit?.getD 0 def getId (s : Ident) : Name := s.raw.getId def getScientific (s : ScientificLit) : Nat × Bool × Nat := s.raw.isScientificLit?.getD (0, false, 0) def getString (s : StrLit) : String := s.raw.isStrLit?.getD "" def getChar (s : CharLit) : Char := s.raw.isCharLit?.getD default def getName (s : NameLit) : Name := s.raw.isNameLit?.getD .anonymous namespace Compat scoped instance : CoeTail (Array Syntax) (Syntax.TSepArray k sep) where coe a := (a : TSyntaxArray k) end Compat end TSyntax /-- Reflect a runtime datum back to surface syntax (best-effort). -/ class Quote (α : Type) (k : SyntaxNodeKind := `term) where quote : α → TSyntax k export Quote (quote) instance [Quote α k] [CoeHTCT (TSyntax k) (TSyntax [k'])] : Quote α k' := ⟨fun a => quote (k := k) a⟩ instance : Quote Term := ⟨id⟩ instance : Quote Bool := ⟨fun | true => mkCIdent ``Bool.true | false => mkCIdent ``Bool.false⟩ instance : Quote String strLitKind := ⟨Syntax.mkStrLit⟩ instance : Quote Nat numLitKind := ⟨fun n => Syntax.mkNumLit <| toString n⟩ instance : Quote Substring := ⟨fun s => Syntax.mkCApp ``String.toSubstring' #[quote s.toString]⟩ -- in contrast to `Name.toString`, we can, and want to be, precise here private def getEscapedNameParts? (acc : List String) : Name → Option (List String) | Name.anonymous => if acc.isEmpty then none else some acc | Name.str n s => do let s ← Name.escapePart s getEscapedNameParts? (s::acc) n | Name.num _ _ => none def quoteNameMk : Name → Term | .anonymous => mkCIdent ``Name.anonymous | .str n s => Syntax.mkCApp ``Name.mkStr #[quoteNameMk n, quote s] | .num n i => Syntax.mkCApp ``Name.mkNum #[quoteNameMk n, quote i] instance : Quote Name `term where quote n := match getEscapedNameParts? [] n with | some ss => ⟨mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit ("`" ++ ".".intercalate ss)]⟩ | none => ⟨quoteNameMk n⟩ instance [Quote α `term] [Quote β `term] : Quote (α × β) `term where quote | ⟨a, b⟩ => Syntax.mkCApp ``Prod.mk #[quote a, quote b] private def quoteList [Quote α `term] : List α → Term | [] => mkCIdent ``List.nil | (x::xs) => Syntax.mkCApp ``List.cons #[quote x, quoteList xs] instance [Quote α `term] : Quote (List α) `term where quote := quoteList private def quoteArray [Quote α `term] (xs : Array α) : Term := if xs.size <= 8 then go 0 #[] else Syntax.mkCApp ``List.toArray #[quote xs.toList] where go (i : Nat) (args : Array Term) : Term := if h : i < xs.size then go (i+1) (args.push (quote xs[i])) else Syntax.mkCApp (Name.mkStr2 "Array" ("mkArray" ++ toString xs.size)) args termination_by go i _ => xs.size - i instance [Quote α `term] : Quote (Array α) `term where quote := quoteArray instance Option.hasQuote {α : Type} [Quote α `term] : Quote (Option α) `term where quote | none => mkIdent ``none | (some x) => Syntax.mkCApp ``some #[quote x] /-- Evaluator for `prec` DSL -/ def evalPrec (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prec| $num:num) => return num.getNat | _ => Macro.throwErrorAt stx "unexpected precedence" macro_rules | `(prec| $a + $b) => do `(prec| $(quote <| (← evalPrec a) + (← evalPrec b)):num) macro_rules | `(prec| $a - $b) => do `(prec| $(quote <| (← evalPrec a) - (← evalPrec b)):num) macro "eval_prec " p:prec:max : term => return quote (k := `term) (← evalPrec p) /-- Evaluator for `prio` DSL -/ def evalPrio (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prio| $num:num) => return num.getNat | _ => Macro.throwErrorAt stx "unexpected priority" macro_rules | `(prio| $a + $b) => do `(prio| $(quote <| (← evalPrio a) + (← evalPrio b)):num) macro_rules | `(prio| $a - $b) => do `(prio| $(quote <| (← evalPrio a) - (← evalPrio b)):num) macro "eval_prio " p:prio:max : term => return quote (k := `term) (← evalPrio p) def evalOptPrio : Option (TSyntax `prio) → MacroM Nat | some prio => evalPrio prio | none => return 1000 -- TODO: FIX back eval_prio default end Lean namespace Array abbrev getSepElems := @getEvenElems open Lean private partial def filterSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a[i] if (← p stx) then if acc.isEmpty then filterSepElemsMAux a p (i+2) (acc.push stx) else if hz : i ≠ 0 then have : i.pred < i := Nat.pred_lt hz have : i.pred < a.size := Nat.lt_trans this h let sepStx := a[i.pred] filterSepElemsMAux a p (i+2) ((acc.push sepStx).push stx) else filterSepElemsMAux a p (i+2) (acc.push stx) else filterSepElemsMAux a p (i+2) acc else pure acc def filterSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : m (Array Syntax) := filterSepElemsMAux a p 0 #[] def filterSepElems (a : Array Syntax) (p : Syntax → Bool) : Array Syntax := Id.run <| a.filterSepElemsM p private partial def mapSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a[i] if i % 2 == 0 then do let stx ← f stx mapSepElemsMAux a f (i+1) (acc.push stx) else mapSepElemsMAux a f (i+1) (acc.push stx) else pure acc def mapSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : m (Array Syntax) := mapSepElemsMAux a f 0 #[] def mapSepElems (a : Array Syntax) (f : Syntax → Syntax) : Array Syntax := Id.run <| a.mapSepElemsM f end Array namespace Lean.Syntax def SepArray.getElems (sa : SepArray sep) : Array Syntax := sa.elemsAndSeps.getSepElems def TSepArray.getElems (sa : TSepArray k sep) : TSyntaxArray k := .mk sa.elemsAndSeps.getSepElems def TSepArray.push (sa : TSepArray k sep) (e : TSyntax k) : TSepArray k sep := if sa.elemsAndSeps.isEmpty then { elemsAndSeps := #[e] } else { elemsAndSeps := sa.elemsAndSeps.push (mkAtom sep) |>.push e } instance : EmptyCollection (SepArray sep) where emptyCollection := ⟨∅⟩ instance : EmptyCollection (TSepArray sep k) where emptyCollection := ⟨∅⟩ instance : CoeOut (SepArray sep) (Array Syntax) where coe := SepArray.getElems instance : CoeOut (TSepArray k sep) (TSyntaxArray k) where coe := TSepArray.getElems instance [Coe (TSyntax k) (TSyntax k')] : Coe (TSyntaxArray k) (TSyntaxArray k') where coe a := a.map Coe.coe instance : CoeOut (TSyntaxArray k) (Array Syntax) where coe a := a.raw instance : Coe Ident (TSyntax `Lean.Parser.Command.declId) where coe id := mkNode _ #[id, mkNullNode #[]] instance : Coe (Lean.Term) (Lean.TSyntax `Lean.Parser.Term.funBinder) where coe stx := ⟨stx⟩ end Lean.Syntax set_option linter.unusedVariables.funArgs false in /-- Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses the given tactic. Like `optParam`, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ abbrev autoParam.{u} (α : Sort u) (tactic : Lean.Syntax) : Sort u := α /-! # Helper functions for manipulating interpolated strings -/ namespace Lean.Syntax private def decodeInterpStrQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := do match decodeQuotedChar s i with | some r => some r | none => let c := s.get i let i := s.next i if c == '{' then pure ('{', i) else none private partial def decodeInterpStrLit (s : String) : Option String := let rec loop (i : String.Pos) (acc : String) : Option String := let c := s.get i let i := s.next i if c == '\"' || c == '{' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeInterpStrQuotedChar s i loop i (acc.push c) else loop i (acc.push c) loop ⟨1⟩ "" partial def isInterpolatedStrLit? (stx : Syntax) : Option String := match isLit? interpolatedStrLitKind stx with | none => none | some val => decodeInterpStrLit val def getSepArgs (stx : Syntax) : Array Syntax := stx.getArgs.getSepElems end Syntax namespace TSyntax def expandInterpolatedStrChunks (chunks : Array Syntax) (mkAppend : Syntax → Syntax → MacroM Syntax) (mkElem : Syntax → MacroM Syntax) : MacroM Syntax := do let mut i := 0 let mut result := Syntax.missing for elem in chunks do let elem ← match elem.isInterpolatedStrLit? with | none => mkElem elem | some str => mkElem (Syntax.mkStrLit str) if i == 0 then result := elem else result ← mkAppend result elem i := i+1 return result open TSyntax.Compat in def expandInterpolatedStr (interpStr : TSyntax interpolatedStrKind) (type : Term) (toTypeFn : Term) : MacroM Term := do let r ← expandInterpolatedStrChunks interpStr.raw.getArgs (fun a b => `($a ++ $b)) (fun a => `($toTypeFn $a)) `(($r : $type)) end TSyntax namespace Meta inductive TransparencyMode where | all | default | reducible | instances deriving Inhabited, BEq, Repr inductive EtaStructMode where /-- Enable eta for structure and classes. -/ | all /-- Enable eta only for structures that are not classes. -/ | notClasses /-- Disable eta for structures and classes. -/ | none deriving Inhabited, BEq, Repr namespace DSimp structure Config where zeta : Bool := true beta : Bool := true eta : Bool := true etaStruct : EtaStructMode := .all iota : Bool := true proj : Bool := true decide : Bool := false autoUnfold : Bool := false deriving Inhabited, BEq, Repr end DSimp namespace Simp def defaultMaxSteps := 100000 structure Config where maxSteps : Nat := defaultMaxSteps maxDischargeDepth : Nat := 2 contextual : Bool := false memoize : Bool := true singlePass : Bool := false zeta : Bool := true beta : Bool := true eta : Bool := true etaStruct : EtaStructMode := .all iota : Bool := true proj : Bool := true decide : Bool := true arith : Bool := false autoUnfold : Bool := false /-- If `dsimp := true`, then switches to `dsimp` on dependent arguments where there is no congruence theorem that allows `simp` to visit them. If `dsimp := false`, then argument is not visited. -/ dsimp : Bool := true deriving Inhabited, BEq, Repr -- Configuration object for `simp_all` structure ConfigCtx extends Config where contextual := true def neutralConfig : Simp.Config := { zeta := false beta := false eta := false iota := false proj := false decide := false arith := false autoUnfold := false } end Simp namespace Rewrite structure Config where transparency : TransparencyMode := TransparencyMode.reducible offsetCnstrs : Bool := true end Rewrite end Meta namespace Parser.Tactic /-- `erw [rules]` is a shorthand for `rw (config := { transparency := .default }) [rules]`. This does rewriting up to unfolding of regular definitions (by comparison to regular `rw` which only unfolds `@[reducible]` definitions). -/ macro "erw " s:rwRuleSeq loc:(location)? : tactic => `(tactic| rw (config := { transparency := .default }) $s $(loc)?) syntax simpAllKind := atomic("(" &"all") " := " &"true" ")" syntax dsimpKind := atomic("(" &"dsimp") " := " &"true" ")" macro (name := declareSimpLikeTactic) doc?:(docComment)? "declare_simp_like_tactic" opt:((simpAllKind <|> dsimpKind)?) tacName:ident tacToken:str updateCfg:term : command => do let (kind, tkn, stx) ← if opt.raw.isNone then pure (← `(``simp), ← `("simp"), ← `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&" only")? (" [" (simpStar <|> simpErase <|> simpLemma),* "]")? (location)? : tactic)) else if opt.raw[0].getKind == ``simpAllKind then pure (← `(``simpAll), ← `("simp_all"), ← `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&" only")? (" [" (simpErase <|> simpLemma),* "]")? : tactic)) else pure (← `(``dsimp), ← `("dsimp"), ← `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&" only")? (" [" (simpErase <|> simpLemma),* "]")? (location)? : tactic)) `($stx:command @[macro $tacName] def expandSimp : Macro := fun s => do let c ← match s[1][0] with | `(config| (config := $$c)) => `(config| (config := $updateCfg $$c)) | _ => `(config| (config := $updateCfg {})) let s := s.setKind $kind let s := s.setArg 0 (mkAtomFrom s[0] $tkn (canonical := true)) let r := s.setArg 1 (mkNullNode #[c]) return r) /-- `simp!` is shorthand for `simp` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic simpAutoUnfold "simp! " fun (c : Lean.Meta.Simp.Config) => { c with autoUnfold := true } /-- `simp_arith` is shorthand for `simp` with `arith := true`. This enables the use of normalization by linear arithmetic. -/ declare_simp_like_tactic simpArith "simp_arith " fun (c : Lean.Meta.Simp.Config) => { c with arith := true } /-- `simp_arith!` is shorthand for `simp_arith` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic simpArithAutoUnfold "simp_arith! " fun (c : Lean.Meta.Simp.Config) => { c with arith := true, autoUnfold := true } /-- `simp_all!` is shorthand for `simp_all` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic (all := true) simpAllAutoUnfold "simp_all! " fun (c : Lean.Meta.Simp.ConfigCtx) => { c with autoUnfold := true } /-- `simp_all_arith` combines the effects of `simp_all` and `simp_arith`. -/ declare_simp_like_tactic (all := true) simpAllArith "simp_all_arith " fun (c : Lean.Meta.Simp.ConfigCtx) => { c with arith := true } /-- `simp_all_arith!` combines the effects of `simp_all`, `simp_arith` and `simp!`. -/ declare_simp_like_tactic (all := true) simpAllArithAutoUnfold "simp_all_arith! " fun (c : Lean.Meta.Simp.ConfigCtx) => { c with arith := true, autoUnfold := true } /-- `dsimp!` is shorthand for `dsimp` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic (dsimp := true) dsimpAutoUnfold "dsimp! " fun (c : Lean.Meta.DSimp.Config) => { c with autoUnfold := true } end Parser.Tactic end Lean
39427462b2f969d4de21be9300e0e9bef0a958df
c45b34bfd44d8607a2e8762c926e3cfaa7436201
/uexp/src/uexp/rules/removeSemiJoin.lean
f78429b5673dc56d0faf93e5d1c5fb573c5df355
[ "BSD-2-Clause" ]
permissive
Shamrock-Frost/Cosette
b477c442c07e45082348a145f19ebb35a7f29392
24cbc4adebf627f13f5eac878f04ffa20d1209af
refs/heads/master
1,619,721,304,969
1,526,082,841,000
1,526,082,841,000
121,695,605
1
0
null
1,518,737,210,000
1,518,737,210,000
null
UTF-8
Lean
false
false
1,839
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..ucongr import ..TDP set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int theorem rule: forall ( Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT1 (right⋅left⋅emp_ename) FROM1 (product (table rel_emp) (table rel_dept)) WHERE (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅dept_deptno)))) :SQL Γ _) = denoteSQL ((SELECT1 (right⋅left⋅emp_ename) FROM1 (product (table rel_emp) (table rel_dept)) WHERE (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅dept_deptno)))) :SQL Γ _) := begin intros, unfold_all_denotations, funext, try {simp}, try {TDP' ucongr}, end
618c76667d92591f466ccc8c3e2c0a8f1675d2b0
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Lean/Elab/AutoBound.lean
d7313ea277a76bb3eff3e4a10deca350437210fe
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,286
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.Data.Options /- Basic support for auto bound implicit local names -/ namespace Lean.Elab builtin_initialize registerOption `autoBoundImplicitLocal { defValue := true group := "" descr := "Unbound local variables in declaration headers become implicit arguments if they are a lower case or greek letter followed by numeric digits. For example, `def f (x : Vector α n) : Vector α n :=` automatically introduces the implicit variables {α n}" } def getAutoBoundImplicitLocalOption (opts : Options) : Bool := opts.get `autoBoundImplicitLocal true private def allNumeral (s : Substring) : Bool := s.all fun c => c.isDigit || isNumericSubscript c def isValidAutoBoundImplicitName (n : Name) : Bool := match n.eraseMacroScopes with | Name.str Name.anonymous s _ => s.length > 0 && (isGreek s[0] || s[0].isLower) && allNumeral (s.toSubstring.drop 1) | _ => false def isValidAutoBoundLevelName (n : Name) : Bool := match n.eraseMacroScopes with | Name.str Name.anonymous s _ => s.length > 0 && s[0].isLower && allNumeral (s.toSubstring.drop 1) | _ => false end Lean.Elab
328109c29b8f72842dac5348c1274c853a6b2223
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/order/filter/basic.lean
b95be5aabf014d4609e6935221af26b9df631667
[ "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
112,421
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad -/ import data.set.finite import order.copy import order.zorn import tactic.monotonicity /-! # Theory of filters on sets ## Main definitions * `filter` : filters on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `prod` : operations on filters; * `tendsto` : limit with respect to filters; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `ne_bot f` : an utility class stating that `f` is a non-trivial filter. Filters on a type `X` are sets of sets of `X` satisfying three conditions. They are mostly used to abstract two related kinds of ideas: * *limits*, including finite or infinite limits of sequences, finite or infinite limits of functions at a point or at infinity, etc... * *things happening eventually*, including things happening for large enough `n : ℕ`, or near enough a point `x`, or for close enough pairs of points, or things happening almost everywhere in the sense of measure theory. Dually, filters can also express the idea of *things happening often*: for arbitrarily large `n`, or at a point in any neighborhood of given a point etc... In this file, we define the type `filter X` of filters on `X`, and endow it with a complete lattice structure. This structure is lifted from the lattice structure on `set (set X)` using the Galois insertion which maps a filter to its elements in one direction, and an arbitrary set of sets to the smallest filter containing it in the other direction. We also prove `filter` is a monadic functor, with a push-forward operation `filter.map` and a pull-back operation `filter.comap` that form a Galois connections for the order on filters. Finally we describe a product operation `filter X → filter Y → filter (X × Y)`. The examples of filters appearing in the description of the two motivating ideas are: * `(at_top : filter ℕ)` : made of sets of `ℕ` containing `{n | n ≥ N}` for some `N` * `𝓝 x` : made of neighborhoods of `x` in a topological space (defined in topology.basic) * `𝓤 X` : made of entourages of a uniform space (those space are generalizations of metric spaces defined in topology.uniform_space.basic) * `μ.ae` : made of sets whose complement has zero measure with respect to `μ` (defined in `measure_theory.measure_space`) The general notion of limit of a map with respect to filters on the source and target types is `filter.tendsto`. It is defined in terms of the order and the push-forward operation. The predicate "happening eventually" is `filter.eventually`, and "happening often" is `filter.frequently`, whose definitions are immediate after `filter` is defined (but they come rather late in this file in order to immediately relate them to the lattice structure). For instance, anticipating on topology.basic, the statement: "if a sequence `u` converges to some `x` and `u n` belongs to a set `M` for `n` large enough then `x` is in the closure of `M`" is formalized as: `tendsto u at_top (𝓝 x) → (∀ᶠ n in at_top, u n ∈ M) → x ∈ closure M`, which is a special case of `mem_closure_of_tendsto` from topology.basic. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`; * `f =ᶠ[l] g` : `∀ᶠ x in l, f x = g x`; * `f ≤ᶠ[l] g` : `∀ᶠ x in l, f x ≤ g x`; * `f ×ᶠ g` : `filter.prod f g`, localized in `filter`; * `𝓟 s` : `principal s`, localized in `filter`. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] Important note: Bourbaki requires that a filter on `X` cannot contain all sets of `X`, which we do *not* require. This gives `filter X` better formal properties, in particular a bottom element `⊥` for its lattice structure, at the cost of including the assumption `[ne_bot f]` in a number of lemmas and definitions. -/ open set universes u v w x y open_locale classical /-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`, is upwards-closed, and is stable under intersection. We do not forbid this collection to be all sets of `α`. -/ structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} @[simp] protected lemma mem_mk {t : set (set α)} {h₁ h₂ h₃} : s ∈ mk t h₁ h₂ h₃ ↔ s ∈ t := iff.rfl @[simp] protected lemma mem_sets : s ∈ f.sets ↔ s ∈ f := iff.rfl instance inhabited_mem : inhabited {s : set α // s ∈ f} := ⟨⟨univ, f.univ_sets⟩⟩ lemma filter_eq : ∀ {f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by simp only [filter_eq_iff, ext_iff, filter.mem_sets] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 @[simp] lemma univ_mem : univ ∈ f := f.univ_sets lemma mem_of_superset : ∀ {x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem : ∀ {s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets @[simp] lemma inter_mem_iff {s t} : s ∩ t ∈ f ↔ s ∈ f ∧ t ∈ f := ⟨λ h, ⟨mem_of_superset h (inter_subset_left s t), mem_of_superset h (inter_subset_right s t)⟩, and_imp.2 inter_mem⟩ lemma univ_mem' (h : ∀ a, a ∈ s) : s ∈ f := mem_of_superset univ_mem (λ x _, h x) lemma mp_mem (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_of_superset (inter_mem hs h) $ λ x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_mem hs (mem_of_superset h (λ x, iff.mp)), λ hs, mp_mem hs (mem_of_superset h (λ x, iff.mpr))⟩ @[simp] lemma bInter_mem {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := finite.induction_on hf (by simp) (λ i s hi _ hs, by simp [hs]) @[simp] lemma bInter_finset_mem {β : Type v} {s : β → set α} (is : finset β) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := bInter_mem is.finite_to_set alias bInter_finset_mem ← finset.Inter_mem_sets attribute [protected] finset.Inter_mem_sets @[simp] lemma sInter_mem {s : set (set α)} (hfin : finite s) : ⋂₀ s ∈ f ↔ ∀ U ∈ s, U ∈ f := by rw [sInter_eq_bInter, bInter_mem hfin] @[simp] lemma Inter_mem {β : Type v} {s : β → set α} [fintype β] : (⋂ i, s i) ∈ f ↔ ∀ i, s i ∈ f := by simpa using bInter_mem finite_univ lemma exists_mem_subset_iff : (∃ t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨λ ⟨t, ht, ts⟩, mem_of_superset ht ts, λ hs, ⟨s, hs, subset.rfl⟩⟩ lemma monotone_mem {f : filter α} : monotone (λ s, s ∈ f) := λ s t hst h, mem_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀ x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_mem >> eapply e), eapplyc `filter.univ_mem', `[dsimp only [set.mem_set_of_eq]], match e' with | some e := interactive.exact e | none := skip end add_tactic_doc { name := "filter_upwards", category := doc_category.tactic, decl_names := [`tactic.interactive.filter_upwards], tags := ["goal management", "lemma application"] } end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := λ x y hx, subset.trans hx, inter_sets := λ x y, subset_inter } localized "notation `𝓟` := filter.principal" in filter instance : inhabited (filter α) := ⟨𝓟 ∅⟩ @[simp] lemma mem_principal {s t : set α} : s ∈ 𝓟 t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ 𝓟 s := subset.rfl end principal open_locale filter section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [mem_set_of_eq, univ_sets, ← filter.mem_sets, set_of_true], sets_of_superset := λ x y hx xy, mem_of_superset hx $ λ f h, mem_of_superset h xy, inter_sets := λ x y hx hy, mem_of_superset (inter_mem hx hy) $ λ f ⟨h₁, h₂⟩, inter_mem h₁ h₂ } @[simp] lemma mem_join {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λ f g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := λ a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := λ a, subset.rfl, le_trans := λ a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := λ x y, generate_sets.superset, inter_sets := λ s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (λ h u hu, h $ generate_sets.basic $ hu) (λ h u hu, hu.rec_on h univ_mem (λ x y _ hxy hx, mem_of_superset hx hxy) (λ x y _ _ hx hy, inter_mem hx hy)) lemma mem_generate_iff {s : set $ set α} {U : set α} : U ∈ generate s ↔ ∃ t ⊆ s, finite t ∧ ⋂₀ t ⊆ U := begin split ; intro h, { induction h with V V_in V W V_in hVW hV V W V_in W_in hV hW, { use {V}, simp [V_in] }, { use ∅, simp [subset.refl, univ] }, { rcases hV with ⟨t, hts, htfin, hinter⟩, exact ⟨t, hts, htfin, hinter.trans hVW⟩ }, { rcases hV with ⟨t, hts, htfin, htinter⟩, rcases hW with ⟨z, hzs, hzfin, hzinter⟩, refine ⟨t ∪ z, union_subset hts hzs, htfin.union hzfin, _⟩, rw sInter_union, exact inter_subset_inter htinter hzinter } }, { rcases h with ⟨t, ts, tfin, h⟩, apply generate_sets.superset _ h, revert ts, apply finite.induction_on tfin, { intro h, rw sInter_empty, exact generate_sets.univ }, { intros V r hV rfin hinter h, cases insert_subset.mp h with V_in r_sub, rw [insert_eq V r, sInter_union], apply generate_sets.inter _ (hinter r_sub), rw sInter_singleton, exact generate_sets.basic V_in } }, end /-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly `s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/ protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem : univ ∈ generate s), sets_of_superset := λ x y, hs ▸ (mem_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := λ x y, hs ▸ (inter_mem : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ λ u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /-- Galois insertion from sets of sets into filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := λ s f, sets_iff_generate, le_l_u := λ f u h, generate_sets.basic h, choice := λ s hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_rfl), choice_eq := λ s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), s = a ∩ b }, univ_sets := ⟨_, univ_mem, _, univ_mem, by simp⟩, sets_of_superset := begin rintro x y ⟨a, ha, b, hb, rfl⟩ xy, refine ⟨a ∪ y, mem_of_superset ha (subset_union_left a y), b ∪ y, mem_of_superset hb (subset_union_left b y), _⟩, rw [← inter_union_distrib_right, union_eq_self_of_subset_left xy] end, inter_sets := begin rintro x y ⟨a, ha, b, hb, rfl⟩ ⟨c, hc, d, hd, rfl⟩, refine ⟨a ∩ c, inter_mem ha hc, b ∩ d, inter_mem hb hd, _⟩, ac_refl end }⟩ lemma mem_inf_iff {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, s = t₁ ∩ t₂ := iff.rfl lemma mem_inf_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem, (inter_univ s).symm⟩ lemma mem_inf_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem, s, h, (univ_inter s).symm⟩ lemma inter_mem_inf {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := ⟨s, hs, t, ht, rfl⟩ lemma mem_inf_of_inter {f g : filter α} {s t u : set α} (hs : s ∈ f) (ht : t ∈ g) (h : s ∩ t ⊆ u) : u ∈ f ⊓ g := mem_of_superset (inter_mem_inf hs ht) h lemma mem_inf_iff_superset {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, t₁ ∩ t₂ ⊆ s := ⟨λ ⟨t₁, h₁, t₂, h₂, eq⟩, ⟨t₁, h₁, t₂, h₂, eq ▸ subset.rfl⟩, λ ⟨t₁, h₁, t₂, h₂, sub⟩, mem_inf_of_inter h₁ h₂ sub⟩ instance : has_top (filter α) := ⟨{ sets := {s | ∀ x, x ∈ s}, univ_sets := λ x, mem_univ x, sets_of_superset := λ x y hx hxy a, hxy (hx a), inter_sets := λ x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀ x, x ∈ s) := iff.rfl @[simp] lemma mem_top {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.has_top).1 (top_unique $ λ s hs, by simp [mem_top.1 hs]) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (λ s, mem_inf_of_left) (λ s, mem_inf_of_right)) (begin rintro s ⟨a, ha, b, hb, rfl⟩, exact inter_sets _ (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb) end) end /- Sup -/ (join ∘ 𝓟) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice /-- A filter is `ne_bot` if it is not equal to `⊥`, or equivalently the empty set does not belong to the filter. Bourbaki include this assumption in the definition of a filter but we prefer to have a `complete_lattice` structure on filter, so we use a typeclass argument in lemmas instead. -/ class ne_bot (f : filter α) : Prop := (ne' : f ≠ ⊥) lemma ne_bot_iff {f : filter α} : ne_bot f ↔ f ≠ ⊥ := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma ne_bot.ne {f : filter α} (hf : ne_bot f) : f ≠ ⊥ := ne_bot.ne' @[simp] lemma not_ne_bot {α : Type*} {f : filter α} : ¬ f.ne_bot ↔ f = ⊥ := not_iff_comm.1 ne_bot_iff.symm lemma ne_bot.mono {f g : filter α} (hf : ne_bot f) (hg : f ≤ g) : ne_bot g := ⟨ne_bot_of_le_ne_bot hf.1 hg⟩ lemma ne_bot_of_le {f g : filter α} [hf : ne_bot f] (hg : f ≤ g) : ne_bot g := hf.mono hg lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂ f ∈ s, (f : filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂ i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl lemma union_mem_sup {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∪ t ∈ f ⊔ g := ⟨mem_of_superset hs (subset_union_left s t), mem_of_superset ht (subset_union_right s t)⟩ @[simp] lemma mem_Sup {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀ f ∈ s, x ∈ (f : filter α)) := iff.rfl @[simp] lemma mem_supr {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀ i, x ∈ f i) := by simp only [← filter.mem_sets, supr_sets_eq, iff_self, mem_Inter] lemma infi_eq_generate (s : ι → filter α) : infi s = generate (⋃ i, (s i).sets) := show generate _ = generate _, from congr_arg _ supr_range lemma mem_infi_of_mem {f : ι → filter α} (i : ι) : ∀ {s}, s ∈ f i → s ∈ ⨅ i, f i := show (⨅ i, f i) ≤ f i, from infi_le _ _ lemma mem_infi_of_Inter {ι} {s : ι → filter α} {U : set α} {I : set ι} (I_fin : finite I) {V : I → set α} (hV : ∀ i, V i ∈ s i) (hU : (⋂ i, V i) ⊆ U) : U ∈ ⨅ i, s i := begin haveI := I_fin.fintype, refine mem_of_superset (Inter_mem.2 $ λ i, _) hU, exact mem_infi_of_mem i (hV _) end lemma mem_infi {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : I → set α, (∀ i, V i ∈ s i) ∧ U = ⋂ i, V i := begin split, { rw [infi_eq_generate, mem_generate_iff], rintro ⟨t, tsub, tfin, tinter⟩, rcases eq_finite_Union_of_finite_subset_Union tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩, rw sInter_Union at tinter, set V := λ i, U ∪ ⋂₀ σ i with hV, have V_in : ∀ i, V i ∈ s i, { rintro i, have : (⋂₀ σ i) ∈ s i, { rw sInter_mem (σfin _), apply σsub }, exact mem_of_superset this (subset_union_right _ _) }, refine ⟨I, Ifin, V, V_in, _⟩, rwa [hV, ← union_Inter, union_eq_self_of_subset_right] }, { rintro ⟨I, Ifin, V, V_in, rfl⟩, exact mem_infi_of_Inter Ifin V_in subset.rfl } end lemma mem_infi' {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : ι → set α, (∀ i ∈ I, V i ∈ s i) ∧ U = ⋂ i ∈ I, V i := begin simp only [mem_infi, set_coe.forall', bInter_eq_Inter], refine ⟨_, λ ⟨I, If, V, hV⟩, ⟨I, If, λ i, V i, hV⟩⟩, rintro ⟨I, If, V, hV⟩, lift V to ι → set α using trivial, exact ⟨I, If, V, hV⟩ end lemma exists_Inter_of_mem_infi {ι : Type*} {α : Type*} {f : ι → filter α} {s} (hs : s ∈ ⨅ i, f i) : ∃ t : ι → set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i := begin classical, rcases mem_infi'.mp hs with ⟨I, I_fin, V, hV, rfl⟩, refine ⟨λ i, if i ∈ I then V i else univ, _, _⟩, { intro i, split_ifs, exacts [hV i h, univ_mem] }, { simp [Inter_ite] }, end lemma mem_infi_of_fintype {ι : Type*} [fintype ι] {α : Type*} {f : ι → filter α} (s) : s ∈ (⨅ i, f i) ↔ ∃ t : ι → set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i := begin refine ⟨exists_Inter_of_mem_infi, _⟩, rw mem_infi', rintros ⟨t, ht, ht'⟩, exact ⟨univ, finite_univ, ⟨t, λ i _, ht i, by simp [ht']⟩⟩ end @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ 𝓟 s ↔ s ∈ f := show (∀ {t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨λ h, h (subset.refl s), λ hs t ht, mem_of_superset hs ht⟩ lemma principal_mono {s t : set α} : 𝓟 s ≤ 𝓟 t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal] @[mono] lemma monotone_principal : monotone (𝓟 : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : 𝓟 s = 𝓟 t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (𝓟 s) = Sup s := rfl @[simp] lemma principal_univ : 𝓟 (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top, eq_self_iff_true] @[simp] lemma principal_empty : 𝓟 (∅ : set α) = ⊥ := bot_unique $ λ s _, empty_subset _ /-! ### Lattice equations -/ lemma empty_mem_iff_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨λ h, bot_unique $ λ s _, mem_of_superset h (empty_subset s), λ h, h.symm ▸ mem_bot⟩ lemma nonempty_of_mem {f : filter α} [hf : ne_bot f] {s : set α} (hs : s ∈ f) : s.nonempty := s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_mem_iff_bot.mp hf.1)) id lemma ne_bot.nonempty_of_mem {f : filter α} (hf : ne_bot f) {s : set α} (hs : s ∈ f) : s.nonempty := @nonempty_of_mem α f hf s hs @[simp] lemma empty_not_mem (f : filter α) [ne_bot f] : ¬(∅ ∈ f) := λ h, (nonempty_of_mem h).ne_empty rfl lemma nonempty_of_ne_bot (f : filter α) [ne_bot f] : nonempty α := nonempty_of_exists $ nonempty_of_mem (univ_mem : univ ∈ f) lemma compl_not_mem {f : filter α} {s : set α} [ne_bot f] (h : s ∈ f) : sᶜ ∉ f := λ hsc, (nonempty_of_mem (inter_mem h hsc)).ne_empty $ inter_compl_self s lemma filter_eq_bot_of_is_empty [is_empty α] (f : filter α) : f = ⊥ := empty_mem_iff_bot.mp $ univ_mem' is_empty_elim /-- There is exactly one filter on an empty type. --/ -- TODO[gh-6025]: make this globally an instance once safe to do so local attribute [instance] protected def unique [is_empty α] : unique (filter α) := { default := ⊥, uniq := filter_eq_bot_of_is_empty } lemma forall_mem_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ ne_bot f := ⟨λ h, ⟨λ hf, empty_not_nonempty (h ∅ $ hf.symm ▸ mem_bot)⟩, @nonempty_of_mem _ _⟩ lemma nontrivial_iff_nonempty : nontrivial (filter α) ↔ nonempty α := ⟨λ ⟨⟨f, g, hfg⟩⟩, by_contra $ λ h, hfg $ by haveI : is_empty α := not_nonempty_iff.1 h; exact subsingleton.elim _ _, λ ⟨x⟩, ⟨⟨⊤, ⊥, ne_bot.ne $ forall_mem_nonempty_iff_ne_bot.1 $ λ s hs, by rwa [mem_top.1 hs, ← nonempty_iff_univ_nonempty]⟩⟩⟩ lemma eq_Inf_of_mem_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) [ne : nonempty ι] : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], intros x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_iff_exists_mem (λ s, by simp only [filter.mem_mk, mem_Union, filter.mem_sets]), congr_arg filter.sets this.symm lemma mem_infi_of_directed {f : ι → filter α} (h : directed (≥) f) [nonempty ι] (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [← filter.mem_sets, infi_sets_eq h, mem_Union] lemma mem_binfi_of_directed {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i ∈ s, f i) ↔ ∃ i ∈ s, t ∈ f i := by haveI : nonempty {x // x ∈ s} := ne.to_subtype; erw [infi_subtype', mem_infi_of_directed h.directed_coe, subtype.exists]; refl lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i ∈ s, f i).sets = ⋃ i ∈ s, (f i).sets := ext $ λ t, by simp [mem_binfi_of_directed h ne] lemma infi_sets_eq_finite {ι : Type*} (f : ι → filter α) : (⨅ i, f i).sets = (⋃ t : finset ι, (⨅ i ∈ t, f i).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λ s₁ s₂ hs, infi_le_infi $ λ i, infi_le_infi_const $ λ h, hs h), end lemma infi_sets_eq_finite' (f : ι → filter α) : (⨅ i, f i).sets = (⋃ t : finset (plift ι), (⨅ i ∈ t, f (plift.down i)).sets) := by { rw [← infi_sets_eq_finite, ← equiv.plift.surjective.infi_comp], refl } lemma mem_infi_finite {ι : Type*} {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t : finset ι, s ∈ ⨅ i ∈ t, f i := (set.ext_iff.1 (infi_sets_eq_finite f) s).trans mem_Union lemma mem_infi_finite' {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t : finset (plift ι), s ∈ ⨅ i ∈ t, f (plift.down i) := (set.ext_iff.1 (infi_sets_eq_finite' f) s).trans mem_Union @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter.ext $ λ x, by simp only [mem_sup, mem_join] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆ x, join (f x)) = join (⨆ x, f x) := filter.ext $ λ x, by simp only [mem_supr, mem_join] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin intros x y z s, simp only [and_assoc, mem_inf_iff, mem_sup, exists_prop, exists_imp_distrib, and_imp], rintro hs t₁ ht₁ t₂ ht₂ rfl, exact ⟨t₁, x.sets_of_superset hs (inter_subset_left t₁ t₂), ht₁, t₂, x.sets_of_superset hs (inter_subset_right t₁ t₂), ht₂, rfl⟩ end, ..filter.complete_lattice } /- the complementary version with ⨆ i, f ⊓ g i does not hold! -/ lemma infi_sup_left {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ λ i, sup_le_sup_left (infi_le _ _) _), rintro t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite'] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅ i, f ⊔ g i) ≤ f ⊔ s.inf (λ i, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_of_le_right le_top }, { rintro ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma infi_sup_right {f : filter α} {g : ι → filter α} : (⨅ x, g x ⊔ f) = infi g ⊔ f := by simp [sup_comm, ← infi_sup_left] lemma binfi_sup_right (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (f i ⊔ g)) = (⨅ i (h : p i), f i) ⊔ g := by rw [infi_subtype', infi_sup_right, infi_subtype'] lemma binfi_sup_left (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (g ⊔ f i)) = g ⊔ (⨅ i (h : p i), f i) := by rw [infi_subtype', infi_sup_left, infi_subtype'] lemma mem_infi_finset {s : finset α} {f : α → filter β} : ∀ t, t ∈ (⨅ a ∈ s, f a) ↔ (∃ p : α → set β, (∀ a ∈ s, p a ∈ f a) ∧ t = ⋂ a ∈ s, p a) := show ∀ t, t ∈ (⨅ a ∈ s, f a) ↔ (∃ p : α → set β, (∀ a ∈ s, p a ∈ f a) ∧ t = ⨅ a ∈ s, p a), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_iff, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { rintro t₁ ht₁ t₂ p hp ht₂ rfl, use function.update p a t₁, have : ∀ a' ∈ s, function.update p a t₁ a' = p a', from λ a' ha', have a' ≠ a, from λ h, has $ h ▸ ha', function.update_noteq this _ _, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, refl }, rintro p hpa hp rfl, exact ⟨p a, hpa, s.inf p, ⟨p, hp, rfl⟩, rfl⟩ } end /-- If `f : ι → filter α` is directed, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) (hb : ∀ i, ne_bot (f i)) : ne_bot (infi f) := ⟨begin intro h, have he : ∅ ∈ (infi f), from h.symm ▸ (mem_bot : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃ i, ∅ ∈ f i, from (mem_infi_of_directed hd ∅).1 he, exact (hb i).ne (empty_mem_iff_bot.1 hi) end⟩ /-- If `f : ι → filter α` is directed, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} [hn : nonempty α] (hd : directed (≥) f) (hb : ∀ i, ne_bot (f i)) : ne_bot (infi f) := if hι : nonempty ι then @infi_ne_bot_of_directed' _ _ _ hι hd hb else ⟨λ h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ λ i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x)⟩ lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) : ne_bot (infi f) ↔ ∀ i, ne_bot (f i) := ⟨λ H i, H.mono (infi_le _ i), infi_ne_bot_of_directed' hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} [nonempty α] (hd : directed (≥) f) : ne_bot (infi f) ↔ (∀ i, ne_bot (f i)) := ⟨λ H i, H.mono (infi_le _ i), infi_ne_bot_of_directed hd⟩ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀ {i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) : p s := begin rw [mem_infi_finite'] at hs, simp only [← finset.inf_eq_infi] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { intros s hs, rwa [mem_top.1 hs] }, { rintro ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_iff] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, rfl⟩, exact ins hs₁ (ih hs₂) } end /-! #### `principal` equations -/ @[simp] lemma inf_principal {s t : set α} : 𝓟 s ⊓ 𝓟 t = 𝓟 (s ∩ t) := le_antisymm (by simp only [le_principal_iff, mem_inf_iff]; exact ⟨s, subset.rfl, t, subset.rfl, rfl⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : 𝓟 s ⊔ 𝓟 t = 𝓟 (s ∪ t) := filter.ext $ λ u, by simp only [union_subset_iff, mem_sup, mem_principal] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆ x, 𝓟 (s x)) = 𝓟 (⋃ i, s i) := filter.ext $ λ x, by simp only [mem_supr, mem_principal, Union_subset_iff] @[simp] lemma principal_eq_bot_iff {s : set α} : 𝓟 s = ⊥ ↔ s = ∅ := empty_mem_iff_bot.symm.trans $ mem_principal.trans subset_empty_iff @[simp] lemma principal_ne_bot_iff {s : set α} : ne_bot (𝓟 s) ↔ s.nonempty := ne_bot_iff.trans $ (not_congr principal_eq_bot_iff).trans ne_empty_iff_nonempty lemma is_compl_principal (s : set α) : is_compl (𝓟 s) (𝓟 sᶜ) := ⟨by simp only [inf_principal, inter_compl_self, principal_empty, le_refl], by simp only [sup_principal, union_compl_self, principal_univ, le_refl]⟩ theorem mem_inf_principal {f : filter α} {s t : set α} : s ∈ f ⊓ 𝓟 t ↔ {x | x ∈ t → x ∈ s} ∈ f := begin simp only [← le_principal_iff, (is_compl_principal s).le_left_iff, disjoint, inf_assoc, inf_principal, imp_iff_not_or], rw [← disjoint, ← (is_compl_principal (t ∩ sᶜ)).le_right_iff, compl_inter, compl_compl], refl end lemma supr_inf_principal (f : ι → filter α) (s : set α) : (⨆ i, f i ⊓ 𝓟 s) = (⨆ i, f i) ⊓ 𝓟 s := by { ext, simp only [mem_supr, mem_inf_principal] } lemma inf_principal_eq_bot {f : filter α} {s : set α} : f ⊓ 𝓟 s = ⊥ ↔ sᶜ ∈ f := by { rw [← empty_mem_iff_bot, mem_inf_principal], refl } lemma mem_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ 𝓟 sᶜ = ⊥) : s ∈ f := by rwa [inf_principal_eq_bot, compl_compl] at h lemma diff_mem_inf_principal_compl {f : filter α} {s : set α} (hs : s ∈ f) (t : set α) : s \ t ∈ f ⊓ 𝓟 tᶜ := begin rw mem_inf_principal, filter_upwards [hs], intros a has hat, exact ⟨has, hat⟩ end lemma principal_le_iff {s : set α} {f : filter α} : 𝓟 s ≤ f ↔ ∀ V ∈ f, s ⊆ V := begin change (∀ V, V ∈ f → V ∈ _) ↔ _, simp_rw mem_principal, end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅ i ∈ s, 𝓟 (f i)) = 𝓟 (⋂ i ∈ s, f i) := begin induction s using finset.induction_on with i s hi hs, { simp }, { rw [finset.infi_insert, finset.set_bInter_insert, hs, inf_principal] }, end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅ i, 𝓟 (f i)) = 𝓟 (⋂ i, f i) := by simpa using infi_principal_finset finset.univ f lemma infi_principal_finite {ι : Type w} {s : set ι} (hs : finite s) (f : ι → set α) : (⨅ i ∈ s, 𝓟 (f i)) = 𝓟 (⋂ i ∈ s, f i) := begin unfreezingI { lift s to finset ι using hs }, -- TODO: why `unfreezingI` is needed? exact_mod_cast infi_principal_finset s f end end lattice @[mono] lemma join_mono {f₁ f₂ : filter (filter α)} (h : f₁ ≤ f₂) : join f₁ ≤ join f₂ := λ s hs, h hs /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r lemma eventually_iff {f : filter α} {P : α → Prop} : (∀ᶠ x in f, P x) ↔ {x | P x} ∈ f := iff.rfl protected lemma ext' {f₁ f₂ : filter α} (h : ∀ p : α → Prop, (∀ᶠ x in f₁, p x) ↔ (∀ᶠ x in f₂, p x)) : f₁ = f₂ := filter.ext h lemma eventually.filter_mono {f₁ f₂ : filter α} (h : f₁ ≤ f₂) {p : α → Prop} (hp : ∀ᶠ x in f₂, p x) : ∀ᶠ x in f₁, p x := h hp lemma eventually_of_mem {f : filter α} {P : α → Prop} {U : set α} (hU : U ∈ f) (h : ∀ x ∈ U, P x) : ∀ᶠ x in f, P x := mem_of_superset hU h protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem @[simp] lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem lemma eventually_of_forall {p : α → Prop} {f : filter α} (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem' hp @[simp] lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_mem_iff_bot @[simp] lemma eventually_const {f : filter α} [t : ne_bot f] {p : Prop} : (∀ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simp [h]) (λ h, by simpa [h] using t.ne) lemma eventually_iff_exists_mem {p : α → Prop} {f : filter α} : (∀ᶠ x in f, p x) ↔ ∃ v ∈ f, ∀ y ∈ v, p y := exists_mem_subset_iff.symm lemma eventually.exists_mem {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) : ∃ v ∈ f, ∀ y ∈ v, p y := eventually_iff_exists_mem.1 hp lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_mem hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (eventually_of_forall hq) @[simp] lemma eventually_and {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := inter_mem_iff lemma eventually.congr {f : filter α} {p q : α → Prop} (h' : ∀ᶠ x in f, p x) (h : ∀ᶠ x in f, p x ↔ q x) : ∀ᶠ x in f, q x := h'.mp (h.mono $ λ x hx, hx.mp) lemma eventually_congr {f : filter α} {p q : α → Prop} (h : ∀ᶠ x in f, p x ↔ q x) : (∀ᶠ x in f, p x) ↔ (∀ᶠ x in f, q x) := ⟨λ hp, hp.congr h, λ hq, hq.congr $ by simpa only [iff.comm] using h⟩ @[simp] lemma eventually_all {ι} [fintype ι] {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i, p i x) ↔ ∀ i, ∀ᶠ x in l, p i x := by simpa only [filter.eventually, set_of_forall] using Inter_mem @[simp] lemma eventually_all_finite {ι} {I : set ι} (hI : I.finite) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ (∀ i ∈ I, ∀ᶠ x in l, p i x) := by simpa only [filter.eventually, set_of_forall] using bInter_mem hI alias eventually_all_finite ← set.finite.eventually_all attribute [protected] set.finite.eventually_all @[simp] lemma eventually_all_finset {ι} (I : finset ι) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ ∀ i ∈ I, ∀ᶠ x in l, p i x := I.finite_to_set.eventually_all alias eventually_all_finset ← finset.eventually_all attribute [protected] finset.eventually_all @[simp] lemma eventually_or_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p ∨ q x) ↔ (p ∨ ∀ᶠ x in f, q x) := classical.by_cases (λ h : p, by simp [h]) (λ h, by simp [h]) @[simp] lemma eventually_or_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x ∨ q) ↔ ((∀ᶠ x in f, p x) ∨ q) := by simp only [or_comm _ q, eventually_or_distrib_left] @[simp] lemma eventually_imp_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p → q x) ↔ (p → ∀ᶠ x in f, q x) := by simp only [imp_iff_not_or, eventually_or_distrib_left] @[simp] lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩ @[simp] lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) := iff.rfl @[simp] lemma eventually_sup {p : α → Prop} {f g : filter α} : (∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) := iff.rfl @[simp] lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} : (∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) := iff.rfl @[simp] lemma eventually_supr {p : α → Prop} {fs : β → filter α} : (∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) := mem_supr @[simp] lemma eventually_principal {a : set α} {p : α → Prop} : (∀ᶠ x in 𝓟 a, p x) ↔ (∀ x ∈ a, p x) := iff.rfl lemma eventually_inf {f g : filter α} {p : α → Prop} : (∀ᶠ x in f ⊓ g, p x) ↔ ∃ (s ∈ f) (t ∈ g), ∀ x ∈ s ∩ t, p x := mem_inf_iff_superset theorem eventually_inf_principal {f : filter α} {p : α → Prop} {s : set α} : (∀ᶠ x in f ⊓ 𝓟 s, p x) ↔ ∀ᶠ x in f, x ∈ s → p x := mem_inf_principal /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := compl_not_mem h lemma frequently_of_forall {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ x, p x) : ∃ᶠ x in f, p x := eventually.frequently (eventually_of_forall h) lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.filter_mono {p : α → Prop} {f g : filter α} (h : ∃ᶠ x in f, p x) (hle : f ≤ g) : ∃ᶠ x in g, p x := mt (λ h', h'.filter_mono hle) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, exact λ x hpq hq hp, hpq ⟨hp, hq⟩ end lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} [ne_bot f] (hp : ∀ᶠ x in f, p x) : ∃ x, p x := hp.frequently.exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨λ hp q hq, (hp.and_eventually hq).exists, λ H hp, by simpa only [and_not_self, exists_false] using H hp⟩ lemma frequently_iff {f : filter α} {P : α → Prop} : (∃ᶠ x in f, P x) ↔ ∀ {U}, U ∈ f → ∃ x ∈ U, P x := begin rw frequently_iff_forall_eventually_exists_and, split ; intro h, { intros U U_in, simpa [exists_prop, and_comm] using h U_in }, { intros H H', simpa [and_comm] using h H' }, end @[simp] lemma not_eventually {p : α → Prop} {f : filter α} : (¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) := by simp [filter.frequently] @[simp] lemma not_frequently {p : α → Prop} {f : filter α} : (¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) := by simp only [filter.frequently, not_not] @[simp] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ ne_bot f := by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot, ne_bot_iff] @[simp] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp @[simp] lemma frequently_const {f : filter α} [ne_bot f] {p : Prop} : (∃ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simpa [h]) (λ h, by simp [h]) @[simp] lemma frequently_or_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x ∨ q x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in f, q x) := by simp only [filter.frequently, ← not_and_distrib, not_or_distrib, eventually_and] lemma frequently_or_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∨ q x) ↔ (p ∨ ∃ᶠ x in f, q x) := by simp lemma frequently_or_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∨ q) ↔ (∃ᶠ x in f, p x) ∨ q := by simp @[simp] lemma frequently_imp_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x → q x) ↔ ((∀ᶠ x in f, p x) → ∃ᶠ x in f, q x) := by simp [imp_iff_not_or, not_eventually, frequently_or_distrib] lemma frequently_imp_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p → q x) ↔ (p → ∃ᶠ x in f, q x) := by simp lemma frequently_imp_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x → q) ↔ ((∀ᶠ x in f, p x) → q) := by simp @[simp] lemma eventually_imp_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x → q) ↔ ((∃ᶠ x in f, p x) → q) := by simp only [imp_iff_not_or, eventually_or_distrib_right, not_frequently] @[simp] lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp @[simp] lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) := by simp [filter.frequently] @[simp] lemma frequently_principal {a : set α} {p : α → Prop} : (∃ᶠ x in 𝓟 a, p x) ↔ (∃ x ∈ a, p x) := by simp [filter.frequently, not_forall] lemma frequently_sup {p : α → Prop} {f g : filter α} : (∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) := by simp only [filter.frequently, eventually_sup, not_and_distrib] @[simp] lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} : (∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) := by simp [filter.frequently, -not_eventually, not_forall] @[simp] lemma frequently_supr {p : α → Prop} {fs : β → filter α} : (∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) := by simp [filter.frequently, -not_eventually, not_forall] /-! ### Relation “eventually equal” -/ /-- Two functions `f` and `g` are *eventually equal* along a filter `l` if the set of `x` such that `f x = g x` belongs to `l`. -/ def eventually_eq (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x = g x notation f ` =ᶠ[`:50 l:50 `] `:0 g:50 := eventually_eq l f g lemma eventually_eq.eventually {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∀ᶠ x in l, f x = g x := h lemma eventually_eq.rw {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) (p : α → β → Prop) (hf : ∀ᶠ x in l, p x (f x)) : ∀ᶠ x in l, p x (g x) := hf.congr $ h.mono $ λ x hx, hx ▸ iff.rfl lemma eventually_eq_set {s t : set α} {l : filter α} : s =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ s ↔ x ∈ t := eventually_congr $ eventually_of_forall $ λ x, ⟨eq.to_iff, iff.to_eq⟩ alias eventually_eq_set ↔ filter.eventually_eq.mem_iff filter.eventually.set_eq lemma eventually_eq.exists_mem {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∃ s ∈ l, eq_on f g s := h.exists_mem lemma eventually_eq_of_mem {l : filter α} {f g : α → β} {s : set α} (hs : s ∈ l) (h : eq_on f g s) : f =ᶠ[l] g := eventually_of_mem hs h lemma eventually_eq_iff_exists_mem {l : filter α} {f g : α → β} : (f =ᶠ[l] g) ↔ ∃ s ∈ l, eq_on f g s := eventually_iff_exists_mem lemma eventually_eq.filter_mono {l l' : filter α} {f g : α → β} (h₁ : f =ᶠ[l] g) (h₂ : l' ≤ l) : f =ᶠ[l'] g := h₂ h₁ @[refl] lemma eventually_eq.refl (l : filter α) (f : α → β) : f =ᶠ[l] f := eventually_of_forall $ λ x, rfl lemma eventually_eq.rfl {l : filter α} {f : α → β} : f =ᶠ[l] f := eventually_eq.refl l f @[symm] lemma eventually_eq.symm {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) : g =ᶠ[l] f := H.mono $ λ _, eq.symm @[trans] lemma eventually_eq.trans {f g h : α → β} {l : filter α} (H₁ : f =ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f =ᶠ[l] h := H₂.rw (λ x y, f x = y) H₁ lemma eventually_eq.prod_mk {l} {f f' : α → β} (hf : f =ᶠ[l] f') {g g' : α → γ} (hg : g =ᶠ[l] g') : (λ x, (f x, g x)) =ᶠ[l] (λ x, (f' x, g' x)) := hf.mp $ hg.mono $ by { intros, simp only * } lemma eventually_eq.fun_comp {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) (h : β → γ) : (h ∘ f) =ᶠ[l] (h ∘ g) := H.mono $ λ x hx, congr_arg h hx lemma eventually_eq.comp₂ {δ} {f f' : α → β} {g g' : α → γ} {l} (Hf : f =ᶠ[l] f') (h : β → γ → δ) (Hg : g =ᶠ[l] g') : (λ x, h (f x) (g x)) =ᶠ[l] (λ x, h (f' x) (g' x)) := (Hf.prod_mk Hg).fun_comp (function.uncurry h) @[to_additive] lemma eventually_eq.mul [has_mul β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x * f' x) =ᶠ[l] (λ x, g x * g' x)) := h.comp₂ (*) h' @[to_additive] lemma eventually_eq.inv [has_inv β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : ((λ x, (f x)⁻¹) =ᶠ[l] (λ x, (g x)⁻¹)) := h.fun_comp has_inv.inv lemma eventually_eq.div [group_with_zero β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.div' [group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.sub [add_group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x - f' x) =ᶠ[l] (λ x, g x - g' x)) := by simpa only [sub_eq_add_neg] using h.add h'.neg lemma eventually_eq.inter {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∩ s' : set α) =ᶠ[l] (t ∩ t' : set α) := h.comp₂ (∧) h' lemma eventually_eq.union {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∪ s' : set α) =ᶠ[l] (t ∪ t' : set α) := h.comp₂ (∨) h' lemma eventually_eq.compl {s t : set α} {l : filter α} (h : s =ᶠ[l] t) : (sᶜ : set α) =ᶠ[l] (tᶜ : set α) := h.fun_comp not lemma eventually_eq.diff {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s \ s' : set α) =ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma eventually_eq_empty {s : set α} {l : filter α} : s =ᶠ[l] (∅ : set α) ↔ ∀ᶠ x in l, x ∉ s := eventually_eq_set.trans $ by simp lemma inter_eventually_eq_left {s t : set α} {l : filter α} : (s ∩ t : set α) =ᶠ[l] s ↔ ∀ᶠ x in l, x ∈ s → x ∈ t := by simp only [eventually_eq_set, mem_inter_eq, and_iff_left_iff_imp] lemma inter_eventually_eq_right {s t : set α} {l : filter α} : (s ∩ t : set α) =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ t → x ∈ s := by rw [inter_comm, inter_eventually_eq_left] @[simp] lemma eventually_eq_principal {s : set α} {f g : α → β} : f =ᶠ[𝓟 s] g ↔ eq_on f g s := iff.rfl lemma eventually_eq_inf_principal_iff {F : filter α} {s : set α} {f g : α → β} : (f =ᶠ[F ⊓ 𝓟 s] g) ↔ ∀ᶠ x in F, x ∈ s → f x = g x := eventually_inf_principal lemma eventually_eq.sub_eq [add_group β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : f - g =ᶠ[l] 0 := by simpa using (eventually_eq.sub (eventually_eq.refl l f) h).symm lemma eventually_eq_iff_sub [add_group β] {f g : α → β} {l : filter α} : f =ᶠ[l] g ↔ f - g =ᶠ[l] 0 := ⟨λ h, h.sub_eq, λ h, by simpa using h.add (eventually_eq.refl l g)⟩ section has_le variables [has_le β] {l : filter α} /-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/ def eventually_le (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x ≤ g x notation f ` ≤ᶠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g lemma eventually_le.congr {f f' g g' : α → β} (H : f ≤ᶠ[l] g) (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f' ≤ᶠ[l] g' := H.mp $ hg.mp $ hf.mono $ λ x hf hg H, by rwa [hf, hg] at H lemma eventually_le_congr {f f' g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f ≤ᶠ[l] g ↔ f' ≤ᶠ[l] g' := ⟨λ H, H.congr hf hg, λ H, H.congr hf.symm hg.symm⟩ end has_le section preorder variables [preorder β] {l : filter α} {f g h : α → β} lemma eventually_eq.le (h : f =ᶠ[l] g) : f ≤ᶠ[l] g := h.mono $ λ x, le_of_eq @[refl] lemma eventually_le.refl (l : filter α) (f : α → β) : f ≤ᶠ[l] f := eventually_eq.rfl.le lemma eventually_le.rfl : f ≤ᶠ[l] f := eventually_le.refl l f @[trans] lemma eventually_le.trans (H₁ : f ≤ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₂.mp $ H₁.mono $ λ x, le_trans @[trans] lemma eventually_eq.trans_le (H₁ : f =ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₁.le.trans H₂ @[trans] lemma eventually_le.trans_eq (H₁ : f ≤ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f ≤ᶠ[l] h := H₁.trans H₂.le end preorder lemma eventually_le.antisymm [partial_order β] {l : filter α} {f g : α → β} (h₁ : f ≤ᶠ[l] g) (h₂ : g ≤ᶠ[l] f) : f =ᶠ[l] g := h₂.mp $ h₁.mono $ λ x, le_antisymm lemma eventually_le_antisymm_iff [partial_order β] {l : filter α} {f g : α → β} : f =ᶠ[l] g ↔ f ≤ᶠ[l] g ∧ g ≤ᶠ[l] f := by simp only [eventually_eq, eventually_le, le_antisymm_iff, eventually_and] lemma eventually_le.le_iff_eq [partial_order β] {l : filter α} {f g : α → β} (h : f ≤ᶠ[l] g) : g ≤ᶠ[l] f ↔ g =ᶠ[l] f := ⟨λ h', h'.antisymm h, eventually_eq.le⟩ @[mono] lemma eventually_le.inter {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∩ s' : set α) ≤ᶠ[l] (t ∩ t' : set α) := h'.mp $ h.mono $ λ x, and.imp @[mono] lemma eventually_le.union {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∪ s' : set α) ≤ᶠ[l] (t ∪ t' : set α) := h'.mp $ h.mono $ λ x, or.imp @[mono] lemma eventually_le.compl {s t : set α} {l : filter α} (h : s ≤ᶠ[l] t) : (tᶜ : set α) ≤ᶠ[l] (sᶜ : set α) := h.mono $ λ x, mt @[mono] lemma eventually_le.diff {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : t' ≤ᶠ[l] s') : (s \ s' : set α) ≤ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma join_le {f : filter (filter α)} {l : filter α} (h : ∀ᶠ m in f, m ≤ l) : join f ≤ l := λ s hs, h.mono $ λ m hm, hm hs /-! ### Push-forwards, pull-backs, and the monad structure -/ section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem, sets_of_superset := λ s t hs st, mem_of_superset hs $ preimage_mono st, inter_sets := λ s t hs ht, inter_mem hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (𝓟 s) = 𝓟 (set.image f s) := filter.ext $ λ a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma eventually_map {P : β → Prop} : (∀ᶠ b in map m f, P b) ↔ ∀ᶠ a in f, P (m a) := iff.rfl @[simp] lemma frequently_map {P : β → Prop} : (∃ᶠ b in map m f, P b) ↔ ∃ᶠ a in f, P (m a) := iff.rfl @[simp] lemma mem_map : t ∈ map m f ↔ m ⁻¹' t ∈ f := iff.rfl lemma mem_map' : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma image_mem_map_iff (hf : function.injective m) : m '' s ∈ map m f ↔ s ∈ f := ⟨λ h, by rwa [← preimage_image_eq s hf], image_mem_map⟩ lemma range_mem_map : range m ∈ map m f := by { rw ←image_univ, exact image_mem_map univ_mem } lemma mem_map_iff_exists_image : t ∈ map m f ↔ (∃ s ∈ f, m '' s ⊆ t) := ⟨λ ht, ⟨m ⁻¹' t, ht, image_preimage_subset _ _⟩, λ ⟨s, hs, ht⟩, mem_of_superset (image_mem_map hs) ht⟩ @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_id' : filter.map (λ x, x) f = f := map_id @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ λ _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f /-- If functions `m₁` and `m₂` are eventually equal at a filter `f`, then they map this filter to the same filter. -/ lemma map_congr {m₁ m₂ : α → β} {f : filter α} (h : m₁ =ᶠ[f] m₂) : map m₁ f = map m₂ f := filter.ext' $ λ p, by { simp only [eventually_map], exact eventually_congr (h.mono $ λ x hx, hx ▸ iff.rfl) } end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃ t ∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := λ a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', ma'a.trans ab⟩, inter_sets := λ a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } lemma eventually_comap' {f : filter β} {φ : α → β} {p : β → Prop} (hf : ∀ᶠ b in f, p b) : ∀ᶠ a in comap φ f, p (φ a) := ⟨_, hf, (λ a h, h)⟩ @[simp] lemma eventually_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∀ᶠ a in comap φ f, P a) ↔ ∀ᶠ b in f, ∀ a, φ a = b → P a := begin split ; intro h, { rcases h with ⟨t, t_in, ht⟩, apply mem_of_superset t_in, rintro y y_in _ rfl, apply ht y_in }, { exact ⟨_, h, λ _ x_in, x_in _ rfl⟩ } end @[simp] lemma frequently_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∃ᶠ a in comap φ f, P a) ↔ ∃ᶠ b in f, ∃ a, φ a = b ∧ P a := begin classical, erw [← not_iff_not, not_not, not_not, filter.eventually_comap], simp only [not_exists, not_and], end end comap /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃ u ∈ f, ∃ t ∈ g, (∀ m ∈ u, ∀ x ∈ t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem, univ, univ_mem, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, λ s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, λ x hx y hy, hst $ h _ hx _ hy⟩, λ s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem ht₀ hu₀, t₁ ∩ u₁, inter_mem ht₁ hu₁, λ x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `𝓟 {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl @[simp] lemma eventually_pure {a : α} {p : α → Prop} : (∀ᶠ x in pure a, p x) ↔ p a := iff.rfl @[simp] lemma principal_singleton (a : α) : 𝓟 {a} = pure a := filter.ext $ λ s, by simp only [mem_pure, mem_principal, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen /-- The monad structure on filters. -/ protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := λ α f, filter_eq rfl, pure_bind := λ α β, pure_bind, bind_assoc := λ α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := λ α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map', mem_join, mem_set_of_eq, function.comp, mem_pure] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λ α, ⊥, orelse := λ α x y, x ⊔ y } @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /-! #### `map` and `comap` equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap : s ∈ comap m g ↔ ∃ t ∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.rfl⟩ lemma comap_id : comap id f = f := le_antisymm (λ s, preimage_mem_comap) (λ s ⟨t, ht, hst⟩, mem_of_superset ht hst) lemma comap_const_of_not_mem {x : α} {f : filter α} {V : set α} (hV : V ∈ f) (hx : x ∉ V) : comap (λ y : α, x) f = ⊥ := begin ext W, suffices : ∃ t ∈ f, (λ (y : α), x) ⁻¹' t ⊆ W, by simpa, use [V, hV], simp [preimage_const_of_not_mem hx], end lemma comap_const_of_mem {x : α} {f : filter α} (h : ∀ V ∈ f, x ∈ V) : comap (λ y : α, x) f = ⊤ := begin ext W, suffices : (∃ (t : set α), t ∈ f ∧ (λ (y : α), x) ⁻¹' t ⊆ W) ↔ W = univ, by simpa, split, { rintro ⟨V, V_in, hW⟩, simpa [preimage_const_of_mem (h V V_in), univ_subset_iff] using hW }, { rintro rfl, use univ, simp [univ_mem] }, end lemma comap_comap {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (λ c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (λ c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from (preimage_mono h₁).trans h₂⟩) section comm variables {δ : Type*} /-! The variables in the following lemmas are used as in this diagram: ``` φ α → β θ ↓ ↓ ψ γ → δ ρ ``` -/ variables {φ : α → β} {θ : α → γ} {ψ : β → δ} {ρ : γ → δ} (H : ψ ∘ φ = ρ ∘ θ) include H lemma map_comm (F : filter α) : map ψ (map φ F) = map ρ (map θ F) := by rw [filter.map_map, H, ← filter.map_map] lemma comap_comm (G : filter δ) : comap φ (comap ψ G) = comap θ (comap ρ G) := by rw [filter.comap_comap, H, ← filter.comap_comap] end comm @[simp] theorem comap_principal {t : set β} : comap m (𝓟 t) = 𝓟 (m ⁻¹' t) := filter.ext $ λ s, ⟨λ ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, (preimage_mono hu).trans b, λ h, ⟨t, subset.refl t, h⟩⟩ @[simp] theorem comap_pure {b : β} : comap m (pure b) = 𝓟 (m ⁻¹' {b}) := by rw [← principal_singleton, comap_principal] lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨λ h s ⟨t, ht, hts⟩, mem_of_superset (h ht) hts, λ h s ht, h ⟨_, ht, subset.rfl⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := λ f g, map_le_iff_le_comap @[mono] lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l @[mono] lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆ i, f i) = (⨆ i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅ i, f i) = (⨅ i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by { rw [comap_top], exact le_top } lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ λ s _, ⟨∅, by simp only [mem_bot], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆ i, comap m (f i)) := le_antisymm (λ s hs, have ∀ i, ∃ t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap, exists_prop, mem_supr] using mem_supr.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃ i, t i, mem_supr.2 $ λ i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], exact λ i, (ht i).2 end⟩) (supr_le $ λ i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆ f ∈ s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := by rw [sup_eq_supr, comap_supr, supr_bool_eq, bool.cond_tt, bool.cond_ff] lemma map_comap (f : filter β) (m : α → β) : (f.comap m).map m = f ⊓ 𝓟 (range m) := begin refine le_antisymm (le_inf map_comap_le $ le_principal_iff.2 range_mem_map) _, rintro t' ⟨t, ht, sub⟩, refine mem_inf_principal.2 (mem_of_superset ht _), rintro _ hxt ⟨x, rfl⟩, exact sub hxt end lemma map_comap_of_mem {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := by rw [map_comap, inf_eq_left.2 (le_principal_iff.2 hf)] lemma comap_le_comap_iff {f g : filter β} {m : α → β} (hf : range m ∈ f) : comap m f ≤ comap m g ↔ f ≤ g := ⟨λ h, map_comap_of_mem hf ▸ (map_mono h).trans map_comap_le, λ h, comap_mono h⟩ theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := map_comap_of_mem $ by simp only [hf.range_eq, univ_mem] lemma subtype_coe_map_comap (s : set α) (f : filter α) : map (coe : s → α) (comap (coe : s → α) f) = f ⊓ 𝓟 s := by rw [map_comap, subtype.range_coe] lemma subtype_coe_map_comap_prod (s : set α) (f : filter (α × α)) : map (coe : s × s → α × α) (comap (coe : s × s → α × α) f) = f ⊓ 𝓟 (s.prod s) := have (coe : s × s → α × α) = (λ x, (x.1, x.2)), by ext ⟨x, y⟩; refl, by simp [this, map_comap, ← prod_range_range_eq] lemma image_mem_of_mem_comap {f : filter α} {c : β → α} (h : range c ∈ f) {W : set β} (W_in : W ∈ comap c f) : c '' W ∈ f := begin rw ← map_comap_of_mem h, exact image_mem_map W_in end lemma image_coe_mem_of_mem_comap {f : filter α} {U : set α} (h : U ∈ f) {W : set U} (W_in : W ∈ comap (coe : U → α) f) : coe '' W ∈ f := image_mem_of_mem_comap (by simp [h]) W_in lemma comap_map {f : filter α} {m : α → β} (h : function.injective m) : comap m (map m f) = f := le_antisymm (λ s hs, mem_of_superset (preimage_mem_comap $ image_mem_map hs) $ by simp only [preimage_image_eq s h]) le_comap_map lemma mem_comap_iff {f : filter β} {m : α → β} (inj : function.injective m) (large : set.range m ∈ f) {S : set α} : S ∈ comap m f ↔ m '' S ∈ f := by rw [← image_mem_map_iff inj, map_comap_of_mem large] lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := λ t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem hsg ht)] λ a has ⟨b, ⟨hbs, hb⟩, h⟩, hm _ hbs _ has h ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : function.injective m) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this lemma comap_ne_bot_iff {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin rw ← forall_mem_nonempty_iff_ne_bot, exact ⟨λ h t t_in, h (m ⁻¹' t) ⟨t, t_in, subset.rfl⟩, λ h s ⟨u, u_in, hu⟩, let ⟨x, hx⟩ := h u u_in in ⟨x, hu hx⟩⟩, end lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀ t ∈ f, ∃ a, m a ∈ t) : ne_bot (comap m f) := comap_ne_bot_iff.mpr hm lemma comap_ne_bot_iff_frequently {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∃ᶠ y in f, y ∈ range m := by simp [comap_ne_bot_iff, frequently_iff, ← exists_and_distrib_left, and.comm] lemma comap_ne_bot_iff_compl_range {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ (range m)ᶜ ∉ f := comap_ne_bot_iff_frequently lemma ne_bot.comap_of_range_mem {f : filter β} {m : α → β} (hf : ne_bot f) (hm : range m ∈ f) : ne_bot (comap m f) := comap_ne_bot_iff_frequently.2 $ eventually.frequently hm lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f ⊓ 𝓟 s) := begin refine ⟨compl_compl s ▸ mt mem_of_eq_bot _⟩, rintro ⟨t, ht, hts⟩, rcases hf.nonempty_of_mem (inter_mem hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma comap_coe_ne_bot_of_le_principal {s : set γ} {l : filter γ} [h : ne_bot l] (h' : l ≤ 𝓟 s) : ne_bot (comap (coe : s → γ) l) := h.comap_of_range_mem $ (@subtype.range_coe γ s).symm ▸ h' (mem_principal_self s) lemma ne_bot.comap_of_surj {f : filter β} {m : α → β} (hf : ne_bot f) (hm : function.surjective m) : ne_bot (comap m f) := hf.comap_of_range_mem $ univ_mem' hm lemma ne_bot.comap_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f) := hf.comap_of_range_mem $ mem_of_superset hs (image_subset_range _ _) @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by { rw [←empty_mem_iff_bot, ←empty_mem_iff_bot], exact id }, λ h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot_iff (f : α → β) {F : filter α} : ne_bot (map f F) ↔ ne_bot F := by simp only [ne_bot_iff, ne, map_eq_bot_iff] lemma ne_bot.map (hf : ne_bot f) (m : α → β) : ne_bot (map m f) := (map_ne_bot_iff m).2 hf instance map_ne_bot [hf : ne_bot f] : ne_bot (f.map m) := hf.map m lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀ (comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, filter.mem_sets, mem_comap, this, and_imp, exists_prop, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ λ i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) [nonempty ι] : map m (infi f) = (⨅ i, map m (f i)) := map_infi_le.antisymm (λ s (hs : preimage m s ∈ infi f), let ⟨i, hi⟩ := (mem_infi_of_directed hf _).1 hs in have (⨅ i, map m (f i)) ≤ 𝓟 s, from infi_le_of_le i $ by { simp only [le_principal_iff, mem_map], assumption }, filter.le_principal_iff.1 this) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃ i, p i) : map m (⨅ i (h : p i), f i) = (⨅ i (h : p i), map m (f i)) := begin haveI := nonempty_subtype.2 ne, simp only [infi_subtype'], exact map_infi_eq h.directed_coe end lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀ x ∈ t, ∀ y ∈ t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm map_inf_le (λ s hs, _), simp only [mem_inf_iff, exists_prop, mem_map, mem_preimage, mem_inf_iff] at hs, rcases hs with ⟨t₁, h₁, t₂, h₂, hs : m ⁻¹' s = t₁ ∩ t₂⟩, have : m '' (t₁ ∩ t) ∩ m '' (t₂ ∩ t) ∈ map m f ⊓ map m g, { apply inter_mem_inf ; apply image_mem_map, exacts [inter_mem h₁ htf, inter_mem h₂ htg] }, apply mem_of_superset this, { rw [image_inter_on], { refine image_subset_iff.2 _, rw hs, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem univ_mem (λ x _ y _ hxy, h hxy) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (λ b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (λ b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀ s ∈ f, m '' s ∈ g) : g ≤ f.map m := λ s hs, mem_of_superset (h _ hs) $ image_preimage_subset _ _ protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) : map f (F ⊓ comap f G) = map f F ⊓ G := begin apply le_antisymm, { calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le ... ≤ map f F ⊓ G : inf_le_inf_left (map f F) map_comap_le }, { rintro U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩, apply mem_inf_of_inter (image_mem_map V_in) Z_in, calc f '' V ∩ Z = f '' (V ∩ f ⁻¹' Z) : by rw image_inter_preimage ... ⊆ f '' (V ∩ W) : image_subset _ (inter_subset_inter_right _ ‹_›) ... = f '' (f ⁻¹' U) : by rw h ... ⊆ U : image_preimage_subset f U } end protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) : map f (comap f G ⊓ F) = G ⊓ map f F := by simp only [filter.push_pull, inf_comm] section applicative lemma singleton_mem_pure {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_injective : function.injective (pure : α → filter α) := λ a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl instance pure_ne_bot {α : Type u} {a : α} : ne_bot (pure a) := ⟨mt empty_mem_iff_bot.2 $ not_mem_empty a⟩ @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure, λ h s hs, mem_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃ u ∈ f, ∃ t ∈ g, ∀ x ∈ u, ∀ y ∈ t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃ u ∈ f, ∃ t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃ t u, t ∈ g ∧ u ∈ f ∧ ∀ x ∈ u, ∀ y ∈ t, m x y ∈ s) := iff.intro (λ ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, λ a, hts _⟩) (λ ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, λ f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, λ f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀ t ∈ f, ∀ u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := λ s ⟨t, ht, u, hu, hs⟩, mem_of_superset (hh _ ht _ hu) $ λ b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha @[mono] lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ λ s hs t ht, seq_mem_seq (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ λ s hs, _) (le_seq $ λ s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq _ hs, exact singleton_mem_pure }, { refine sets_of_superset (map g f) (image_mem_map ht) _, rintro b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λ g : α → β, g a) f := begin refine le_antisymm (le_map $ λ s hs, _) (le_seq $ λ s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq hs singleton_mem_pure }, { refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintro b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ λ s hs t ht, _) (le_seq $ λ s hs t ht, _), { rcases mem_seq_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_iff_exists_image.1 hu with ⟨w, hw, hu⟩, refine mem_of_superset _ (set.seq_mono ((set.seq_mono hu subset.rfl).trans hs) subset.rfl), rw ← set.seq_seq, exact seq_mem_seq hw (seq_mem_seq hv ht) }, { rcases mem_seq_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_of_superset _ (set.seq_mono subset.rfl ht), rw set.seq_seq, exact seq_mem_seq (seq_mem_seq (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λ b a, (a, b)) g) f := begin refine le_antisymm (le_seq $ λ s hs t ht, _) (le_seq $ λ s hs t ht, _), { rcases mem_map_iff_exists_image.1 hs with ⟨u, hu, hs⟩, refine mem_of_superset _ (set.seq_mono hs subset.rfl), rw ← set.prod_image_seq_comm, exact seq_mem_seq (image_mem_map ht) hu }, { rcases mem_map_iff_exists_image.1 hs with ⟨u, hu, hs⟩, refine mem_of_superset _ (set.seq_mono hs subset.rfl), rw set.prod_image_seq_comm, exact seq_mem_seq (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := λ α f, map_id, comp_map := λ α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := λ α β, pure_seq_eq_map, map_pure := λ α β, map_pure, seq_pure := λ α β, seq_pure, seq_assoc := λ α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨λ α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /-! #### `bind` equations -/ section bind @[simp] lemma eventually_bind {f : filter α} {m : α → filter β} {p : β → Prop} : (∀ᶠ y in bind f m, p y) ↔ ∀ᶠ x in f, ∀ᶠ y in m x, p y := iff.rfl @[simp] lemma eventually_eq_bind {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ =ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ =ᶠ[m x] g₂ := iff.rfl @[simp] lemma eventually_le_bind [has_le γ] {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ ≤ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ ≤ᶠ[m x] g₂ := iff.rfl lemma mem_bind' {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ {a | s ∈ m a} ∈ f := iff.rfl @[simp] lemma mem_bind {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃ t ∈ f, ∀ x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : iff.rfl ... ↔ (∃ t ∈ f, t ⊆ {a | s ∈ m a}) : exists_mem_subset_iff.symm ... ↔ (∃ t ∈ f, ∀ x ∈ t, s ∈ m x) : iff.rfl lemma bind_le {f : filter α} {g : α → filter β} {l : filter β} (h : ∀ᶠ x in f, g x ≤ l) : f.bind g ≤ l := join_le $ eventually_map.2 h @[mono] lemma bind_mono {f₁ f₂ : filter α} {g₁ g₂ : α → filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ᶠ[f₁] g₂) : bind f₁ g₁ ≤ bind f₂ g₂ := begin refine le_trans (λ s hs, _) (join_mono $ map_mono hf), simp only [mem_join, mem_bind', mem_map] at hs ⊢, filter_upwards [hg, hs], exact λ x hx hs, hx hs end lemma bind_inf_principal {f : filter α} {g : α → filter β} {s : set β} : f.bind (λ x, g x ⊓ 𝓟 s) = (f.bind g) ⊓ 𝓟 s := filter.ext $ λ s, by simp only [mem_bind, mem_inf_principal] lemma sup_bind {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma principal_bind {s : set α} {f : α → filter β} : (bind (𝓟 s) f) = (⨆ x ∈ s, f x) := show join (map f (𝓟 s)) = (⨆ x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind section list_traverse /- This is a separate section in order to open `list`, but mostly because of universe equality requirements in `traverse` -/ open list lemma sequence_mono : ∀ (as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_rfl | (a :: as) (b :: bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) variables {α' β' γ' : Type u} {f : β' → filter α'} {s : γ' → set α'} lemma mem_traverse : ∀ (fs : list β') (us : list γ'), forall₂ (λ b c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure.2 $ mem_singleton _ | (f :: fs) (u :: us) (forall₂.cons h hs) := seq_mem_seq (image_mem_map h) (mem_traverse fs us hs) lemma mem_traverse_iff (fs : list β') (t : set (list α')) : t ∈ traverse f fs ↔ (∃ us : list (set α'), forall₂ (λ b (s : set α'), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure, imp_self, forall₂_nil_left_iff, exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { intro ht, rcases mem_seq_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_iff_exists_image.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, (set.seq_mono hwu hu).trans ht⟩ } }, { rintro ⟨us, hus, hs⟩, exact mem_of_superset (mem_traverse _ _ hus) hs } end end list_traverse /-! ### Limits -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ ⦃p : β → Prop⦄, (∀ᶠ y in l₂, p y) → ∀ᶠ x in l₁, p (f x) := iff.rfl lemma tendsto.eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∀ᶠ y in l₂, p y) : ∀ᶠ x in l₁, p (f x) := hf h lemma tendsto.frequently {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∃ᶠ x in l₁, p (f x)) : ∃ᶠ y in l₂, p y := mt hf.eventually h lemma tendsto.frequently_map {l₁ : filter α} {l₂ : filter β} {p : α → Prop} {q : β → Prop} (f : α → β) (c : filter.tendsto f l₁ l₂) (w : ∀ x, p x → q (f x)) (h : ∃ᶠ x in l₁, p x) : ∃ᶠ y in l₂, q y := c.frequently (h.mono w) @[simp] lemma tendsto_bot {f : α → β} {l : filter β} : tendsto f ⊥ l := by simp [tendsto] @[simp] lemma tendsto_top {f : α → β} {l : filter α} : tendsto f l ⊤ := le_top lemma le_map_of_right_inverse {mab : α → β} {mba : β → α} {f : filter α} {g : filter β} (h₁ : mab ∘ mba =ᶠ[g] id) (h₂ : tendsto mba g f) : g ≤ map mab f := by { rw [← @map_id _ g, ← map_congr h₁, ← map_map], exact map_mono h₂ } lemma tendsto_of_is_empty [is_empty α] {f : α → β} {la : filter α} {lb : filter β} : tendsto f la lb := by simp only [filter_eq_bot_of_is_empty la, tendsto_bot] lemma eventually_eq_of_left_inv_of_right_inv {f : α → β} {g₁ g₂ : β → α} {fa : filter α} {fb : filter β} (hleft : ∀ᶠ x in fa, g₁ (f x) = x) (hright : ∀ᶠ y in fb, f (g₂ y) = y) (htendsto : tendsto g₂ fb fa) : g₁ =ᶠ[fb] g₂ := (htendsto.eventually hleft).mp $ hright.mono $ λ y hr hl, (congr_arg g₁ hr.symm).trans hl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap alias tendsto_iff_comap ↔ filter.tendsto.le_comap _ lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_congr hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto.mono_left {f : α → β} {x y : filter α} {z : filter β} (hx : tendsto f x z) (h : y ≤ x) : tendsto f y z := (map_mono h).trans hx lemma tendsto.mono_right {f : α → β} {x : filter α} {y z : filter β} (hy : tendsto f x y) (hz : y ≤ z) : tendsto f x z := le_trans hy hz lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) [hx : ne_bot x] : ne_bot y := (hx.map _).mono h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by { rw [tendsto, map_map], refl } lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨λ h, tendsto_comap.comp h, λ h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by { rw [tendsto, ← map_compose], simp only [(∘), map_comap_of_mem h, tendsto] } lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine ((comap_mono $ map_le_iff_le_comap.1 hψ).trans _).antisymm (map_le_iff_le_comap.1 hφ), rw [comap_comap, eq, comap_id], exact le_rfl end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_rfl end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ @[simp] lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅ i, y i) ↔ ∀ i, tendsto f x (y i) := by simp only [tendsto, iff_self, le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) (hi : tendsto f (x i) y) : tendsto f (⨅ i, x i) y := hi.mono_left $ infi_le _ _ lemma tendsto_sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f (x₁ ⊔ x₂) y ↔ tendsto f x₁ y ∧ tendsto f x₂ y := by simp only [tendsto, map_sup, sup_le_iff] lemma tendsto.sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f x₁ y → tendsto f x₂ y → tendsto f (x₁ ⊔ x₂) y := λ h₁ h₂, tendsto_sup.mpr ⟨ h₁, h₂ ⟩ @[simp] lemma tendsto_supr {f : α → β} {x : ι → filter α} {y : filter β} : tendsto f (⨆ i, x i) y ↔ ∀ i, tendsto f (x i) y := by simp only [tendsto, map_supr, supr_le_iff] @[simp] lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} : tendsto f l (𝓟 s) ↔ ∀ᶠ a in l, f a ∈ s := by simp only [tendsto, le_principal_iff, mem_map', filter.eventually] @[simp] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (𝓟 s) (𝓟 t) ↔ ∀ a ∈ s, f a ∈ t := by simp only [tendsto_principal, eventually_principal] @[simp] lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ ∀ᶠ x in a, f x = b := by simp only [tendsto, le_pure_iff, mem_map', mem_singleton_iff, filter.eventually] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λ x, b) a (pure b) := tendsto_pure.2 $ univ_mem' $ λ _, rfl lemma pure_le_iff {a : α} {l : filter α} : pure a ≤ l ↔ ∀ s ∈ l, a ∈ s := iff.rfl lemma tendsto_pure_left {f : α → β} {a : α} {l : filter β} : tendsto f (pure a) l ↔ ∀ s ∈ l, f a ∈ s := iff.rfl @[simp] lemma map_inf_principal_preimage {f : α → β} {s : set β} {l : filter α} : map f (l ⊓ 𝓟 (f ⁻¹' s)) = map f l ⊓ 𝓟 s := filter.ext $ λ t, by simp only [mem_map', mem_inf_principal, mem_set_of_eq, mem_preimage] /-- If two filters are disjoint, then a function cannot tend to both of them along a non-trivial filter. -/ lemma tendsto.not_tendsto {f : α → β} {a : filter α} {b₁ b₂ : filter β} (hf : tendsto f a b₁) [ne_bot a] (hb : disjoint b₁ b₂) : ¬ tendsto f a b₂ := λ hf', (tendsto_inf.2 ⟨hf, hf'⟩).ne_bot.ne hb.eq_bot lemma tendsto.if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [∀ x, decidable (p x)] (h₀ : tendsto f (l₁ ⊓ 𝓟 {x | p x}) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin simp only [tendsto_def, mem_inf_principal] at *, intros s hs, filter_upwards [h₀ s hs, h₁ s hs], simp only [mem_preimage], intros x hp₀ hp₁, split_ifs, exacts [hp₀ h, hp₁ h] end lemma tendsto.piecewise {l₁ : filter α} {l₂ : filter β} {f g : α → β} {s : set α} [∀ x, decidable (x ∈ s)] (h₀ : tendsto f (l₁ ⊓ 𝓟 s) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 sᶜ) l₂) : tendsto (piecewise s f g) l₁ l₂ := h₀.if h₁ /-! ### Products of filters -/ section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃ n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀ i:ℕ, ∃ n, [n..∞] × {i} ⊆ s Now ⋃ i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd localized "infix ` ×ᶠ `:60 := filter.prod" in filter lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ f ×ᶠ g := inter_mem_inf (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f ×ᶠ g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, { rintro ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, rfl⟩, exact ⟨s₁, hs₁, s₂, hs₂, λ p ⟨h, h'⟩, ⟨hts₁ h, hts₂ h'⟩⟩ }, { rintro ⟨t₁, ht₁, t₂, ht₂, h⟩, exact mem_inf_of_inter (preimage_mem_comap ht₁) (preimage_mem_comap ht₂) h } end @[simp] lemma prod_mem_prod_iff {s : set α} {t : set β} {f : filter α} {g : filter β} [f.ne_bot] [g.ne_bot] : s.prod t ∈ f ×ᶠ g ↔ s ∈ f ∧ t ∈ g := ⟨λ h, let ⟨s', hs', t', ht', H⟩ := mem_prod_iff.1 h in (prod_subset_prod_iff.1 H).elim (λ ⟨hs's, ht't⟩, ⟨mem_of_superset hs' hs's, mem_of_superset ht' ht't⟩) (λ h, h.elim (λ hs'e, absurd hs'e (nonempty_of_mem hs').ne_empty) (λ ht'e, absurd ht'e (nonempty_of_mem ht').ne_empty)), λ h, prod_mem_prod h.1 h.2⟩ lemma comap_prod (f : α → β × γ) (b : filter β) (c : filter γ) : comap f (b ×ᶠ c) = (comap (prod.fst ∘ f) b) ⊓ (comap (prod.snd ∘ f) c) := by erw [comap_inf, filter.comap_comap, filter.comap_comap] lemma sup_prod (f₁ f₂ : filter α) (g : filter β) : (f₁ ⊔ f₂) ×ᶠ g = (f₁ ×ᶠ g) ⊔ (f₂ ×ᶠ g) := by rw [filter.prod, comap_sup, inf_sup_right, ← filter.prod, ← filter.prod] lemma prod_sup (f : filter α) (g₁ g₂ : filter β) : f ×ᶠ (g₁ ⊔ g₂) = (f ×ᶠ g₁) ⊔ (f ×ᶠ g₂) := by rw [filter.prod, comap_sup, inf_sup_left, ← filter.prod, ← filter.prod] lemma eventually_prod_iff {p : α × β → Prop} {f : filter α} {g : filter β} : (∀ᶠ x in f ×ᶠ g, p x) ↔ ∃ (pa : α → Prop) (ha : ∀ᶠ x in f, pa x) (pb : β → Prop) (hb : ∀ᶠ y in g, pb y), ∀ {x}, pa x → ∀ {y}, pb y → p (x, y) := by simpa only [set.prod_subset_iff] using @mem_prod_iff α β p f g lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (f ×ᶠ g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (f ×ᶠ g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λ x, (m₁ x, m₂ x)) f (g ×ᶠ h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma eventually.prod_inl {la : filter α} {p : α → Prop} (h : ∀ᶠ x in la, p x) (lb : filter β) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).1 := tendsto_fst.eventually h lemma eventually.prod_inr {lb : filter β} {p : β → Prop} (h : ∀ᶠ x in lb, p x) (la : filter α) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).2 := tendsto_snd.eventually h lemma eventually.prod_mk {la : filter α} {pa : α → Prop} (ha : ∀ᶠ x in la, pa x) {lb : filter β} {pb : β → Prop} (hb : ∀ᶠ y in lb, pb y) : ∀ᶠ p in la ×ᶠ lb, pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl lb).and (hb.prod_inr la) lemma eventually.curry {la : filter α} {lb : filter β} {p : α × β → Prop} (h : ∀ᶠ x in la ×ᶠ lb, p x) : ∀ᶠ x in la, ∀ᶠ y in lb, p (x, y) := begin rcases eventually_prod_iff.1 h with ⟨pa, ha, pb, hb, h⟩, exact ha.mono (λ a ha, hb.mono $ λ b hb, h ha hb) end lemma prod_infi_left [nonempty ι] {f : ι → filter α} {g : filter β}: (⨅ i, f i) ×ᶠ g = (⨅ i, (f i) ×ᶠ g) := by { rw [filter.prod, comap_infi, infi_inf], simp only [filter.prod, eq_self_iff_true] } lemma prod_infi_right [nonempty ι] {f : filter α} {g : ι → filter β} : f ×ᶠ (⨅ i, g i) = (⨅ i, f ×ᶠ (g i)) := by { rw [filter.prod, comap_infi, inf_infi], simp only [filter.prod, eq_self_iff_true] } @[mono] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ ×ᶠ g₁ ≤ f₂ ×ᶠ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : (comap m₁ f₁) ×ᶠ (comap m₂ f₂) = comap (λ p : β₁×β₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := by simp only [filter.prod, comap_comap, eq_self_iff_true, comap_inf] lemma prod_comm' : f ×ᶠ g = comap (prod.swap) (g ×ᶠ f) := by simp only [filter.prod, comap_comap, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : f ×ᶠ g = map (λ p : β×α, (p.2, p.1)) (g ×ᶠ f) := by { rw [prod_comm', ← map_swap_eq_comap_swap], refl } lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : (map m₁ f₁) ×ᶠ (map m₂ f₂) = map (λ p : α₁×α₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := le_antisymm (λ s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λ p : α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp le_rfl tendsto_fst).prod_mk (tendsto.comp le_rfl tendsto_snd)) lemma prod_map_map_eq' {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} (f : α₁ → α₂) (g : β₁ → β₂) (F : filter α₁) (G : filter β₁) : (map f F) ×ᶠ (map g G) = map (prod.map f g) (F ×ᶠ G) := prod_map_map_eq lemma tendsto.prod_map {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a ×ᶠ b) (c ×ᶠ d) := begin erw [tendsto, ← prod_map_map_eq], exact filter.prod_mono hf hg, end lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f ×ᶠ g) = (f.map (λ a b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], intro s, split, exact λ ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, λ x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact λ ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, λ ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f ×ᶠ g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : (f₁ ×ᶠ g₁) ⊓ (f₂ ×ᶠ g₂) = (f₁ ⊓ f₂) ×ᶠ (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, inf_left_comm] @[simp] lemma prod_bot {f : filter α} : f ×ᶠ (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : (⊥ : filter α) ×ᶠ g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : (𝓟 s) ×ᶠ (𝓟 t) = 𝓟 (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma pure_prod {a : α} {f : filter β} : pure a ×ᶠ f = map (prod.mk a) f := by rw [prod_eq, map_pure, pure_seq_eq_map] @[simp] lemma prod_pure {f : filter α} {b : β} : f ×ᶠ pure b = map (λ a, (a, b)) f := by rw [prod_eq, seq_pure, map_map] lemma prod_pure_pure {a : α} {b : β} : (pure a) ×ᶠ (pure b) = pure (a, b) := by simp lemma prod_eq_bot {f : filter α} {g : filter β} : f ×ᶠ g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { intro h, rcases mem_prod_iff.1 (empty_mem_iff_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_mem_iff_bot.1 (s_eq ▸ hs) }, { right, exact empty_mem_iff_bot.1 (t_eq ▸ ht) } }, { rintro (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : ne_bot (f ×ᶠ g) ↔ (ne_bot f ∧ ne_bot g) := by simp only [ne_bot_iff, ne, prod_eq_bot, not_or_distrib] lemma ne_bot.prod {f : filter α} {g : filter β} (hf : ne_bot f) (hg : ne_bot g) : ne_bot (f ×ᶠ g) := prod_ne_bot.2 ⟨hf, hg⟩ instance prod_ne_bot' {f : filter α} {g : filter β} [hf : ne_bot f] [hg : ne_bot g] : ne_bot (f ×ᶠ g) := hf.prod hg lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (x ×ᶠ y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod /-! ### Coproducts of filters -/ section coprod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /-- Coproduct of filters. -/ protected def coprod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊔ g.comap prod.snd lemma mem_coprod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f.coprod g ↔ ((∃ t₁ ∈ f, prod.fst ⁻¹' t₁ ⊆ s) ∧ (∃ t₂ ∈ g, prod.snd ⁻¹' t₂ ⊆ s)) := by simp [filter.coprod] @[mono] lemma coprod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.coprod g₁ ≤ f₂.coprod g₂ := sup_le_sup (comap_mono hf) (comap_mono hg) lemma principal_coprod_principal (s : set α) (t : set β) : (𝓟 s).coprod (𝓟 t) = 𝓟 (sᶜ.prod tᶜ)ᶜ := begin rw [filter.coprod, comap_principal, comap_principal, sup_principal], congr, ext x, simp ; tauto, end -- this inequality can be strict; see `map_const_principal_coprod_map_id_principal` and -- `map_prod_map_const_id_principal_coprod_principal` below. lemma map_prod_map_coprod_le {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : map (prod.map m₁ m₂) (f₁.coprod f₂) ≤ (map m₁ f₁).coprod (map m₂ f₂) := begin intros s, simp only [mem_map, mem_coprod_iff], rintro ⟨⟨u₁, hu₁, h₁⟩, u₂, hu₂, h₂⟩, refine ⟨⟨m₁ ⁻¹' u₁, hu₁, λ _ hx, h₁ _⟩, ⟨m₂ ⁻¹' u₂, hu₂, λ _ hx, h₂ _⟩⟩; convert hx end /-- Characterization of the coproduct of the `filter.map`s of two principal filters `𝓟 {a}` and `𝓟 {i}`, the first under the constant function `λ a, b` and the second under the identity function. Together with the next lemma, `map_prod_map_const_id_principal_coprod_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_const_principal_coprod_map_id_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : (map (λ _ : α, b) (𝓟 {a})).coprod (map id (𝓟 {i})) = 𝓟 (({b} : set β).prod (univ : set ι) ∪ (univ : set β).prod {i}) := begin rw [map_principal, map_principal, principal_coprod_principal], congr, ext ⟨b', i'⟩, simp, tauto, end /-- Characterization of the `filter.map` of the coproduct of two principal filters `𝓟 {a}` and `𝓟 {i}`, under the `prod.map` of two functions, respectively the constant function `λ a, b` and the identity function. Together with the previous lemma, `map_const_principal_coprod_map_id_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_prod_map_const_id_principal_coprod_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : map (prod.map (λ _ : α, b) id) ((𝓟 {a}).coprod (𝓟 {i})) = 𝓟 (({b} : set β).prod (univ : set ι)) := begin rw [principal_coprod_principal, map_principal], congr, ext ⟨b', i'⟩, split, { rintro ⟨⟨a'', i''⟩, h₁, h₂, h₃⟩, simp }, { rintro ⟨h₁, h₂⟩, use (a, i'), simpa using h₁.symm } end lemma tendsto.prod_map_coprod {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a.coprod b) (c.coprod d) := map_prod_map_coprod_le.trans (coprod_mono hf hg) end coprod /-! ### `n`-ary coproducts of filters -/ section Coprod variables {δ : Type*} {κ : δ → Type*} -- {f : Π d, filter (κ d)} /-- Coproduct of filters. -/ protected def Coprod (f : Π d, filter (κ d)) : filter (Π d, κ d) := ⨆ d : δ, (f d).comap (λ k, k d) lemma mem_Coprod_iff {s : set (Π d, κ d)} {f : Π d, filter (κ d)} : (s ∈ (filter.Coprod f)) ↔ (∀ d : δ, (∃ t₁ ∈ f d, (λ k : (Π d, κ d), k d) ⁻¹' t₁ ⊆ s)) := by simp [filter.Coprod] @[mono] lemma Coprod_mono {f₁ f₂ : Π d, filter (κ d)} (hf : ∀ d, f₁ d ≤ f₂ d) : filter.Coprod f₁ ≤ filter.Coprod f₂ := supr_le_supr $ λ d, comap_mono (hf d) lemma map_pi_map_Coprod_le {μ : δ → Type*} {f : Π d, filter (κ d)} {m : Π d, κ d → μ d} : map (λ (k : Π d, κ d), λ d, m d (k d)) (filter.Coprod f) ≤ filter.Coprod (λ d, map (m d) (f d)) := begin intros s h, rw [mem_map', mem_Coprod_iff], intros d, rw mem_Coprod_iff at h, obtain ⟨t, H, hH⟩ := h d, rw mem_map at H, refine ⟨{x : κ d | m d x ∈ t}, H, _⟩, intros x hx, simp only [mem_set_of_eq, preimage_set_of_eq] at hx, rw mem_set_of_eq, exact set.mem_of_subset_of_mem hH (mem_preimage.mpr hx), end lemma tendsto.pi_map_Coprod {μ : δ → Type*} {f : Π d, filter (κ d)} {m : Π d, κ d → μ d} {g : Π d, filter (μ d)} (hf : ∀ d, tendsto (m d) (f d) (g d)) : tendsto (λ (k : Π d, κ d), λ d, m d (k d)) (filter.Coprod f) (filter.Coprod g) := map_pi_map_Coprod_le.trans (Coprod_mono hf) end Coprod end filter open_locale filter lemma set.eq_on.eventually_eq {α β} {s : set α} {f g : α → β} (h : eq_on f g s) : f =ᶠ[𝓟 s] g := h lemma set.eq_on.eventually_eq_of_mem {α β} {s : set α} {l : filter α} {f g : α → β} (h : eq_on f g s) (hl : s ∈ l) : f =ᶠ[l] g := h.eventually_eq.filter_mono $ filter.le_principal_iff.2 hl lemma set.subset.eventually_le {α} {l : filter α} {s t : set α} (h : s ⊆ t) : s ≤ᶠ[l] t := filter.eventually_of_forall h lemma set.maps_to.tendsto {α β} {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) : filter.tendsto f (𝓟 s) (𝓟 t) := filter.tendsto_principal_principal.2 h
53809edb09193c263dba7f089c5cf84341410386
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/qpf/multivariate/constructions/cofix.lean
ba67e60e0df8beeccc48b7e72f272a8dc2fc8d1e
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
19,005
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import control.functor.multivariate import data.pfunctor.multivariate.basic import data.pfunctor.multivariate.M import data.qpf.multivariate.basic /-! # The final co-algebra of a multivariate qpf is again a qpf. For a `(n+1)`-ary QPF `F (α₀,..,αₙ)`, we take the least fixed point of `F` with regards to its last argument `αₙ`. The result is a `n`-ary functor: `fix F (α₀,..,αₙ₋₁)`. Making `fix F` into a functor allows us to take the fixed point, compose with other functors and take a fixed point again. ## Main definitions * `cofix.mk` - constructor * `cofix.dest` - destructor * `cofix.corec` - corecursor: useful for formulating infinite, productive computations * `cofix.bisim` - bisimulation: proof technique to show the equality of possibly infinite values of `cofix F α` ## Implementation notes For `F` a QPF, we define `cofix F α` in terms of the M-type of the polynomial functor `P` of `F`. We define the relation `Mcongr` and take its quotient as the definition of `cofix F α`. `Mcongr` is taken as the weakest bisimulation on M-type. See [avigad-carneiro-hudon2019] for more details. ## Reference * Jeremy Avigad, Mario M. Carneiro and Simon Hudon. [*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u open_locale mvfunctor namespace mvqpf open typevec mvpfunctor open mvfunctor (liftp liftr) variables {n : ℕ} {F : typevec.{u} (n+1) → Type u} [mvfunctor F] [q : mvqpf F] include q /-- `corecF` is used as a basis for defining the corecursor of `cofix F α`. `corecF` uses corecursion to construct the M-type generated by `q.P` and uses function on `F` as a corecursive step -/ def corecF {α : typevec n} {β : Type*} (g : β → F (α.append1 β)) : β → q.P.M α := M.corec _ (λ x, repr (g x)) theorem corecF_eq {α : typevec n} {β : Type*} (g : β → F (α.append1 β)) (x : β) : M.dest q.P (corecF g x) = append_fun id (corecF g) <$$> repr (g x) := by rw [corecF, M.dest_corec] /-- Characterization of desirable equivalence relations on M-types -/ def is_precongr {α : typevec n} (r : q.P.M α → q.P.M α → Prop) : Prop := ∀ ⦃x y⦄, r x y → abs (append_fun id (quot.mk r) <$$> M.dest q.P x) = abs (append_fun id (quot.mk r) <$$> M.dest q.P y) /-- Equivalence relation on M-types representing a value of type `cofix F` -/ def Mcongr {α : typevec n} (x y : q.P.M α) : Prop := ∃ r, is_precongr r ∧ r x y /-- Greatest fixed point of functor F. The result is a functor with one fewer parameters than the input. For `F a b c` a ternary functor, fix F is a binary functor such that ```lean cofix F a b = F a b (cofix F a b) ``` -/ def cofix (F : typevec (n + 1) → Type u) [mvfunctor F] [q : mvqpf F] (α : typevec n) := quot (@Mcongr _ F _ q α) instance {α : typevec n} [inhabited q.P.A] [Π (i : fin2 n), inhabited (α i)] : inhabited (cofix F α) := ⟨ quot.mk _ default ⟩ /-- maps every element of the W type to a canonical representative -/ def Mrepr {α : typevec n} : q.P.M α → q.P.M α := corecF (abs ∘ M.dest q.P) /-- the map function for the functor `cofix F` -/ def cofix.map {α β : typevec n} (g : α ⟹ β) : cofix F α → cofix F β := quot.lift (λ x : q.P.M α, quot.mk Mcongr (g <$$> x)) begin rintros aa₁ aa₂ ⟨r, pr, ra₁a₂⟩, apply quot.sound, let r' := λ b₁ b₂, ∃ a₁ a₂ : q.P.M α, r a₁ a₂ ∧ b₁ = g <$$> a₁ ∧ b₂ = g <$$> a₂, use r', split, { show is_precongr r', rintros b₁ b₂ ⟨a₁, a₂, ra₁a₂, b₁eq, b₂eq⟩, let u : quot r → quot r' := quot.lift (λ x : q.P.M α, quot.mk r' (g <$$> x)) (by { intros a₁ a₂ ra₁a₂, apply quot.sound, exact ⟨a₁, a₂, ra₁a₂, rfl, rfl⟩ }), have hu : (quot.mk r' ∘ λ x : q.P.M α, g <$$> x) = u ∘ quot.mk r, { ext x, refl }, rw [b₁eq, b₂eq, M.dest_map, M.dest_map, ←q.P.comp_map, ←q.P.comp_map], rw [←append_fun_comp, id_comp, hu, hu, ←comp_id g, append_fun_comp], rw [q.P.comp_map, q.P.comp_map, abs_map, pr ra₁a₂, ←abs_map] }, show r' (g <$$> aa₁) (g <$$> aa₂), from ⟨aa₁, aa₂, ra₁a₂, rfl, rfl⟩ end instance cofix.mvfunctor : mvfunctor (cofix F) := { map := @cofix.map _ _ _ _} /-- Corecursor for `cofix F` -/ def cofix.corec {α : typevec n} {β : Type u} (g : β → F (α.append1 β)) : β → cofix F α := λ x, quot.mk _ (corecF g x) /-- Destructor for `cofix F` -/ def cofix.dest {α : typevec n} : cofix F α → F (α.append1 (cofix F α)) := quot.lift (λ x, append_fun id (quot.mk Mcongr) <$$> (abs (M.dest q.P x))) begin rintros x y ⟨r, pr, rxy⟩, dsimp, have : ∀ x y, r x y → Mcongr x y, { intros x y h, exact ⟨r, pr, h⟩ }, rw [←quot.factor_mk_eq _ _ this], dsimp, conv { to_lhs, rw [append_fun_comp_id, comp_map, ←abs_map, pr rxy, abs_map, ←comp_map, ←append_fun_comp_id] } end /-- Abstraction function for `cofix F α` -/ def cofix.abs {α} : q.P.M α → cofix F α := quot.mk _ /-- Representation function for `cofix F α` -/ def cofix.repr {α} : cofix F α → q.P.M α := M.corec _ $ repr ∘ cofix.dest /-- Corecursor for `cofix F` -/ def cofix.corec'₁ {α : typevec n} {β : Type u} (g : Π {X}, (β → X) → F (α.append1 X)) (x : β) : cofix F α := cofix.corec (λ x, g id) x /-- More flexible corecursor for `cofix F`. Allows the return of a fully formed value instead of making a recursive call -/ def cofix.corec' {α : typevec n} {β : Type u} (g : β → F (α.append1 (cofix F α ⊕ β))) (x : β) : cofix F α := let f : α ::: cofix F α ⟹ α ::: (cofix F α ⊕ β) := id ::: sum.inl in cofix.corec (sum.elim (mvfunctor.map f ∘ cofix.dest) g) (sum.inr x : cofix F α ⊕ β) /-- Corecursor for `cofix F`. The shape allows recursive calls to look like recursive calls. -/ def cofix.corec₁ {α : typevec n} {β : Type u} (g : Π {X}, (cofix F α → X) → (β → X) → β → F (α ::: X)) (x : β) : cofix F α := cofix.corec' (λ x, g sum.inl sum.inr x) x theorem cofix.dest_corec {α : typevec n} {β : Type u} (g : β → F (α.append1 β)) (x : β) : cofix.dest (cofix.corec g x) = append_fun id (cofix.corec g) <$$> g x := begin conv { to_lhs, rw [cofix.dest, cofix.corec] }, dsimp, rw [corecF_eq, abs_map, abs_repr, ←comp_map, ←append_fun_comp], reflexivity end /-- constructor for `cofix F` -/ def cofix.mk {α : typevec n} : F (α.append1 $ cofix F α) → cofix F α := cofix.corec (λ x, append_fun id (λ i : cofix F α, cofix.dest.{u} i) <$$> x) /-! ## Bisimulation principles for `cofix F` The following theorems are bisimulation principles. The general idea is to use a bisimulation relation to prove the equality between specific values of type `cofix F α`. A bisimulation relation `R` for values `x y : cofix F α`: * holds for `x y`: `R x y` * for any values `x y` that satisfy `R`, their root has the same shape and their children can be paired in such a way that they satisfy `R`. -/ private theorem cofix.bisim_aux {α : typevec n} (r : cofix F α → cofix F α → Prop) (h' : ∀ x, r x x) (h : ∀ x y, r x y → append_fun id (quot.mk r) <$$> cofix.dest x = append_fun id (quot.mk r) <$$> cofix.dest y) : ∀ x y, r x y → x = y := begin intro x, apply quot.induction_on x, clear x, intros x y, apply quot.induction_on y, clear y, intros y rxy, apply quot.sound, let r' := λ x y, r (quot.mk _ x) (quot.mk _ y), have : is_precongr r', { intros a b r'ab, have h₀ : append_fun id (quot.mk r ∘ quot.mk Mcongr) <$$> abs (M.dest q.P a) = append_fun id (quot.mk r ∘ quot.mk Mcongr) <$$> abs (M.dest q.P b) := by rw [append_fun_comp_id, comp_map, comp_map]; exact h _ _ r'ab, have h₁ : ∀ u v : q.P.M α, Mcongr u v → quot.mk r' u = quot.mk r' v, { intros u v cuv, apply quot.sound, dsimp [r'], rw quot.sound cuv, apply h' }, let f : quot r → quot r' := quot.lift (quot.lift (quot.mk r') h₁) begin intro c, apply quot.induction_on c, clear c, intros c d, apply quot.induction_on d, clear d, intros d rcd, apply quot.sound, apply rcd end, have : f ∘ quot.mk r ∘ quot.mk Mcongr = quot.mk r' := rfl, rw [←this, append_fun_comp_id, q.P.comp_map, q.P.comp_map, abs_map, abs_map, abs_map, abs_map, h₀] }, refine ⟨r', this, rxy⟩ end /-- Bisimulation principle using `map` and `quot.mk` to match and relate children of two trees. -/ theorem cofix.bisim_rel {α : typevec n} (r : cofix F α → cofix F α → Prop) (h : ∀ x y, r x y → append_fun id (quot.mk r) <$$> cofix.dest x = append_fun id (quot.mk r) <$$> cofix.dest y) : ∀ x y, r x y → x = y := let r' x y := x = y ∨ r x y in begin intros x y rxy, apply cofix.bisim_aux r', { intro x, left, reflexivity }, { intros x y r'xy, cases r'xy, { rw r'xy }, have : ∀ x y, r x y → r' x y := λ x y h, or.inr h, rw ←quot.factor_mk_eq _ _ this, dsimp, rw [append_fun_comp_id, append_fun_comp_id], rw [@comp_map _ _ _ q _ _ _ (append_fun id (quot.mk r)), @comp_map _ _ _ q _ _ _ (append_fun id (quot.mk r))], rw h _ _ r'xy }, right, exact rxy end /-- Bisimulation principle using `liftr` to match and relate children of two trees. -/ theorem cofix.bisim {α : typevec n} (r : cofix F α → cofix F α → Prop) (h : ∀ x y, r x y → liftr (rel_last α r) (cofix.dest x) (cofix.dest y)) : ∀ x y, r x y → x = y := begin apply cofix.bisim_rel, intros x y rxy, rcases (liftr_iff (rel_last α r) _ _).mp (h x y rxy) with ⟨a, f₀, f₁, dxeq, dyeq, h'⟩, rw [dxeq, dyeq, ←abs_map, ←abs_map, mvpfunctor.map_eq, mvpfunctor.map_eq], rw [←split_drop_fun_last_fun f₀, ←split_drop_fun_last_fun f₁], rw [append_fun_comp_split_fun, append_fun_comp_split_fun], rw [id_comp, id_comp], congr' 2 with i j, cases i with _ i; dsimp, { apply quot.sound, apply h' _ j }, { change f₀ _ j = f₁ _ j, apply h' _ j }, end open mvfunctor /-- Bisimulation principle using `liftr'` to match and relate children of two trees. -/ theorem cofix.bisim₂ {α : typevec n} (r : cofix F α → cofix F α → Prop) (h : ∀ x y, r x y → liftr' (rel_last' α r) (cofix.dest x) (cofix.dest y)) : ∀ x y, r x y → x = y := cofix.bisim _ $ by intros; rw ← liftr_last_rel_iff; apply h; assumption /-- Bisimulation principle the values `⟨a,f⟩` of the polynomial functor representing `cofix F α` as well as an invariant `Q : β → Prop` and a state `β` generating the left-hand side and right-hand side of the equality through functions `u v : β → cofix F α` -/ theorem cofix.bisim' {α : typevec n} {β : Type*} (Q : β → Prop) (u v : β → cofix F α) (h : ∀ x, Q x → ∃ a f' f₀ f₁, cofix.dest (u x) = abs ⟨a, q.P.append_contents f' f₀⟩ ∧ cofix.dest (v x) = abs ⟨a, q.P.append_contents f' f₁⟩ ∧ ∀ i, ∃ x', Q x' ∧ f₀ i = u x' ∧ f₁ i = v x') : ∀ x, Q x → u x = v x := λ x Qx, let R := λ w z : cofix F α, ∃ x', Q x' ∧ w = u x' ∧ z = v x' in cofix.bisim R (λ x y ⟨x', Qx', xeq, yeq⟩, begin rcases h x' Qx' with ⟨a, f', f₀, f₁, ux'eq, vx'eq, h'⟩, rw liftr_iff, refine ⟨a, q.P.append_contents f' f₀, q.P.append_contents f' f₁, xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, _⟩, intro i, cases i, { apply h' }, { intro j, apply eq.refl }, end) _ _ ⟨x, Qx, rfl, rfl⟩ lemma cofix.mk_dest {α : typevec n} (x : cofix F α) : cofix.mk (cofix.dest x) = x := begin apply cofix.bisim_rel (λ x y : cofix F α, x = cofix.mk (cofix.dest y)) _ _ _ rfl, dsimp, intros x y h, rw h, conv { to_lhs, congr, skip, rw [cofix.mk], rw cofix.dest_corec}, rw [←comp_map, ←append_fun_comp, id_comp], rw [←comp_map, ←append_fun_comp, id_comp, ←cofix.mk], congr' 2 with u, apply quot.sound, refl end lemma cofix.dest_mk {α : typevec n} (x : F (α.append1 $ cofix F α)) : cofix.dest (cofix.mk x) = x := begin have : cofix.mk ∘ cofix.dest = @_root_.id (cofix F α) := funext cofix.mk_dest, rw [cofix.mk, cofix.dest_corec, ←comp_map, ←cofix.mk, ← append_fun_comp, this, id_comp, append_fun_id_id, mvfunctor.id_map] end lemma cofix.ext {α : typevec n} (x y : cofix F α) (h : x.dest = y.dest) : x = y := by rw [← cofix.mk_dest x,h,cofix.mk_dest] lemma cofix.ext_mk {α : typevec n} (x y : F (α ::: cofix F α)) (h : cofix.mk x = cofix.mk y) : x = y := by rw [← cofix.dest_mk x,h,cofix.dest_mk] /-! `liftr_map`, `liftr_map_last` and `liftr_map_last'` are useful for reasoning about the induction step in bisimulation proofs. -/ section liftr_map omit q theorem liftr_map {α β : typevec n} {F' : typevec n → Type u} [mvfunctor F'] [is_lawful_mvfunctor F'] (R : β ⊗ β ⟹ repeat n Prop) (x : F' α) (f g : α ⟹ β) (h : α ⟹ subtype_ R) (hh : subtype_val _ ⊚ h = (f ⊗' g) ⊚ prod.diag) : liftr' R (f <$$> x) (g <$$> x) := begin rw liftr_def, existsi h <$$> x, rw [mvfunctor.map_map,comp_assoc,hh,← comp_assoc,fst_prod_mk,comp_assoc,fst_diag], rw [mvfunctor.map_map,comp_assoc,hh,← comp_assoc,snd_prod_mk,comp_assoc,snd_diag], dsimp [liftr'], split; refl, end open function theorem liftr_map_last [is_lawful_mvfunctor F] {α : typevec n} {ι ι'} (R : ι' → ι' → Prop) (x : F (α ::: ι)) (f g : ι → ι') (hh : ∀ x : ι, R (f x) (g x)) : liftr' (rel_last' _ R) ((id ::: f) <$$> x) ((id ::: g) <$$> x) := let h : ι → { x : ι' × ι' // uncurry R x } := λ x, ⟨ (f x,g x), hh x ⟩ in let b : α ::: ι ⟹ _ := @diag_sub n α ::: h, c : subtype_ α.repeat_eq ::: {x // uncurry R x} ⟹ (λ (i : fin2 (n)), {x // of_repeat (α.rel_last' R i.fs x)}) ::: subtype (uncurry R) := of_subtype _ ::: id in have hh : subtype_val _ ⊚ to_subtype _ ⊚ from_append1_drop_last ⊚ c ⊚ b = (id ::: f ⊗' id ::: g) ⊚ prod.diag, by { dsimp [c,b], apply eq_of_drop_last_eq, { dsimp, simp only [prod_map_id, drop_fun_prod, drop_fun_append_fun, drop_fun_diag, id_comp, drop_fun_to_subtype], erw [to_subtype_of_subtype_assoc,id_comp], clear_except, ext i x : 2, induction i, refl, apply i_ih, }, simp only [h, last_fun_from_append1_drop_last, last_fun_to_subtype, last_fun_append_fun, last_fun_subtype_val, comp.left_id, last_fun_comp, last_fun_prod], dsimp, ext1, refl }, liftr_map _ _ _ _ (to_subtype _ ⊚ from_append1_drop_last ⊚ c ⊚ b) hh theorem liftr_map_last' [is_lawful_mvfunctor F] {α : typevec n} {ι} (R : ι → ι → Prop) (x : F (α ::: ι)) (f : ι → ι) (hh : ∀ x : ι, R (f x) x) : liftr' (rel_last' _ R) ((id ::: f) <$$> x) x := begin have := liftr_map_last R x f id hh, rwa [append_fun_id_id,mvfunctor.id_map] at this, end end liftr_map lemma cofix.abs_repr {α} (x : cofix F α) : quot.mk _ (cofix.repr x) = x := begin let R := λ x y : cofix F α, cofix.abs (cofix.repr y) = x, refine cofix.bisim₂ R _ _ _ rfl, clear x, rintros x y h, dsimp [R] at h, subst h, dsimp [cofix.dest,cofix.abs], induction y using quot.ind, simp only [cofix.repr, M.dest_corec, abs_map, abs_repr], conv { congr, skip, rw cofix.dest }, dsimp, rw [mvfunctor.map_map,mvfunctor.map_map,← append_fun_comp_id,← append_fun_comp_id], let f : α ::: (P F).M α ⟹ subtype_ (α.rel_last' R) := split_fun diag_sub (λ x, ⟨(cofix.abs (cofix.abs x).repr, cofix.abs x),_⟩), refine liftr_map _ _ _ _ f _, { simp only [←append_prod_append_fun, prod_map_id], apply eq_of_drop_last_eq, { dsimp, simp only [drop_fun_diag], erw subtype_val_diag_sub }, ext1, simp only [cofix.abs, prod.mk.inj_iff, prod_map, function.comp_app, last_fun_append_fun, last_fun_subtype_val, last_fun_comp, last_fun_split_fun], dsimp [drop_fun_rel_last,last_fun,prod.diag], split; refl, }, dsimp [rel_last',split_fun,function.uncurry,R], refl, end section tactic setup_tactic_parser open tactic omit q /-- tactic for proof by bisimulation -/ meta def mv_bisim (e : parse texpr) (ids : parse with_ident_list) : tactic unit := do e ← to_expr e, (expr.pi n bi d b) ← retrieve $ do { generalize e, target }, `(@eq %%t %%l %%r) ← pure b, x ← mk_local_def `n d, v₀ ← mk_local_def `a t, v₁ ← mk_local_def `b t, x₀ ← mk_app ``eq [v₀,l.instantiate_var x], x₁ ← mk_app ``eq [v₁,r.instantiate_var x], xx ← mk_app ``and [x₀,x₁], ex ← lambdas [x] xx, ex ← mk_app ``Exists [ex] >>= lambdas [v₀,v₁], R ← pose `R none ex, refine ``(cofix.bisim₂ %%R _ _ _ ⟨_,rfl,rfl⟩), let f (a b : name) : name := if a = `_ then b else a, let ids := (ids ++ list.replicate 5 `_).zip_with f [`a,`b,`x,`Ha,`Hb], (ids₀,w::ids₁) ← pure $ list.split_at 2 ids, intro_lst ids₀, h ← intro1, [(_,[w,h],_)] ← cases_core h [w], cases h ids₁, pure () run_cmd add_interactive [``mv_bisim] end tactic theorem corec_roll {α : typevec n} {X Y} {x₀ : X} (f : X → Y) (g : Y → F (α ::: X)) : cofix.corec (g ∘ f) x₀ = cofix.corec (mvfunctor.map (id ::: f) ∘ g) (f x₀) := begin mv_bisim x₀, rw [Ha,Hb,cofix.dest_corec,cofix.dest_corec], rw [mvfunctor.map_map,← append_fun_comp_id], refine liftr_map_last _ _ _ _ _, intros a, refine ⟨a,rfl,rfl⟩ end theorem cofix.dest_corec' {α : typevec n} {β : Type u} (g : β → F (α.append1 (cofix F α ⊕ β))) (x : β) : cofix.dest (cofix.corec' g x) = append_fun id (sum.elim id (cofix.corec' g)) <$$> g x := begin rw [cofix.corec',cofix.dest_corec], dsimp, congr' with (i|i); rw corec_roll; dsimp [cofix.corec'], { mv_bisim i, rw [Ha,Hb,cofix.dest_corec], dsimp [(∘)], repeat { rw [mvfunctor.map_map,← append_fun_comp_id] }, apply liftr_map_last', dsimp [(∘),R], intros, exact ⟨_,rfl,rfl⟩ }, { congr' with y, erw [append_fun_id_id], simp [mvfunctor.id_map] }, end theorem cofix.dest_corec₁ {α : typevec n} {β : Type u} (g : Π {X}, (cofix F α → X) → (β → X) → β → F (α.append1 X)) (x : β) (h : ∀ X Y (f : cofix F α → X) (f' : β → X) (k : X → Y), g (k ∘ f) (k ∘ f') x = (id ::: k) <$$> g f f' x) : cofix.dest (cofix.corec₁ @g x) = g id (cofix.corec₁ @g) x := by rw [cofix.corec₁,cofix.dest_corec',← h]; refl instance mvqpf_cofix : mvqpf (cofix F) := { P := q.P.Mp, abs := λ α, quot.mk Mcongr, repr := λ α, cofix.repr, abs_repr := λ α, cofix.abs_repr, abs_map := λ α β g x, rfl } end mvqpf
581da58d9a85d1c0360836016fc7137edab30497
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/Elab/Macro.lean
c85607869f48e641303e16d6105dca3a3acae850
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
1,682
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.MacroArgUtil namespace Lean.Elab.Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command @[builtinMacro Lean.Parser.Command.macro] def expandMacro : Macro | `($[$doc?:docComment]? $attrKind:attrKind macro$[:$prec?]? $[(name := $name?)]? $[(priority := $prio?)]? $args:macroArg* : $cat => $rhs) => do let prio ← evalOptPrio prio? let (stxParts, patArgs) := (← args.mapM expandMacroArg).unzip -- name let name ← match name? with | some name => pure name.getId | none => mkNameFromParserSyntax cat.getId (mkNullNode stxParts) /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let pat := Syntax.node ((← Macro.getCurrNamespace) ++ name) patArgs let stxCmd ← `($[$doc?:docComment]? $attrKind:attrKind syntax$[:$prec?]? (name := $(← mkIdentFromRef name)) (priority := $(quote prio)) $[$stxParts]* : $cat) let macroRulesCmd ← if rhs.getArgs.size == 1 then -- `rhs` is a `term` let rhs := rhs[0] `($[$doc?:docComment]? macro_rules | `($pat) => $rhs) else -- `rhs` is of the form `` `( $body ) `` let rhsBody := rhs[1] `($[$doc?:docComment]? macro_rules | `($pat) => `($rhsBody)) return mkNullNode #[stxCmd, macroRulesCmd] | _ => Macro.throwUnsupported end Lean.Elab.Command
52c1e346ef7e4ba03687453a94d62a64c6975ece
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/order.lean
4db4a590ae6fc36309aed6944123d08648a24e8a
[ "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
33,805
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 topology.tactic /-! # Ordering on topologies and (co)induced topologies Topologies on a fixed type `α` are ordered, by reverse inclusion. That is, for topologies `t₁` and `t₂` on `α`, we write `t₁ ≤ t₂` if every set open in `t₂` is also open in `t₁`. (One also calls `t₁` finer than `t₂`, and `t₂` coarser than `t₁`.) Any function `f : α → β` induces `induced f : topological_space β → topological_space α` and `coinduced f : topological_space α → topological_space β`. Continuity, the ordering on topologies and (co)induced topologies are related as follows: * The identity map (α, t₁) → (α, t₂) is continuous iff t₁ ≤ t₂. * A map f : (α, t) → (β, u) is continuous iff t ≤ induced f u (`continuous_iff_le_induced`) iff coinduced f t ≤ u (`continuous_iff_coinduced_le`). Topologies on α form a complete lattice, with ⊥ the discrete topology and ⊤ the indiscrete topology. For a function f : α → β, (coinduced f, induced f) is a Galois connection between topologies on α and topologies on β. ## Implementation notes There is a Galois insertion between topologies on α (with the inclusion ordering) and all collections of sets in α. The complete lattice structure on topologies on α is defined as the reverse of the one obtained via this Galois insertion. ## Tags finer, coarser, induced topology, coinduced topology -/ open set filter classical open_locale classical topological_space filter universes u v w namespace topological_space variables {α : Type u} /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generate_open (g : set (set α)) : set α → Prop | basic : ∀s∈g, generate_open s | univ : generate_open univ | inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t) | sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (g : set (set α)) : topological_space α := { is_open := generate_open g, is_open_univ := generate_open.univ, is_open_inter := generate_open.inter, is_open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set α)} {a : α} : @nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, 𝓟 s) := by rw nhds_def; exact le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, begin revert as, clear_, induction hs, case generate_open.basic : s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter : s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≤ 𝓟 s ⊓ 𝓟 t : le_inf (hs has) (ht hat) ... = _ : inf_principal }, case generate_open.sUnion : k hk' hk { exact λ ⟨t, htk, hat⟩, calc _ ≤ 𝓟 t : hk t htk hat ... ≤ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk } end) lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β} (h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f) : tendsto m f (@nhds β (generate_from g) b) := by rw [nhds_generate_from]; exact (tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs) /-- Construct a topology on α given the filter of neighborhoods of each point of α. -/ protected def mk_of_nhds (n : α → filter α) : topological_space α := { is_open := λs, ∀a∈s, s ∈ n a, is_open_univ := assume x h, univ_mem, is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem (hs x hxs) (ht x hxt), is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) } lemma nhds_mk_of_nhds (n : α → filter α) (a : α) (h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ n a → ∃ t ∈ n a, t ⊆ s ∧ ∀a' ∈ t, s ∈ n a') : @nhds α (topological_space.mk_of_nhds n) a = n a := begin letI := topological_space.mk_of_nhds n, refine le_antisymm (assume s hs, _) (assume s hs, _), { have h₀ : {b | s ∈ n b} ⊆ s := assume b hb, mem_pure.1 $ h₀ b hb, have h₁ : {b | s ∈ n b} ∈ 𝓝 a, { refine is_open.mem_nhds (assume b (hb : s ∈ n b), _) hs, rcases h₁ hb with ⟨t, ht, hts, h⟩, exact mem_of_superset ht h }, exact mem_of_superset h₁ h₀ }, { rcases (@mem_nhds_iff α (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩, exact (n a).sets_of_superset (ht _ hat) hts }, end end topological_space section lattice variables {α : Type u} {β : Type v} /-- The inclusion ordering on topologies on α. We use it to get a complete lattice instance via the Galois insertion method, but the partial order that we will eventually impose on `topological_space α` is the reverse one. -/ def tmp_order : partial_order (topological_space α) := { le := λt s, t.is_open ≤ s.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ } local attribute [instance] tmp_order /- We'll later restate this lemma in terms of the correct order on `topological_space α`. -/ private lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} : topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} := iff.intro (assume ht s hs, ht _ $ topological_space.generate_open.basic s hs) (assume hg s hs, hs.rec_on (assume v hv, hg hv) t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k)) /-- If `s` equals the collection of open sets in the topology it generates, then `s` defines a topology. -/ protected def mk_of_closure (s : set (set α)) (hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α := { is_open := λu, u ∈ s, is_open_univ := hs ▸ topological_space.generate_open.univ, is_open_inter := hs ▸ topological_space.generate_open.inter, is_open_sUnion := hs ▸ topological_space.generate_open.sUnion } lemma mk_of_closure_sets {s : set (set α)} {hs : {u | (topological_space.generate_from s).is_open u} = s} : mk_of_closure s hs = topological_space.generate_from s := topological_space_eq hs.symm /-- The Galois insertion between `set (set α)` and `topological_space α` whose lower part sends a collection of subsets of α to the topology they generate, and whose upper part sends a topology to its collection of open subsets. -/ def gi_generate_from (α : Type*) : galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) := { gc := assume g t, generate_from_le_iff_subset_is_open, le_l_u := assume ts s hs, topological_space.generate_open.basic s hs, choice := λg hg, mk_of_closure g (subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) : topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ := (gi_generate_from _).gc.monotone_l h lemma generate_from_set_of_is_open (t : topological_space α) : topological_space.generate_from {s | t.is_open s} = t := (gi_generate_from α).l_u_eq t lemma left_inverse_generate_from : function.left_inverse topological_space.generate_from (λ t : topological_space α, {s | t.is_open s}) := (gi_generate_from α).left_inverse_l_u lemma generate_from_surjective : function.surjective (topological_space.generate_from : set (set α) → topological_space α) := (gi_generate_from α).l_surjective lemma set_of_is_open_injective : function.injective (λ t : topological_space α, {s | t.is_open s}) := (gi_generate_from α).u_injective /-- The "temporary" order `tmp_order` on `topological_space α`, i.e. the inclusion order, is a complete lattice. (Note that later `topological_space α` will equipped with the dual order to `tmp_order`). -/ def tmp_complete_lattice {α : Type u} : complete_lattice (topological_space α) := (gi_generate_from α).lift_complete_lattice /-- The ordering on topologies on the type `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (topological_space α) := { le := λ t s, s.is_open ≤ t.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, le_trans h₂ h₁ } lemma le_generate_from_iff_subset_is_open {g : set (set α)} {t : topological_space α} : t ≤ topological_space.generate_from g ↔ g ⊆ {s | t.is_open s} := generate_from_le_iff_subset_is_open /-- Topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of topologies is the topology generated by all their open sets, while the supremem is the topology whose open sets are those sets open in every member of the collection. -/ instance : complete_lattice (topological_space α) := @order_dual.complete_lattice _ tmp_complete_lattice lemma is_open_implies_is_open_iff {a b : topological_space α} : (∀ s, a.is_open s → b.is_open s) ↔ b ≤ a := @galois_insertion.u_le_u_iff _ (order_dual (topological_space α)) _ _ _ _ (gi_generate_from α) a b /-- A topological space is discrete if every set is open, that is, its topology equals the discrete topology `⊥`. -/ class discrete_topology (α : Type*) [t : topological_space α] : Prop := (eq_bot [] : t = ⊥) @[priority 100] instance discrete_topology_bot (α : Type*) : @discrete_topology α ⊥ := { eq_bot := rfl } @[simp] lemma is_open_discrete [topological_space α] [discrete_topology α] (s : set α) : is_open s := (discrete_topology.eq_bot α).symm ▸ trivial @[simp] lemma is_closed_discrete [topological_space α] [discrete_topology α] (s : set α) : is_closed s := is_open_compl_iff.1 $ (discrete_topology.eq_bot α).symm ▸ trivial @[nontriviality] lemma continuous_of_discrete_topology [topological_space α] [discrete_topology α] [topological_space β] {f : α → β} : continuous f := continuous_def.2 $ λs hs, is_open_discrete _ lemma nhds_bot (α : Type*) : (@nhds α ⊥) = pure := begin refine le_antisymm _ (@pure_le_nhds α ⊥), assume a s hs, exact @is_open.mem_nhds α ⊥ a s trivial hs end lemma nhds_discrete (α : Type*) [topological_space α] [discrete_topology α] : (@nhds α _) = pure := (discrete_topology.eq_bot α).symm ▸ nhds_bot α lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x ≤ @nhds α t₂ x) : t₁ ≤ t₂ := assume s, show @is_open α t₂ s → @is_open α t₁ s, by { simp only [is_open_iff_nhds, le_principal_iff], exact assume hs a ha, h _ $ hs _ ha } lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x = @nhds α t₂ x) : t₁ = t₂ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) lemma eq_bot_of_singletons_open {t : topological_space α} (h : ∀ x, t.is_open {x}) : t = ⊥ := bot_unique $ λ s hs, bUnion_of_singleton s ▸ is_open_bUnion (λ x _, h x) lemma forall_open_iff_discrete {X : Type*} [topological_space X] : (∀ s : set X, is_open s) ↔ discrete_topology X := ⟨λ h, ⟨by { ext U , show is_open U ↔ true, simp [h U] }⟩, λ a, @is_open_discrete _ _ a⟩ lemma singletons_open_iff_discrete {X : Type*} [topological_space X] : (∀ a : X, is_open ({a} : set X)) ↔ discrete_topology X := ⟨λ h, ⟨eq_bot_of_singletons_open h⟩, λ a _, @is_open_discrete _ _ a _⟩ end lattice section galois_connection variables {α : Type*} {β : Type*} {γ : Type*} /-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of sets that are preimages of some open set in `β`. This is the coarsest topology that makes `f` continuous. -/ def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) : topological_space α := { is_open := λs, ∃s', t.is_open s' ∧ f ⁻¹' s' = s, is_open_univ := ⟨univ, t.is_open_univ, preimage_univ⟩, is_open_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩; exact ⟨s'₁ ∩ s'₂, t.is_open_inter _ _ hs₁ hs₂, preimage_inter⟩, is_open_sUnion := assume s h, begin simp only [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h), simp only [sUnion_eq_bUnion, preimage_Union, (λx h, (hf x h).right)], refine ⟨_, rfl⟩, exact (@is_open_Union β _ t _ $ assume i, show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left) end } lemma is_open_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_open α (t.induced f) s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) := iff.rfl lemma is_open_induced_iff' [t : topological_space β] {s : set α} {f : α → β} : (t.induced f).is_open s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) := iff.rfl lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ f ⁻¹' t = s) := begin simp only [← is_open_compl_iff, is_open_induced_iff], exact ⟨λ ⟨t, ht, heq⟩, ⟨tᶜ, by rwa compl_compl, by simp [preimage_compl, heq, compl_compl]⟩, λ ⟨t, ht, heq⟩, ⟨tᶜ, ht, by simp only [preimage_compl, heq.symm]⟩⟩ end /-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) : topological_space β := { is_open := λs, t.is_open (f ⁻¹' s), is_open_univ := by rw preimage_univ; exact t.is_open_univ, is_open_inter := assume s₁ s₂ h₁ h₂, by rw preimage_inter; exact t.is_open_inter _ _ h₁ h₂, is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i, show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from @is_open_Union _ _ t _ $ assume hi, h i hi) } lemma is_open_coinduced {t : topological_space α} {s : set β} {f : α → β} : @is_open β (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) := iff.rfl lemma preimage_nhds_coinduced [topological_space α] {π : α → β} {s : set β} {a : α} (hs : s ∈ @nhds β (topological_space.coinduced π ‹_›) (π a)) : π ⁻¹' s ∈ 𝓝 a := begin letI := topological_space.coinduced π ‹_›, rcases mem_nhds_iff.mp hs with ⟨V, hVs, V_op, mem_V⟩, exact mem_nhds_iff.mpr ⟨π ⁻¹' V, set.preimage_mono hVs, V_op, mem_V⟩ end variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α} lemma continuous.coinduced_le (h : @continuous α β t t' f) : t.coinduced f ≤ t' := λ s hs, (continuous_def.1 h s hs : _) lemma coinduced_le_iff_le_induced {f : α → β} {tα : topological_space α} {tβ : topological_space β} : tα.coinduced f ≤ tβ ↔ tα ≤ tβ.induced f := iff.intro (assume h s ⟨t, ht, hst⟩, hst ▸ h _ ht) (assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩) lemma continuous.le_induced (h : @continuous α β t t' f) : t ≤ t'.induced f := coinduced_le_iff_le_induced.1 h.coinduced_le lemma gc_coinduced_induced (f : α → β) : galois_connection (topological_space.coinduced f) (topological_space.induced f) := assume f g, coinduced_le_iff_le_induced lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g := (gc_coinduced_induced g).monotone_u h lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f := (gc_coinduced_induced f).monotone_l h @[simp] lemma induced_top : (⊤ : topological_space α).induced g = ⊤ := (gc_coinduced_induced g).u_top @[simp] lemma induced_inf : (t₁ ⊓ t₂).induced g = t₁.induced g ⊓ t₂.induced g := (gc_coinduced_induced g).u_inf @[simp] lemma induced_infi {ι : Sort w} {t : ι → topological_space α} : (⨅i, t i).induced g = (⨅i, (t i).induced g) := (gc_coinduced_induced g).u_infi @[simp] lemma coinduced_bot : (⊥ : topological_space α).coinduced f = ⊥ := (gc_coinduced_induced f).l_bot @[simp] lemma coinduced_sup : (t₁ ⊔ t₂).coinduced f = t₁.coinduced f ⊔ t₂.coinduced f := (gc_coinduced_induced f).l_sup @[simp] lemma coinduced_supr {ι : Sort w} {t : ι → topological_space α} : (⨆i, t i).coinduced f = (⨆i, (t i).coinduced f) := (gc_coinduced_induced f).l_supr lemma induced_id [t : topological_space α] : t.induced id = t := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', hs, h⟩, h ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩ lemma induced_compose [tγ : topological_space γ] {f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁ ▸ h₂ ▸ ⟨s, hs, rfl⟩, assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩ lemma induced_const [t : topological_space α] {x : α} : t.induced (λ y : β, x) = ⊤ := le_antisymm le_top (@continuous_const β α ⊤ t x).le_induced lemma coinduced_id [t : topological_space α] : t.coinduced id = t := topological_space_eq rfl lemma coinduced_compose [tα : topological_space α] {f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) := topological_space_eq rfl end galois_connection /- constructions using the complete lattice structure -/ section constructions open topological_space variables {α : Type u} {β : Type v} instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) := ⟨⊤⟩ @[priority 100] instance subsingleton.unique_topological_space [subsingleton α] : unique (topological_space α) := { default := ⊥, uniq := λ t, eq_bot_of_singletons_open $ λ x, subsingleton.set_cases (@is_open_empty _ t) (@is_open_univ _ t) ({x} : set α) } @[priority 100] instance subsingleton.discrete_topology [t : topological_space α] [subsingleton α] : discrete_topology α := ⟨unique.eq_default t⟩ instance : topological_space empty := ⊥ instance : discrete_topology empty := ⟨rfl⟩ instance : topological_space pempty := ⊥ instance : discrete_topology pempty := ⟨rfl⟩ instance : topological_space punit := ⊥ instance : discrete_topology punit := ⟨rfl⟩ instance : topological_space bool := ⊥ instance : discrete_topology bool := ⟨rfl⟩ instance : topological_space ℕ := ⊥ instance : discrete_topology ℕ := ⟨rfl⟩ instance : topological_space ℤ := ⊥ instance : discrete_topology ℤ := ⟨rfl⟩ instance sierpinski_space : topological_space Prop := generate_from {{true}} lemma le_generate_from {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) : t ≤ generate_from g := le_generate_from_iff_subset_is_open.2 h lemma induced_generate_from_eq {α β} {b : set (set β)} {f : α → β} : (generate_from b).induced f = topological_space.generate_from (preimage f '' b) := le_antisymm (le_generate_from $ ball_image_iff.2 $ assume s hs, ⟨s, generate_open.basic _ hs, rfl⟩) (coinduced_le_iff_le_induced.1 $ le_generate_from $ assume s hs, generate_open.basic _ $ mem_image_of_mem _ hs) lemma le_induced_generate_from {α β} [t : topological_space α] {b : set (set β)} {f : α → β} (h : ∀ (a : set β), a ∈ b → is_open (f ⁻¹' a)) : t ≤ induced f (generate_from b) := begin rw induced_generate_from_eq, apply le_generate_from, simp only [mem_image, and_imp, forall_apply_eq_imp_iff₂, exists_imp_distrib], exact h, end /-- This construction is left adjoint to the operation sending a topology on `α` to its neighborhood filter at a fixed point `a : α`. -/ protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α := { is_open := λs, a ∈ s → s ∈ f, is_open_univ := assume s, univ_mem, is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem (hs has) (ht hat), is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) } lemma gc_nhds (a : α) : galois_connection (topological_space.nhds_adjoint a) (λt, @nhds α t a) := assume f t, by { rw le_nhds_iff, exact ⟨λ H s hs has, H _ has hs, λ H s has hs, H _ hs has⟩ } lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₁ a ≤ @nhds α t₂ a := (gc_nhds a).monotone_u h lemma nhds_infi {ι : Sort*} {t : ι → topological_space α} {a : α} : @nhds α (infi t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).u_infi lemma nhds_Inf {s : set (topological_space α)} {a : α} : @nhds α (Inf s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).u_Inf lemma nhds_inf {t₁ t₂ : topological_space α} {a : α} : @nhds α (t₁ ⊓ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).u_inf lemma nhds_top {a : α} : @nhds α ⊤ a = ⊤ := (gc_nhds a).u_top local notation `cont` := @continuous _ _ local notation `tspace` := topological_space open topological_space variables {γ : Type*} {f : α → β} {ι : Sort*} lemma continuous_iff_coinduced_le {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ coinduced f t₁ ≤ t₂ := continuous_def.trans iff.rfl lemma continuous_iff_le_induced {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ t₁ ≤ induced f t₂ := iff.trans continuous_iff_coinduced_le (gc_coinduced_induced f _ _) theorem continuous_generated_from {t : tspace α} {b : set (set β)} (h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f := continuous_iff_coinduced_le.2 $ le_generate_from h @[continuity] lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f := by { rw continuous_def, assume s h, exact ⟨_, h, rfl⟩ } lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ} (h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g := begin rw continuous_def, rintros s ⟨t, ht, s_eq⟩, simpa [← s_eq] using continuous_def.1 h t ht, end lemma continuous_induced_rng' [topological_space α] [topological_space β] [topological_space γ] {g : γ → α} (f : α → β) (H : ‹topological_space α› = ‹topological_space β›.induced f) (h : continuous (f ∘ g)) : continuous g := H.symm ▸ continuous_induced_rng h lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f := by { rw continuous_def, assume s h, exact h } lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ} (h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g := begin rw continuous_def at h ⊢, assume s hs, exact h _ hs end lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : t₂ ≤ t₁) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f := begin rw continuous_def at h₂ ⊢, assume s h, exact h₁ _ (h₂ s h) end lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : t₂ ≤ t₃) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f := begin rw continuous_def at h₂ ⊢, assume s h, exact h₂ s (h₁ s h) end lemma continuous_sup_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊔ t₂) t₃ f := begin rw continuous_def at h₁ h₂ ⊢, assume s h, exact ⟨h₁ s h, h₂ s h⟩ end lemma continuous_sup_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₂ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_left lemma continuous_sup_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₃ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_right lemma continuous_Sup_dom {t₁ : set (tspace α)} {t₂ : tspace β} (h : ∀t∈t₁, cont t t₂ f) : cont (Sup t₁) t₂ f := continuous_iff_le_induced.2 $ Sup_le $ assume t ht, continuous_iff_le_induced.1 $ h t ht lemma continuous_Sup_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β} (h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Sup t₂) f := continuous_iff_coinduced_le.2 $ le_Sup_of_le h₁ $ continuous_iff_coinduced_le.1 hf lemma continuous_supr_dom {t₁ : ι → tspace α} {t₂ : tspace β} (h : ∀i, cont (t₁ i) t₂ f) : cont (supr t₁) t₂ f := continuous_Sup_dom $ assume t ⟨i, (t_eq : t₁ i = t)⟩, t_eq ▸ h i lemma continuous_supr_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι} (h : cont t₁ (t₂ i) f) : cont t₁ (supr t₂) f := continuous_Sup_rng ⟨i, rfl⟩ h lemma continuous_inf_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊓ t₃) f := continuous_iff_coinduced_le.2 $ le_inf (continuous_iff_coinduced_le.1 h₁) (continuous_iff_coinduced_le.1 h₂) lemma continuous_inf_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₁ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_left lemma continuous_inf_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₂ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_right lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β} {t : tspace α} (h₁ : t ∈ t₁) : cont t t₂ f → cont (Inf t₁) t₂ f := continuous_le_dom $ Inf_le h₁ lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)} (h : ∀t∈t₂, cont t₁ t f) : cont t₁ (Inf t₂) f := continuous_iff_coinduced_le.2 $ le_Inf $ assume b hb, continuous_iff_coinduced_le.1 $ h b hb lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β} {i : ι} : cont (t₁ i) t₂ f → cont (infi t₁) t₂ f := continuous_le_dom $ infi_le _ _ lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β} (h : ∀i, cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f := continuous_iff_coinduced_le.2 $ le_infi $ assume i, continuous_iff_coinduced_le.1 $ h i @[continuity] lemma continuous_bot {t : tspace β} : cont ⊥ t f := continuous_iff_le_induced.2 $ bot_le @[continuity] lemma continuous_top {t : tspace α} : cont t ⊤ f := continuous_iff_coinduced_le.2 $ le_top /- 𝓝 in the induced topology -/ theorem mem_nhds_induced [T : topological_space α] (f : β → α) (a : β) (s : set β) : s ∈ @nhds β (topological_space.induced f T) a ↔ ∃ u ∈ 𝓝 (f a), f ⁻¹' u ⊆ s := begin simp only [mem_nhds_iff, is_open_induced_iff, exists_prop, set.mem_set_of_eq], split, { rintros ⟨u, usub, ⟨v, openv, ueq⟩, au⟩, exact ⟨v, ⟨v, set.subset.refl v, openv, by rwa ←ueq at au⟩, by rw ueq; exact usub⟩ }, rintros ⟨u, ⟨v, vsubu, openv, amem⟩, finvsub⟩, exact ⟨f ⁻¹' v, set.subset.trans (set.preimage_mono vsubu) finvsub, ⟨⟨v, openv, rfl⟩, amem⟩⟩ end theorem nhds_induced [T : topological_space α] (f : β → α) (a : β) : @nhds β (topological_space.induced f T) a = comap f (𝓝 (f a)) := by { ext s, rw [mem_nhds_induced, mem_comap] } lemma induced_iff_nhds_eq [tα : topological_space α] [tβ : topological_space β] (f : β → α) : tβ = tα.induced f ↔ ∀ b, 𝓝 b = comap f (𝓝 $ f b) := ⟨λ h a, h.symm ▸ nhds_induced f a, λ h, eq_of_nhds_eq_nhds $ λ x, by rw [h, nhds_induced]⟩ theorem map_nhds_induced_of_surjective [T : topological_space α] {f : β → α} (hf : function.surjective f) (a : β) : map f (@nhds β (topological_space.induced f T) a) = 𝓝 (f a) := by rw [nhds_induced, map_comap_of_surjective hf] end constructions section induced open topological_space variables {α : Type*} {β : Type*} variables [t : topological_space β] {f : α → β} theorem is_open_induced_eq {s : set α} : @is_open _ (induced f t) s ↔ s ∈ preimage f '' {s | is_open s} := iff.rfl theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) := ⟨s, h, rfl⟩ lemma map_nhds_induced_eq (a : α) : map f (@nhds α (induced f t) a) = 𝓝[range f] (f a) := by rw [nhds_induced, filter.map_comap, nhds_within] lemma map_nhds_induced_of_mem {a : α} (h : range f ∈ 𝓝 (f a)) : map f (@nhds α (induced f t) a) = 𝓝 (f a) := by rw [nhds_induced, filter.map_comap_of_mem h] lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α} : a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) := by simp only [mem_closure_iff_frequently, nhds_induced, frequently_comap, mem_image, and_comm] end induced section sierpinski variables {α : Type*} [topological_space α] @[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) := topological_space.generate_open.basic _ (by simp) lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} := ⟨assume h : continuous p, have is_open (p ⁻¹' {true}), from is_open_singleton_true.preimage h, by simp [preimage, eq_true] at this; assumption, assume h : is_open {x | p x}, continuous_generated_from $ assume s (hs : s ∈ {{true}}), by simp at hs; simp [hs, preimage, eq_true, h]⟩ lemma is_open_iff_continuous_mem {s : set α} : is_open s ↔ continuous (λ x, x ∈ s) := continuous_Prop.symm end sierpinski section infi variables {α : Type u} {ι : Sort v} lemma generate_from_union (a₁ a₂ : set (set α)) : topological_space.generate_from (a₁ ∪ a₂) = topological_space.generate_from a₁ ⊓ topological_space.generate_from a₂ := @galois_connection.l_sup _ (order_dual (topological_space α)) a₁ a₂ _ _ _ _ (λ g t, generate_from_le_iff_subset_is_open) lemma set_of_is_open_sup (t₁ t₂ : topological_space α) : {s | (t₁ ⊔ t₂).is_open s} = {s | t₁.is_open s} ∩ {s | t₂.is_open s} := @galois_connection.u_inf _ (order_dual (topological_space α)) t₁ t₂ _ _ _ _ (λ g t, generate_from_le_iff_subset_is_open) lemma generate_from_Union {f : ι → set (set α)} : topological_space.generate_from (⋃ i, f i) = (⨅ i, topological_space.generate_from (f i)) := @galois_connection.l_supr _ (order_dual (topological_space α)) _ _ _ _ _ (λ g t, generate_from_le_iff_subset_is_open) f lemma set_of_is_open_supr {t : ι → topological_space α} : {s | (⨆ i, t i).is_open s} = ⋂ i, {s | (t i).is_open s} := @galois_connection.u_infi _ (order_dual (topological_space α)) _ _ _ _ _ (λ g t, generate_from_le_iff_subset_is_open) t lemma generate_from_sUnion {S : set (set (set α))} : topological_space.generate_from (⋃₀ S) = (⨅ s ∈ S, topological_space.generate_from s) := @galois_connection.l_Sup _ (order_dual (topological_space α)) _ _ _ _ (λ g t, generate_from_le_iff_subset_is_open) S lemma set_of_is_open_Sup {T : set (topological_space α)} : {s | (Sup T).is_open s} = ⋂ t ∈ T, {s | (t : topological_space α).is_open s} := @galois_connection.u_Inf _ (order_dual (topological_space α)) _ _ _ _ (λ g t, generate_from_le_iff_subset_is_open) T lemma generate_from_union_is_open (a b : topological_space α) : topological_space.generate_from ({s | a.is_open s} ∪ {s | b.is_open s}) = a ⊓ b := @galois_insertion.l_sup_u _ (order_dual (topological_space α)) _ _ _ _ (gi_generate_from α) a b lemma generate_from_Union_is_open (f : ι → topological_space α) : topological_space.generate_from (⋃ i, {s | (f i).is_open s}) = ⨅ i, (f i) := @galois_insertion.l_supr_u _ (order_dual (topological_space α)) _ _ _ _ (gi_generate_from α) _ f lemma generate_from_inter (a b : topological_space α) : topological_space.generate_from ({s | a.is_open s} ∩ {s | b.is_open s}) = a ⊔ b := @galois_insertion.l_inf_u _ (order_dual (topological_space α)) _ _ _ _ (gi_generate_from α) a b lemma generate_from_Inter (f : ι → topological_space α) : topological_space.generate_from (⋂ i, {s | (f i).is_open s}) = ⨆ i, (f i) := @galois_insertion.l_infi_u _ (order_dual (topological_space α)) _ _ _ _ (gi_generate_from α) _ f lemma generate_from_Inter_of_generate_from_eq_self (f : ι → set (set α)) (hf : ∀ i, {s | (topological_space.generate_from (f i)).is_open s} = f i) : topological_space.generate_from (⋂ i, (f i)) = ⨆ i, topological_space.generate_from (f i) := @galois_insertion.l_infi_of_ul_eq_self _ (order_dual (topological_space α)) _ _ _ _ (gi_generate_from α) _ f hf variables {t : ι → topological_space α} lemma is_open_supr_iff {s : set α} : @is_open _ (⨆ i, t i) s ↔ ∀ i, @is_open _ (t i) s := show s ∈ set_of (supr t).is_open ↔ s ∈ {x : set α | ∀ (i : ι), (t i).is_open x}, by simp [set_of_is_open_supr] lemma is_closed_infi_iff {s : set α} : @is_closed _ (⨆ i, t i) s ↔ ∀ i, @is_closed _ (t i) s := by simp [← is_open_compl_iff, is_open_supr_iff] end infi
1d3779ef0109f1ab07ffb6c44d55208bb63c61c3
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/topology/metric_space/emetric_space.lean
d132c4f10076fc920ce43e97fd744e1f5f6be00e
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
46,324
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.real.ennreal import data.finset.intervals import topology.uniform_space.uniform_embedding import topology.uniform_space.pi import topology.uniform_space.uniform_convergence import topology.paracompact import set_theory.ordinal /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ℝ≥0∞`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity. The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). -/ open set filter classical noncomputable theory open_locale uniformity topological_space big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, 𝓟 {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) class has_edist (α : Type*) := (edist : α → α → ℝ≥0∞) export has_edist (edist) /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ℝ≥0∞) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ℝ≥0∞) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } -- the uniform structure is embedded in the emetric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Extended metric spaces, with an extended distance `edist` possibly taking the value ∞ Each emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating an `emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating an `emetric_space` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ class emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) /- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [emetric_space α] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space α := emetric_space.to_uniform_space export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle) attribute [simp] edist_self /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : α} : (edist x y ≤ 0) ↔ x = y := nonpos_iff_eq_zero.trans edist_eq_zero /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right (edist_triangle x y z) _ /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ℝ≥0∞) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ ∑ i in finset.range n, d i := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : α} (h : ∀ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} := emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_edist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : ℝ≥0, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) theorem uniformity_basis_edist_inv_two_pow : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < 2⁻¹ ^ n}) := emetric.mk_uniformity_basis (λ n _, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_two_pow_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ℝ≥0∞} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric theorem uniformity_has_countable_basis : is_countably_generated (𝓤 α) := is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩ /-- ε-δ characterization of uniform continuity on a set for emetric spaces -/ theorem uniform_continuous_on_iff [emetric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b}, a ∈ s → b ∈ s → edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_on_iff uniformity_basis_edist /-- ε-δ characterization of uniform continuity on emetric spaces -/ theorem uniform_continuous_iff [emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on emetric spaces -/ theorem uniform_embedding_iff [emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [emetric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- ε-δ characterization of Cauchy sequences on emetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := by rw ← ne_bot_iff; exact uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ℝ≥0∞) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences uniformity_has_countable_basis (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete emetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis /-- Expressing locally uniform convergence on a set using `edist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, mem_univ, forall_const, exists_prop, nhds_within_univ] /-- Expressing uniform convergence using `edist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by simp only [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff, mem_univ, forall_const] end emetric open emetric /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated_space α := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α) (H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space) : emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) } /-- The extended metric induced by an injective function taking values in an emetric space. -/ def emetric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : emetric_space β) : emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced coe (λ x y, subtype.ext_iff_val.2) /-- The extended distance on a subset of an emetric space is the restriction of the original distance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [set.ext_iff, εpos] end } lemma edist_pi_def [Π b, emetric_space (π b)] (f g : Π b, π b) : edist f g = finset.sup univ (λb, edist (f b) (g b)) := rfl @[simp] lemma edist_pi_const [nonempty β] (a b : α) : edist (λ x : β, a) (λ _, b) = edist a b := finset.sup_const univ_nonempty (edist a b) end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ℝ≥0∞} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ℝ≥0∞) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ≥0∞) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist theorem nhds_basis_closed_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_edist_le theorem nhds_eq : 𝓝 x = (⨅ε>0, 𝓟 (ball x ε)) := nhds_basis_eball.eq_binfi theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $ ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩ theorem ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) theorem ball_prod_same [emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : (ball x r).prod (ball y r) = ball (x, y) r := ext $ λ z, max_lt_iff.symm theorem closed_ball_prod_same [emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : (closed_ball x r).prod (closed_ball y r) = closed_ball (x, y) r := ext $ λ z, max_le_iff.symm /-- ε-characterization of the closure in emetric spaces -/ theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] /-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually, the edistance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ℝ≥0∞), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `ℝ≥0` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : ℝ≥0, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- An `emetric_space` is always a paracompact space. Formalization is based on [MR0236876]. -/ @[priority 100] -- See note [lower instance priority] instance : paracompact_space α := begin classical, /- We start with trivial observations about `1 / 2 ^ k`. Here and below we use `1 / 2 ^ k` in the comments and `2⁻¹ ^ k` in the code. -/ have pow_pos : ∀ k : ℕ, (0 : ℝ≥0∞) < 2⁻¹ ^ k, from λ k, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _, have hpow_le : ∀ {m n : ℕ}, m ≤ n → (2⁻¹ : ℝ≥0∞) ^ n ≤ 2⁻¹ ^ m, from λ m n h, ennreal.pow_le_pow_of_le_one (ennreal.inv_le_one.2 ennreal.one_lt_two.le) h, have h2pow : ∀ n : ℕ, 2 * (2⁻¹ : ℝ≥0∞) ^ (n + 1) = 2⁻¹ ^ n, by { intro n, simp [pow_succ, ← mul_assoc, ennreal.mul_inv_cancel] }, -- Consider an open covering `S : set (set α)` refine ⟨λ ι s ho hcov, _⟩, simp only [Union_eq_univ_iff] at hcov, -- choose a well founded order on `S` letI : linear_order ι := linear_order_of_STO' well_ordering_rel, have wf : well_founded ((<) : ι → ι → Prop) := @is_well_order.wf ι well_ordering_rel _, -- Let `ind x` be the minimal index `s : S` such that `x ∈ s`. set ind : α → ι := λ x, wf.min {i : ι | x ∈ s i} (hcov x), have mem_ind : ∀ x, x ∈ s (ind x), from λ x, wf.min_mem _ (hcov x), have nmem_of_lt_ind : ∀ {x i}, i < (ind x) → x ∉ s i, from λ x i hlt hxi, wf.not_lt_min _ (hcov x) hxi hlt, /- The refinement `D : ℕ → ι → set α` is defined recursively. For each `n` and `i`, `D n i` is the union of balls `ball x (1 / 2 ^ n)` over all points `x` such that * `ind x = i`; * `x` does not belong to any `D m j`, `m < n`; * `ball x (3 / 2 ^ n) ⊆ s i`; We define this sequence using `nat.strong_rec_on'`, then restate it as `Dn` and `memD`. -/ set D : ℕ → ι → set α := λ n, nat.strong_rec_on' n (λ n D' i, ⋃ (x : α) (hxs : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D' m ‹_› j), ball x (2⁻¹ ^ n)), have Dn : ∀ n i, D n i = ⋃ (x : α) (hxs : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D m j), ball x (2⁻¹ ^ n), from λ n s, by { simp only [D], rw nat.strong_rec_on_beta' }, have memD : ∀ {n i y}, y ∈ D n i ↔ ∃ x (hi : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D m j), edist y x < 2⁻¹ ^ n, { intros n i y, rw [Dn n i], simp only [mem_Union, mem_ball] }, -- The sets `D n i` cover the whole space. Indeed, for each `x` we can choose `n` such that -- `ball x (3 / 2 ^ n) ⊆ s (ind x)`, then either `x ∈ D n i`, or `x ∈ D m i` for some `m < n`. have Dcov : ∀ x, ∃ n i, x ∈ D n i, { intro x, obtain ⟨n, hn⟩ : ∃ n : ℕ, ball x (3 * 2⁻¹ ^ n) ⊆ s (ind x), { -- This proof takes 5 lines because we can't import `specific_limits` here rcases is_open_iff.1 (ho $ ind x) x (mem_ind x) with ⟨ε, ε0, hε⟩, have : 0 < ε / 3 := ennreal.div_pos_iff.2 ⟨ε0.lt.ne', ennreal.coe_ne_top⟩, rcases ennreal.exists_inv_two_pow_lt this.ne' with ⟨n, hn⟩, refine ⟨n, subset.trans (ball_subset_ball _) hε⟩, simpa only [div_eq_mul_inv, mul_comm] using (ennreal.mul_lt_of_lt_div hn).le }, by_contra h, push_neg at h, apply h n (ind x), exact memD.2 ⟨x, rfl, hn, λ _ _ _, h _ _, mem_ball_self (pow_pos _)⟩ }, -- Each `D n i` is a union of open balls, hence it is an open set have Dopen : ∀ n i, is_open (D n i), { intros n i, rw Dn, iterate 4 { refine is_open_Union (λ _, _) }, exact is_open_ball }, -- the covering `D n i` is a refinement of the original covering: `D n i ⊆ s i` have HDS : ∀ n i, D n i ⊆ s i, { intros n s x, rw memD, rintro ⟨y, rfl, hsub, -, hyx⟩, refine hsub (lt_of_lt_of_le hyx _), calc 2⁻¹ ^ n = 1 * 2⁻¹ ^ n : (one_mul _).symm ... ≤ 3 * 2⁻¹ ^ n : ennreal.mul_le_mul _ le_rfl, -- TODO: use `norm_num` have : ((1 : ℕ) : ℝ≥0∞) ≤ (3 : ℕ), from ennreal.coe_nat_le_coe_nat.2 (by norm_num1), exact_mod_cast this }, -- Let us show the rest of the properties. Since the definition expects a family indexed -- by a single parameter, we use `ℕ × ι` as the domain. refine ⟨ℕ × ι, λ ni, D ni.1 ni.2, λ _, Dopen _ _, _, _, λ ni, ⟨ni.2, HDS _ _⟩⟩, -- The sets `D n i` cover the whole space as we proved earlier { refine Union_eq_univ_iff.2 (λ x, _), rcases Dcov x with ⟨n, i, h⟩, exact ⟨⟨n, i⟩, h⟩ }, { /- Let us prove that the covering `D n i` is locally finite. Take a point `x` and choose `n`, `i` so that `x ∈ D n i`. Since `D n i` is an open set, we can choose `k` so that `B = ball x (1 / 2 ^ (n + k + 1)) ⊆ D n i`. -/ intro x, rcases Dcov x with ⟨n, i, hn⟩, have : D n i ∈ 𝓝 x, from mem_nhds_sets (Dopen _ _) hn, rcases (nhds_basis_uniformity uniformity_basis_edist_inv_two_pow).mem_iff.1 this with ⟨k, -, hsub : ball x (2⁻¹ ^ k) ⊆ D n i⟩, set B := ball x (2⁻¹ ^ (n + k + 1)), refine ⟨B, ball_mem_nhds _ (pow_pos _), _⟩, -- The sets `D m i`, `m > n + k`, are disjoint with `B` have Hgt : ∀ (m ≥ n + k + 1) (i : ι), disjoint (D m i) B, { rintros m hm i y ⟨hym, hyx⟩, rcases memD.1 hym with ⟨z, rfl, hzi, H, hz⟩, have : z ∉ ball x (2⁻¹ ^ k), from λ hz, H n (by linarith) i (hsub hz), apply this, calc edist z x ≤ edist y z + edist y x : edist_triangle_left _ _ _ ... < (2⁻¹ ^ m) + (2⁻¹ ^ (n + k + 1)) : ennreal.add_lt_add hz hyx ... ≤ (2⁻¹ ^ (k + 1)) + (2⁻¹ ^ (k + 1)) : add_le_add (hpow_le $ by linarith) (hpow_le $ by linarith) ... = (2⁻¹ ^ k) : by rw [← two_mul, h2pow] }, -- For each `m ≤ n + k` there is at most one `j` such that `D m j ∩ B` is nonempty. have Hle : ∀ m ≤ n + k, set.subsingleton {j | (D m j ∩ B).nonempty}, { rintros m hm j₁ ⟨y, hyD, hyB⟩ j₂ ⟨z, hzD, hzB⟩, by_contra h, wlog h : j₁ < j₂ := ne.lt_or_lt h using [j₁ j₂ y z, j₂ j₁ z y], rcases memD.1 hyD with ⟨y', rfl, hsuby, -, hdisty⟩, rcases memD.1 hzD with ⟨z', rfl, -, -, hdistz⟩, suffices : edist z' y' < 3 * 2⁻¹ ^ m, from nmem_of_lt_ind h (hsuby this), calc edist z' y' ≤ edist z' x + edist x y' : edist_triangle _ _ _ ... ≤ (edist z z' + edist z x) + (edist y x + edist y y') : add_le_add (edist_triangle_left _ _ _) (edist_triangle_left _ _ _) ... < (2⁻¹ ^ m + 2⁻¹ ^ (n + k + 1)) + (2⁻¹ ^ (n + k + 1) + 2⁻¹ ^ m) : by apply_rules [ennreal.add_lt_add] ... = 2 * (2⁻¹ ^ m + 2⁻¹ ^ (n + k + 1)) : by simp only [two_mul, add_comm] ... ≤ 2 * (2⁻¹ ^ m + 2⁻¹ ^ (m + 1)) : ennreal.mul_le_mul le_rfl $ add_le_add le_rfl $ hpow_le (add_le_add hm le_rfl) ... = 3 * 2⁻¹ ^ m : by rw [mul_add, h2pow, bit1, add_mul, one_mul] }, -- Finally, we glue `Hgt` and `Hle` have : (⋃ (m ≤ n + k) (i ∈ {i : ι | (D m i ∩ B).nonempty}), {(m, i)}).finite, from (finite_le_nat _).bUnion (λ i hi, (Hle i hi).finite.bUnion (λ _ _, finite_singleton _)), refine this.subset (λ I hI, _), simp only [mem_Union], refine ⟨I.1, _, I.2, hI, prod.mk.eta.symm⟩, exact not_lt.1 (λ hlt, Hgt I.1 hlt I.2 hI.some_spec) } end @[priority 100] -- see Note [lower instance priority] instance normal_of_emetric : normal_space α := normal_of_paracompact_t2 /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/ lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin have A : ∀ (e:ℝ≥0∞), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) := totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1, -- assume e, finite_cover_balls_of_compact hs, have B : ∀ (e:ℝ≥0∞), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)), { intro e, cases le_or_gt e 0 with h, { exact ⟨∅, by finish⟩ }, { rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }}, /-The desired countable set is obtained by taking for each `n` the centers of a finite cover by balls of radius `1/n`, and then the union over `n`. -/ choose T T_in_s finite_T using B, let t := ⋃n:ℕ, T n⁻¹, have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end, have T₂ : countable t := by finish [countable_Union, finite.countable], have T₃ : s ⊆ closure t, { intros x x_in_s, apply mem_closure_iff.2, intros ε εpos, rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩, have inv_n_pos : (0 : ℝ≥0∞) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) := mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos), rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩, simp at Dxy, -- Dxy : edist x y < 1 / ↑n have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)), have : edist x y < ε := lt_trans Dxy hn, exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ }, have T₄ : closure t ⊆ s := calc closure t ⊆ closure s : closure_mono T₁ ... = s : hs.is_closed.closure_eq, exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩ end end compact section first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section second_countable open topological_space /-- A separable emetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] : second_countable_topology α := uniform_space.second_countable_of_separable uniformity_has_countable_basis end second_countable section diam /-- The diameter of a set in an emetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff_forall_edist_le {d : ℝ≥0∞} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := diam_le_iff_forall_edist_le.1 (le_refl _) x hx y hy /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_edist_le {d : ℝ≥0∞} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff_forall_edist_le.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := nonpos_iff_eq_zero.1 $ diam_le_of_forall_edist_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_refl _ /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := begin have := not_congr (@diam_eq_zero_iff _ _ s), dunfold set.subsingleton at this, push_neg at this, simpa only [pos_iff_ne_zero, exists_prop] using this end lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff_forall_edist_le, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and, forall_and_distrib, and_self, ← and_assoc] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right] lemma diam_triple : diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_right, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le_of_forall_edist_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add (add_le_add (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le_of_forall_edist_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _) ... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ℝ≥0∞} : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_edist_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] lemma diam_ball {r : ℝ≥0∞} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace
8b5943362347d9d1369880dd512c81cc1daf1fd1
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/analysis/measure_theory/lebesgue_measure.lean
9f6956844f632b0dfc9f0298247e1778e3dec0b3
[ "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
10,412
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 Lebesgue measure on the real line -/ import analysis.measure_theory.measure_space analysis.measure_theory.borel_space noncomputable theory open classical set lattice filter open ennreal (of_real) namespace measure_theory /-- Length of an interval. This is the largest monotonic function which correctly measures all intervals. -/ def lebesgue_length (s : set ℝ) : ennreal := ⨅a b (h : s ⊆ Ico a b), of_real (b - a) @[simp] lemma lebesgue_length_empty : lebesgue_length ∅ = 0 := le_zero_iff_eq.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp @[simp] lemma lebesgue_length_Ico (a b : ℝ) : lebesgue_length (Ico a b) = of_real (b - a) := begin refine le_antisymm (infi_le_of_le a $ infi_le_of_le b $ infi_le _ (by refl)) (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, _), cases le_or_lt b a with ab ab, { rw ennreal.of_real_of_nonpos (sub_nonpos.2 ab), simp }, cases (Ico_subset_Ico_iff ab).1 h with h₁ h₂, exact ennreal.of_real_le_of_real (sub_le_sub h₂ h₁) end lemma lebesgue_length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) : lebesgue_length s₁ ≤ lebesgue_length s₂ := infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h', ⟨subset.trans h h', le_refl _⟩ lemma lebesgue_length_eq_infi_Ioo (s) : lebesgue_length s = ⨅a b (h : s ⊆ Ioo a b), of_real (b - a) := begin refine le_antisymm (infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h, ⟨subset.trans h Ioo_subset_Ico_self, le_refl _⟩) _, refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _), refine ennreal.le_of_forall_epsilon_le (λ ε ε0 _, _), refine infi_le_of_le (a - ε) (infi_le_of_le b $ infi_le_of_le (subset.trans h $ Ico_subset_Ioo_left $ (sub_lt_self_iff _).2 ε0) _), rw ← sub_add, apply ennreal.of_real_add_le end @[simp] lemma lebesgue_length_Ioo (a b : ℝ) : lebesgue_length (Ioo a b) = of_real (b - a) := begin rw ← lebesgue_length_Ico, refine le_antisymm (lebesgue_length_mono Ioo_subset_Ico_self) _, rw lebesgue_length_eq_infi_Ioo (Ioo a b), refine (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, _), cases le_or_lt b a with ab ab, {simp [ab]}, cases (Ioo_subset_Ioo_iff ab).1 h with h₁ h₂, rw lebesgue_length_Ico, exact ennreal.of_real_le_of_real (sub_le_sub h₂ h₁) end lemma lebesgue_length_eq_infi_Icc (s) : lebesgue_length s = ⨅a b (h : s ⊆ Icc a b), of_real (b - a) := begin refine le_antisymm _ (infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h, ⟨subset.trans h Ico_subset_Icc_self, le_refl _⟩), refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _), refine ennreal.le_of_forall_epsilon_le (λ ε ε0 _, _), refine infi_le_of_le a (infi_le_of_le (b + ε) $ infi_le_of_le (subset.trans h $ Icc_subset_Ico_right $ (lt_add_iff_pos_right _).2 ε0) _), rw [sub_eq_add_neg, add_right_comm], apply ennreal.of_real_add_le end @[simp] lemma lebesgue_length_Icc (a b : ℝ) : lebesgue_length (Icc a b) = of_real (b - a) := begin rw ← lebesgue_length_Ico, refine le_antisymm _ (lebesgue_length_mono Ico_subset_Icc_self), rw lebesgue_length_eq_infi_Icc (Icc a b), exact infi_le_of_le a (infi_le_of_le b $ infi_le_of_le (by refl) (by simp)) end /-- The Lebesgue outer measure, as an outer measure of ℝ. -/ def lebesgue_outer : outer_measure ℝ := outer_measure.of_function lebesgue_length lebesgue_length_empty lemma lebesgue_outer_le_length (s : set ℝ) : lebesgue_outer s ≤ lebesgue_length s := outer_measure.of_function_le _ _ _ lemma lebesgue_length_subadditive {a b : ℝ} {c d : ℕ → ℝ} (ss : Icc a b ⊆ ⋃i, Ioo (c i) (d i)) : of_real (b - a) ≤ ∑ i, of_real (d i - c i) := begin suffices : ∀ (s:finset ℕ) b (cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)), of_real (b - a) ≤ s.sum (λ i, of_real (d i - c i)), { rcases @compact_elim_finite_subcover_image _ _ _ (Icc a b) univ (λ i, Ioo (c i) (d i)) compact_Icc (λ i _, is_open_Ioo) (by simpa using ss) with ⟨s, su, hf, hs⟩, have e : (⋃ i ∈ (↑hf.to_finset:set ℕ), Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), {simp [set.ext_iff]}, rw ennreal.tsum_eq_supr_sum, refine le_trans _ (le_supr _ hf.to_finset), exact this hf.to_finset _ (by simpa [e]) }, clear ss b, refine λ s, finset.strong_induction_on s (λ s IH b cv, _), cases le_total b a with ab ab, { rw ennreal.of_real_of_nonpos (sub_nonpos.2 ab), simp }, have := cv ⟨ab, le_refl _⟩, simp at this, rcases this with ⟨i, is, cb, bd⟩, rw [← finset.insert_erase is] at cv ⊢, rw [finset.coe_insert, bUnion_insert] at cv, rw [finset.sum_insert (finset.not_mem_erase _ _)], refine le_trans _ (add_le_add_left' (IH _ (finset.erase_ssubset is) (c i) _)), { refine le_trans (ennreal.of_real_le_of_real _) ennreal.of_real_add_le, rw sub_add_sub_cancel, exact sub_le_sub_right (le_of_lt bd) _ }, { rintro x ⟨h₁, h₂⟩, refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left (mt and.left (not_lt_of_le h₂)) } end @[simp] lemma lebesgue_outer_Icc (a b : ℝ) : lebesgue_outer (Icc a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Icc; apply lebesgue_outer_le_length) (le_infi $ λ f, le_infi $ λ hf, ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.zero_lt_of_real_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left' (le_of_lt hε)), rw ← ennreal.tsum_add, have : ∀ i, ∃ p:ℝ×ℝ, f i ⊆ Ioo p.1 p.2 ∧ of_real (p.2 - p.1) < lebesgue_length (f i) + of_real (ε' i), { intro i, have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h) (ennreal.zero_lt_of_real_iff.2 (ε'0 i))), conv at this {to_lhs, rw lebesgue_length_eq_infi_Ioo}, simpa [infi_lt_iff] }, cases axiom_of_choice this with g hg, dsimp only at g hg, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hg i).2), exact lebesgue_length_subadditive (subset.trans hf $ Union_subset_Union $ λ i, (hg i).1) end @[simp] lemma lebesgue_outer_singleton (a : ℝ) : lebesgue_outer {a} = 0 := by simpa using lebesgue_outer_Icc a a @[simp] lemma lebesgue_outer_Ico (a b : ℝ) : lebesgue_outer (Ico a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Ico; apply lebesgue_outer_le_length) (ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), have := @ennreal.of_real_add_le (b - a - ε) ε, rw [sub_add_cancel, sub_right_comm, ← lebesgue_outer_Icc a (b-ε)] at this, exact le_trans this (add_le_add_right' $ lebesgue_outer.mono $ Icc_subset_Ico_right $ (sub_lt_self_iff _).2 ε0) end @[simp] lemma lebesgue_outer_Ioo (a b : ℝ) : lebesgue_outer (Ioo a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Ioo; apply lebesgue_outer_le_length) (ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), have := @ennreal.of_real_add_le (b - a - ε) ε, rw [sub_add_cancel, sub_sub, ← lebesgue_outer_Ico (a+ε) b] at this, exact le_trans this (add_le_add_right' $ lebesgue_outer.mono $ Ico_subset_Ioo_left $ (lt_add_iff_pos_right _).2 ε0) end lemma is_lebesgue_measurable_Iio {c : ℝ} : lebesgue_outer.caratheodory.is_measurable (Iio c) := outer_measure.caratheodory_is_measurable $ λ t, le_infi $ λ a, le_infi $ λ b, le_infi $ λ h, begin refine le_trans (add_le_add' (lebesgue_length_mono $ inter_subset_inter_left _ h) (lebesgue_length_mono $ diff_subset_diff_left h)) _, cases le_total a c with hac hca; cases le_total b c with hbc hcb; simp [*, max_eq_right, max_eq_left, min_eq_left, min_eq_right, -sub_eq_add_neg, sub_add_sub_cancel'], rw ennreal.of_real_of_nonpos, {simp}, exact sub_nonpos.2 (le_trans hbc hca) end theorem lebesgue_outer_trim : lebesgue_outer.trim = lebesgue_outer := begin refine le_antisymm (λ s, _) (outer_measure.trim_ge _), rw outer_measure.trim_eq_infi, refine le_infi (λ f, le_infi $ λ hf, ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.zero_lt_of_real_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left' (le_of_lt hε)), rw ← ennreal.tsum_add, have : ∀ i, ∃ s, f i ⊆ s ∧ is_measurable s ∧ lebesgue_outer s ≤ lebesgue_length (f i) + of_real (ε' i), { intro i, have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h) (ennreal.zero_lt_of_real_iff.2 (ε'0 i))), conv at this {to_lhs, rw lebesgue_length}, simp only [infi_lt_iff] at this, rcases this with ⟨a, b, h₁, h₂⟩, rw ← lebesgue_outer_Ico at h₂, exact ⟨_, h₁, is_measurable_Ico, le_of_lt h₂⟩ }, cases axiom_of_choice this with g hg, dsimp at g hg, apply infi_le_of_le (Union g), apply infi_le_of_le (subset.trans hf $ Union_subset_Union (λ i, (hg i).1)), apply infi_le_of_le (is_measurable.Union (λ i, (hg i).2.1)), exact le_trans (lebesgue_outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2) end /-- Lebesgue measure on the Borel sets The outer Lebesgue measure is the completion of this measure. (TODO: proof this) -/ def lebesgue : measure ℝ := lebesgue_outer.to_measure $ calc borel ℝ = measurable_space.generate_from (⋃a:ℚ, {Iio a}) : real.borel_eq_generate_from_Iio_rat ... ≤ lebesgue_outer.caratheodory : measurable_space.generate_from_le $ by simp [is_lebesgue_measurable_Iio] {contextual := tt} @[simp] theorem lebesgue_to_outer_measure : lebesgue.to_outer_measure = lebesgue_outer := (to_measure_to_outer_measure _ _).trans lebesgue_outer_trim theorem lebesgue_val (s) : lebesgue s = lebesgue_outer s := (congr_arg (λ m:outer_measure ℝ, m s) lebesgue_to_outer_measure : _) @[simp] lemma lebesgue_Ico {a b : ℝ} : lebesgue (Ico a b) = of_real (b - a) := by simp [lebesgue_val] @[simp] lemma lebesgue_Icc {a b : ℝ} : lebesgue (Icc a b) = of_real (b - a) := by simp [lebesgue_val] @[simp] lemma lebesgue_Ioo {a b : ℝ} : lebesgue (Ioo a b) = of_real (b - a) := by simp [lebesgue_val] @[simp] lemma lebesgue_singleton {a : ℝ} : lebesgue {a} = 0 := by simp [lebesgue_val] end measure_theory
2ed1fb1838413a794585a9a26969ce59be1caa68
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/PPGoal.lean
f0fd2885f9f8d56716aa59c0f6f70278a9b90b18
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
9,316
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Lean.Meta.InferType import Lean.Meta.MatchUtil namespace Lean.Meta register_builtin_option pp.auxDecls : Bool := { defValue := false group := "pp" descr := "display auxiliary declarations used to compile recursive functions" } register_builtin_option pp.inaccessibleNames : Bool := { defValue := false group := "pp" descr := "display inaccessible declarations in the local context" } def withPPInaccessibleNamesImp (flag : Bool) (x : MetaM α) : MetaM α := withTheReader Core.Context (fun ctx => { ctx with options := pp.inaccessibleNames.setIfNotSet ctx.options flag }) x def withPPInaccessibleNames [MonadControlT MetaM m] [Monad m] (x : m α) (flag := true) : m α := mapMetaM (withPPInaccessibleNamesImp flag) x namespace ToHide structure State where hiddenInaccessibleProp : FVarIdSet := {} -- FVarIds of Propostions with inaccessible names but containing only visible names. We show only their types hiddenInaccessible : FVarIdSet := {} -- FVarIds with inaccessible names, but not in hiddenInaccessibleProp modified : Bool := false structure Context where goalTarget : Expr abbrev M := ReaderT Context $ StateRefT State MetaM /- Return true if `fvarId` is marked as an hidden inaccessible or inaccessible proposition -/ def isMarked (fvarId : FVarId) : M Bool := do let s ← get return s.hiddenInaccessible.contains fvarId || s.hiddenInaccessibleProp.contains fvarId /- If `fvarId` isMarked, then unmark it. -/ def unmark (fvarId : FVarId) : M Unit := do modify fun s => { hiddenInaccessible := s.hiddenInaccessible.erase fvarId hiddenInaccessibleProp := s.hiddenInaccessibleProp.erase fvarId modified := true } def moveToHiddeProp (fvarId : FVarId) : M Unit := do modify fun s => { hiddenInaccessible := s.hiddenInaccessible.erase fvarId hiddenInaccessibleProp := s.hiddenInaccessibleProp.insert fvarId modified := true } /- Return true if the given local declaration has a "visible dependency", that is, it contains a free variable that is `hiddenInaccessible` Recall that hiddenInaccessibleProps are visible, only their names are hidden -/ def hasVisibleDep (localDecl : LocalDecl) : M Bool := do let s ← get return (← getMCtx).findLocalDeclDependsOn localDecl fun fvarId => !s.hiddenInaccessible.contains fvarId /- Return true if the given local declaration has a "nonvisible dependency", that is, it contains a free variable that is `hiddenInaccessible` or `hiddenInaccessibleProp` -/ def hasInaccessibleNameDep (localDecl : LocalDecl) : M Bool := do let s ← get return (← getMCtx).findLocalDeclDependsOn localDecl fun fvarId => s.hiddenInaccessible.contains fvarId || s.hiddenInaccessibleProp.contains fvarId /- If `e` is visible, then any inaccessible in `e` marked as hidden should be unmarked. -/ partial def visitVisibleExpr (e : Expr) : M Unit := do visit (← instantiateMVars e) |>.run where visit (e : Expr) : MonadCacheT Expr Unit M Unit := do if e.hasFVar then checkCache e fun _ => do match e with | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a _ => visit f; visit a | Expr.mdata _ b _ => visit b | Expr.proj _ _ b _ => visit b | Expr.fvar fvarId _ => if (← isMarked fvarId) then unmark fvarId | _ => pure () def fixpointStep : M Unit := do visitVisibleExpr (← read).goalTarget -- The goal target is a visible forward dependency (← getLCtx).forM fun localDecl => do let fvarId := localDecl.fvarId if (← get).hiddenInaccessible.contains fvarId then if (← hasVisibleDep localDecl) then /- localDecl is marked to be hidden, but it has a (backward) visible dependency. -/ unmark fvarId if (← isProp localDecl.type) then unless (← hasInaccessibleNameDep localDecl) do moveToHiddeProp fvarId else visitVisibleExpr localDecl.type match localDecl.value? with | some value => visitVisibleExpr value | _ => pure () partial def fixpoint : M Unit := do modify fun s => { s with modified := false } fixpointStep if (← get).modified then fixpoint /- If pp.inaccessibleNames == false, then collect two sets of `FVarId`s : `hiddenInaccessible` and `hiddenInaccessibleProp` 1- `hiddenInaccessible` contains `FVarId`s of free variables with inaccessible names that a) are not propositions or are propositions containing "visible" names. 2- `hiddenInaccessibleProp` contains `FVarId`s of free variables with inaccessible names that are propositions containing "visible" names. Both sets do not contain `FVarId`s that contain visible backward or forward dependencies. The `goalTarget` counts as a forward dependency. We say a name is visible if it is a free variable with FVarId not in `hiddenInaccessible` nor `hiddenInaccessibleProp` -/ def collect (goalTarget : Expr) : MetaM (FVarIdSet × FVarIdSet) := do if pp.inaccessibleNames.get (← getOptions) then /- Don't hide inaccessible names when `pp.inaccessibleNames` is set to true. -/ return ({}, {}) else let lctx ← getLCtx let hiddenInaccessible := lctx.foldl (init := {}) fun hiddenInaccessible localDecl => Id.run <| do if localDecl.userName.isInaccessibleUserName then hiddenInaccessible.insert localDecl.fvarId else hiddenInaccessible let (_, s) ← fixpoint.run { goalTarget := goalTarget } |>.run { hiddenInaccessible := hiddenInaccessible } return (s.hiddenInaccessible, s.hiddenInaccessibleProp) end ToHide private def addLine (fmt : Format) : Format := if fmt.isNil then fmt else fmt ++ Format.line def ppGoal (mvarId : MVarId) : MetaM Format := do match (← getMCtx).findDecl? mvarId with | none => pure "unknown goal" | some mvarDecl => do let indent := 2 -- Use option let ppAuxDecls := pp.auxDecls.get (← getOptions) let lctx := mvarDecl.lctx let lctx := lctx.sanitizeNames.run' { options := (← getOptions) } withLCtx lctx mvarDecl.localInstances do let (hidden, hiddenProp) ← ToHide.collect mvarDecl.type -- The followint two `let rec`s are being used to control the generated code size. -- Then should be remove after we rewrite the compiler in Lean let rec pushPending (ids : List Name) (type? : Option Expr) (fmt : Format) : MetaM Format := if ids.isEmpty then pure fmt else let fmt := addLine fmt match type? with | none => pure fmt | some type => do let typeFmt ← ppExpr type pure $ fmt ++ (Format.joinSep ids.reverse (format " ") ++ " :" ++ Format.nest indent (Format.line ++ typeFmt)).group let rec ppVars (varNames : List Name) (prevType? : Option Expr) (fmt : Format) (localDecl : LocalDecl) : MetaM (List Name × Option Expr × Format) := do if hiddenProp.contains localDecl.fvarId then let fmt ← pushPending varNames prevType? fmt let fmt := addLine fmt let type ← instantiateMVars localDecl.type let typeFmt ← ppExpr type let fmt := fmt ++ " : " ++ typeFmt pure ([], none, fmt) else match localDecl with | LocalDecl.cdecl _ _ varName type _ => let varName := varName.simpMacroScopes let type ← instantiateMVars type if prevType? == none || prevType? == some type then pure (varName :: varNames, some type, fmt) else do let fmt ← pushPending varNames prevType? fmt pure ([varName], some type, fmt) | LocalDecl.ldecl _ _ varName type val _ => do let varName := varName.simpMacroScopes let fmt ← pushPending varNames prevType? fmt let fmt := addLine fmt let type ← instantiateMVars type let val ← instantiateMVars val let typeFmt ← ppExpr type let valFmt ← ppExpr val let fmt := fmt ++ (format varName ++ " : " ++ typeFmt ++ " :=" ++ Format.nest indent (Format.line ++ valFmt)).group pure ([], none, fmt) let (varNames, type?, fmt) ← lctx.foldlM (init := ([], none, Format.nil)) fun (varNames, prevType?, fmt) (localDecl : LocalDecl) => if !ppAuxDecls && localDecl.isAuxDecl || hidden.contains localDecl.fvarId then pure (varNames, prevType?, fmt) else ppVars varNames prevType? fmt localDecl let fmt ← pushPending varNames type? fmt let fmt := addLine fmt let typeFmt ← ppExpr (← instantiateMVars mvarDecl.type) let fmt := fmt ++ "⊢ " ++ Format.nest indent typeFmt match mvarDecl.userName with | Name.anonymous => pure fmt | name => return "case " ++ format name.eraseMacroScopes ++ Format.line ++ fmt end Lean.Meta
fd94f7bf7f69a3f47af9d42156d85be806287ce9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/coset.lean
e89d65f50d69774388b5c4ba8fdc4a12fcea5f21
[ "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
27,339
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import algebra.quotient import group_theory.group_action.basic import tactic.group /-! # Cosets This file develops the basic theory of left and right cosets. ## Main definitions * `left_coset a s`: the left coset `a * s` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `left_add_coset a s`. * `right_coset s a`: the right coset `s * a` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `right_add_coset s a`. * `quotient_group.quotient s`: the quotient type representing the left cosets with respect to a subgroup `s`, for an `add_group` this is `quotient_add_group.quotient s`. * `quotient_group.mk`: the canonical map from `α` to `α/s` for a subgroup `s` of `α`, for an `add_group` this is `quotient_add_group.mk`. * `subgroup.left_coset_equiv_subgroup`: the natural bijection between a left coset and the subgroup, for an `add_group` this is `add_subgroup.left_coset_equiv_add_subgroup`. ## Notation * `a *l s`: for `left_coset a s`. * `a +l s`: for `left_add_coset a s`. * `s *r a`: for `right_coset s a`. * `s +r a`: for `right_add_coset s a`. * `G ⧸ H` is the quotient of the (additive) group `G` by the (additive) subgroup `H` ## TODO Add `to_additive` to `preimage_mk_equiv_subgroup_times_set`. -/ open set function variable {α : Type*} /-- The left coset `a * s` for an element `a : α` and a subset `s : set α` -/ @[to_additive left_add_coset "The left coset `a+s` for an element `a : α` and a subset `s : set α`"] def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s /-- The right coset `s * a` for an element `a : α` and a subset `s : set α` -/ @[to_additive right_add_coset "The right coset `s+a` for an element `a : α` and a subset `s : set α`"] def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s localized "infix (name := left_coset) ` *l `:70 := left_coset" in coset localized "infix (name := left_add_coset) ` +l `:70 := left_add_coset" in coset localized "infix (name := right_coset) ` *r `:70 := right_coset" in coset localized "infix (name := right_add_coset) ` +r `:70 := right_add_coset" in coset section coset_mul variable [has_mul α] @[to_additive mem_left_add_coset] lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s := mem_image_of_mem (λ b : α, a * b) hxS @[to_additive mem_right_add_coset] lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a := mem_image_of_mem (λ b : α, b * a) hxS /-- Equality of two left cosets `a * s` and `b * s`. -/ @[to_additive left_add_coset_equivalence "Equality of two left cosets `a + s` and `b + s`."] def left_coset_equivalence (s : set α) (a b : α) := a *l s = b *l s @[to_additive left_add_coset_equivalence_rel] lemma left_coset_equivalence_rel (s : set α) : equivalence (left_coset_equivalence s) := mk_equivalence (left_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) /-- Equality of two right cosets `s * a` and `s * b`. -/ @[to_additive right_add_coset_equivalence "Equality of two right cosets `s + a` and `s + b`."] def right_coset_equivalence (s : set α) (a b : α) := s *r a = s *r b @[to_additive right_add_coset_equivalence_rel] lemma right_coset_equivalence_rel (s : set α) : equivalence (right_coset_equivalence s) := mk_equivalence (right_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) end coset_mul section coset_semigroup variable [semigroup α] @[simp, to_additive left_add_coset_assoc] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] @[simp, to_additive right_add_coset_assoc] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] @[to_additive left_add_coset_right_add_coset] lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] end coset_semigroup section coset_monoid variables [monoid α] (s : set α) @[simp, to_additive zero_left_add_coset] lemma one_left_coset : 1 *l s = s := set.ext $ by simp [left_coset] @[simp, to_additive right_add_coset_zero] lemma right_coset_one : s *r 1 = s := set.ext $ by simp [right_coset] end coset_monoid section coset_submonoid open submonoid variables [monoid α] (s : submonoid α) @[to_additive mem_own_left_add_coset] lemma mem_own_left_coset (a : α) : a ∈ a *l s := suffices a * 1 ∈ a *l s, by simpa, mem_left_coset a (one_mem s : 1 ∈ s) @[to_additive mem_own_right_add_coset] lemma mem_own_right_coset (a : α) : a ∈ (s : set α) *r a := suffices 1 * a ∈ (s : set α) *r a, by simpa, mem_right_coset a (one_mem s : 1 ∈ s) @[to_additive mem_left_add_coset_left_add_coset] lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_left_coset s a @[to_additive mem_right_add_coset_right_add_coset] lemma mem_right_coset_right_coset {a : α} (ha : (s : set α) *r a = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_right_coset s a end coset_submonoid section coset_group variables [group α] {s : set α} {x : α} @[to_additive mem_left_add_coset_iff] lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨a⁻¹ * x, h, by simp⟩) @[to_additive mem_right_add_coset_iff] lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨x * a⁻¹, h, by simp⟩) end coset_group section coset_subgroup open subgroup variables [group α] (s : subgroup α) @[to_additive left_add_coset_mem_left_add_coset] lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s := set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_left (s.inv_mem ha)] @[to_additive right_add_coset_mem_right_add_coset] lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : (s : set α) *r a = s := set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_right (s.inv_mem ha)] @[to_additive] lemma orbit_subgroup_eq_right_coset (a : α) : mul_action.orbit s a = s *r a := set.ext (λ b, ⟨λ ⟨c, d⟩, ⟨c, c.2, d⟩, λ ⟨c, d, e⟩, ⟨⟨c, d⟩, e⟩⟩) @[to_additive] lemma orbit_subgroup_eq_self_of_mem {a : α} (ha : a ∈ s) : mul_action.orbit s a = s := (orbit_subgroup_eq_right_coset s a).trans (right_coset_mem_right_coset s ha) @[to_additive] lemma orbit_subgroup_one_eq_self : mul_action.orbit s (1 : α) = s := orbit_subgroup_eq_self_of_mem s s.one_mem @[to_additive eq_add_cosets_of_normal] theorem eq_cosets_of_normal (N : s.normal) (g : α) : g *l s = s *r g := set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [N.mem_comm_iff] @[to_additive normal_of_eq_add_cosets] theorem normal_of_eq_cosets (h : ∀ g : α, g *l s = s *r g) : s.normal := ⟨assume a ha g, show g * a * g⁻¹ ∈ (s : set α), by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩ @[to_additive normal_iff_eq_add_cosets] theorem normal_iff_eq_cosets : s.normal ↔ ∀ g : α, g *l s = s *r g := ⟨@eq_cosets_of_normal _ _ s, normal_of_eq_cosets s⟩ @[to_additive left_add_coset_eq_iff] lemma left_coset_eq_iff {x y : α} : left_coset x s = left_coset y s ↔ x⁻¹ * y ∈ s := begin rw set.ext_iff, simp_rw [mem_left_coset_iff, set_like.mem_coe], split, { intro h, apply (h y).mpr, rw mul_left_inv, exact s.one_mem }, { intros h z, rw ←mul_inv_cancel_right x⁻¹ y, rw mul_assoc, exact s.mul_mem_cancel_left h }, end @[to_additive right_add_coset_eq_iff] lemma right_coset_eq_iff {x y : α} : right_coset ↑s x = right_coset s y ↔ y * x⁻¹ ∈ s := begin rw set.ext_iff, simp_rw [mem_right_coset_iff, set_like.mem_coe], split, { intro h, apply (h y).mpr, rw mul_right_inv, exact s.one_mem }, { intros h z, rw ←inv_mul_cancel_left y x⁻¹, rw ←mul_assoc, exact s.mul_mem_cancel_right h }, end end coset_subgroup run_cmd to_additive.map_namespace `quotient_group `quotient_add_group namespace quotient_group variables [group α] (s : subgroup α) /-- The equivalence relation corresponding to the partition of a group by left cosets of a subgroup.-/ @[to_additive "The equivalence relation corresponding to the partition of a group by left cosets of a subgroup."] def left_rel : setoid α := mul_action.orbit_rel s.opposite α variables {s} @[to_additive] lemma left_rel_apply {x y : α} : @setoid.r _ (left_rel s) x y ↔ (x⁻¹ * y ∈ s) := calc (∃ a : s.opposite, y * mul_opposite.unop a = x) ↔ ∃ a : s, y * a = x : s.opposite_equiv.symm.exists_congr_left ... ↔ ∃ a : s, x⁻¹ * y = a⁻¹ : by simp only [inv_mul_eq_iff_eq_mul, eq_mul_inv_iff_mul_eq] ... ↔ x⁻¹ * y ∈ s : by simp [set_like.exists] variables (s) @[to_additive] lemma left_rel_eq : @setoid.r _ (left_rel s) = λ x y, x⁻¹ * y ∈ s := funext₂ $ by { simp only [eq_iff_iff], apply left_rel_apply } lemma left_rel_r_eq_left_coset_equivalence : @setoid.r _ (quotient_group.left_rel s) = left_coset_equivalence s := by { ext, rw left_rel_eq, exact (left_coset_eq_iff s).symm } @[to_additive] instance left_rel_decidable [decidable_pred (∈ s)] : decidable_rel (left_rel s).r := λ x y, by { rw left_rel_eq, exact ‹decidable_pred (∈ s)› _ } /-- `α ⧸ s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `α ⧸ s` is a group -/ @[to_additive "`α ⧸ s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `α ⧸ s` is a group"] instance : has_quotient α (subgroup α) := ⟨λ s, quotient (left_rel s)⟩ /-- The equivalence relation corresponding to the partition of a group by right cosets of a subgroup. -/ @[to_additive "The equivalence relation corresponding to the partition of a group by right cosets of a subgroup."] def right_rel : setoid α := mul_action.orbit_rel s α variables {s} @[to_additive] lemma right_rel_apply {x y : α} : @setoid.r _ (right_rel s) x y ↔ (y * x⁻¹ ∈ s) := calc (∃ a : s, (a:α) * y = x) ↔ ∃ a : s, y * x⁻¹ = a⁻¹ : by simp only [mul_inv_eq_iff_eq_mul, eq_inv_mul_iff_mul_eq] ... ↔ y * x⁻¹ ∈ s : by simp [set_like.exists] variables (s) @[to_additive] lemma right_rel_eq : @setoid.r _ (right_rel s) = λ x y, y * x⁻¹ ∈ s := funext₂ $ by { simp only [eq_iff_iff], apply right_rel_apply } lemma right_rel_r_eq_right_coset_equivalence : @setoid.r _ (quotient_group.right_rel s) = right_coset_equivalence s := by { ext, rw right_rel_eq, exact (right_coset_eq_iff s).symm } @[to_additive] instance right_rel_decidable [decidable_pred (∈ s)] : decidable_rel (right_rel s).r := λ x y, by { rw right_rel_eq, exact ‹decidable_pred (∈ s)› _ } /-- Right cosets are in bijection with left cosets. -/ @[to_additive "Right cosets are in bijection with left cosets."] def quotient_right_rel_equiv_quotient_left_rel : quotient (quotient_group.right_rel s) ≃ α ⧸ s := { to_fun := quotient.map' (λ g, g⁻¹) (λ a b, by { rw [left_rel_apply, right_rel_apply], exact λ h, (congr_arg (∈ s) (by group)).mp (s.inv_mem h) }), inv_fun := quotient.map' (λ g, g⁻¹) (λ a b, by { rw [left_rel_apply, right_rel_apply], exact λ h, (congr_arg (∈ s) (by group)).mp (s.inv_mem h) }), left_inv := λ g, quotient.induction_on' g (λ g, quotient.sound' (by { simp only [inv_inv], exact quotient.exact' rfl })), right_inv := λ g, quotient.induction_on' g (λ g, quotient.sound' (by { simp only [inv_inv], exact quotient.exact' rfl })) } @[to_additive] instance fintype_quotient_right_rel [fintype (α ⧸ s)] : fintype (quotient (quotient_group.right_rel s)) := fintype.of_equiv (α ⧸ s) (quotient_group.quotient_right_rel_equiv_quotient_left_rel s).symm @[to_additive] lemma card_quotient_right_rel [fintype (α ⧸ s)] : fintype.card (quotient (quotient_group.right_rel s)) = fintype.card (α ⧸ s) := fintype.of_equiv_card (quotient_group.quotient_right_rel_equiv_quotient_left_rel s).symm end quotient_group namespace quotient_group variables [group α] {s : subgroup α} @[to_additive] instance fintype [fintype α] (s : subgroup α) [decidable_rel (left_rel s).r] : fintype (α ⧸ s) := quotient.fintype (left_rel s) /-- The canonical map from a group `α` to the quotient `α ⧸ s`. -/ @[to_additive "The canonical map from an `add_group` `α` to the quotient `α ⧸ s`."] abbreviation mk (a : α) : α ⧸ s := quotient.mk' a @[to_additive] lemma mk_surjective : function.surjective $ @mk _ _ s := quotient.surjective_quotient_mk' @[elab_as_eliminator, to_additive] lemma induction_on {C : α ⧸ s → Prop} (x : α ⧸ s) (H : ∀ z, C (quotient_group.mk z)) : C x := quotient.induction_on' x H @[to_additive] instance : has_coe_t α (α ⧸ s) := ⟨mk⟩ -- note [use has_coe_t] @[elab_as_eliminator, to_additive] lemma induction_on' {C : α ⧸ s → Prop} (x : α ⧸ s) (H : ∀ z : α, C z) : C x := quotient.induction_on' x H @[simp, to_additive] lemma quotient_lift_on_coe {β} (f : α → β) (h) (x : α) : quotient.lift_on' (x : α ⧸ s) f h = f x := rfl @[to_additive] lemma forall_coe {C : α ⧸ s → Prop} : (∀ x : α ⧸ s, C x) ↔ ∀ x : α, C x := mk_surjective.forall @[to_additive] lemma exists_coe {C : α ⧸ s → Prop} : (∃ x : α ⧸ s, C x) ↔ ∃ x : α, C x := mk_surjective.exists @[to_additive] instance (s : subgroup α) : inhabited (α ⧸ s) := ⟨((1 : α) : α ⧸ s)⟩ @[to_additive quotient_add_group.eq] protected lemma eq {a b : α} : (a : α ⧸ s) = b ↔ a⁻¹ * b ∈ s := calc _ ↔ @setoid.r _ (left_rel s) a b : quotient.eq' ... ↔ _ : by rw left_rel_apply @[to_additive quotient_add_group.eq'] lemma eq' {a b : α} : (mk a : α ⧸ s) = mk b ↔ a⁻¹ * b ∈ s := quotient_group.eq @[to_additive quotient_add_group.out_eq'] lemma out_eq' (a : α ⧸ s) : mk a.out' = a := quotient.out_eq' a variables (s) /- It can be useful to write `obtain ⟨h, H⟩ := mk_out'_eq_mul ...`, and then `rw [H]` or `simp_rw [H]` or `simp only [H]`. In order for `simp_rw` and `simp only` to work, this lemma is stated in terms of an arbitrary `h : s`, rathern that the specific `h = g⁻¹ * (mk g).out'`. -/ @[to_additive quotient_add_group.mk_out'_eq_mul] lemma mk_out'_eq_mul (g : α) : ∃ h : s, (mk g : α ⧸ s).out' = g * h := ⟨⟨g⁻¹ * (mk g).out', eq'.mp (mk g).out_eq'.symm⟩, by rw [set_like.coe_mk, mul_inv_cancel_left]⟩ variables {s} @[to_additive quotient_add_group.mk_mul_of_mem] lemma mk_mul_of_mem (g₁ g₂ : α) (hg₂ : g₂ ∈ s) : (mk (g₁ * g₂) : α ⧸ s) = mk g₁ := by rwa [eq', mul_inv_rev, inv_mul_cancel_right, s.inv_mem_iff] @[to_additive] lemma eq_class_eq_left_coset (s : subgroup α) (g : α) : {x : α | (x : α ⧸ s) = g} = left_coset g s := set.ext $ λ z, by rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq, set_like.mem_coe] @[to_additive] lemma preimage_image_coe (N : subgroup α) (s : set α) : coe ⁻¹' ((coe : α → α ⧸ N) '' s) = ⋃ x : N, (λ y : α, y * x) ⁻¹' s := begin ext x, simp only [quotient_group.eq, set_like.exists, exists_prop, set.mem_preimage, set.mem_Union, set.mem_image, set_like.coe_mk, ← eq_inv_mul_iff_mul_eq], exact ⟨λ ⟨y, hs, hN⟩, ⟨_, N.inv_mem hN, by simpa using hs⟩, λ ⟨z, hz, hxz⟩, ⟨x*z, hxz, by simpa using hz⟩⟩, end end quotient_group namespace subgroup open quotient_group variables [group α] {s : subgroup α} /-- The natural bijection between a left coset `g * s` and `s`. -/ @[to_additive "The natural bijection between the cosets `g + s` and `s`."] def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s := ⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩, λ x, ⟨g * x.1, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- The natural bijection between a right coset `s * g` and `s`. -/ @[to_additive "The natural bijection between the cosets `s + g` and `s`."] def right_coset_equiv_subgroup (g : α) : right_coset ↑s g ≃ s := ⟨λ x, ⟨x.1 * g⁻¹, (mem_right_coset_iff _).1 x.2⟩, λ x, ⟨x.1 * g, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- A (non-canonical) bijection between a group `α` and the product `(α/s) × s` -/ @[to_additive "A (non-canonical) bijection between an add_group `α` and the product `(α/s) × s`"] noncomputable def group_equiv_quotient_times_subgroup : α ≃ (α ⧸ s) × s := calc α ≃ Σ L : α ⧸ s, {x : α // (x : α ⧸ s) = L} : (equiv.sigma_fiber_equiv quotient_group.mk).symm ... ≃ Σ L : α ⧸ s, left_coset (quotient.out' L) s : equiv.sigma_congr_right (λ L, begin rw ← eq_class_eq_left_coset, show _root_.subtype (λ x : α, quotient.mk' x = L) ≃ _root_.subtype (λ x : α, quotient.mk' x = quotient.mk' _), simp [-quotient.eq'], end) ... ≃ Σ L : α ⧸ s, s : equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _) ... ≃ (α ⧸ s) × s : equiv.sigma_equiv_prod _ _ variables {t : subgroup α} /-- If two subgroups `M` and `N` of `G` are equal, their quotients are in bijection. -/ @[to_additive "If two subgroups `M` and `N` of `G` are equal, their quotients are in bijection."] def quotient_equiv_of_eq (h : s = t) : α ⧸ s ≃ α ⧸ t := { to_fun := quotient.map' id (λ a b h', h ▸ h'), inv_fun := quotient.map' id (λ a b h', h.symm ▸ h'), left_inv := λ q, induction_on' q (λ g, rfl), right_inv := λ q, induction_on' q (λ g, rfl) } lemma quotient_equiv_of_eq_mk (h : s = t) (a : α) : quotient_equiv_of_eq h (quotient_group.mk a) = (quotient_group.mk a) := rfl /-- If `H ≤ K`, then `G/H ≃ G/K × K/H` constructively, using the provided right inverse of the quotient map `G → G/K`. The classical version is `quotient_equiv_prod_of_le`. -/ @[to_additive "If `H ≤ K`, then `G/H ≃ G/K × K/H` constructively, using the provided right inverse of the quotient map `G → G/K`. The classical version is `quotient_equiv_prod_of_le`.", simps] def quotient_equiv_prod_of_le' (h_le : s ≤ t) (f : α ⧸ t → α) (hf : function.right_inverse f quotient_group.mk) : α ⧸ s ≃ (α ⧸ t) × (t ⧸ s.subgroup_of t) := { to_fun := λ a, ⟨a.map' id (λ b c h, left_rel_apply.mpr (h_le (left_rel_apply.mp h))), a.map' (λ g : α, ⟨(f (quotient.mk' g))⁻¹ * g, left_rel_apply.mp (quotient.exact' (hf g))⟩) (λ b c h, by { rw left_rel_apply, change ((f b)⁻¹ * b)⁻¹ * ((f c)⁻¹ * c) ∈ s, have key : f b = f c := congr_arg f (quotient.sound' (left_rel_apply.mpr (h_le (left_rel_apply.mp h)))), rwa [key, mul_inv_rev, inv_inv, mul_assoc, mul_inv_cancel_left, ← left_rel_apply] })⟩, inv_fun := λ a, a.2.map' (λ b, f a.1 * b) (λ b c h, by { rw left_rel_apply at ⊢ h, change (f a.1 * b)⁻¹ * (f a.1 * c) ∈ s, rwa [mul_inv_rev, mul_assoc, inv_mul_cancel_left] }), left_inv := by { refine quotient.ind' (λ a, _), simp_rw [quotient.map'_mk', id.def, set_like.coe_mk, mul_inv_cancel_left] }, right_inv := by { refine prod.rec _, refine quotient.ind' (λ a, _), refine quotient.ind' (λ b, _), have key : quotient.mk' (f (quotient.mk' a) * b) = quotient.mk' a := (quotient_group.mk_mul_of_mem (f a) ↑b b.2).trans (hf a), simp_rw [quotient.map'_mk', id.def, key, inv_mul_cancel_left, subtype.coe_eta] } } /-- If `H ≤ K`, then `G/H ≃ G/K × K/H` nonconstructively. The constructive version is `quotient_equiv_prod_of_le'`. -/ @[to_additive "If `H ≤ K`, then `G/H ≃ G/K × K/H` nonconstructively. The constructive version is `quotient_equiv_prod_of_le'`.", simps] noncomputable def quotient_equiv_prod_of_le (h_le : s ≤ t) : α ⧸ s ≃ (α ⧸ t) × (t ⧸ s.subgroup_of t) := quotient_equiv_prod_of_le' h_le quotient.out' quotient.out_eq' /-- If `s ≤ t`, then there is an embedding `s ⧸ H.subgroup_of s ↪ t ⧸ H.subgroup_of t`. -/ @[to_additive "If `s ≤ t`, then there is an embedding `s ⧸ H.add_subgroup_of s ↪ t ⧸ H.add_subgroup_of t`."] def quotient_subgroup_of_embedding_of_le (H : subgroup α) (h : s ≤ t) : s ⧸ H.subgroup_of s ↪ t ⧸ H.subgroup_of t := { to_fun := quotient.map' (inclusion h) (λ a b, by { simp_rw left_rel_eq, exact id }), inj' := quotient.ind₂' $ by { intros a b h, simpa only [quotient.map'_mk', eq'] using h } } @[simp, to_additive] lemma quotient_subgroup_of_embedding_of_le_apply_mk (H : subgroup α) (h : s ≤ t) (g : s) : quotient_subgroup_of_embedding_of_le H h (quotient_group.mk g) = quotient_group.mk (inclusion h g) := rfl /-- If `s ≤ t`, then there is a map `H ⧸ s.subgroup_of H → H ⧸ t.subgroup_of H`. -/ @[to_additive "If `s ≤ t`, then there is an map `H ⧸ s.add_subgroup_of H → H ⧸ t.add_subgroup_of H`."] def quotient_subgroup_of_map_of_le (H : subgroup α) (h : s ≤ t) : H ⧸ s.subgroup_of H → H ⧸ t.subgroup_of H := quotient.map' id $ λ a b, by { simp_rw [left_rel_eq], apply h } @[simp, to_additive] lemma quotient_subgroup_of_map_of_le_apply_mk (H : subgroup α) (h : s ≤ t) (g : H) : quotient_subgroup_of_map_of_le H h (quotient_group.mk g) = quotient_group.mk g := rfl /-- If `s ≤ t`, then there is a map `α ⧸ s → α ⧸ t`. -/ @[to_additive "If `s ≤ t`, then there is an map `α ⧸ s → α ⧸ t`."] def quotient_map_of_le (h : s ≤ t) : α ⧸ s → α ⧸ t := quotient.map' id $ λ a b, by { simp_rw [left_rel_eq], apply h } @[simp, to_additive] lemma quotient_map_of_le_apply_mk (h : s ≤ t) (g : α) : quotient_map_of_le h (quotient_group.mk g) = quotient_group.mk g := rfl /-- The natural embedding `H ⧸ (⨅ i, f i).subgroup_of H ↪ Π i, H ⧸ (f i).subgroup_of H`. -/ @[to_additive "The natural embedding `H ⧸ (⨅ i, f i).add_subgroup_of H) ↪ Π i, H ⧸ (f i).add_subgroup_of H`.", simps] def quotient_infi_subgroup_of_embedding {ι : Type*} (f : ι → subgroup α) (H : subgroup α) : H ⧸ (⨅ i, f i).subgroup_of H ↪ Π i, H ⧸ (f i).subgroup_of H := { to_fun := λ q i, quotient_subgroup_of_map_of_le H (infi_le f i) q, inj' := quotient.ind₂' $ by simp_rw [funext_iff, quotient_subgroup_of_map_of_le_apply_mk, eq', mem_subgroup_of, mem_infi, imp_self, forall_const] } @[simp, to_additive] lemma quotient_infi_subgroup_of_embedding_apply_mk {ι : Type*} (f : ι → subgroup α) (H : subgroup α) (g : H) (i : ι) : quotient_infi_subgroup_of_embedding f H (quotient_group.mk g) i = quotient_group.mk g := rfl /-- The natural embedding `α ⧸ (⨅ i, f i) ↪ Π i, α ⧸ f i`. -/ @[to_additive "The natural embedding `α ⧸ (⨅ i, f i) ↪ Π i, α ⧸ f i`.", simps] def quotient_infi_embedding {ι : Type*} (f : ι → subgroup α) : α ⧸ (⨅ i, f i) ↪ Π i, α ⧸ f i := { to_fun := λ q i, quotient_map_of_le (infi_le f i) q, inj' := quotient.ind₂' $ by simp_rw [funext_iff, quotient_map_of_le_apply_mk, eq', mem_infi, imp_self, forall_const] } @[simp, to_additive] lemma quotient_infi_embedding_apply_mk {ι : Type*} (f : ι → subgroup α) (g : α) (i : ι) : quotient_infi_embedding f (quotient_group.mk g) i = quotient_group.mk g := rfl @[to_additive] lemma card_eq_card_quotient_mul_card_subgroup [fintype α] (s : subgroup α) [fintype s] [decidable_pred (λ a, a ∈ s)] : fintype.card α = fintype.card (α ⧸ s) * fintype.card s := by rw ← fintype.card_prod; exact fintype.card_congr (subgroup.group_equiv_quotient_times_subgroup) /-- **Lagrange's Theorem**: The order of a subgroup divides the order of its ambient group. -/ @[to_additive "**Lagrange's Theorem**: The order of an additive subgroup divides the order of its ambient group."] lemma card_subgroup_dvd_card [fintype α] (s : subgroup α) [fintype s] : fintype.card s ∣ fintype.card α := by classical; simp [card_eq_card_quotient_mul_card_subgroup s, @dvd_mul_left ℕ] @[to_additive] lemma card_quotient_dvd_card [fintype α] (s : subgroup α) [decidable_pred (λ a, a ∈ s)] [fintype s] : fintype.card (α ⧸ s) ∣ fintype.card α := by simp [card_eq_card_quotient_mul_card_subgroup s, @dvd_mul_right ℕ] open fintype variables {H : Type*} [group H] @[to_additive] lemma card_dvd_of_injective [fintype α] [fintype H] (f : α →* H) (hf : function.injective f) : card α ∣ card H := by classical; calc card α = card (f.range : subgroup H) : card_congr (equiv.of_injective f hf) ...∣ card H : card_subgroup_dvd_card _ @[to_additive] lemma card_dvd_of_le {H K : subgroup α} [fintype H] [fintype K] (hHK : H ≤ K) : card H ∣ card K := card_dvd_of_injective (inclusion hHK) (inclusion_injective hHK) @[to_additive] lemma card_comap_dvd_of_injective (K : subgroup H) [fintype K] (f : α →* H) [fintype (K.comap f)] (hf : function.injective f) : fintype.card (K.comap f) ∣ fintype.card K := by haveI : fintype ((K.comap f).map f) := fintype.of_equiv _ (equiv_map_of_injective _ _ hf).to_equiv; calc fintype.card (K.comap f) = fintype.card ((K.comap f).map f) : fintype.card_congr (equiv_map_of_injective _ _ hf).to_equiv ... ∣ fintype.card K : card_dvd_of_le (map_comap_le _ _) end subgroup namespace quotient_group variables [group α] -- FIXME -- why is there no `to_additive`? /-- If `s` is a subgroup of the group `α`, and `t` is a subset of `α/s`, then there is a (typically non-canonical) bijection between the preimage of `t` in `α` and the product `s × t`. -/ noncomputable def preimage_mk_equiv_subgroup_times_set (s : subgroup α) (t : set (α ⧸ s)) : quotient_group.mk ⁻¹' t ≃ s × t := have h : ∀ {x : α ⧸ s} {a : α}, x ∈ t → a ∈ s → (quotient.mk' (quotient.out' x * a) : α ⧸ s) = quotient.mk' (quotient.out' x) := λ x a hx ha, quotient.sound' $ by rwa [left_rel_apply, ← s.inv_mem_iff, mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul], { to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out' (quotient.mk' a))⁻¹ * a, left_rel_apply.mp (@quotient.exact' _ (left_rel s) _ _ $ (quotient.out_eq' _))⟩, ⟨quotient.mk' a, ha⟩⟩, inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨quotient.out' x * a, show quotient.mk' _ ∈ t, by simp [h hx ha, hx]⟩, left_inv := λ ⟨a, ha⟩, subtype.eq $ show _ * _ = a, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, show (_, _) = _, by simp [h hx ha] } end quotient_group /-- We use the class `has_coe_t` instead of `has_coe` if the first argument is a variable, or if the second argument is a variable not occurring in the first. Using `has_coe` would cause looping of type-class inference. See <https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/remove.20all.20instances.20with.20variable.20domain> -/ library_note "use has_coe_t"
fd275f153c841e1f74a5f3488ff3e0a103a025e8
fe25de614feb5587799621c41487aaee0d083b08
/stage0/src/Lean/Elab/SyntheticMVars.lean
be87cdfaba759dff492c7888644a57ae32d12617
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,545
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, Sebastian Ullrich -/ import Lean.Util.ForEachExpr import Lean.Elab.Term import Lean.Elab.Tactic.Basic namespace Lean.Elab.Term open Tactic (TacticM evalTactic getUnsolvedGoals withTacticInfoContext) open Meta /-- Auxiliary function used to implement `synthesizeSyntheticMVars`. -/ private def resumeElabTerm (stx : Syntax) (expectedType? : Option Expr) (errToSorry := true) : TermElabM Expr := -- Remark: if `ctx.errToSorry` is already false, then we don't enable it. Recall tactics disable `errToSorry` withReader (fun ctx => { ctx with errToSorry := ctx.errToSorry && errToSorry }) do elabTerm stx expectedType? false /-- Try to elaborate `stx` that was postponed by an elaboration method using `Expection.postpone`. It returns `true` if it succeeded, and `false` otherwise. It is used to implement `synthesizeSyntheticMVars`. -/ private def resumePostponed (savedContext : SavedContext) (stx : Syntax) (mvarId : MVarId) (postponeOnError : Bool) : TermElabM Bool := withRef stx <| withMVarContext mvarId do let s ← get try withSavedContext savedContext do let mvarDecl ← getMVarDecl mvarId let expectedType ← instantiateMVars mvarDecl.type withInfoHole mvarId do let result ← resumeElabTerm stx expectedType (!postponeOnError) /- We must ensure `result` has the expected type because it is the one expected by the method that postponed stx. That is, the method does not have an opportunity to check whether `result` has the expected type or not. -/ let result ← withRef stx <| ensureHasType expectedType result /- We must perform `occursCheck` here since `result` may contain `mvarId` when it has synthetic `sorry`s. -/ if (← occursCheck mvarId result) then assignExprMVar mvarId result return true else return false catch | ex@(Exception.internal id _) => if id == postponeExceptionId then set s return false else throw ex | ex@(Exception.error _ _) => if postponeOnError then set s return false else logException ex return true /-- Similar to `synthesizeInstMVarCore`, but makes sure that `instMVar` local context and instances are used. It also logs any error message produced. -/ private def synthesizePendingInstMVar (instMVar : MVarId) : TermElabM Bool := withMVarContext instMVar do try synthesizeInstMVarCore instMVar catch | ex@(Exception.error _ _) => logException ex; return true | _ => unreachable! /-- Similar to `synthesizePendingInstMVar`, but generates type mismatch error message. Remark: `eNew` is of the form `@coe ... mvar`, where `mvar` is the metavariable for the `CoeT ...` instance. If `mvar` can be synthesized, then assign `auxMVarId := (expandCoe eNew)`. -/ private def synthesizePendingCoeInstMVar (auxMVarId : MVarId) (errorMsgHeader? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Bool := do let instMVarId := eNew.appArg!.mvarId! withMVarContext instMVarId do if (← isDefEq expectedType eType) then /- This case may seem counterintuitive since we created the coercion because the `isDefEq expectedType eType` test failed before. However, it may succeed here because we have more information, for example, metavariables occurring at `expectedType` and `eType` may have been assigned. -/ if (← occursCheck auxMVarId e) then assignExprMVar auxMVarId e return true else return false try if (← synthesizeCoeInstMVarCore instMVarId) then let eNew ← expandCoe eNew if (← occursCheck auxMVarId eNew) then assignExprMVar auxMVarId eNew return true return false catch | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg | _ => unreachable! /-- Try to synthesize a value for `mvarId` using the given default instance. Return `some (val, mvarDecls)` if successful, where `val` is the value assigned to `mvarId`, and `mvarDecls` is a list of new type class instances that need to be synthesized. -/ private def tryToSynthesizeUsingDefaultInstance (mvarId : MVarId) (defaultInstance : Name) : TermElabM (Option (Expr × List SyntheticMVarDecl)) := commitWhenSome? do let candidate ← mkConstWithFreshMVarLevels defaultInstance let (mvars, bis, _) ← forallMetaTelescopeReducing (← inferType candidate) let candidate := mkAppN candidate mvars trace[Elab.resume] "trying default instance for {mkMVar mvarId} := {candidate}" if (← isDefEqGuarded (mkMVar mvarId) candidate) then -- Succeeded. Collect new TC problems let mut result := [] for i in [:bis.size] do if bis[i] == BinderInfo.instImplicit then result := { mvarId := mvars[i].mvarId!, stx := (← getRef), kind := SyntheticMVarKind.typeClass } :: result trace[Elab.resume] "worked" return some (candidate, result) else return none private def tryToSynthesizeUsingDefaultInstances (mvarId : MVarId) (prio : Nat) : TermElabM (Option (Expr × List SyntheticMVarDecl)) := withMVarContext mvarId do let mvarType := (← Meta.getMVarDecl mvarId).type match (← isClass? mvarType) with | none => return none | some className => match (← getDefaultInstances className) with | [] => return none | defaultInstances => for (defaultInstance, instPrio) in defaultInstances do if instPrio == prio then match (← tryToSynthesizeUsingDefaultInstance mvarId defaultInstance) with | some result => return some result | none => continue return none /- Used to implement `synthesizeUsingDefault`. This method only consider default instances with the given priority. -/ private def synthesizeUsingDefaultPrio (prio : Nat) : TermElabM Bool := do let rec visit (syntheticMVars : List SyntheticMVarDecl) (syntheticMVarsNew : List SyntheticMVarDecl) : TermElabM Bool := do match syntheticMVars with | [] => return false | mvarDecl :: mvarDecls => match mvarDecl.kind with | SyntheticMVarKind.typeClass => match (← withRef mvarDecl.stx <| tryToSynthesizeUsingDefaultInstances mvarDecl.mvarId prio) with | none => visit mvarDecls (mvarDecl :: syntheticMVarsNew) | some (val, newMVarDecls) => for newMVarDecl in newMVarDecls do -- Register that `newMVarDecl.mvarId`s are implicit arguments of the value assigned to `mvarDecl.mvarId` registerMVarErrorImplicitArgInfo newMVarDecl.mvarId (← getRef) val let syntheticMVarsNew := newMVarDecls ++ syntheticMVarsNew let syntheticMVarsNew := mvarDecls.reverse ++ syntheticMVarsNew modify fun s => { s with syntheticMVars := syntheticMVarsNew } return true | _ => visit mvarDecls (mvarDecl :: syntheticMVarsNew) /- Recall that s.syntheticMVars is essentially a stack. The first metavariable was the last one created. We want to apply the default instance in reverse creation order. Otherwise, `toString 0` will produce a `OfNat String _` cannot be synthesized error. -/ visit (← get).syntheticMVars.reverse [] /-- Apply default value to any pending synthetic metavariable of kind `SyntheticMVarKind.withDefault` Return true if something was synthesized. -/ private def synthesizeUsingDefault : TermElabM Bool := do let prioSet ← getDefaultInstancesPriorities /- Recall that `prioSet` is stored in descending order -/ for prio in prioSet do if (← synthesizeUsingDefaultPrio prio) then return true return false /-- Report an error for each synthetic metavariable that could not be resolved. Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments. -/ private def reportStuckSyntheticMVars (ignoreStuckTC := false) : TermElabM Unit := do let syntheticMVars ← modifyGet fun s => (s.syntheticMVars, { s with syntheticMVars := [] }) for mvarSyntheticDecl in syntheticMVars do withRef mvarSyntheticDecl.stx do match mvarSyntheticDecl.kind with | SyntheticMVarKind.typeClass => unless ignoreStuckTC do withMVarContext mvarSyntheticDecl.mvarId do let mvarDecl ← getMVarDecl mvarSyntheticDecl.mvarId unless (← get).messages.hasErrors do throwError "typeclass instance problem is stuck, it is often due to metavariables{indentExpr mvarDecl.type}" | SyntheticMVarKind.coe header eNew expectedType eType e f? => let mvarId := eNew.appArg!.mvarId! withMVarContext mvarId do let mvarDecl ← getMVarDecl mvarId throwTypeMismatchError header expectedType eType e f? (some ("failed to create type class instance for " ++ indentExpr mvarDecl.type)) | _ => unreachable! -- TODO handle other cases. private def getSomeSynthethicMVarsRef : TermElabM Syntax := do let s ← get match s.syntheticMVars.find? fun (mvarDecl : SyntheticMVarDecl) => !mvarDecl.stx.getPos?.isNone with | some mvarDecl => return mvarDecl.stx | none => return Syntax.missing mutual partial def runTactic (mvarId : MVarId) (tacticCode : Syntax) : TermElabM Unit := do /- Recall, `tacticCode` is the whole `by ...` expression. -/ let byTk := tacticCode[0] let code := tacticCode[1] modifyThe Meta.State fun s => { s with mctx := s.mctx.instantiateMVarDeclMVars mvarId } let remainingGoals ← withInfoHole mvarId <| Tactic.run mvarId do withTacticInfoContext tacticCode (evalTactic code) synthesizeSyntheticMVars (mayPostpone := false) unless remainingGoals.isEmpty do reportUnsolvedGoals remainingGoals /-- Try to synthesize the given pending synthetic metavariable. -/ private partial def synthesizeSyntheticMVar (mvarSyntheticDecl : SyntheticMVarDecl) (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := withRef mvarSyntheticDecl.stx do match mvarSyntheticDecl.kind with | SyntheticMVarKind.typeClass => synthesizePendingInstMVar mvarSyntheticDecl.mvarId | SyntheticMVarKind.coe header? eNew expectedType eType e f? => synthesizePendingCoeInstMVar mvarSyntheticDecl.mvarId header? eNew expectedType eType e f? -- NOTE: actual processing at `synthesizeSyntheticMVarsAux` | SyntheticMVarKind.postponed savedContext => resumePostponed savedContext mvarSyntheticDecl.stx mvarSyntheticDecl.mvarId postponeOnError | SyntheticMVarKind.tactic tacticCode savedContext => withSavedContext savedContext do if runTactics then runTactic mvarSyntheticDecl.mvarId tacticCode return true else return false /-- Try to synthesize the current list of pending synthetic metavariables. Return `true` if at least one of them was synthesized. -/ private partial def synthesizeSyntheticMVarsStep (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do let ctx ← read traceAtCmdPos `Elab.resuming fun _ => m!"resuming synthetic metavariables, mayPostpone: {ctx.mayPostpone}, postponeOnError: {postponeOnError}" let syntheticMVars := (← get).syntheticMVars let numSyntheticMVars := syntheticMVars.length -- We reset `syntheticMVars` because new synthetic metavariables may be created by `synthesizeSyntheticMVar`. modify fun s => { s with syntheticMVars := [] } -- Recall that `syntheticMVars` is a list where head is the most recent pending synthetic metavariable. -- We use `filterRevM` instead of `filterM` to make sure we process the synthetic metavariables using the order they were created. -- It would not be incorrect to use `filterM`. let remainingSyntheticMVars ← syntheticMVars.filterRevM fun mvarDecl => do -- We use `traceM` because we want to make sure the metavar local context is used to trace the message traceM `Elab.postpone (withMVarContext mvarDecl.mvarId do addMessageContext m!"resuming {mkMVar mvarDecl.mvarId}") let succeeded ← synthesizeSyntheticMVar mvarDecl postponeOnError runTactics trace[Elab.postpone] if succeeded then format "succeeded" else format "not ready yet" pure !succeeded -- Merge new synthetic metavariables with `remainingSyntheticMVars`, i.e., metavariables that still couldn't be synthesized modify fun s => { s with syntheticMVars := s.syntheticMVars ++ remainingSyntheticMVars } return numSyntheticMVars != remainingSyntheticMVars.length /-- Try to process pending synthetic metavariables. If `mayPostpone == false`, then `syntheticMVars` is `[]` after executing this method. It keeps executing `synthesizeSyntheticMVarsStep` while progress is being made. If `mayPostpone == false`, then it applies default instances to `SyntheticMVarKind.typeClass` (if available) metavariables that are still unresolved, and then tries to resolve metavariables with `mayPostpone == false`. That is, we force them to produce error messages and/or commit to a "best option". If, after that, we still haven't made progress, we report "stuck" errors. Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments. Then, pending TC problems become implicit parameters for the simp theorem. -/ partial def synthesizeSyntheticMVars (mayPostpone := true) (ignoreStuckTC := false) : TermElabM Unit := let rec loop (u : Unit) : TermElabM Unit := do withRef (← getSomeSynthethicMVarsRef) <| withIncRecDepth do unless (← get).syntheticMVars.isEmpty do if ← synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then loop () else if !mayPostpone then /- Resume pending metavariables with "elaboration postponement" disabled. We postpone elaboration errors in this step by setting `postponeOnError := true`. Example: ``` #check let x := ⟨1, 2⟩; Prod.fst x ``` The term `⟨1, 2⟩` can't be elaborated because the expected type is not know. The `x` at `Prod.fst x` is not elaborated because the type of `x` is not known. When we execute the following step with "elaboration postponement" disabled, the elaborator fails at `⟨1, 2⟩` and postpones it, and succeeds at `x` and learns that its type must be of the form `Prod ?α ?β`. Recall that we postponed `x` at `Prod.fst x` because its type it is not known. We the type of `x` may learn later its type and it may contain implicit and/or auto arguments. By disabling postponement, we are essentially giving up the opportunity of learning `x`s type and assume it does not have implict and/or auto arguments. -/ if ← withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := true) (runTactics := false) then loop () else if ← synthesizeUsingDefault then loop () else if ← withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then loop () else if ← synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := true) then loop () else reportStuckSyntheticMVars ignoreStuckTC loop () end def synthesizeSyntheticMVarsNoPostponing : TermElabM Unit := synthesizeSyntheticMVars (mayPostpone := false) /- Keep invoking `synthesizeUsingDefault` until it returns false. -/ private partial def synthesizeUsingDefaultLoop : TermElabM Unit := do if (← synthesizeUsingDefault) then synthesizeSyntheticMVars (mayPostpone := true) synthesizeUsingDefaultLoop def synthesizeSyntheticMVarsUsingDefault : TermElabM Unit := do synthesizeSyntheticMVars (mayPostpone := true) synthesizeUsingDefaultLoop private partial def withSynthesizeImp {α} (k : TermElabM α) (mayPostpone : Bool) : TermElabM α := do let syntheticMVarsSaved := (← get).syntheticMVars modify fun s => { s with syntheticMVars := [] } try let a ← k synthesizeSyntheticMVars mayPostpone if mayPostpone then synthesizeUsingDefaultLoop return a finally modify fun s => { s with syntheticMVars := s.syntheticMVars ++ syntheticMVarsSaved } /-- Execute `k`, and synthesize pending synthetic metavariables created while executing `k` are solved. If `mayPostpone == false`, then all of them must be synthesized. Remark: even if `mayPostpone == true`, the method still uses `synthesizeUsingDefault` -/ @[inline] def withSynthesize [MonadFunctorT TermElabM m] [Monad m] (k : m α) (mayPostpone := false) : m α := monadMap (m := TermElabM) (withSynthesizeImp . mayPostpone) k /-- Elaborate `stx`, and make sure all pending synthetic metavariables created while elaborating `stx` are solved. -/ def elabTermAndSynthesize (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := withRef stx do instantiateMVars (← withSynthesize <| elabTerm stx expectedType?) end Lean.Elab.Term
b77c05e84d4cc4a08c5cc8d1de83be6a5f93142d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/order/hom/ring.lean
2f86a97b9bb6396d13db7cb168453ea54211d174
[ "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
14,991
lean
/- Copyright (c) 2022 Alex J. Best, Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best, Yaël Dillies -/ import algebra.order.archimedean import algebra.order.hom.monoid import algebra.order.ring import algebra.ring.equiv /-! # Ordered ring homomorphisms Homomorphisms between ordered (semi)rings that respect the ordering. ## Main definitions * `order_ring_hom` : Monotone semiring homomorphisms. * `order_ring_iso` : Monotone semiring isomorphisms. ## Notation * `→+*o`: Ordered ring homomorphisms. * `≃+*o`: Ordered ring isomorphisms. ## Tags ordered ring homomorphism, order homomorphism -/ open function variables {F α β γ δ : Type*} /-- `order_ring_hom α β` is the type of monotone semiring homomorphisms from `α` to `β`. When possible, instead of parametrizing results over `(f : order_ring_hom α β)`, you should parametrize over `(F : Type*) [order_ring_hom_class F α β] (f : F)`. When you extend this structure, make sure to extend `order_ring_hom_class`. -/ structure order_ring_hom (α β : Type*) [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] extends α →+* β := (monotone' : monotone to_fun) /-- Reinterpret an ordered ring homomorphism as a ring homomorphism. -/ add_decl_doc order_ring_hom.to_ring_hom infix ` →+*o `:25 := order_ring_hom /-- `order_ring_hom α β` is the type of order-preserving semiring isomorphisms between `α` and `β`. When possible, instead of parametrizing results over `(f : order_ring_iso α β)`, you should parametrize over `(F : Type*) [order_ring_iso_class F α β] (f : F)`. When you extend this structure, make sure to extend `order_ring_iso_class`. -/ structure order_ring_iso (α β : Type*) [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β] extends α ≃+* β := (map_le_map_iff' {a b : α} : to_fun a ≤ to_fun b ↔ a ≤ b) infix ` ≃+*o `:25 := order_ring_iso /-- `order_ring_hom_class F α β` states that `F` is a type of ordered semiring homomorphisms. You should extend this typeclass when you extend `order_ring_hom`. -/ class order_ring_hom_class (F : Type*) (α β : out_param $ Type*) [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] extends ring_hom_class F α β := (monotone (f : F) : monotone f) /-- `order_ring_iso_class F α β` states that `F` is a type of ordered semiring isomorphisms. You should extend this class when you extend `order_ring_iso`. -/ class order_ring_iso_class (F : Type*) (α β : out_param Type*) [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β] extends ring_equiv_class F α β := (map_le_map_iff (f : F) {a b : α} : f a ≤ f b ↔ a ≤ b) @[priority 100] -- See note [lower priority instance] instance order_ring_hom_class.to_order_add_monoid_hom_class [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] [order_ring_hom_class F α β] : order_add_monoid_hom_class F α β := { .. ‹order_ring_hom_class F α β› } @[priority 100] -- See note [lower priority instance] instance order_ring_hom_class.to_order_monoid_with_zero_hom_class [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] [order_ring_hom_class F α β] : order_monoid_with_zero_hom_class F α β := { .. ‹order_ring_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance order_ring_iso_class.to_order_iso_class [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β] [order_ring_iso_class F α β] : order_iso_class F α β := { ..‹order_ring_iso_class F α β› } @[priority 100] -- See note [lower instance priority] instance order_ring_iso_class.to_order_ring_hom_class [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] [order_ring_iso_class F α β] : order_ring_hom_class F α β := { monotone := λ f, order_hom_class.mono f, ..‹order_ring_iso_class F α β› } instance [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] [order_ring_hom_class F α β] : has_coe_t F (α →+*o β) := ⟨λ f, ⟨f, order_hom_class.mono f⟩⟩ instance [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β] [order_ring_iso_class F α β] : has_coe_t F (α ≃+*o β) := ⟨λ f, ⟨f, λ a b, map_le_map_iff f⟩⟩ /-! ### Ordered ring homomorphisms -/ namespace order_ring_hom variables [non_assoc_semiring α] [preorder α] section preorder variables [non_assoc_semiring β] [preorder β] [non_assoc_semiring γ] [preorder γ] [non_assoc_semiring δ] [preorder δ] /-- Reinterpret an ordered ring homomorphism as an ordered additive monoid homomorphism. -/ def to_order_add_monoid_hom (f : α →+*o β) : α →+o β := { ..f } /-- Reinterpret an ordered ring homomorphism as an order homomorphism. -/ def to_order_monoid_with_zero_hom (f : α →+*o β) : α →*₀o β := { ..f } instance : order_ring_hom_class (α →+*o β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by obtain ⟨⟨_, _⟩, _⟩ := f; obtain ⟨⟨_, _⟩, _⟩ := g; congr', map_mul := λ f, f.map_mul', map_one := λ f, f.map_one', map_add := λ f, f.map_add', map_zero := λ f, f.map_zero', monotone := λ f, f.monotone' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α →+*o β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ lemma to_fun_eq_coe (f : α →+*o β) : f.to_fun = ⇑f := rfl @[ext] lemma ext {f g : α →+*o β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h @[simp] lemma to_ring_hom_eq_coe (f : α →+*o β) : f.to_ring_hom = f := ring_hom.ext $ λ _, rfl @[simp] lemma to_order_add_monoid_hom_eq_coe (f : α →+*o β) : f.to_order_add_monoid_hom = f := rfl @[simp] lemma to_order_monoid_with_zero_hom_eq_coe (f : α →+*o β) : f.to_order_monoid_with_zero_hom = f := rfl @[simp] lemma coe_coe_ring_hom (f : α →+*o β) : ⇑(f : α →+* β) = f := rfl @[simp] lemma coe_coe_order_add_monoid_hom (f : α →+*o β) : ⇑(f : α →+o β) = f := rfl @[simp] lemma coe_coe_order_monoid_with_zero_hom (f : α →+*o β) : ⇑(f : α →*₀o β) = f := rfl @[norm_cast] lemma coe_ring_hom_apply (f : α →+*o β) (a : α) : (f : α →+* β) a = f a := rfl @[norm_cast] lemma coe_order_add_monoid_hom_apply (f : α →+*o β) (a : α) : (f : α →+o β) a = f a := rfl @[norm_cast] lemma coe_order_monoid_with_zero_hom_apply (f : α →+*o β) (a : α) : (f : α →*₀o β) a = f a := rfl /-- Copy of a `order_ring_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : α →+*o β) (f' : α → β) (h : f' = f) : α →+*o β := { .. f.to_ring_hom.copy f' h, .. f.to_order_add_monoid_hom.copy f' h } variable (α) /-- The identity as an ordered ring homomorphism. -/ protected def id : α →+*o α := { ..ring_hom.id _, ..order_hom.id } instance : inhabited (α →+*o α) := ⟨order_ring_hom.id α⟩ @[simp] lemma coe_id : ⇑(order_ring_hom.id α) = id := rfl variable {α} @[simp] lemma id_apply (a : α) : order_ring_hom.id α a = a := rfl @[simp] lemma coe_ring_hom_id : (order_ring_hom.id α : α →+* α) = ring_hom.id α := rfl @[simp] lemma coe_order_add_monoid_hom_id : (order_ring_hom.id α : α →+o α) = order_add_monoid_hom.id α := rfl @[simp] lemma coe_order_monoid_with_zero_hom_id : (order_ring_hom.id α : α →*₀o α) = order_monoid_with_zero_hom.id α := rfl /-- Composition of two `order_ring_hom`s as an `order_ring_hom`. -/ protected def comp (f : β →+*o γ) (g : α →+*o β) : α →+*o γ := { ..f.to_ring_hom.comp g.to_ring_hom, ..f.to_order_add_monoid_hom.comp g.to_order_add_monoid_hom } @[simp] lemma coe_comp (f : β →+*o γ) (g : α →+*o β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : β →+*o γ) (g : α →+*o β) (a : α) : f.comp g a = f (g a) := rfl lemma comp_assoc (f : γ →+*o δ) (g : β →+*o γ) (h : α →+*o β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : α →+*o β) : f.comp (order_ring_hom.id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : α →+*o β) : (order_ring_hom.id β).comp f = f := ext $ λ x, rfl lemma cancel_right {f₁ f₂ : β →+*o γ} {g : α →+*o β} (hg : surjective g) : f₁.comp g = f₂.comp g ↔ f₁ = f₂ := ⟨λ h, ext $ hg.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {f : β →+*o γ} {g₁ g₂ : α →+*o β} (hf : injective f) : f.comp g₁ = f.comp g₂ ↔ g₁ = g₂ := ⟨λ h, ext $ λ a, hf $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end preorder variables [non_assoc_semiring β] instance [preorder β] : preorder (order_ring_hom α β) := preorder.lift (coe_fn : _ → α → β) instance [partial_order β] : partial_order (order_ring_hom α β) := partial_order.lift _ fun_like.coe_injective end order_ring_hom /-! ### Ordered ring isomorphisms -/ namespace order_ring_iso section has_le variables [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β] [has_mul γ] [has_add γ] [has_le γ] [has_mul δ] [has_add δ] [has_le δ] /-- Reinterpret an ordered ring isomorphism as an order isomorphism. -/ def to_order_iso (f : α ≃+*o β) : α ≃o β := ⟨f.to_ring_equiv.to_equiv, λ _ _, f.map_le_map_iff'⟩ instance : order_ring_iso_class (α ≃+*o β) α β := { coe := λ f, f.to_fun, inv := λ f, f.inv_fun, coe_injective' := λ f g h₁ h₂, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_add := λ f, f.map_add', map_mul := λ f, f.map_mul', map_le_map_iff := λ f _ _, f.map_le_map_iff', left_inv := λ f, f.left_inv, right_inv := λ f, f.right_inv } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α ≃+*o β) (λ _, α → β) := fun_like.has_coe_to_fun lemma to_fun_eq_coe (f : α ≃+*o β) : f.to_fun = f := rfl @[ext] lemma ext {f g : α ≃+*o β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h @[simp] lemma coe_mk (e : α ≃+* β) (h) : ⇑(⟨e, h⟩ : α ≃+*o β) = e := rfl @[simp] lemma mk_coe (e : α ≃+*o β) (h) : (⟨e, h⟩ : α ≃+*o β) = e := ext $ λ _, rfl @[simp] lemma to_ring_equiv_eq_coe (f : α ≃+*o β) : f.to_ring_equiv = f := ring_equiv.ext $ λ _, rfl @[simp] lemma to_order_iso_eq_coe (f : α ≃+*o β) : f.to_order_iso = f := order_iso.ext rfl @[simp, norm_cast] lemma coe_to_ring_equiv (f : α ≃+*o β) : ⇑(f : α ≃+* β) = f := rfl @[simp, norm_cast] lemma coe_to_order_iso (f : α ≃+*o β) : ⇑(f : α ≃o β) = f := rfl variable (α) /-- The identity map as an ordered ring isomorphism. -/ @[refl] protected def refl : α ≃+*o α := ⟨ring_equiv.refl α, λ _ _, iff.rfl⟩ instance : inhabited (α ≃+*o α) := ⟨order_ring_iso.refl α⟩ @[simp] lemma refl_apply (x : α) : order_ring_iso.refl α x = x := rfl @[simp] lemma coe_ring_equiv_refl : (order_ring_iso.refl α : α ≃+* α) = ring_equiv.refl α := rfl @[simp] lemma coe_order_iso_refl : (order_ring_iso.refl α : α ≃o α) = order_iso.refl α := rfl variables {α} /-- The inverse of an ordered ring isomorphism as an ordered ring isomorphism. -/ @[symm] protected def symm (e : α ≃+*o β) : β ≃+*o α := ⟨e.to_ring_equiv.symm, λ a b, by erw [←map_le_map_iff e, e.1.apply_symm_apply, e.1.apply_symm_apply]⟩ /-- See Note [custom simps projection] -/ def simps.symm_apply (e : α ≃+*o β) : β → α := e.symm @[simp] lemma symm_symm (e : α ≃+*o β) : e.symm.symm = e := ext $ λ _, rfl /-- Composition of `order_ring_iso`s as an `order_ring_iso`. -/ @[trans, simps] protected def trans (f : α ≃+*o β) (g : β ≃+*o γ) : α ≃+*o γ := ⟨f.to_ring_equiv.trans g.to_ring_equiv, λ a b, (map_le_map_iff g).trans (map_le_map_iff f)⟩ @[simp] lemma trans_apply (f : α ≃+*o β) (g : β ≃+*o γ) (a : α) : f.trans g a = g (f a) := rfl @[simp] lemma self_trans_symm (e : α ≃+*o β) : e.trans e.symm = order_ring_iso.refl α := ext e.left_inv @[simp] lemma symm_trans_self (e : α ≃+*o β) : e.symm.trans e = order_ring_iso.refl β := ext e.right_inv lemma symm_bijective : bijective (order_ring_iso.symm : (α ≃+*o β) → β ≃+*o α) := ⟨λ f g h, f.symm_symm.symm.trans $ (congr_arg order_ring_iso.symm h).trans g.symm_symm, λ f, ⟨f.symm, f.symm_symm⟩⟩ end has_le section non_assoc_semiring variables [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β] [non_assoc_semiring γ] [preorder γ] /-- Reinterpret an ordered ring isomorphism as an ordered ring homomorphism. -/ def to_order_ring_hom (f : α ≃+*o β) : α →+*o β := ⟨f.to_ring_equiv.to_ring_hom, λ a b, (map_le_map_iff f).2⟩ @[simp] lemma to_order_ring_hom_eq_coe (f : α ≃+*o β) : f.to_order_ring_hom = f := rfl @[simp, norm_cast] lemma coe_to_order_ring_hom (f : α ≃+*o β) : ⇑(f : α →+*o β) = f := rfl @[simp] lemma coe_to_order_ring_hom_refl : (order_ring_iso.refl α : α →+*o α) = order_ring_hom.id α := rfl lemma to_order_ring_hom_injective : injective (to_order_ring_hom : (α ≃+*o β) → α →+*o β) := λ f g h, fun_like.coe_injective $ by convert fun_like.ext'_iff.1 h end non_assoc_semiring end order_ring_iso /-! ### Uniqueness There is at most one ordered ring homomorphism from a linear ordered field to an archimedean linear ordered field. Reciprocally, such an ordered ring homomorphism exists when the codomain is further conditionally complete. -/ /-- There is at most one ordered ring homomorphism from a linear ordered field to an archimedean linear ordered field. -/ instance order_ring_hom.subsingleton [linear_ordered_field α] [linear_ordered_field β] [archimedean β] : subsingleton (α →+*o β) := ⟨λ f g, begin ext x, by_contra' h, wlog h : f x < g x using [f g, g f], { exact ne.lt_or_lt h }, obtain ⟨q, hf, hg⟩ := exists_rat_btwn h, rw ←map_rat_cast f at hf, rw ←map_rat_cast g at hg, exact (lt_asymm ((order_hom_class.mono g).reflect_lt hg) $ (order_hom_class.mono f).reflect_lt hf).elim, end⟩ /-- There is at most one ordered ring isomorphism between a linear ordered field and an archimedean linear ordered field. -/ instance order_ring_iso.subsingleton_right [linear_ordered_field α] [linear_ordered_field β] [archimedean β] : subsingleton (α ≃+*o β) := order_ring_iso.to_order_ring_hom_injective.subsingleton /-- There is at most one ordered ring isomorphism between an archimedean linear ordered field and a linear ordered field. -/ instance order_ring_iso.subsingleton_left [linear_ordered_field α] [archimedean α] [linear_ordered_field β] : subsingleton (α ≃+*o β) := order_ring_iso.symm_bijective.injective.subsingleton
cbb5279c446d995f95f8daf348b46dd4ae32e4cf
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/meta/rb_map.lean
d2948c921be3261870a60eda6e58ac55003cb228
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,061
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.option.defs import data.list.defs /-! # rb_map This file defines additional operations on native rb_maps and rb_sets. These structures are defined in core in `init.meta.rb_map`. They are meta objects, and are generally the most efficient dictionary structures to use for pure metaprogramming right now. -/ namespace native /-! ### Declarations about `rb_set` -/ namespace rb_set meta instance {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : inhabited (rb_set key) := ⟨mk_rb_set⟩ /-- `filter s P` returns the subset of elements of `s` satisfying `P`. -/ meta def filter {key} (s : rb_set key) (P : key → bool) : rb_set key := s.fold s (λ a m, if P a then m else m.erase a) /-- `mfilter s P` returns the subset of elements of `s` satisfying `P`, where the check `P` is monadic. -/ meta def mfilter {m} [monad m] {key} (s : rb_set key) (P : key → m bool) : m (rb_set key) := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) /-- `union s t` returns an rb_set containing every element that appears in either `s` or `t`. -/ meta def union {key} (s t : rb_set key) : rb_set key := s.fold t (λ a t, t.insert a) /-- `of_list_core empty l` turns a list of keys into an `rb_set`. It takes a user_provided `rb_set` to use for the base case. This can be used to pre-seed the set with additional elements, and/or to use a custom comparison operator. -/ meta def of_list_core {key} (base : rb_set key) : list key → rb_map key unit | [] := base | (x::xs) := rb_set.insert (of_list_core xs) x /-- `of_list l` transforms a list `l : list key` into an `rb_set`, inferring an order on the type `key`. -/ meta def of_list {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : list key → rb_set key := of_list_core mk_rb_set /-- `sdiff s1 s2` returns the set of elements that are in `s1` but not in `s2`. It does so by folding over `s2`. If `s1` is significantly smaller than `s2`, it may be worth it to reverse the fold. -/ meta def sdiff {α} (s1 s2 : rb_set α) : rb_set α := s2.fold s1 $ λ v s, s.erase v /-- `insert_list s l` inserts each element of `l` into `s`. -/ meta def insert_list {key} (s : rb_set key) (l : list key) : rb_set key := l.foldl rb_set.insert s end rb_set /-! ### Declarations about `rb_map` -/ namespace rb_map meta instance {key data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : inhabited (rb_map key data) := ⟨mk_rb_map⟩ /-- `find_def default m k` returns the value corresponding to `k` in `m`, if it exists. Otherwise it returns `default`. -/ meta def find_def {key value} (default : value) (m : rb_map key value) (k : key) := (m.find k).get_or_else default /-- `ifind m key` returns the value corresponding to `key` in `m`, if it exists. Otherwise it returns the default value of `value`. -/ meta def ifind {key value} [inhabited value] (m : rb_map key value) (k : key) : value := (m.find k).iget /-- `zfind m key` returns the value corresponding to `key` in `m`, if it exists. Otherwise it returns 0. -/ meta def zfind {key value} [has_zero value] (m : rb_map key value) (k : key) : value := (m.find k).get_or_else 0 /-- Returns the pointwise sum of `m1` and `m2`, treating nonexistent values as 0. -/ meta def add {key value} [has_add value] [has_zero value] [decidable_eq value] (m1 m2 : rb_map key value) : rb_map key value := m1.fold m2 (λ n v m, let nv := v + m2.zfind n in if nv = 0 then m.erase n else m.insert n nv) variables {m : Type → Type*} [monad m] open function /-- `mfilter P s` filters `s` by the monadic predicate `P` on keys and values. -/ meta def mfilter {key val} [has_lt key] [decidable_rel ((<) : key → key → Prop)] (P : key → val → m bool) (s : rb_map key val) : m (rb_map.{0 0} key val) := rb_map.of_list <$> s.to_list.mfilter (uncurry P) /-- `mmap f s` maps the monadic function `f` over values in `s`. -/ meta def mmap {key val val'} [has_lt key] [decidable_rel ((<) : key → key → Prop)] (f : val → m val') (s : rb_map key val) : m (rb_map.{0 0} key val') := rb_map.of_list <$> s.to_list.mmap (λ ⟨a,b⟩, prod.mk a <$> f b) /-- `scale b m` multiplies every value in `m` by `b`. -/ meta def scale {key value} [has_lt key] [decidable_rel ((<) : key → key → Prop)] [has_mul value] (b : value) (m : rb_map key value) : rb_map key value := m.map ((*) b) section open format prod variables {key : Type} {data : Type} [has_to_tactic_format key] [has_to_tactic_format data] private meta def pp_key_data (k : key) (d : data) (first : bool) : tactic format := do fk ← tactic.pp k, fd ← tactic.pp d, return $ (if first then to_fmt "" else to_fmt "," ++ line) ++ fk ++ space ++ to_fmt "←" ++ space ++ fd meta instance : has_to_tactic_format (rb_map key data) := ⟨λ m, do (fmt, _) ← fold m (return (to_fmt "", tt)) (λ k d p, do p ← p, pkd ← pp_key_data k d (snd p), return (fst p ++ pkd, ff)), return $ group $ to_fmt "⟨" ++ nest 1 fmt ++ to_fmt "⟩"⟩ end end rb_map /-! ### Declarations about `rb_lmap` -/ namespace rb_lmap meta instance (key : Type) [has_lt key] [decidable_rel ((<) : key → key → Prop)] (data : Type) : inhabited (rb_lmap key data) := ⟨rb_lmap.mk _ _⟩ /-- Construct a rb_lmap from a list of key-data pairs -/ protected meta def of_list {key : Type} {data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : list (key × data) → rb_lmap key data | [] := rb_lmap.mk key data | ((k, v)::ls) := (of_list ls).insert k v /-- Returns the list of values of an `rb_lmap`. -/ protected meta def values {key data} (m : rb_lmap key data) : list data := m.fold [] (λ _, (++)) end rb_lmap end native /-! ### Declarations about `name_set` -/ namespace name_set meta instance : inhabited name_set := ⟨mk_name_set⟩ /-- `filter P s` returns the subset of elements of `s` satisfying `P`. -/ meta def filter (P : name → bool) (s : name_set) : name_set := s.fold s (λ a m, if P a then m else m.erase a) /-- `mfilter P s` returns the subset of elements of `s` satisfying `P`, where the check `P` is monadic. -/ meta def mfilter {m} [monad m] (P : name → m bool) (s : name_set) : m name_set := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) /-- `mmap f s` maps the monadic function `f` over values in `s`. -/ meta def mmap {m} [monad m] (f : name → m name) (s : name_set) : m name_set := s.fold (pure mk_name_set) (λ a m, do x ← m, b ← f a, (pure $ x.insert b)) /-- `insert_list s l` inserts every element of `l` into `s`. -/ meta def insert_list (s : name_set) (l : list name) : name_set := l.foldr (λ n s', s'.insert n) s /-- `local_list_to_name_set lcs` is the set of unique names of the local constants `lcs`. If any of the `lcs` are not local constants, the returned set will contain bogus names. -/ meta def local_list_to_name_set (lcs : list expr) : name_set := lcs.foldl (λ ns h, ns.insert h.local_uniq_name) mk_name_set end name_set /-! ### Declarations about `name_map` -/ namespace name_map meta instance {data : Type} : inhabited (name_map data) := ⟨mk_name_map⟩ end name_map /-! ### Declarations about `expr_set` -/ namespace expr_set /-- `local_set_to_name_set lcs` is the set of unique names of the local constants `lcs`. If any of the `lcs` are not local constants, the returned set will contain bogus names. -/ meta def local_set_to_name_set (lcs : expr_set) : name_set := lcs.fold mk_name_set $ λ h ns, ns.insert h.local_uniq_name end expr_set namespace list /-- `to_rb_map as` is the map that associates each index `i` of `as` with the corresponding element of `as`. ``` to_rb_map ['a', 'b', 'c'] = rb_map.of_list [(0, 'a'), (1, 'b'), (2, 'c')] ``` -/ meta def to_rb_map {α : Type} : list α → native.rb_map ℕ α := foldl_with_index (λ i mapp a, mapp.insert i a) native.mk_rb_map end list
6cbaa496c796b9791152392536f6e7bbee573be7
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/set_of.lean
4a5b295f36f267f509dfd9c748d252182e4c760a
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
191
lean
check {x : nat | x > 0} check {x | x > 0} check {p : nat × nat | p.1 > p.2 } set_option pp.binder_types false check {x : nat | x > 0} check {x | x > 0} check {p : nat × nat | p.1 > p.2 }
b43f98d410b8494d364985fb7580bb26d7a962b2
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/rewrite_search/frontend.lean
a3f8b4b7a9d5cf5f2a3fc8a261a835824725a352
[ "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
4,055
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek, Scott Morrison -/ import tactic.rewrite_search.explain import tactic.rewrite_search.discovery import tactic.rewrite_search.search /-! # `rewrite_search`: solving goals by searching for a series of rewrites. `rewrite_search` is a tactic for solving equalities or iff statements by searching for a sequence of rewrite tactic applications. ## Algorithm sketch The fundamental data structure behind the search algorithm is a graph of expressions. Each vertex represents one expression, and an edge in the graph represents a way to rewrite one expression into another with a single application of a rewrite tactic. Thus, a path in the graph represents a way to rewrite one expression into another with multiple applications of a rewrite tactic. The graph starts out with two vertices, one for the left hand side of the equality, and one for the right hand side of the equality. The basic loop of the algorithm is to repeatedly add edges to the graph by taking vertices in the graph and applying a possible rewrite to them. Through this process, the graph is made up of two connected components; one component contains expressions that are equivalent to the left hand side, and one component contains expressions that are equivalent to the right hand side. The algorithm completes when we discover an edge that connects the two components, creating a path of rewrites that connects the left hand side and right hand side of the graph. For more detail, see Keeley's report at https://hoek.io/res/2018.s2.lean.report.pdf, although note that the edit distance mechanism described is currently not implemented, only plain breadth-first search. This algorithm is generally superior to one that only expands nodes starting from a single side, because it is replacing one tree of depth `2d` with two trees of depth `d`. This is a quadratic speedup for regular trees; our trees aren't regular but it's still probably a much better algorithm. We can only use this specific algorithm for rewrite-type tactics, though, not general sequences of tactics, because it relies on the fact that any rewrite can be reversed. ## File structure * `discovery.lean` contains the logic for figuring out which rewrite rules to consider. * `search.lean` contains the graph algorithms to find a successful sequence of tactics. * `explain.lean` generates concise Lean code to run a tactic, from the autogenerated sequence of tactics. * `frontend.lean` contains the user-facing interface to the `rewrite_search` tactics. * `types.lean` contains data structures shared across multiple of these components. -/ namespace tactic.interactive open lean.parser interactive interactive.types tactic.rewrite_search /-- Search for a chain of rewrites to prove an equation or iff statement. Collects rewrite rules, runs a graph search to find a chain of rewrites to prove the current target, and generates a string explanation for it. Takes an optional list of rewrite rules specified in the same way as the `rw` tactic accepts. -/ meta def rewrite_search (explain : parse $ optional (tk "?")) (rs : parse $ optional (list_of (rw_rule_p $ lean.parser.pexpr 0))) (cfg : config := {}) : tactic unit := do t ← tactic.target, if t.has_meta_var then tactic.fail "rewrite_search is not suitable for goals containing metavariables" else tactic.skip, implicit_rules ← collect_rules, explicit_rules ← (rs.get_or_else []).mmap (λ ⟨_, dir, pe⟩, do e ← to_expr' pe, return (e, dir)), let rules := implicit_rules ++ explicit_rules, g ← mk_graph cfg rules t, (_, proof, steps) ← g.find_proof, tactic.exact proof, if explain.is_some then explain_search_result cfg rules proof steps else skip add_tactic_doc { name := "rewrite_search", category := doc_category.tactic, decl_names := [`tactic.interactive.rewrite_search], tags := ["rewriting", "automation"] } end tactic.interactive
6204d18dffaf692d9c4ac98649f1c0cfd0270f75
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/calculus/fderiv_measurable_auto.lean
fe2b29f130bbbb8c53e371ca09e57a28403d0d88
[]
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,783
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.calculus.deriv import Mathlib.measure_theory.borel_space import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Derivative is measurable In this file we prove that the derivative of any function with complete codomain is a measurable function. Namely, we prove: * `is_measurable_set_of_differentiable_at`: the set `{x | differentiable_at 𝕜 f x}` is measurable; * `measurable_fderiv`: the function `fderiv 𝕜 f` is measurable; * `measurable_fderiv_apply_const`: for a fixed vector `y`, the function `λ x, fderiv 𝕜 f x y` is measurable; * `measurable_deriv`: the function `deriv f` is measurable (for `f : 𝕜 → F`). ## Implementation We give a proof that avoids second-countability issues, by expressing the differentiability set as a function of open sets in the following way. Define `A (L, r, ε)` to be the set of points where, on a ball of radius roughly `r` around `x`, the function is uniformly approximated by the linear map `L`, up to `ε r`. It is an open set. Let also `B (L, r, s, ε) = A (L, r, ε) ∩ A (L, s, ε)`: we require that at two possibly different scales `r` and `s`, the function is well approximated by the linear map `L`. It is also open. We claim that the differentiability set of `f` is exactly `D = ⋂ ε > 0, ⋃ δ > 0, ⋂ r, s < δ, ⋃ L, B (L, r, s, ε)`. In other words, for any `ε > 0`, we require that there is a size `δ` such that, for any two scales below this size, the function is well approximated by a linear map, common to the two scales. The set `⋃ L, B (L, r, s, ε)` is open, as a union of open sets. Converting the intersections and unions to countable ones (using real numbers of the form `2 ^ (-n)`), it follows that the differentiability set is measurable. To prove the claim, there are two inclusions. One is trivial: if the function is differentiable at `x`, then `x` belongs to `D` (just take `L` to be the derivative, and use that the differentiability exactly says that the map is well approximated by `L`). This is proved in `mem_A_of_differentiable` and `differentiable_set_subset_D`. For the other direction, the difficulty is that `L` in the union may depend on `ε, r, s`. The key point is that, in fact, it doesn't depend too much on them. First, if `x` belongs both to `A (L, r, ε)` and `A (L', r, ε)`, then `L` and `L'` have to be close on a shell, and thus `∥L - L'∥` is bounded by `ε` (see `norm_sub_le_of_mem_A`). Assume now `x ∈ D`. If one has two maps `L` and `L'` such that `x` belongs to `A (L, r, ε)` and to `A (L', r', ε')`, one deduces that `L` is close to `L'` by arguing as follows. Consider another scale `s` smaller than `r` and `r'`. Take a linear map `L₁` that approximates `f` around `x` both at scales `r` and `s` w.r.t. `ε` (it exists as `x` belongs to `D`). Take also `L₂` that approximates `f` around `x` both at scales `r'` and `s` w.r.t. `ε'`. Then `L₁` is close to `L` (as they are close on a shell of radius `r`), and `L₂` is close to `L₁` (as they are close on a shell of radius `s`), and `L'` is close to `L₂` (as they are close on a shell of radius `r'`). It follows that `L` is close to `L'`, as we claimed. It follows that the different approximating linear maps that show up form a Cauchy sequence when `ε` tends to `0`. When the target space is complete, this sequence converges, to a limit `f'`. With the same kind of arguments, one checks that `f` is differentiable with derivative `f'`. To show that the derivative itself is measurable, add in the definition of `B` and `D` a set `K` of continuous linear maps to which `L` should belong. Then, when `K` is complete, the set `D K` is exactly the set of points where `f` is differentiable with a derivative in `K`. ## Tags derivative, measurable function, Borel σ-algebra -/ namespace continuous_linear_map protected instance measurable_space {𝕜 : Type u_1} {E : Type u_2} {F : Type u_3} [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] : measurable_space (continuous_linear_map 𝕜 E F) := borel (continuous_linear_map 𝕜 E F) protected instance borel_space {𝕜 : Type u_1} {E : Type u_2} {F : Type u_3} [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] : borel_space (continuous_linear_map 𝕜 E F) := borel_space.mk rfl theorem measurable_apply {𝕜 : Type u_1} {E : Type u_2} {F : Type u_3} [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F] (x : E) : measurable fun (f : continuous_linear_map 𝕜 E F) => coe_fn f x := continuous.measurable (continuous_linear_map.continuous (apply 𝕜 F x)) theorem measurable_apply' {𝕜 : Type u_1} {E : Type u_2} {F : Type u_3} [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] [measurable_space E] [opens_measurable_space E] [measurable_space F] [borel_space F] : measurable fun (x : E) (f : continuous_linear_map 𝕜 E F) => coe_fn f x := measurable_pi_lambda (fun (x : E) (f : continuous_linear_map 𝕜 E F) => coe_fn f x) fun (f : continuous_linear_map 𝕜 E F) => continuous_linear_map.measurable f theorem measurable_apply₂ {𝕜 : Type u_1} {E : Type u_2} {F : Type u_3} [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] [measurable_space E] [opens_measurable_space E] [topological_space.second_countable_topology E] [topological_space.second_countable_topology (continuous_linear_map 𝕜 E F)] [measurable_space F] [borel_space F] : measurable fun (p : continuous_linear_map 𝕜 E F × E) => coe_fn (prod.fst p) (prod.snd p) := continuous.measurable (is_bounded_bilinear_map.continuous is_bounded_bilinear_map_apply) theorem measurable_coe {𝕜 : Type u_1} {E : Type u_2} {F : Type u_3} [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F] : measurable fun (f : continuous_linear_map 𝕜 E F) (x : E) => coe_fn f x := measurable_pi_lambda (fun (f : continuous_linear_map 𝕜 E F) (x : E) => coe_fn f x) measurable_apply end continuous_linear_map namespace fderiv_measurable_aux /-- The set `A f L r ε` is the set of points `x` around which the function `f` is well approximated at scale `r` by the linear map `L`, up to an error `ε`. We tweak the definition to make sure that this is an open set.-/ def A {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (f : E → F) (L : continuous_linear_map 𝕜 E F) (r : ℝ) (ε : ℝ) : set E := set_of fun (x : E) => ∃ (r' : ℝ), ∃ (H : r' ∈ set.Ioc (r / bit0 1) r), ∀ (y z : E), y ∈ metric.ball x r' → z ∈ metric.ball x r' → norm (f z - f y - coe_fn L (z - y)) ≤ ε * r /-- The set `B f K r s ε` is the set of points `x` around which there exists a continuous linear map `L` belonging to `K` (a given set of continuous linear maps) that approximates well the function `f` (up to an error `ε`), simultaneously at scales `r` and `s`. -/ def B {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (f : E → F) (K : set (continuous_linear_map 𝕜 E F)) (r : ℝ) (s : ℝ) (ε : ℝ) : set E := set.Union fun (L : continuous_linear_map 𝕜 E F) => set.Union fun (H : L ∈ K) => A f L r ε ∩ A f L s ε /-- The set `D f K` is a complicated set constructed using countable intersections and unions. Its main use is that, when `K` is complete, it is exactly the set of points where `f` is differentiable, with a derivative in `K`. -/ def D {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (f : E → F) (K : set (continuous_linear_map 𝕜 E F)) : set E := set.Inter fun (e : ℕ) => set.Union fun (n : ℕ) => set.Inter fun (p : ℕ) => set.Inter fun (H : p ≥ n) => set.Inter fun (q : ℕ) => set.Inter fun (H : q ≥ n) => B f K ((1 / bit0 1) ^ p) ((1 / bit0 1) ^ q) ((1 / bit0 1) ^ e) theorem is_open_A {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {f : E → F} (L : continuous_linear_map 𝕜 E F) (r : ℝ) (ε : ℝ) : is_open (A f L r ε) := sorry theorem is_open_B {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {f : E → F} {K : set (continuous_linear_map 𝕜 E F)} {r : ℝ} {s : ℝ} {ε : ℝ} : is_open (B f K r s ε) := sorry theorem A_mono {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {f : E → F} (L : continuous_linear_map 𝕜 E F) (r : ℝ) {ε : ℝ} {δ : ℝ} (h : ε ≤ δ) : A f L r ε ⊆ A f L r δ := sorry theorem le_of_mem_A {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {f : E → F} {r : ℝ} {ε : ℝ} {L : continuous_linear_map 𝕜 E F} {x : E} (hx : x ∈ A f L r ε) {y : E} {z : E} (hy : y ∈ metric.closed_ball x (r / bit0 1)) (hz : z ∈ metric.closed_ball x (r / bit0 1)) : norm (f z - f y - coe_fn L (z - y)) ≤ ε * r := sorry theorem mem_A_of_differentiable {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {f : E → F} {ε : ℝ} (hε : 0 < ε) {x : E} (hx : differentiable_at 𝕜 f x) : ∃ (R : ℝ), ∃ (H : R > 0), ∀ (r : ℝ), r ∈ set.Ioo 0 R → x ∈ A f (fderiv 𝕜 f x) r ε := sorry theorem norm_sub_le_of_mem_A {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {f : E → F} {c : 𝕜} (hc : 1 < norm c) {r : ℝ} {ε : ℝ} (hε : 0 < ε) (hr : 0 < r) {x : E} {L₁ : continuous_linear_map 𝕜 E F} {L₂ : continuous_linear_map 𝕜 E F} (h₁ : x ∈ A f L₁ r ε) (h₂ : x ∈ A f L₂ r ε) : norm (L₁ - L₂) ≤ bit0 (bit0 1) * norm c * ε := sorry /-- Easy inclusion: a differentiability point with derivative in `K` belongs to `D f K`. -/ theorem differentiable_set_subset_D {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {f : E → F} (K : set (continuous_linear_map 𝕜 E F)) : (set_of fun (x : E) => differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K) ⊆ D f K := sorry /-- Harder inclusion: at a point in `D f K`, the function `f` has a derivative, in `K`. -/
77b81bca949b623a7463fff334ad8e2dc1267660
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/field_theory/minpoly.lean
e53c37f2457c490f56c7fd5588395cab5e615103
[ "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
17,444
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johan Commelin -/ import data.polynomial.field_division import ring_theory.integral_closure import ring_theory.polynomial.gauss_lemma /-! # Minimal polynomials This file defines the minimal polynomial of an element `x` of an `A`-algebra `B`, under the assumption that x is integral over `A`. After stating the defining property we specialize to the setting of field extensions and derive some well-known properties, amongst which the fact that minimal polynomials are irreducible, and uniquely determined by their defining property. -/ open_locale classical open polynomial set function variables {A B : Type*} section min_poly_def variables (A) [comm_ring A] [ring B] [algebra A B] /-- Suppose `x : B`, where `B` is an `A`-algebra. The minimal polynomial `minpoly A x` of `x` is a monic polynomial with coefficients in `A` of smallest degree that has `x` as its root, if such exists (`is_integral A x`) or zero otherwise. For example, if `V` is a `𝕜`-vector space for some field `𝕜` and `f : V →ₗ[𝕜] V` then the minimal polynomial of `f` is `minpoly 𝕜 f`. -/ noncomputable def minpoly (x : B) : polynomial A := if hx : is_integral A x then well_founded.min degree_lt_wf _ hx else 0 end min_poly_def namespace minpoly section ring variables [comm_ring A] [ring B] [algebra A B] variables {x : B} /-- A minimal polynomial is monic. -/ lemma monic (hx : is_integral A x) : monic (minpoly A x) := by { delta minpoly, rw dif_pos hx, exact (well_founded.min_mem degree_lt_wf _ hx).1 } /-- A minimal polynomial is nonzero. -/ lemma ne_zero [nontrivial A] (hx : is_integral A x) : minpoly A x ≠ 0 := ne_zero_of_monic (monic hx) lemma eq_zero (hx : ¬ is_integral A x) : minpoly A x = 0 := dif_neg hx variables (A x) /-- An element is a root of its minimal polynomial. -/ @[simp] lemma aeval : aeval x (minpoly A x) = 0 := begin delta minpoly, split_ifs with hx, { exact (well_founded.min_mem degree_lt_wf _ hx).2 }, { exact aeval_zero _ } end lemma mem_range_of_degree_eq_one (hx : (minpoly A x).degree = 1) : x ∈ (algebra_map A B).range := begin have h : is_integral A x, { by_contra h, rw [eq_zero h, degree_zero, ←with_bot.coe_one] at hx, exact (ne_of_lt (show ⊥ < ↑1, from with_bot.bot_lt_coe 1) hx) }, have key := minpoly.aeval A x, rw [eq_X_add_C_of_degree_eq_one hx, (minpoly.monic h).leading_coeff, C_1, one_mul, aeval_add, aeval_C, aeval_X, ←eq_neg_iff_add_eq_zero, ←ring_hom.map_neg] at key, exact ⟨-(minpoly A x).coeff 0, key.symm⟩, end /-- The defining property of the minimal polynomial of an element `x`: it is the monic polynomial with smallest degree that has `x` as its root. -/ lemma min {p : polynomial A} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := begin delta minpoly, split_ifs with hx, { exact le_of_not_lt (well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩) }, { simp only [degree_zero, bot_le] } end end ring section integral_domain variables [integral_domain A] section ring variables [ring B] [algebra A B] [nontrivial B] variables {x : B} /-- The degree of a minimal polynomial, as a natural number, is positive. -/ lemma nat_degree_pos (hx : is_integral A x) : 0 < nat_degree (minpoly A x) := begin rw pos_iff_ne_zero, intro ndeg_eq_zero, have eq_one : minpoly A x = 1, { rw eq_C_of_nat_degree_eq_zero ndeg_eq_zero, convert C_1, simpa only [ndeg_eq_zero.symm] using (monic hx).leading_coeff }, simpa only [eq_one, alg_hom.map_one, one_ne_zero] using aeval A x end /-- The degree of a minimal polynomial is positive. -/ lemma degree_pos (hx : is_integral A x) : 0 < degree (minpoly A x) := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos hx) /-- If `B/A` is an injective ring extension, and `a` is an element of `A`, then the minimal polynomial of `algebra_map A B a` is `X - C a`. -/ lemma eq_X_sub_C_of_algebra_map_inj [nontrivial A] (a : A) (hf : function.injective (algebra_map A B)) : minpoly A (algebra_map A B a) = X - C a := begin have hdegle : (minpoly A (algebra_map A B a)).nat_degree ≤ 1, { apply with_bot.coe_le_coe.1, rw [←degree_eq_nat_degree (ne_zero (@is_integral_algebra_map A B _ _ _ a)), with_top.coe_one, ←degree_X_sub_C a], refine min A (algebra_map A B a) (monic_X_sub_C a) _, simp only [aeval_C, aeval_X, alg_hom.map_sub, sub_self] }, have hdeg : (minpoly A (algebra_map A B a)).degree = 1, { apply (degree_eq_iff_nat_degree_eq (ne_zero (@is_integral_algebra_map A B _ _ _ a))).2, apply le_antisymm hdegle (nat_degree_pos (@is_integral_algebra_map A B _ _ _ a)) }, have hrw := eq_X_add_C_of_degree_eq_one hdeg, simp only [monic (@is_integral_algebra_map A B _ _ _ a), one_mul, monic.leading_coeff, ring_hom.map_one] at hrw, have h0 : (minpoly A (algebra_map A B a)).coeff 0 = -a, { have hroot := aeval A (algebra_map A B a), rw [hrw, add_comm] at hroot, simp only [aeval_C, aeval_X, aeval_add] at hroot, replace hroot := eq_neg_of_add_eq_zero hroot, rw [←ring_hom.map_neg _ a] at hroot, exact (hf hroot) }, rw hrw, simp only [h0, ring_hom.map_neg, sub_eq_add_neg], end variables (A x) /-- A minimal polynomial is not a unit. -/ lemma not_is_unit : ¬ is_unit (minpoly A x) := begin by_cases hx : is_integral A x, { assume H, exact (ne_of_lt (degree_pos hx)).symm (degree_eq_zero_of_is_unit H) }, { delta minpoly, rw dif_neg hx, simp only [not_is_unit_zero, not_false_iff] } end end ring section domain variables [domain B] [algebra A B] variables {x : B} /-- If `a` strictly divides the minimal polynomial of `x`, then `x` cannot be a root for `a`. -/ lemma aeval_ne_zero_of_dvd_not_unit_minpoly {a : polynomial A} (hx : is_integral A x) (hamonic : a.monic) (hdvd : dvd_not_unit a (minpoly A x)) : polynomial.aeval x a ≠ 0 := begin intro ha, refine not_lt_of_ge (minpoly.min A x hamonic ha) _, obtain ⟨hzeroa, b, hb_nunit, prod⟩ := hdvd, have hbmonic : b.monic, { rw monic.def, have := monic hx, rwa [monic.def, prod, leading_coeff_mul, monic.def.mp hamonic, one_mul] at this }, have hzerob : b ≠ 0 := hbmonic.ne_zero, have degbzero : 0 < b.nat_degree, { apply nat.pos_of_ne_zero, intro h, have h₁ := eq_C_of_nat_degree_eq_zero h, rw [←h, ←leading_coeff, monic.def.1 hbmonic, C_1] at h₁, rw h₁ at hb_nunit, have := is_unit_one, contradiction }, rw [prod, degree_mul, degree_eq_nat_degree hzeroa, degree_eq_nat_degree hzerob], exact_mod_cast lt_add_of_pos_right _ degbzero, end /-- A minimal polynomial is irreducible. -/ lemma irreducible (hx : is_integral A x) : irreducible (minpoly A x) := begin cases irreducible_or_factor (minpoly A x) (not_is_unit A x) with hirr hred, { exact hirr }, exfalso, obtain ⟨a, b, ha_nunit, hb_nunit, hab_eq⟩ := hred, have coeff_prod : a.leading_coeff * b.leading_coeff = 1, { rw [←monic.def.1 (monic hx), ←hab_eq], simp only [leading_coeff_mul] }, have hamonic : (a * C b.leading_coeff).monic, { rw monic.def, simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have hbmonic : (b * C a.leading_coeff).monic, { rw [monic.def, mul_comm], simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have prod : minpoly A x = (a * C b.leading_coeff) * (b * C a.leading_coeff), { symmetry, calc a * C b.leading_coeff * (b * C a.leading_coeff) = a * b * (C a.leading_coeff * C b.leading_coeff) : by ring ... = a * b * (C (a.leading_coeff * b.leading_coeff)) : by simp only [ring_hom.map_mul] ... = a * b : by rw [coeff_prod, C_1, mul_one] ... = minpoly A x : hab_eq }, have hzero := aeval A x, rw [prod, aeval_mul, mul_eq_zero] at hzero, cases hzero, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hamonic _ hzero, exact ⟨hamonic.ne_zero, _, mt is_unit_of_mul_is_unit_left hb_nunit, prod⟩ }, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hbmonic _ hzero, rw mul_comm at prod, exact ⟨hbmonic.ne_zero, _, mt is_unit_of_mul_is_unit_left ha_nunit, prod⟩ }, end end domain end integral_domain section field variables [field A] section ring variables [ring B] [algebra A B] variables {x : B} variables (A x) /-- If an element `x` is a root of a nonzero polynomial `p`, then the degree of `p` is at least the degree of the minimal polynomial of `x`. -/ lemma degree_le_of_ne_zero {p : polynomial A} (pnz : p ≠ 0) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := calc degree (minpoly A x) ≤ degree (p * C (leading_coeff p)⁻¹) : min A x (monic_mul_leading_coeff_inv pnz) (by simp [hp]) ... = degree p : degree_mul_leading_coeff_inv p pnz /-- The minimal polynomial of an element `x` is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has `x` as a root, then this polynomial is equal to the minimal polynomial of `x`. -/ lemma unique {p : polynomial A} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) (pmin : ∀ q : polynomial A, q.monic → polynomial.aeval x q = 0 → degree p ≤ degree q) : p = minpoly A x := begin have hx : is_integral A x := ⟨p, pmonic, hp⟩, symmetry, apply eq_of_sub_eq_zero, by_contra hnz, have := degree_le_of_ne_zero A x hnz (by simp [hp]), contrapose! this, apply degree_sub_lt _ (ne_zero hx), { rw [(monic hx).leading_coeff, pmonic.leading_coeff] }, { exact le_antisymm (min A x pmonic hp) (pmin (minpoly A x) (monic hx) (aeval A x)) } end /-- If an element `x` is a root of a polynomial `p`, then the minimal polynomial of `x` divides `p`. -/ lemma dvd {p : polynomial A} (hp : polynomial.aeval x p = 0) : minpoly A x ∣ p := begin by_cases hp0 : p = 0, { simp only [hp0, dvd_zero] }, have hx : is_integral A x, { rw ← is_algebraic_iff_is_integral, exact ⟨p, hp0, hp⟩ }, rw ← dvd_iff_mod_by_monic_eq_zero (monic hx), by_contra hnz, have := degree_le_of_ne_zero A x hnz _, { contrapose! this, exact degree_mod_by_monic_lt _ (monic hx) (ne_zero hx) }, { rw ← mod_by_monic_add_div p (monic hx) at hp, simpa using hp } end lemma dvd_map_of_is_scalar_tower (A K : Type*) {R : Type*} [comm_ring A] [field K] [comm_ring R] [algebra A K] [algebra A R] [algebra K R] [is_scalar_tower A K R] (x : R) : minpoly K x ∣ (minpoly A x).map (algebra_map A K) := by { refine minpoly.dvd K x _, rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } variables {A x} theorem unique' [nontrivial B] {p : polynomial A} (hp1 : _root_.irreducible p) (hp2 : polynomial.aeval x p = 0) (hp3 : p.monic) : p = minpoly A x := let ⟨q, hq⟩ := dvd A x hp2 in eq_of_monic_of_associated hp3 (monic ⟨p, ⟨hp3, hp2⟩⟩) $ mul_one (minpoly A x) ▸ hq.symm ▸ associated_mul_mul (associated.refl _) $ associated_one_iff_is_unit.2 $ (hp1.is_unit_or_is_unit hq).resolve_left $ not_is_unit A x /-- If `y` is the image of `x` in an extension, their minimal polynomials coincide. We take `h : y = algebra_map L T x` as an argument because `rw h` typically fails since `is_integral R y` depends on y. -/ lemma eq_of_algebra_map_eq {K S T : Type*} [field K] [comm_ring S] [comm_ring T] [algebra K S] [algebra K T] [algebra S T] [is_scalar_tower K S T] (hST : function.injective (algebra_map S T)) {x : S} {y : T} (hx : is_integral K x) (h : y = algebra_map S T x) : minpoly K x = minpoly K y := minpoly.unique _ _ (minpoly.monic hx) (by rw [h, ← is_scalar_tower.algebra_map_aeval, minpoly.aeval, ring_hom.map_zero]) (λ q q_monic root_q, minpoly.min _ _ q_monic (is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero K S T hST (h ▸ root_q : polynomial.aeval (algebra_map S T x) q = 0))) section gcd_domain /-- For GCD domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. -/ lemma gcd_domain_eq_field_fractions {A K R : Type*} [integral_domain A] [gcd_monoid A] [field K] [integral_domain R] (f : fraction_map A K) [algebra f.codomain R] [algebra A R] [is_scalar_tower A f.codomain R] {x : R} (hx : is_integral A x) : minpoly f.codomain x = (minpoly A x).map (localization_map.to_ring_hom f) := begin refine (unique' _ _ _).symm, { exact (polynomial.is_primitive.irreducible_iff_irreducible_map_fraction_map f (polynomial.monic.is_primitive (monic hx))).1 (irreducible hx) }, { have htower := is_scalar_tower.aeval_apply A f.codomain R x (minpoly A x), simp only [localization_map.algebra_map_eq, aeval] at htower, exact htower.symm }, { exact monic_map _ (monic hx) } end /-- The minimal polynomial over `ℤ` is the same as the minimal polynomial over `ℚ`. -/ --TODO use `gcd_domain_eq_field_fractions` directly when localizations are defined -- in terms of algebras instead of `ring_hom`s lemma over_int_eq_over_rat {A : Type*} [integral_domain A] {x : A} [hℚA : algebra ℚ A] (hx : is_integral ℤ x) : minpoly ℚ x = map (int.cast_ring_hom ℚ) (minpoly ℤ x) := begin refine (unique' _ _ _).symm, { exact (is_primitive.int.irreducible_iff_irreducible_map_cast (polynomial.monic.is_primitive (monic hx))).1 (irreducible hx) }, { have htower := is_scalar_tower.aeval_apply ℤ ℚ A x (minpoly ℤ x), simp only [localization_map.algebra_map_eq, aeval] at htower, exact htower.symm }, { exact monic_map _ (monic hx) } end /-- For GCD domains, the minimal polynomial divides any primitive polynomial that has the integral element as root. -/ lemma gcd_domain_dvd {A K R : Type*} [integral_domain A] [gcd_monoid A] [field K] [integral_domain R] (f : fraction_map A K) [algebra f.codomain R] [algebra A R] [is_scalar_tower A f.codomain R] {x : R} (hx : is_integral A x) {P : polynomial A} (hprim : is_primitive P) (hroot : polynomial.aeval x P = 0) : minpoly A x ∣ P := begin apply (is_primitive.dvd_iff_fraction_map_dvd_fraction_map f (monic.is_primitive (monic hx)) hprim ).2, rw [← gcd_domain_eq_field_fractions f hx], refine dvd _ _ _, rwa [← localization_map.algebra_map_eq, ← is_scalar_tower.aeval_apply] end /-- The minimal polynomial over `ℤ` divides any primitive polynomial that has the integral element as root. -/ -- TODO use `gcd_domain_dvd` directly when localizations are defined in terms of algebras -- instead of `ring_hom`s lemma integer_dvd {A : Type*} [integral_domain A] [algebra ℚ A] {x : A} (hx : is_integral ℤ x) {P : polynomial ℤ} (hprim : is_primitive P) (hroot : polynomial.aeval x P = 0) : minpoly ℤ x ∣ P := begin apply (is_primitive.int.dvd_iff_map_cast_dvd_map_cast _ _ (monic.is_primitive (monic hx)) hprim ).2, rw [← over_int_eq_over_rat hx], refine dvd _ _ _, rwa [(int.cast_ring_hom ℚ).ext_int (algebra_map ℤ ℚ), ← is_scalar_tower.aeval_apply] end end gcd_domain variables (B) [nontrivial B] /-- If `B/K` is a nontrivial algebra over a field, and `x` is an element of `K`, then the minimal polynomial of `algebra_map K B x` is `X - C x`. -/ lemma eq_X_sub_C (a : A) : minpoly A (algebra_map A B a) = X - C a := eq_X_sub_C_of_algebra_map_inj a (algebra_map A B).injective lemma eq_X_sub_C' (a : A) : minpoly A a = X - C a := eq_X_sub_C A a variables (A) /-- The minimal polynomial of `0` is `X`. -/ @[simp] lemma zero : minpoly A (0:B) = X := by simpa only [add_zero, C_0, sub_eq_add_neg, neg_zero, ring_hom.map_zero] using eq_X_sub_C B (0:A) /-- The minimal polynomial of `1` is `X - 1`. -/ @[simp] lemma one : minpoly A (1:B) = X - 1 := by simpa only [ring_hom.map_one, C_1, sub_eq_add_neg] using eq_X_sub_C B (1:A) end ring section domain variables [domain B] [algebra A B] variables {x : B} /-- A minimal polynomial is prime. -/ lemma prime (hx : is_integral A x) : prime (minpoly A x) := begin refine ⟨ne_zero hx, not_is_unit A x, _⟩, rintros p q ⟨d, h⟩, have : polynomial.aeval x (p*q) = 0 := by simp [h, aeval A x], replace : polynomial.aeval x p = 0 ∨ polynomial.aeval x q = 0 := by simpa, exact or.imp (dvd A x) (dvd A x) this end /-- If `L/K` is a field extension and an element `y` of `K` is a root of the minimal polynomial of an element `x ∈ L`, then `y` maps to `x` under the field embedding. -/ lemma root {x : B} (hx : is_integral A x) {y : A} (h : is_root (minpoly A x) y) : algebra_map A B y = x := have key : minpoly A x = X - C y := eq_of_monic_of_associated (monic hx) (monic_X_sub_C y) (associated_of_dvd_dvd (dvd_symm_of_irreducible (irreducible_X_sub_C y) (irreducible hx) (dvd_iff_is_root.2 h)) (dvd_iff_is_root.2 h)), by { have := aeval A x, rwa [key, alg_hom.map_sub, aeval_X, aeval_C, sub_eq_zero, eq_comm] at this } /-- The constant coefficient of the minimal polynomial of `x` is `0` if and only if `x = 0`. -/ @[simp] lemma coeff_zero_eq_zero (hx : is_integral A x) : coeff (minpoly A x) 0 = 0 ↔ x = 0 := begin split, { intro h, have zero_root := zero_is_root_of_coeff_zero_eq_zero h, rw ← root hx zero_root, exact ring_hom.map_zero _ }, { rintro rfl, simp } end /-- The minimal polynomial of a nonzero element has nonzero constant coefficient. -/ lemma coeff_zero_ne_zero (hx : is_integral A x) (h : x ≠ 0) : coeff (minpoly A x) 0 ≠ 0 := by { contrapose! h, simpa only [hx, coeff_zero_eq_zero] using h } end domain end field end minpoly
b24a88be25f44ac5cd94049e87a6b1b668bbf89e
1a61aba1b67cddccce19532a9596efe44be4285f
/library/data/int/div.lean
add7a967914765ae0b0a2f7a7efc61eeb7076fd3
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
29,492
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Definitions and properties of div and mod, following the SSReflect library. Following SSReflect and the SMTlib standard, we define a mod b so that 0 ≤ a mod b < |b| when b ≠ 0. -/ import data.int.order data.nat.div open [coercions] [reduce-hints] nat open [declarations] nat (succ) open eq.ops namespace int /- definitions -/ definition divide (a b : ℤ) : ℤ := sign b * (match a with | of_nat m := #nat m div (nat_abs b) | -[1+m] := -[1+ (#nat m div (nat_abs b))] end) notation [priority int.prio] a div b := divide a b definition modulo (a b : ℤ) : ℤ := a - a div b * b notation [priority int.prio] a mod b := modulo a b notation [priority int.prio] a `≡` b `[mod`:100 c `]`:0 := a mod c = b mod c /- div -/ theorem of_nat_div (m n : nat) : of_nat (#nat m div n) = m div n := nat.cases_on n (by rewrite [↑divide, sign_zero, zero_mul, nat.div_zero]) (take n, by rewrite [↑divide, sign_of_succ, one_mul]) theorem neg_succ_of_nat_div (m : nat) {b : ℤ} (H : b > 0) : -[1+m] div b = -(m div b + 1) := calc -[1+m] div b = sign b * _ : rfl ... = -[1+(#nat m div (nat_abs b))] : by rewrite [sign_of_pos H, one_mul] ... = -(m div b + 1) : by rewrite [↑divide, sign_of_pos H, one_mul] theorem div_neg (a b : ℤ) : a div -b = -(a div b) := by rewrite [↑divide, sign_neg, neg_mul_eq_neg_mul, nat_abs_neg] theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a div b = -((-a - 1) div b + 1) := obtain m (H1 : a = -[1+m]), from exists_eq_neg_succ_of_nat Ha, calc a div b = -(m div b + 1) : by rewrite [H1, neg_succ_of_nat_div _ Hb] ... = -((-a -1) div b + 1) : by rewrite [H1, neg_succ_of_nat_eq', neg_sub, sub_neg_eq_add, add.comm 1, add_sub_cancel] theorem div_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a div b ≥ 0 := obtain (m : ℕ) (Hm : a = m), from exists_eq_of_nat Ha, obtain (n : ℕ) (Hn : b = n), from exists_eq_of_nat Hb, calc a div b = (#nat m div n) : by rewrite [Hm, Hn, of_nat_div] ... ≥ 0 : begin change (0 ≤ #nat m div n), apply trivial end theorem div_nonpos {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≤ 0) : a div b ≤ 0 := calc a div b = -(a div -b) : by rewrite [div_neg, neg_neg] ... ≤ 0 : neg_nonpos_of_nonneg (div_nonneg Ha (neg_nonneg_of_nonpos Hb)) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a div b < 0 := have -a - 1 ≥ 0, from le_sub_one_of_lt (neg_pos_of_neg Ha), have (-a - 1) div b + 1 > 0, from lt_add_one_of_le (div_nonneg this (le_of_lt Hb)), calc a div b = -((-a - 1) div b + 1) : div_of_neg_of_pos Ha Hb ... < 0 : neg_neg_of_pos this set_option pp.coercions true theorem zero_div (b : ℤ) : 0 div b = 0 := calc 0 div b = sign b * (#nat 0 div (nat_abs b)) : rfl ... = sign b * (0:nat) : nat.zero_div ... = 0 : mul_zero theorem div_zero (a : ℤ) : a div 0 = 0 := by rewrite [↑divide, sign_zero, zero_mul] theorem div_one (a : ℤ) :a div 1 = a := assert 1 > 0, from dec_trivial, int.cases_on a (take m, by rewrite [-of_nat_div, nat.div_one]) (take m, by rewrite [!neg_succ_of_nat_div this, -of_nat_div, nat.div_one]) theorem eq_div_mul_add_mod (a b : ℤ) : a = a div b * b + a mod b := !add.comm ▸ eq_add_of_sub_eq rfl theorem div_eq_zero_of_lt {a b : ℤ} : 0 ≤ a → a < b → a div b = 0 := int.cases_on a (take m, assume H, int.cases_on b (take n, assume H : m < n, calc m div n = #nat m div n : of_nat_div ... = (0:nat) : nat.div_eq_zero_of_lt (lt_of_of_nat_lt_of_nat H)) (take n, assume H : m < -[1+n], have H1 : ¬(m < -[1+n]), from dec_trivial, absurd H H1)) (take m, assume H : 0 ≤ -[1+m], have ¬ (0 ≤ -[1+m]), from dec_trivial, absurd H this) theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a div b = 0 := lt.by_cases (suppose b < 0, assert a < -b, from abs_of_neg this ▸ H2, calc a div b = - (a div -b) : by rewrite [div_neg, neg_neg] ... = 0 : by rewrite [div_eq_zero_of_lt H1 this, neg_zero]) (suppose b = 0, this⁻¹ ▸ !div_zero) (suppose b > 0, have a < b, from abs_of_pos this ▸ H2, div_eq_zero_of_lt H1 this) private theorem add_mul_div_self_aux1 {a : ℤ} {k : ℕ} (n : ℕ) (H1 : a ≥ 0) (H2 : #nat k > 0) : (a + n * k) div k = a div k + n := obtain m (Hm : a = of_nat m), from exists_eq_of_nat H1, Hm⁻¹ ▸ (calc (m + n * k) div k = (#nat (m + n * k)) div k : rfl ... = (#nat (m + n * k) div k) : of_nat_div ... = (#nat m div k + n) : !nat.add_mul_div_self H2 ... = (#nat m div k) + n : rfl ... = m div k + n : of_nat_div) private theorem add_mul_div_self_aux2 {a : ℤ} {k : ℕ} (n : ℕ) (H1 : a < 0) (H2 : #nat k > 0) : (a + n * k) div k = a div k + n := obtain m (Hm : a = -[1+m]), from exists_eq_neg_succ_of_nat H1, or.elim (nat.lt_or_ge m (#nat n * k)) (assume m_lt_nk : #nat m < n * k, have H3 : #nat (m + 1 ≤ n * k), from nat.succ_le_of_lt m_lt_nk, have H4 : #nat m div k + 1 ≤ n, from nat.succ_le_of_lt (nat.div_lt_of_lt_mul m_lt_nk), Hm⁻¹ ▸ (calc (-[1+m] + n * k) div k = (n * k - (m + 1)) div k : by rewrite [add.comm, neg_succ_of_nat_eq] ... = ((#nat n * k) - (#nat m + 1)) div k : rfl ... = (#nat n * k - (m + 1)) div k : {(of_nat_sub H3)⁻¹} ... = #nat (n * k - (m + 1)) div k : of_nat_div ... = #nat (k * n - (m + 1)) div k : nat.mul.comm ... = #nat n - m div k - 1 : nat.mul_sub_div_of_lt (!nat.mul.comm ▸ m_lt_nk) ... = #nat n - (m div k + 1) : nat.sub_sub ... = n - (#nat m div k + 1) : of_nat_sub H4 ... = -(m div k + 1) + n : by rewrite [add.comm, -sub_eq_add_neg, of_nat_add, of_nat_div] ... = -[1+m] div k + n : neg_succ_of_nat_div m (of_nat_lt_of_nat_of_lt H2))) (assume nk_le_m : #nat n * k ≤ m, eq.symm (Hm⁻¹ ▸ (calc -[1+m] div k + n = -(m div k + 1) + n : neg_succ_of_nat_div m (of_nat_lt_of_nat_of_lt H2) ... = -((#nat m div k) + 1) + n : of_nat_div ... = -((#nat (m - n * k + n * k) div k) + 1) + n : nat.sub_add_cancel nk_le_m ... = -((#nat (m - n * k) div k + n) + 1) + n : nat.add_mul_div_self H2 ... = -((#nat m - n * k) div k + 1) : by rewrite [of_nat_add, *neg_add, add.right_comm, neg_add_cancel_right, of_nat_div] ... = -[1+(#nat m - n * k)] div k : neg_succ_of_nat_div _ (of_nat_lt_of_nat_of_lt H2) ... = -((#nat m - n * k) + 1) div k : rfl ... = -(m - (#nat n * k) + 1) div k : of_nat_sub nk_le_m ... = (-(m + 1) + n * k) div k : by rewrite [sub_eq_add_neg, -*add.assoc, *neg_add, neg_neg, add.right_comm] ... = (-[1+m] + n * k) div k : rfl))) private theorem add_mul_div_self_aux3 (a : ℤ) {b c : ℤ} (H1 : b ≥ 0) (H2 : c > 0) : (a + b * c) div c = a div c + b := obtain n (Hn : b = of_nat n), from exists_eq_of_nat H1, obtain k (Hk : c = of_nat k), from exists_eq_of_nat (le_of_lt H2), have knz : k ≠ 0, from assume kz, !lt.irrefl (kz ▸ Hk ▸ H2), have kgt0 : (#nat k > 0), from nat.pos_of_ne_zero knz, have H3 : (a + n * k) div k = a div k + n, from or.elim (lt_or_ge a 0) (assume Ha : a < 0, add_mul_div_self_aux2 _ Ha kgt0) (assume Ha : a ≥ 0, add_mul_div_self_aux1 _ Ha kgt0), Hn⁻¹ ▸ Hk⁻¹ ▸ H3 private theorem add_mul_div_self_aux4 (a b : ℤ) {c : ℤ} (H : c > 0) : (a + b * c) div c = a div c + b := or.elim (le.total 0 b) (assume H1 : 0 ≤ b, add_mul_div_self_aux3 _ H1 H) (assume H1 : 0 ≥ b, eq.symm (calc a div c + b = (a + b * c + -b * c) div c + b : by rewrite [-neg_mul_eq_neg_mul, add_neg_cancel_right] ... = (a + b * c) div c + - b + b : add_mul_div_self_aux3 _ (neg_nonneg_of_nonpos H1) H ... = (a + b * c) div c : neg_add_cancel_right)) theorem add_mul_div_self (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) div c = a div c + b := lt.by_cases (assume H1 : 0 < c, !add_mul_div_self_aux4 H1) (assume H1 : 0 = c, absurd H1⁻¹ H) (assume H1 : 0 > c, have H2 : -c > 0, from neg_pos_of_neg H1, calc (a + b * c) div c = - ((a + -b * -c) div -c) : by rewrite [div_neg, neg_mul_neg, neg_neg] ... = -(a div -c + -b) : !add_mul_div_self_aux4 H2 ... = a div c + b : by rewrite [div_neg, neg_add, *neg_neg]) theorem add_mul_div_self_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) div b = a div b + c := !mul.comm ▸ !add_mul_div_self H theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b div b = a := calc a * b div b = (0 + a * b) div b : zero_add ... = 0 div b + a : !add_mul_div_self H ... = a : by rewrite [zero_div, zero_add] theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b div a = b := !mul.comm ▸ mul_div_cancel b H theorem div_self {a : ℤ} (H : a ≠ 0) : a div a = 1 := !mul_one ▸ !mul_div_cancel_left H /- mod -/ theorem of_nat_mod (m n : nat) : m mod n = (#nat m mod n) := have H : m = (#nat m mod n) + m div n * n, from calc m = of_nat (#nat m div n * n + m mod n) : nat.eq_div_mul_add_mod ... = (#nat m div n) * n + (#nat m mod n) : rfl ... = m div n * n + (#nat m mod n) : of_nat_div ... = (#nat m mod n) + m div n * n : add.comm, calc m mod n = m - m div n * n : rfl ... = (#nat m mod n) : sub_eq_of_eq_add H theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : b > 0) : -[1+m] mod b = b - 1 - m mod b := calc -[1+m] mod b = -(m + 1) - -[1+m] div b * b : rfl ... = -(m + 1) - -(m div b + 1) * b : neg_succ_of_nat_div _ bpos ... = -m + -1 + (b + m div b * b) : by rewrite [neg_add, -neg_mul_eq_neg_mul, sub_neg_eq_add, mul.right_distrib, one_mul, (add.comm b)] ... = b + -1 + (-m + m div b * b) : by rewrite [-*add.assoc, add.comm (-m), add.right_comm (-1), (add.comm b)] ... = b - 1 - m mod b : by rewrite [↑modulo, *sub_eq_add_neg, neg_add, neg_neg] theorem mod_neg (a b : ℤ) : a mod -b = a mod b := calc a mod -b = a - (a div -b) * -b : rfl ... = a - -(a div b) * -b : div_neg ... = a - a div b * b : neg_mul_neg ... = a mod b : rfl theorem mod_abs (a b : ℤ) : a mod (abs b) = a mod b := abs.by_cases rfl !mod_neg theorem zero_mod (b : ℤ) : 0 mod b = 0 := by rewrite [↑modulo, zero_div, zero_mul, sub_zero] theorem mod_zero (a : ℤ) : a mod 0 = a := by rewrite [↑modulo, mul_zero, sub_zero] theorem mod_one (a : ℤ) : a mod 1 = 0 := calc a mod 1 = a - a div 1 * 1 : rfl ... = 0 : by rewrite [mul_one, div_one, sub_self] private lemma of_nat_mod_abs (m : ℕ) (b : ℤ) : m mod (abs b) = (#nat m mod (nat_abs b)) := calc m mod (abs b) = m mod (nat_abs b) : of_nat_nat_abs ... = (#nat m mod (nat_abs b)) : of_nat_mod private lemma of_nat_mod_abs_lt (m : ℕ) {b : ℤ} (H : b ≠ 0) : m mod (abs b) < (abs b) := have H1 : abs b > 0, from abs_pos_of_ne_zero H, have H2 : (#nat nat_abs b > 0), from lt_of_of_nat_lt_of_nat (!of_nat_nat_abs⁻¹ ▸ H1), calc m mod (abs b) = (#nat m mod (nat_abs b)) : of_nat_mod_abs m b ... < nat_abs b : of_nat_lt_of_nat_of_lt (!nat.mod_lt H2) ... = abs b : of_nat_nat_abs _ theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a mod b = a := obtain m (Hm : a = of_nat m), from exists_eq_of_nat H1, obtain n (Hn : b = of_nat n), from exists_eq_of_nat (le_of_lt (lt_of_le_of_lt H1 H2)), begin revert H2, rewrite [Hm, Hn, of_nat_mod, of_nat_lt_of_nat, of_nat_eq_of_nat], apply nat.mod_eq_of_lt end theorem mod_nonneg (a : ℤ) {b : ℤ} (H : b ≠ 0) : a mod b ≥ 0 := have H1 : abs b > 0, from abs_pos_of_ne_zero H, have H2 : a mod (abs b) ≥ 0, from int.cases_on a (take m, (of_nat_mod_abs m b)⁻¹ ▸ of_nat_nonneg (nat.modulo m (nat_abs b))) (take m, have H3 : 1 + m mod (abs b) ≤ (abs b), from (!add.comm ▸ add_one_le_of_lt (of_nat_mod_abs_lt m H)), calc -[1+m] mod (abs b) = abs b - 1 - m mod (abs b) : neg_succ_of_nat_mod _ H1 ... = abs b - (1 + m mod (abs b)) : by rewrite [*sub_eq_add_neg, neg_add, add.assoc] ... ≥ 0 : iff.mpr !sub_nonneg_iff_le H3), !mod_abs ▸ H2 theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a mod b < (abs b) := have H1 : abs b > 0, from abs_pos_of_ne_zero H, have H2 : a mod (abs b) < abs b, from int.cases_on a (take m, of_nat_mod_abs_lt m H) (take m, have H3 : abs b ≠ 0, from assume H', H (eq_zero_of_abs_eq_zero H'), have H4 : 1 + m mod (abs b) > 0, from add_pos_of_pos_of_nonneg dec_trivial (mod_nonneg _ H3), calc -[1+m] mod (abs b) = abs b - 1 - m mod (abs b) : neg_succ_of_nat_mod _ H1 ... = abs b - (1 + m mod (abs b)) : by rewrite [*sub_eq_add_neg, neg_add, add.assoc] ... < abs b : sub_lt_self _ H4), !mod_abs ▸ H2 theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) mod c = a mod c := decidable.by_cases (assume cz : c = 0, by rewrite [cz, mul_zero, add_zero]) (assume cnz, by rewrite [↑modulo, !add_mul_div_self cnz, mul.right_distrib, sub_add_eq_sub_sub_swap, add_sub_cancel]) theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) mod b = a mod b := !mul.comm ▸ !add_mul_mod_self theorem add_mod_self {a b : ℤ} : (a + b) mod b = a mod b := by rewrite -(int.mul_one b) at {1}; apply add_mul_mod_self_left theorem add_mod_self_left {a b : ℤ} : (a + b) mod a = b mod a := !add.comm ▸ !add_mod_self theorem mod_add_mod (m n k : ℤ) : (m mod n + k) mod n = (m + k) mod n := by rewrite [eq_div_mul_add_mod m n at {2}, add.assoc, add.comm (m div n * n), add_mul_mod_self] theorem add_mod_mod (m n k : ℤ) : (m + n mod k) mod k = (m + n) mod k := by rewrite [add.comm, mod_add_mod, add.comm] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m mod n = k mod n) : (m + i) mod n = (k + i) mod n := by rewrite [-mod_add_mod, -mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m mod n = k mod n) : (i + m) mod n = (i + k) mod n := by rewrite [add.comm, add_mod_eq_add_mod_right _ H, add.comm] theorem mod_eq_mod_of_add_mod_eq_add_mod_right {m n k i : ℤ} (H : (m + i) mod n = (k + i) mod n) : m mod n = k mod n := assert H1 : (m + i + (-i)) mod n = (k + i + (-i)) mod n, from add_mod_eq_add_mod_right _ H, by rewrite [*add_neg_cancel_right at H1]; apply H1 theorem mod_eq_mod_of_add_mod_eq_add_mod_left {m n k i : ℤ} : (i + m) mod n = (i + k) mod n → m mod n = k mod n := by rewrite [add.comm i m, add.comm i k]; apply mod_eq_mod_of_add_mod_eq_add_mod_right theorem mul_mod_left (a b : ℤ) : (a * b) mod b = 0 := by rewrite [-zero_add (a * b), add_mul_mod_self, zero_mod] theorem mul_mod_right (a b : ℤ) : (a * b) mod a = 0 := !mul.comm ▸ !mul_mod_left theorem mod_self {a : ℤ} : a mod a = 0 := decidable.by_cases (assume H : a = 0, H⁻¹ ▸ !mod_zero) (assume H : a ≠ 0, calc a mod a = a - a div a * a : rfl ... = 0 : by rewrite [!div_self H, one_mul, sub_self]) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : a mod b < b := !abs_of_pos H ▸ !mod_lt (ne.symm (ne_of_lt H)) /- properties of div and mod -/ theorem mul_div_mul_of_pos_aux {a : ℤ} (b : ℤ) {c : ℤ} (H1 : a > 0) (H2 : c > 0) : a * b div (a * c) = b div c := have H3 : a * c ≠ 0, from ne.symm (ne_of_lt (mul_pos H1 H2)), have H4 : a * (b mod c) < a * c, from mul_lt_mul_of_pos_left (!mod_lt_of_pos H2) H1, have H5 : a * (b mod c) ≥ 0, from mul_nonneg (le_of_lt H1) (!mod_nonneg (ne.symm (ne_of_lt H2))), calc a * b div (a * c) = a * (b div c * c + b mod c) div (a * c) : eq_div_mul_add_mod ... = (a * (b mod c) + a * c * (b div c)) div (a * c) : by rewrite [!add.comm, mul.left_distrib, mul.comm _ c, -!mul.assoc] ... = a * (b mod c) div (a * c) + b div c : !add_mul_div_self_left H3 ... = 0 + b div c : {!div_eq_zero_of_lt H5 H4} ... = b div c : zero_add theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b div (a * c) = b div c := lt.by_cases (assume H1 : c < 0, have H2 : -c > 0, from neg_pos_of_neg H1, calc a * b div (a * c) = - (a * b div (a * -c)) : by rewrite [!neg_mul_eq_mul_neg⁻¹, div_neg, neg_neg] ... = - (b div -c) : mul_div_mul_of_pos_aux _ H H2 ... = b div c : by rewrite [div_neg, neg_neg]) (assume H1 : c = 0, calc a * b div (a * c) = 0 : by rewrite [H1, mul_zero, div_zero] ... = b div c : by rewrite [H1, div_zero]) (assume H1 : c > 0, mul_div_mul_of_pos_aux _ H H1) theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b > 0) : a * b div (c * b) = a div c := !mul.comm ▸ !mul.comm ▸ !mul_div_mul_of_pos H theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b mod (a * c) = a * (b mod c) := by rewrite [↑modulo, !mul_div_mul_of_pos H, mul_sub_left_distrib, mul.left_comm] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : b > 0) : a < (a div b + 1) * b := have H : a - a div b * b < b, from !mod_lt_of_pos H, calc a < a div b * b + b : iff.mpr !lt_add_iff_sub_lt_left H ... = (a div b + 1) * b : by rewrite [mul.right_distrib, one_mul] theorem div_le_of_nonneg_of_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a div b ≤ a := obtain (m : ℕ) (Hm : a = m), from exists_eq_of_nat Ha, obtain (n : ℕ) (Hn : b = n), from exists_eq_of_nat Hb, calc a div b = #nat m div n : by rewrite [Hm, Hn, of_nat_div] ... ≤ m : of_nat_le_of_nat_of_le !nat.div_le_self ... = a : Hm theorem abs_div_le_abs (a b : ℤ) : abs (a div b) ≤ abs a := have H : ∀a b, b > 0 → abs (a div b) ≤ abs a, from take a b, assume H1 : b > 0, or.elim (le_or_gt 0 a) (assume H2 : 0 ≤ a, have H3 : 0 ≤ b, from le_of_lt H1, calc abs (a div b) = a div b : abs_of_nonneg (div_nonneg H2 H3) ... ≤ a : div_le_of_nonneg_of_nonneg H2 H3 ... = abs a : abs_of_nonneg H2) (assume H2 : a < 0, have H3 : -a - 1 ≥ 0, from le_sub_one_of_lt (neg_pos_of_neg H2), have H4 : (-a - 1) div b + 1 ≥ 0, from add_nonneg (div_nonneg H3 (le_of_lt H1)) (of_nat_le_of_nat_of_le !nat.zero_le), have H5 : (-a - 1) div b ≤ -a - 1, from div_le_of_nonneg_of_nonneg H3 (le_of_lt H1), calc abs (a div b) = abs ((-a - 1) div b + 1) : by rewrite [div_of_neg_of_pos H2 H1, abs_neg] ... = (-a - 1) div b + 1 : abs_of_nonneg H4 ... ≤ -a - 1 + 1 : add_le_add_right H5 _ ... = abs a : by rewrite [sub_add_cancel, abs_of_neg H2]), lt.by_cases (assume H1 : b < 0, calc abs (a div b) = abs (a div -b) : by rewrite [div_neg, abs_neg] ... ≤ abs a : H _ _ (neg_pos_of_neg H1)) (assume H1 : b = 0, calc abs (a div b) = 0 : by rewrite [H1, div_zero, abs_zero] ... ≤ abs a : abs_nonneg) (assume H1 : b > 0, H _ _ H1) theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a mod b = 0) : a div b * b = a := by rewrite [eq_div_mul_add_mod a b at {2}, H, add_zero] theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a mod b = 0) : b * (a div b) = a := !mul.comm ▸ div_mul_cancel_of_mod_eq_zero H /- dvd -/ theorem dvd_of_of_nat_dvd_of_nat {m n : ℕ} : of_nat m ∣ of_nat n → (#nat m ∣ n) := nat.by_cases_zero_pos n (assume H, nat.dvd_zero m) (take n', assume H1 : (#nat n' > 0), have H2 : of_nat n' > 0, from of_nat_pos H1, assume H3 : of_nat m ∣ of_nat n', dvd.elim H3 (take c, assume H4 : of_nat n' = of_nat m * c, have H5 : c > 0, from pos_of_mul_pos_left (H4 ▸ H2) !of_nat_nonneg, obtain k (H6 : c = of_nat k), from exists_eq_of_nat (le_of_lt H5), have H7 : n' = (#nat m * k), from (!iff.mp !of_nat_eq_of_nat (H6 ▸ H4)), nat.dvd.intro H7⁻¹)) theorem of_nat_dvd_of_nat_of_dvd {m n : ℕ} (H : #nat m ∣ n) : of_nat m ∣ of_nat n := nat.dvd.elim H (take k, assume H1 : #nat n = m * k, dvd.intro (!iff.mpr !of_nat_eq_of_nat H1⁻¹)) theorem of_nat_dvd_of_nat (m n : ℕ) : of_nat m ∣ of_nat n ↔ (#nat m ∣ n) := iff.intro dvd_of_of_nat_dvd_of_nat of_nat_dvd_of_nat_of_dvd theorem dvd.antisymm {a b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a ∣ b → b ∣ a → a = b := begin rewrite [-abs_of_nonneg H1, -abs_of_nonneg H2, -*of_nat_nat_abs], rewrite [*of_nat_dvd_of_nat, *of_nat_eq_of_nat], apply nat.dvd.antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b mod a = 0) : a ∣ b := dvd.intro (!mul.comm ▸ div_mul_cancel_of_mod_eq_zero H) theorem mod_eq_zero_of_dvd {a b : ℤ} (H : a ∣ b) : b mod a = 0 := dvd.elim H (take z, assume H1 : b = a * z, H1⁻¹ ▸ !mul_mod_right) theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b mod a = 0 := iff.intro mod_eq_zero_of_dvd dvd_of_mod_eq_zero definition dvd.decidable_rel [instance] : decidable_rel dvd := take a n, decidable_of_decidable_of_iff _ (iff.symm !dvd_iff_mod_eq_zero) theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a div b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b div a) = b := !mul.comm ▸ !div_mul_cancel H theorem mul_div_assoc (a : ℤ) {b c : ℤ} (H : c ∣ b) : (a * b) div c = a * (b div c) := decidable.by_cases (assume cz : c = 0, by rewrite [cz, *div_zero, mul_zero]) (assume cnz : c ≠ 0, obtain d (H' : b = d * c), from exists_eq_mul_left_of_dvd H, by rewrite [H', -mul.assoc, *(!mul_div_cancel cnz)]) theorem div_dvd_div {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c) : b div a ∣ c div a := have H3 : b = b div a * a, from (div_mul_cancel H1)⁻¹, have H4 : c = c div a * a, from (div_mul_cancel (dvd.trans H1 H2))⁻¹, decidable.by_cases (assume H5 : a = 0, have H6: c div a = 0, from (congr_arg _ H5 ⬝ !div_zero), H6⁻¹ ▸ !dvd_zero) (assume H5 : a ≠ 0, dvd_of_mul_dvd_mul_right H5 (H3 ▸ H4 ▸ H2)) theorem div_eq_iff_eq_mul_right {a b : ℤ} (c : ℤ) (H : b ≠ 0) (H' : b ∣ a) : a div b = c ↔ a = b * c := iff.intro (assume H1, by rewrite [-H1, mul_div_cancel' H']) (assume H1, by rewrite [H1, !mul_div_cancel_left H]) theorem div_eq_iff_eq_mul_left {a b : ℤ} (c : ℤ) (H : b ≠ 0) (H' : b ∣ a) : a div b = c ↔ a = c * b := !mul.comm ▸ !div_eq_iff_eq_mul_right H H' theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a div b = c) : a = b * c := calc a = b * (a div b) : mul_div_cancel' H1 ... = b * c : H2 theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a div b = c := calc a div b = b * c div b : H2 ... = c : !mul_div_cancel_left H1 theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a div b = c) : a = c * b := !mul.comm ▸ !eq_mul_of_div_eq_right H1 H2 theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a div b = c := div_eq_of_eq_mul_right H1 (!mul.comm ▸ H2) theorem neg_div_of_dvd {a b : ℤ} (H : b ∣ a) : -a div b = -(a div b) := decidable.by_cases (assume H1 : b = 0, by rewrite [H1, *div_zero, neg_zero]) (assume H1 : b ≠ 0, dvd.elim H (take c, assume H' : a = b * c, by rewrite [H', neg_mul_eq_mul_neg, *!mul_div_cancel_left H1])) theorem sign_eq_div_abs (a : ℤ) : sign a = a div (abs a) := decidable.by_cases (suppose a = 0, by subst a) (suppose a ≠ 0, have abs a ≠ 0, from assume H, this (eq_zero_of_abs_eq_zero H), have abs a ∣ a, from abs_dvd_of_dvd !dvd.refl, eq.symm (iff.mpr (!div_eq_iff_eq_mul_left `abs a ≠ 0` this) !eq_sign_mul_abs)) theorem le_of_dvd {a b : ℤ} (bpos : b > 0) (H : a ∣ b) : a ≤ b := or.elim !le_or_gt (suppose a ≤ 0, le.trans this (le_of_lt bpos)) (suppose a > 0, obtain c (Hc : b = a * c), from exists_eq_mul_right_of_dvd H, have a * c > 0, by rewrite -Hc; exact bpos, have c > 0, from int.pos_of_mul_pos_left this (le_of_lt `a > 0`), show a ≤ b, from calc a = a * 1 : mul_one ... ≤ a * c : mul_le_mul_of_nonneg_left (add_one_le_of_lt `c > 0`) (le_of_lt `a > 0`) ... = b : Hc) /- div and ordering -/ theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a div b * b ≤ a := calc a = a div b * b + a mod b : eq_div_mul_add_mod ... ≥ a div b * b : le_add_of_nonneg_right (!mod_nonneg H) theorem div_le_of_le_mul {a b c : ℤ} (H : c > 0) (H' : a ≤ b * c) : a div c ≤ b := le_of_mul_le_mul_right (calc a div c * c = a div c * c + 0 : add_zero ... ≤ a div c * c + a mod c : add_le_add_left (!mod_nonneg (ne_of_gt H)) ... = a : eq_div_mul_add_mod ... ≤ b * c : H') H theorem div_le_self (a : ℤ) {b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a div b ≤ a := or.elim (lt_or_eq_of_le H2) (assume H3 : b > 0, have H4 : b ≥ 1, from add_one_le_of_lt H3, have H5 : a ≤ a * b, from calc a = a * 1 : mul_one ... ≤ a * b : !mul_le_mul_of_nonneg_left H4 H1, div_le_of_le_mul H3 H5) (assume H3 : 0 = b, by rewrite [-H3, div_zero]; apply H1) theorem mul_le_of_le_div {a b c : ℤ} (H1 : c > 0) (H2 : a ≤ b div c) : a * c ≤ b := calc a * c ≤ b div c * c : !mul_le_mul_of_nonneg_right H2 (le_of_lt H1) ... ≤ b : !div_mul_le (ne_of_gt H1) theorem le_div_of_mul_le {a b c : ℤ} (H1 : c > 0) (H2 : a * c ≤ b) : a ≤ b div c := have H3 : a * c < (b div c + 1) * c, from calc a * c ≤ b : H2 ... = b div c * c + b mod c : eq_div_mul_add_mod ... < b div c * c + c : add_lt_add_left (!mod_lt_of_pos H1) ... = (b div c + 1) * c : by rewrite [mul.right_distrib, one_mul], le_of_lt_add_one (lt_of_mul_lt_mul_right H3 (le_of_lt H1)) theorem le_div_iff_mul_le {a b c : ℤ} (H : c > 0) : a ≤ b div c ↔ a * c ≤ b := iff.intro (!mul_le_of_le_div H) (!le_div_of_mul_le H) theorem div_le_div {a b c : ℤ} (H : c > 0) (H' : a ≤ b) : a div c ≤ b div c := le_div_of_mul_le H (le.trans (!div_mul_le (ne_of_gt H)) H') theorem div_lt_of_lt_mul {a b c : ℤ} (H : c > 0) (H' : a < b * c) : a div c < b := lt_of_mul_lt_mul_right (calc a div c * c = a div c * c + 0 : add_zero ... ≤ a div c * c + a mod c : add_le_add_left (!mod_nonneg (ne_of_gt H)) ... = a : eq_div_mul_add_mod ... < b * c : H') (le_of_lt H) theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : c > 0) (H2 : a div c < b) : a < b * c := assert H3 : (a div c + 1) * c ≤ b * c, from !mul_le_mul_of_nonneg_right (add_one_le_of_lt H2) (le_of_lt H1), have H4 : a div c * c + c ≤ b * c, by rewrite [mul.right_distrib at H3, one_mul at H3]; apply H3, calc a = a div c * c + a mod c : eq_div_mul_add_mod ... < a div c * c + c : add_lt_add_left (!mod_lt_of_pos H1) ... ≤ b * c : H4 theorem div_lt_iff_lt_mul {a b c : ℤ} (H : c > 0) : a div c < b ↔ a < b * c := iff.intro (!lt_mul_of_div_lt H) (!div_lt_of_lt_mul H) theorem div_le_iff_le_mul_of_div {a b : ℤ} (c : ℤ) (H : b > 0) (H' : b ∣ a) : a div b ≤ c ↔ a ≤ c * b := by rewrite [propext (!le_iff_mul_le_mul_right H), !div_mul_cancel H'] theorem le_mul_of_div_le_of_div {a b c : ℤ} (H1 : b > 0) (H2 : b ∣ a) (H3 : a div b ≤ c) : a ≤ c * b := iff.mp (!div_le_iff_le_mul_of_div H1 H2) H3 theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : a > 0) (H2 : b ≥ 0) (H3 : b ∣ a) : a div b > 0 := have H4 : b ≠ 0, from (assume H5 : b = 0, have H6 : a = 0, from eq_zero_of_zero_dvd (H5 ▸ H3), ne_of_gt H1 H6), have H6 : (a div b) * b > 0, by rewrite (div_mul_cancel H3); apply H1, pos_of_mul_pos_right H6 H2 theorem div_eq_div_of_dvd_of_dvd {a b c d : ℤ} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a div b = c div d := begin apply div_eq_of_eq_mul_right H3, rewrite [-!mul_div_assoc H2], apply eq.symm, apply div_eq_of_eq_mul_left H4, apply eq.symm H5 end end int
acce306fba7607cb96fc4ba52e954a84bc7ef55a
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/field_theory/intermediate_field.lean
7d10b0776ea471b9c4c96d8ac7f77d164c58b69a
[ "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
14,493
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import field_theory.subfield import field_theory.tower import ring_theory.algebraic /-! # Intermediate fields Let `L / K` be a field extension, given as an instance `algebra K L`. This file defines the type of fields in between `K` and `L`, `intermediate_field K L`. An `intermediate_field K L` is a subfield of `L` which contains (the image of) `K`, i.e. it is a `subfield L` and a `subalgebra K L`. ## Main definitions * `intermediate_field K L` : the type of intermediate fields between `K` and `L`. * `subalgebra.to_intermediate_field`: turns a subalgebra closed under `⁻¹` into an intermediate field * `subfield.to_intermediate_field`: turns a subfield containing the image of `K` into an intermediate field * `intermediate_field.map`: map an intermediate field along an `alg_hom` ## Implementation notes Intermediate fields are defined with a structure extending `subfield` and `subalgebra`. A `subalgebra` is closed under all operations except `⁻¹`, ## Tags intermediate field, field extension -/ open finite_dimensional open_locale big_operators variables (K L : Type*) [field K] [field L] [algebra K L] /-- `S : intermediate_field K L` is a subset of `L` such that there is a field tower `L / S / K`. -/ structure intermediate_field extends subalgebra K L := (neg_mem' : ∀ x ∈ carrier, -x ∈ carrier) (inv_mem' : ∀ x ∈ carrier, x⁻¹ ∈ carrier) /-- Reinterpret an `intermediate_field` as a `subalgebra`. -/ add_decl_doc intermediate_field.to_subalgebra variables {K L} (S : intermediate_field K L) namespace intermediate_field /-- Reinterpret an `intermediate_field` as a `subfield`. -/ def to_subfield : subfield L := { ..S.to_subalgebra, ..S } instance : set_like (intermediate_field K L) L := ⟨λ S, S.to_subalgebra.carrier, by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨h⟩, congr, }⟩ @[simp] lemma mem_carrier {s : intermediate_field K L} {x : L} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- Two intermediate fields are equal if they have the same elements. -/ @[ext] theorem ext {S T : intermediate_field K L} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h @[simp] lemma coe_to_subalgebra : (S.to_subalgebra : set L) = S := rfl @[simp] lemma coe_to_subfield : (S.to_subfield : set L) = S := rfl @[simp] lemma mem_mk (s : set L) (hK : ∀ x, algebra_map K L x ∈ s) (ho hm hz ha hn hi) (x : L) : x ∈ intermediate_field.mk (subalgebra.mk s ho hm hz ha hK) hn hi ↔ x ∈ s := iff.rfl @[simp] lemma mem_to_subalgebra (s : intermediate_field K L) (x : L) : x ∈ s.to_subalgebra ↔ x ∈ s := iff.rfl @[simp] lemma mem_to_subfield (s : intermediate_field K L) (x : L) : x ∈ s.to_subfield ↔ x ∈ s := iff.rfl /-- An intermediate field contains the image of the smaller field. -/ theorem algebra_map_mem (x : K) : algebra_map K L x ∈ S := S.algebra_map_mem' x /-- An intermediate field contains the ring's 1. -/ theorem one_mem : (1 : L) ∈ S := S.one_mem' /-- An intermediate field contains the ring's 0. -/ theorem zero_mem : (0 : L) ∈ S := S.zero_mem' /-- An intermediate field is closed under multiplication. -/ theorem mul_mem : ∀ {x y : L}, x ∈ S → y ∈ S → x * y ∈ S := S.mul_mem' /-- An intermediate field is closed under scalar multiplication. -/ theorem smul_mem {y : L} : y ∈ S → ∀ {x : K}, x • y ∈ S := S.to_subalgebra.smul_mem /-- An intermediate field is closed under addition. -/ theorem add_mem : ∀ {x y : L}, x ∈ S → y ∈ S → x + y ∈ S := S.add_mem' /-- An intermediate field is closed under subtraction -/ theorem sub_mem {x y : L} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S := S.to_subfield.sub_mem hx hy /-- An intermediate field is closed under negation. -/ theorem neg_mem : ∀ {x : L}, x ∈ S → -x ∈ S := S.neg_mem' /-- An intermediate field is closed under inverses. -/ theorem inv_mem : ∀ {x : L}, x ∈ S → x⁻¹ ∈ S := S.inv_mem' /-- An intermediate field is closed under division. -/ theorem div_mem {x y : L} (hx : x ∈ S) (hy : y ∈ S) : x / y ∈ S := S.to_subfield.div_mem hx hy /-- Product of a list of elements in an intermediate_field is in the intermediate_field. -/ lemma list_prod_mem {l : list L} : (∀ x ∈ l, x ∈ S) → l.prod ∈ S := S.to_subfield.list_prod_mem /-- Sum of a list of elements in an intermediate field is in the intermediate_field. -/ lemma list_sum_mem {l : list L} : (∀ x ∈ l, x ∈ S) → l.sum ∈ S := S.to_subfield.list_sum_mem /-- Product of a multiset of elements in an intermediate field is in the intermediate_field. -/ lemma multiset_prod_mem (m : multiset L) : (∀ a ∈ m, a ∈ S) → m.prod ∈ S := S.to_subfield.multiset_prod_mem m /-- Sum of a multiset of elements in a `intermediate_field` is in the `intermediate_field`. -/ lemma multiset_sum_mem (m : multiset L) : (∀ a ∈ m, a ∈ S) → m.sum ∈ S := S.to_subfield.multiset_sum_mem m /-- Product of elements of an intermediate field indexed by a `finset` is in the intermediate_field. -/ lemma prod_mem {ι : Type*} {t : finset ι} {f : ι → L} (h : ∀ c ∈ t, f c ∈ S) : ∏ i in t, f i ∈ S := S.to_subfield.prod_mem h /-- Sum of elements in a `intermediate_field` indexed by a `finset` is in the `intermediate_field`. -/ lemma sum_mem {ι : Type*} {t : finset ι} {f : ι → L} (h : ∀ c ∈ t, f c ∈ S) : ∑ i in t, f i ∈ S := S.to_subfield.sum_mem h lemma pow_mem {x : L} (hx : x ∈ S) : ∀ (n : ℤ), x^n ∈ S | (n : ℕ) := by { rw gpow_coe_nat, exact S.to_subfield.pow_mem hx _, } | -[1+ n] := by { rw [gpow_neg_succ_of_nat], exact S.to_subfield.inv_mem (S.to_subfield.pow_mem hx _) } lemma gsmul_mem {x : L} (hx : x ∈ S) (n : ℤ) : n • x ∈ S := S.to_subfield.gsmul_mem hx n lemma coe_int_mem (n : ℤ) : (n : L) ∈ S := by simp only [← gsmul_one, gsmul_mem, one_mem] end intermediate_field /-- Turn a subalgebra closed under inverses into an intermediate field -/ def subalgebra.to_intermediate_field (S : subalgebra K L) (inv_mem : ∀ x ∈ S, x⁻¹ ∈ S) : intermediate_field K L := { neg_mem' := λ x, S.neg_mem, inv_mem' := inv_mem, .. S } @[simp] lemma to_subalgebra_to_intermediate_field (S : subalgebra K L) (inv_mem : ∀ x ∈ S, x⁻¹ ∈ S) : (S.to_intermediate_field inv_mem).to_subalgebra = S := by { ext, refl } @[simp] lemma to_intermediate_field_to_subalgebra (S : intermediate_field K L) (inv_mem : ∀ x ∈ S.to_subalgebra, x⁻¹ ∈ S) : S.to_subalgebra.to_intermediate_field inv_mem = S := by { ext, refl } /-- Turn a subfield of `L` containing the image of `K` into an intermediate field -/ def subfield.to_intermediate_field (S : subfield L) (algebra_map_mem : ∀ x, algebra_map K L x ∈ S) : intermediate_field K L := { algebra_map_mem' := algebra_map_mem, .. S } namespace intermediate_field /-- An intermediate field inherits a field structure -/ instance to_field : field S := S.to_subfield.to_field @[simp, norm_cast] lemma coe_add (x y : S) : (↑(x + y) : L) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_neg (x : S) : (↑(-x) : L) = -↑x := rfl @[simp, norm_cast] lemma coe_mul (x y : S) : (↑(x * y) : L) = ↑x * ↑y := rfl @[simp, norm_cast] lemma coe_inv (x : S) : (↑(x⁻¹) : L) = (↑x)⁻¹ := rfl @[simp, norm_cast] lemma coe_zero : ((0 : S) : L) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : S) : L) = 1 := rfl @[simp, norm_cast] lemma coe_pow (x : S) (n : ℕ) : (↑(x ^ n) : L) = ↑x ^ n := begin induction n with n ih, { simp }, { simp [pow_succ, ih] } end instance algebra : algebra K S := S.to_subalgebra.algebra instance to_algebra {R : Type*} [semiring R] [algebra L R] : algebra S R := S.to_subalgebra.to_algebra instance is_scalar_tower_bot {R : Type*} [semiring R] [algebra L R] : is_scalar_tower S L R := is_scalar_tower.subalgebra _ _ _ S.to_subalgebra instance is_scalar_tower_mid {R : Type*} [semiring R] [algebra L R] [algebra K R] [is_scalar_tower K L R] : is_scalar_tower K S R := is_scalar_tower.subalgebra' _ _ _ S.to_subalgebra /-- Specialize `is_scalar_tower_mid` to the common case where the top field is `L` -/ instance is_scalar_tower_mid' : is_scalar_tower K S L := S.is_scalar_tower_mid variables {L' : Type*} [field L'] [algebra K L'] /-- If `f : L →+* L'` fixes `K`, `S.map f` is the intermediate field between `L'` and `K` such that `x ∈ S ↔ f x ∈ S.map f`. -/ def map (f : L →ₐ[K] L') : intermediate_field K L' := { inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, S.inv_mem hx, f.map_inv x⟩ }, neg_mem' := λ x hx, (S.to_subalgebra.map f).neg_mem hx, .. S.to_subalgebra.map f} /-- The embedding from an intermediate field of `L / K` to `L`. -/ def val : S →ₐ[K] L := S.to_subalgebra.val @[simp] theorem coe_val : ⇑S.val = coe := rfl @[simp] lemma val_mk {x : L} (hx : x ∈ S) : S.val ⟨x, hx⟩ = x := rfl variables {S} lemma to_subalgebra_injective {S S' : intermediate_field K L} (h : S.to_subalgebra = S'.to_subalgebra) : S = S' := by { ext, rw [← mem_to_subalgebra, ← mem_to_subalgebra, h] } variables (S) lemma set_range_subset : set.range (algebra_map K L) ⊆ S := S.to_subalgebra.range_subset lemma field_range_le : (algebra_map K L).field_range ≤ S.to_subfield := λ x hx, S.to_subalgebra.range_subset (by rwa [set.mem_range, ← ring_hom.mem_field_range]) @[simp] lemma to_subalgebra_le_to_subalgebra {S S' : intermediate_field K L} : S.to_subalgebra ≤ S'.to_subalgebra ↔ S ≤ S' := iff.rfl @[simp] lemma to_subalgebra_lt_to_subalgebra {S S' : intermediate_field K L} : S.to_subalgebra < S'.to_subalgebra ↔ S < S' := iff.rfl variables {S} section tower /-- Lift an intermediate_field of an intermediate_field -/ def lift1 {F : intermediate_field K L} (E : intermediate_field K F) : intermediate_field K L := map E (val F) /-- Lift an intermediate_field of an intermediate_field -/ def lift2 {F : intermediate_field K L} (E : intermediate_field F L) : intermediate_field K L := { carrier := E.carrier, zero_mem' := zero_mem E, add_mem' := λ x y, add_mem E, neg_mem' := λ x, neg_mem E, one_mem' := one_mem E, mul_mem' := λ x y, mul_mem E, inv_mem' := λ x, inv_mem E, algebra_map_mem' := λ x, algebra_map_mem E (algebra_map K F x) } instance has_lift1 {F : intermediate_field K L} : has_lift_t (intermediate_field K F) (intermediate_field K L) := ⟨lift1⟩ instance has_lift2 {F : intermediate_field K L} : has_lift_t (intermediate_field F L) (intermediate_field K L) := ⟨lift2⟩ @[simp] lemma mem_lift2 {F : intermediate_field K L} {E : intermediate_field F L} {x : L} : x ∈ (↑E : intermediate_field K L) ↔ x ∈ E := iff.rfl instance lift2_alg {F : intermediate_field K L} {E : intermediate_field F L} : algebra K E := { to_fun := (algebra_map F E).comp (algebra_map K F), map_zero' := ((algebra_map F E).comp (algebra_map K F)).map_zero, map_one' := ((algebra_map F E).comp (algebra_map K F)).map_one, map_add' := ((algebra_map F E).comp (algebra_map K F)).map_add, map_mul' := ((algebra_map F E).comp (algebra_map K F)).map_mul, smul := λ a b, (((algebra_map F E).comp (algebra_map K F)) a) * b, smul_def' := λ _ _, rfl, commutes' := λ a b, mul_comm (((algebra_map F E).comp (algebra_map K F)) a) b } instance lift2_tower {F : intermediate_field K L} {E : intermediate_field F L} : is_scalar_tower K F E := ⟨λ a b c, by { simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl }⟩ /-- `lift2` is isomorphic to the original `intermediate_field`. -/ def lift2_alg_equiv {F : intermediate_field K L} (E : intermediate_field F L) : (↑E : intermediate_field K L) ≃ₐ[K] E := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, map_add' := λ x y, rfl, map_mul' := λ x y, rfl, commutes' := λ x, rfl } end tower section finite_dimensional variables (F E : intermediate_field K L) instance finite_dimensional_left [finite_dimensional K L] : finite_dimensional K F := finite_dimensional.finite_dimensional_submodule F.to_subalgebra.to_submodule instance finite_dimensional_right [finite_dimensional K L] : finite_dimensional F L := right K F L @[simp] lemma dim_eq_dim_subalgebra : module.rank K F.to_subalgebra = module.rank K F := rfl @[simp] lemma finrank_eq_finrank_subalgebra : finrank K F.to_subalgebra = finrank K F := rfl variables {F} {E} @[simp] lemma to_subalgebra_eq_iff : F.to_subalgebra = E.to_subalgebra ↔ F = E := by { rw [set_like.ext_iff, set_like.ext'_iff, set.ext_iff], refl } lemma eq_of_le_of_finrank_le [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank K E ≤ finrank K F) : F = E := to_subalgebra_injective $ subalgebra.to_submodule_injective $ eq_of_le_of_finrank_le h_le h_finrank lemma eq_of_le_of_finrank_eq [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank K F = finrank K E) : F = E := eq_of_le_of_finrank_le h_le h_finrank.ge lemma eq_of_le_of_finrank_le' [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank F L ≤ finrank E L) : F = E := begin apply eq_of_le_of_finrank_le h_le, have h1 := finrank_mul_finrank K F L, have h2 := finrank_mul_finrank K E L, have h3 : 0 < finrank E L := finrank_pos, nlinarith, end lemma eq_of_le_of_finrank_eq' [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank F L = finrank E L) : F = E := eq_of_le_of_finrank_le' h_le h_finrank.le end finite_dimensional end intermediate_field /-- If `L/K` is algebraic, the `K`-subalgebras of `L` are all fields. -/ def subalgebra_equiv_intermediate_field (alg : algebra.is_algebraic K L) : subalgebra K L ≃o intermediate_field K L := { to_fun := λ S, S.to_intermediate_field (λ x hx, S.inv_mem_of_algebraic (alg (⟨x, hx⟩ : S))), inv_fun := λ S, S.to_subalgebra, left_inv := λ S, to_subalgebra_to_intermediate_field _ _, right_inv := λ S, to_intermediate_field_to_subalgebra _ _, map_rel_iff' := λ S S', iff.rfl } @[simp] lemma mem_subalgebra_equiv_intermediate_field (alg : algebra.is_algebraic K L) {S : subalgebra K L} {x : L} : x ∈ subalgebra_equiv_intermediate_field alg S ↔ x ∈ S := iff.rfl @[simp] lemma mem_subalgebra_equiv_intermediate_field_symm (alg : algebra.is_algebraic K L) {S : intermediate_field K L} {x : L} : x ∈ (subalgebra_equiv_intermediate_field alg).symm S ↔ x ∈ S := iff.rfl
be7a5119b9fa6d90f1c3d55ebcd031473e82e106
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/data/complex/is_R_or_C.lean
b8d54b8483c2b3fbbf4aac25de839fcc56188569
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,159
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.normed_space.basic import analysis.complex.basic /-! # `is_R_or_C`: a typeclass for ℝ or ℂ This file defines the typeclass `is_R_or_C` intended to have only two instances: ℝ and ℂ. It is meant for definitions and theorems which hold for both the real and the complex case, and in particular when the real case follows directly from the complex case by setting `re` to `id`, `im` to zero and so on. Its API follows closely that of ℂ. Possible applications include defining inner products and Hilbert spaces for both the real and complex case. One would produce the definitions and proof for an arbitrary field of this typeclass, which basically amounts to doing the complex case, and the two cases then fall out immediately from the two instances of the class. ## Implementation notes The coercion from reals into an `is_R_or_C` field is done by registering `algebra_map ℝ K` as a `has_coe_t`. For this to work, we must proceed carefully to avoid problems involving circular coercions in the case `K=ℝ`; in particular, we cannot use the plain `has_coe` and must set priorities carefully. This problem was already solved for `ℕ`, and we copy the solution detailed in `data/nat/cast`. See also Note [coercion into rings] for more details. In addition, several lemmas need to be set at priority 900 to make sure that they do not override their counterparts in `complex.lean` (which causes linter errors). -/ open_locale big_operators section local notation `𝓚` := algebra_map ℝ _ /-- This typeclass captures properties shared by ℝ and ℂ, with an API that closely matches that of ℂ. -/ class is_R_or_C (K : Type*) extends nondiscrete_normed_field K, normed_algebra ℝ K, complete_space K := (re : K →+ ℝ) (im : K →+ ℝ) (conj : K →+* K) (I : K) -- Meant to be set to 0 for K=ℝ (I_re_ax : re I = 0) (I_mul_I_ax : I = 0 ∨ I * I = -1) (re_add_im_ax : ∀ (z : K), 𝓚 (re z) + 𝓚 (im z) * I = z) (of_real_re_ax : ∀ r : ℝ, re (𝓚 r) = r) (of_real_im_ax : ∀ r : ℝ, im (𝓚 r) = 0) (mul_re_ax : ∀ z w : K, re (z * w) = re z * re w - im z * im w) (mul_im_ax : ∀ z w : K, im (z * w) = re z * im w + im z * re w) (conj_re_ax : ∀ z : K, re (conj z) = re z) (conj_im_ax : ∀ z : K, im (conj z) = -(im z)) (conj_I_ax : conj I = -I) (norm_sq_eq_def_ax : ∀ (z : K), ∥z∥^2 = (re z) * (re z) + (im z) * (im z)) (mul_im_I_ax : ∀ (z : K), (im z) * im I = im z) (inv_def_ax : ∀ (z : K), z⁻¹ = conj z * 𝓚 ((∥z∥^2)⁻¹)) (div_I_ax : ∀ (z : K), z / I = -(z * I)) end namespace is_R_or_C variables {K : Type*} [is_R_or_C K] local postfix `†`:100 := @is_R_or_C.conj K _ /- The priority must be set at 900 to ensure that coercions are tried in the right order. See Note [coercion into rings], or `data/nat/cast.lean` for more details. -/ @[priority 900] noncomputable instance algebra_map_coe : has_coe_t ℝ K := ⟨algebra_map ℝ K⟩ lemma of_real_alg (x : ℝ) : (x : K) = x • (1 : K) := algebra.algebra_map_eq_smul_one x lemma algebra_map_eq_of_real : ⇑(algebra_map ℝ K) = coe := rfl @[simp] lemma re_add_im (z : K) : ((re z) : K) + (im z) * I = z := is_R_or_C.re_add_im_ax z @[simp, norm_cast] lemma of_real_re : ∀ r : ℝ, re (r : K) = r := is_R_or_C.of_real_re_ax @[simp, norm_cast] lemma of_real_im : ∀ r : ℝ, im (r : K) = 0 := is_R_or_C.of_real_im_ax @[simp] lemma mul_re : ∀ z w : K, re (z * w) = re z * re w - im z * im w := is_R_or_C.mul_re_ax @[simp] lemma mul_im : ∀ z w : K, im (z * w) = re z * im w + im z * re w := is_R_or_C.mul_im_ax theorem inv_def (z : K) : z⁻¹ = conj z * ((∥z∥^2)⁻¹:ℝ) := is_R_or_C.inv_def_ax z theorem ext_iff : ∀ {z w : K}, z = w ↔ re z = re w ∧ im z = im w := λ z w, { mp := by { rintro rfl, cc }, mpr := by { rintro ⟨h₁,h₂⟩, rw [←re_add_im z, ←re_add_im w, h₁, h₂] } } theorem ext : ∀ {z w : K}, re z = re w → im z = im w → z = w := by { simp_rw ext_iff, cc } @[simp, norm_cast, priority 900] lemma of_real_zero : ((0 : ℝ) : K) = 0 := by rw [of_real_alg, zero_smul] @[simp] lemma zero_re' : re (0 : K) = (0 : ℝ) := re.map_zero @[simp, norm_cast, priority 900] lemma of_real_one : ((1 : ℝ) : K) = 1 := by rw [of_real_alg, one_smul] @[simp] lemma one_re : re (1 : K) = 1 := by rw [←of_real_one, of_real_re] @[simp] lemma one_im : im (1 : K) = 0 := by rw [←of_real_one, of_real_im] @[simp, norm_cast, priority 900] theorem of_real_inj {z w : ℝ} : (z : K) = (w : K) ↔ z = w := { mp := λ h, by { convert congr_arg re h; simp only [of_real_re] }, mpr := λ h, by rw h } @[simp] lemma bit0_re (z : K) : re (bit0 z) = bit0 (re z) := by simp [bit0] @[simp] lemma bit1_re (z : K) : re (bit1 z) = bit1 (re z) := by simp only [bit1, add_monoid_hom.map_add, bit0_re, add_right_inj, one_re] @[simp] lemma bit0_im (z : K) : im (bit0 z) = bit0 (im z) := by simp [bit0] @[simp] lemma bit1_im (z : K) : im (bit1 z) = bit0 (im z) := by simp only [bit1, add_right_eq_self, add_monoid_hom.map_add, bit0_im, one_im] @[simp, priority 900] theorem of_real_eq_zero {z : ℝ} : (z : K) = 0 ↔ z = 0 := by rw [←of_real_zero]; exact of_real_inj @[simp, norm_cast, priority 900] lemma of_real_add ⦃r s : ℝ⦄ : ((r + s : ℝ) : K) = r + s := by { apply (@is_R_or_C.ext_iff K _ ((r + s : ℝ) : K) (r + s)).mpr, simp } @[simp, norm_cast, priority 900] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : K) = bit0 (r : K) := ext_iff.2 $ by simp [bit0] @[simp, norm_cast, priority 900] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : K) = bit1 (r : K) := ext_iff.2 $ by simp [bit1] /- Note: This can be proven by `norm_num` once K is proven to be of characteristic zero below. -/ lemma two_ne_zero : (2 : K) ≠ 0 := begin intro h, rw [(show (2 : K) = ((2 : ℝ) : K), by norm_num), ←of_real_zero, of_real_inj] at h, linarith, end @[simp, norm_cast, priority 900] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : K) = -r := ext_iff.2 $ by simp @[simp, norm_cast, priority 900] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : K) = r * s := ext_iff.2 $ by simp lemma of_real_mul_re (r : ℝ) (z : K) : re (↑r * z) = r * re z := by simp only [mul_re, of_real_im, zero_mul, of_real_re, sub_zero] lemma smul_re (r : ℝ) (z : K) : re (↑r * z) = r * (re z) := by simp only [of_real_im, zero_mul, of_real_re, sub_zero, mul_re] lemma smul_im (r : ℝ) (z : K) : im (↑r * z) = r * (im z) := by simp only [add_zero, of_real_im, zero_mul, of_real_re, mul_im] lemma smul_re' : ∀ (r : ℝ) (z : K), re (r • z) = r * (re z) := λ r z, by { rw algebra.smul_def, apply smul_re } lemma smul_im' : ∀ (r : ℝ) (z : K), im (r • z) = r * (im z) := λ r z, by { rw algebra.smul_def, apply smul_im } /-- The real part in a `is_R_or_C` field, as a linear map. -/ noncomputable def re_lm : K →ₗ[ℝ] ℝ := { map_smul' := smul_re', .. re } @[simp] lemma re_lm_coe : (re_lm : K → ℝ) = re := rfl /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ @[simp] lemma I_re : re (I : K) = 0 := I_re_ax @[simp] lemma I_im (z : K) : im z * im (I : K) = im z := mul_im_I_ax z @[simp] lemma I_im' (z : K) : im (I : K) * im z = im z := by rw [mul_comm, I_im _] lemma I_mul_re (z : K) : re (I * z) = - im z := by simp only [I_re, zero_sub, I_im', zero_mul, mul_re] lemma I_mul_I : (I : K) = 0 ∨ (I : K) * I = -1 := I_mul_I_ax @[simp] lemma conj_re (z : K) : re (conj z) = re z := is_R_or_C.conj_re_ax z @[simp] lemma conj_im (z : K) : im (conj z) = -(im z) := is_R_or_C.conj_im_ax z @[simp] lemma conj_of_real (r : ℝ) : conj (r : K) = (r : K) := by { rw ext_iff, simp only [of_real_im, conj_im, eq_self_iff_true, conj_re, and_self, neg_zero] } @[simp] lemma conj_bit0 (z : K) : conj (bit0 z) = bit0 (conj z) := by simp [bit0, ext_iff] @[simp] lemma conj_bit1 (z : K) : conj (bit1 z) = bit1 (conj z) := by simp [bit0, ext_iff] @[simp] lemma conj_neg_I : conj (-I) = (I : K) := by simp [ext_iff] @[simp] lemma conj_conj (z : K) : conj (conj z) = z := by simp [ext_iff] lemma conj_involutive : @function.involutive K is_R_or_C.conj := conj_conj lemma conj_bijective : @function.bijective K K is_R_or_C.conj := conj_involutive.bijective lemma conj_inj (z w : K) : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff lemma conj_eq_zero {z : K} : conj z = 0 ↔ z = 0 := ring_hom.map_eq_zero conj lemma eq_conj_iff_real {z : K} : conj z = z ↔ ∃ r : ℝ, z = (r : K) := begin split, { intro h, suffices : im z = 0, { use (re z), rw ← add_zero (coe _), convert (re_add_im z).symm, simp [this] }, contrapose! h, rw ← re_add_im z, simp only [conj_of_real, ring_hom.map_add, ring_hom.map_mul, conj_I_ax], rw [add_left_cancel_iff, ext_iff], simpa [neg_eq_iff_add_eq_zero, add_self_eq_zero] }, { rintros ⟨r, rfl⟩, apply conj_of_real } end variables (K) /-- Conjugation as a ring equivalence. This is used to convert the inner product into a sesquilinear product. -/ def conj_to_ring_equiv : K ≃+* Kᵒᵖ := { to_fun := opposite.op ∘ conj, inv_fun := conj ∘ opposite.unop, left_inv := λ x, by simp only [conj_conj, function.comp_app, opposite.unop_op], right_inv := λ x, by simp only [conj_conj, opposite.op_unop, function.comp_app], map_mul' := λ x y, by simp [mul_comm], map_add' := λ x y, by simp } variables {K} @[simp] lemma ring_equiv_apply {x : K} : (conj_to_ring_equiv K x).unop = x† := rfl lemma eq_conj_iff_re {z : K} : conj z = z ↔ ((re z) : K) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ /-- The norm squared function. -/ def norm_sq : monoid_with_zero_hom K ℝ := { to_fun := λ z, re z * re z + im z * im z, map_zero' := by simp, map_one' := by simp, map_mul' := λ z w, by { simp, ring } } lemma norm_sq_eq_def {z : K} : ∥z∥^2 = (re z) * (re z) + (im z) * (im z) := norm_sq_eq_def_ax z lemma norm_sq_eq_def' (z : K) : norm_sq z = ∥z∥^2 := by { rw norm_sq_eq_def, refl } @[simp] lemma norm_sq_of_real (r : ℝ) : ∥(r : K)∥^2 = r * r := by simp [norm_sq_eq_def] lemma norm_sq_zero : norm_sq (0 : K) = 0 := norm_sq.map_zero lemma norm_sq_one : norm_sq (1 : K) = 1 := norm_sq.map_one lemma norm_sq_nonneg (z : K) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : K} : norm_sq z = 0 ↔ z = 0 := by { rw [norm_sq_eq_def'], simp [pow_two] } @[simp] lemma norm_sq_pos {z : K} : 0 < norm_sq z ↔ z ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : K) : norm_sq (-z) = norm_sq z := by simp [norm_sq_eq_def'] @[simp] lemma norm_sq_conj (z : K) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : K) : norm_sq (z * w) = norm_sq z * norm_sq w := norm_sq.map_mul z w lemma norm_sq_add (z w : K) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (re (z * conj w)) := by simp [norm_sq, pow_two]; ring lemma re_sq_le_norm_sq (z : K) : re z * re z ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : K) : im z * im z ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : K) : z * conj z = ((norm_sq z) : K) := by simp [ext_iff, norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : K) : z + conj z = 2 * (re z) := by simp [ext_iff, two_mul] /-- The pseudo-coercion `of_real` as a `ring_hom`. -/ noncomputable def of_real_hom : ℝ →+* K := algebra_map ℝ K /-- The coercion from reals as a `ring_hom`. -/ noncomputable def coe_hom : ℝ →+* K := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp, norm_cast, priority 900] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : K) = r - s := ext_iff.2 $ by simp @[simp, norm_cast, priority 900] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : K) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : K) : z - conj z = (2 * im z) * I := by simp [ext_iff, two_mul, sub_eq_add_neg, add_mul, mul_im_I_ax] lemma norm_sq_sub (z w : K) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * re (z * conj w) := by simp [-mul_re, norm_sq_add, add_comm, add_left_comm, sub_eq_add_neg] lemma sqrt_norm_sq_eq_norm {z : K} : real.sqrt (norm_sq z) = ∥z∥ := begin have h₂ : ∥z∥ = real.sqrt (∥z∥^2) := (real.sqrt_sqr (norm_nonneg z)).symm, rw [h₂], exact congr_arg real.sqrt (norm_sq_eq_def' z) end /-! ### Inversion -/ @[simp] lemma inv_re (z : K) : re (z⁻¹) = re z / norm_sq z := by simp [inv_def, norm_sq_eq_def, norm_sq, division_def] @[simp] lemma inv_im (z : K) : im (z⁻¹) = im (-z) / norm_sq z := by simp [inv_def, norm_sq_eq_def, norm_sq, division_def] @[simp, norm_cast, priority 900] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : K) = r⁻¹ := begin rw ext_iff, by_cases r = 0, { simp [h] }, { simp; field_simp [h, norm_sq] }, end protected lemma inv_zero : (0⁻¹ : K) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : K} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ←mul_assoc, mul_conj, ←of_real_mul, ←norm_sq_eq_def', mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] lemma div_re (z w : K) : re (z / w) = re z * re w / norm_sq w + im z * im w / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : K) : im (z / w) = im z * re w / norm_sq w - re z * im w / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] @[simp, norm_cast, priority 900] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : K) = r / s := (@is_R_or_C.coe_hom K _).map_div r s lemma div_re_of_real {z : K} {r : ℝ} : re (z / r) = re z / r := begin by_cases h : r = 0, { simp [h, of_real_zero] }, { change r ≠ 0 at h, rw [div_eq_mul_inv, ←of_real_inv, div_eq_mul_inv], simp [norm_sq, div_mul_eq_div_mul_one_div, div_self h] } end @[simp, norm_cast, priority 900] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : K) = r ^ n := (@is_R_or_C.coe_hom K _).map_fpow r n lemma I_mul_I_of_nonzero : (I : K) ≠ 0 → (I : K) * I = -1 := by { have := I_mul_I_ax, tauto } @[simp] lemma div_I (z : K) : z / I = -(z * I) := begin by_cases h : (I : K) = 0, { simp [h] }, { field_simp [mul_assoc, I_mul_I_of_nonzero h] } end @[simp] lemma inv_I : (I : K)⁻¹ = -I := by { by_cases h : (I : K) = 0; field_simp [h] } @[simp] lemma norm_sq_inv (z : K) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := (@norm_sq K _).map_inv' z @[simp] lemma norm_sq_div (z w : K) : norm_sq (z / w) = norm_sq z / norm_sq w := (@norm_sq K _).map_div z w lemma norm_conj {z : K} : ∥conj z∥ = ∥z∥ := by simp only [←sqrt_norm_sq_eq_norm, norm_sq_conj] lemma conj_inv {z : K} : conj (z⁻¹) = (conj z)⁻¹ := by simp only [inv_def, norm_conj, ring_hom.map_mul, conj_of_real] lemma conj_div {z w : K} : conj (z / w) = (conj z) / (conj w) := by rw [div_eq_inv_mul, div_eq_inv_mul, ring_hom.map_mul]; simp only [conj_inv] /-! ### Cast lemmas -/ @[simp, norm_cast, priority 900] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : K) = n := of_real_hom.map_nat_cast n @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : re (n : K) = n := by rw [← of_real_nat_cast, of_real_re] @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : im (n : K) = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, norm_cast, priority 900] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : K) = n := of_real_hom.map_int_cast n @[simp, norm_cast] lemma int_cast_re (n : ℤ) : re (n : K) = n := by rw [← of_real_int_cast, of_real_re] @[simp, norm_cast] lemma int_cast_im (n : ℤ) : im (n : K) = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, norm_cast, priority 900] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : K) = n := (@is_R_or_C.of_real_hom K _).map_rat_cast n @[simp, norm_cast] lemma rat_cast_re (q : ℚ) : re (q : K) = q := by rw [← of_real_rat_cast, of_real_re] @[simp, norm_cast] lemma rat_cast_im (q : ℚ) : im (q : K) = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ -- TODO: I think this can be instance, because it is a `Prop` /-- ℝ and ℂ are both of characteristic zero. Note: This is not registered as an instance to avoid having multiple instances on ℝ and ℂ. -/ lemma char_zero_R_or_C : char_zero K := char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h theorem re_eq_add_conj (z : K) : ↑(re z) = (z + conj z) / 2 := begin haveI : char_zero K := char_zero_R_or_C, rw [add_conj, mul_div_cancel_left ((re z):K) two_ne_zero'], end /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ @[pp_nodot] noncomputable def abs (z : K) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs local notation `absK` := @abs K _ @[simp, norm_cast] lemma abs_of_real (r : ℝ) : absK r = abs' r := by simp [abs, norm_sq, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma norm_eq_abs (z : K) : ∥z∥ = absK z := by simp [abs, norm_sq_eq_def'] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : absK r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : absK n = n := by { rw [← of_real_nat_cast], exact abs_of_nonneg (nat.cast_nonneg n) } lemma mul_self_abs (z : K) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : absK 0 = 0 := by simp [abs] @[simp] lemma abs_one : absK 1 = 1 := by simp [abs] @[simp] lemma abs_two : absK 2 = 2 := calc absK 2 = absK (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : K) : 0 ≤ absK z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : K} : absK z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero lemma abs_ne_zero {z : K} : abs z ≠ 0 ↔ z ≠ 0 := not_congr abs_eq_zero @[simp] lemma abs_conj (z : K) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : K) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : K) : abs' (re z) ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (re z)) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : K) : abs' (im z) ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (im z)) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : K) : re z ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : K) : im z ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma im_eq_zero_of_le {a : K} (h : abs a ≤ re a) : im a = 0 := begin rw ← zero_eq_mul_self, have : re a * re a = re a * re a + im a * im a, { convert is_R_or_C.mul_self_abs a; linarith [re_le_abs a] }, linarith end lemma re_eq_self_of_le {a : K} (h : abs a ≤ re a) : (re a : K) = a := by { rw ← re_add_im a, simp [im_eq_zero_of_le h] } lemma abs_add (z w : K) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value absK := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : K) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : K} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z : K, abs (-z) = abs z := abv_neg abs lemma abs_sub : ∀ z w : K, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c : K, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z : K, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w : K, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w : K, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_re_div_abs_le_one (z : K) : abs' (re z / abs z) ≤ 1 := begin by_cases hz : z = 0, { simp [hz, zero_le_one] }, { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] } end lemma abs_im_div_abs_le_one (z : K) : abs' (im z / abs z) ≤ 1 := begin by_cases hz : z = 0, { simp [hz, zero_le_one] }, { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] } end @[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : K) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : K) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] lemma re_eq_abs_of_mul_conj (x : K) : re (x * (conj x)) = abs (x * (conj x)) := by rw [mul_conj, of_real_re, abs_of_real, norm_sq_eq_abs, pow_two, _root_.abs_mul, abs_abs] lemma abs_sqr_re_add_conj (x : K) : (abs (x + x†))^2 = (re (x + x†))^2 := by simp [pow_two, ←norm_sq_eq_abs, norm_sq] lemma abs_sqr_re_add_conj' (x : K) : (abs (x† + x))^2 = (re (x† + x))^2 := by simp [pow_two, ←norm_sq_eq_abs, norm_sq] lemma conj_mul_eq_norm_sq_left (x : K) : x† * x = ((norm_sq x) : K) := begin rw ext_iff, refine ⟨by simp [of_real_re, mul_re, conj_re, conj_im, norm_sq],_⟩, simp [of_real_im, mul_im, conj_im, conj_re, mul_comm], end /-- The real part in a `is_R_or_C` field, as a continuous linear map. -/ noncomputable def re_clm : K →L[ℝ] ℝ := re_lm.mk_continuous 1 $ by { simp only [norm_eq_abs, re_lm_coe, one_mul], exact abs_re_le_abs } @[simp] lemma norm_re_clm : ∥(re_clm : K →L[ℝ] ℝ)∥ = 1 := begin apply le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _), convert continuous_linear_map.ratio_le_op_norm _ (1 : K), simp, end @[simp, norm_cast] lemma re_clm_coe : ((re_clm : K →L[ℝ] ℝ) : K →ₗ[ℝ] ℝ) = re_lm := rfl @[simp] lemma re_clm_apply : ((re_clm : K →L[ℝ] ℝ) : K → ℝ) = re := rfl /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq K abs) : is_cau_seq abs' (λ n, re (f n)) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq K abs) : is_cau_seq abs' (λ n, im (f n)) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) /-- The real part of a K Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq K abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a K Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq K abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → K} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ @[simp, norm_cast, priority 900] lemma of_real_prod {α : Type*} (s : finset α) (f : α → ℝ) : ((∏ i in s, f i : ℝ) : K) = ∏ i in s, (f i : K) := ring_hom.map_prod _ _ _ @[simp, norm_cast, priority 900] lemma of_real_sum {α : Type*} (s : finset α) (f : α → ℝ) : ((∑ i in s, f i : ℝ) : K) = ∑ i in s, (f i : K) := ring_hom.map_sum _ _ _ @[simp, norm_cast] lemma of_real_finsupp_sum {α M : Type*} [has_zero M] (f : α →₀ M) (g : α → M → ℝ) : ((f.sum (λ a b, g a b) : ℝ) : K) = f.sum (λ a b, ((g a b) : K)) := ring_hom.map_finsupp_sum _ f g @[simp, norm_cast] lemma of_real_finsupp_prod {α M : Type*} [has_zero M] (f : α →₀ M) (g : α → M → ℝ) : ((f.prod (λ a b, g a b) : ℝ) : K) = f.prod (λ a b, ((g a b) : K)) := ring_hom.map_finsupp_prod _ f g end is_R_or_C namespace finite_dimensional variables {K : Type*} [is_R_or_C K] open_locale classical open is_R_or_C /-- This instance generates a type-class problem with a metavariable `?m` that should satisfy `is_R_or_C ?m`. Since this can only be satisfied by `ℝ` or `ℂ`, this does not cause problems. -/ library_note "is_R_or_C instance" /-- An `is_R_or_C` field is finite-dimensional over `ℝ`, since it is spanned by `{1, I}`. -/ @[nolint dangerous_instance] instance is_R_or_C_to_real : finite_dimensional ℝ K := finite_dimensional.iff_fg.mpr ⟨{1, I}, begin rw eq_top_iff, intros a _, rw [finset.coe_insert, finset.coe_singleton, submodule.mem_span_insert], refine ⟨re a, (im a) • I, _, _⟩, { rw submodule.mem_span_singleton, use im a }, simp [re_add_im a, algebra.smul_def, algebra_map_eq_of_real] end⟩ /-- Over an `is_R_or_C` field, we can register the properness of finite-dimensional normed spaces as an instance. -/ @[priority 900, nolint dangerous_instance] instance proper_is_R_or_C -- note [is_R_or_C instance] {E : Type*} [normed_group E] [normed_space K E] [finite_dimensional K E] : proper_space E := begin letI : normed_space ℝ E := restrict_scalars.normed_space ℝ K E, letI : is_scalar_tower ℝ K E := restrict_scalars.is_scalar_tower _ _ _, letI : finite_dimensional ℝ E := finite_dimensional.trans ℝ K E, apply_instance end end finite_dimensional section instances noncomputable instance real.is_R_or_C : is_R_or_C ℝ := { re := add_monoid_hom.id ℝ, im := 0, conj := ring_hom.id ℝ, I := 0, I_re_ax := by simp only [add_monoid_hom.map_zero], I_mul_I_ax := or.intro_left _ rfl, re_add_im_ax := λ z, by unfold_coes; simp [add_zero, id.def, mul_zero], of_real_re_ax := λ r, by simp only [add_monoid_hom.id_apply, algebra.id.map_eq_self], of_real_im_ax := λ r, by simp only [add_monoid_hom.zero_apply], mul_re_ax := λ z w, by simp only [sub_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply], mul_im_ax := λ z w, by simp only [add_zero, zero_mul, mul_zero, add_monoid_hom.zero_apply], conj_re_ax := λ z, by simp only [ring_hom.id_apply], conj_im_ax := λ z, by simp only [neg_zero, add_monoid_hom.zero_apply], conj_I_ax := by simp only [ring_hom.map_zero, neg_zero], norm_sq_eq_def_ax := λ z, by simp only [pow_two, norm, ←abs_mul, abs_mul_self z, add_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply], mul_im_I_ax := λ z, by simp only [mul_zero, add_monoid_hom.zero_apply], inv_def_ax := λ z, by simp [pow_two, real.norm_eq_abs, abs_mul_abs_self, ← div_eq_mul_inv], div_I_ax := λ z, by simp only [div_zero, mul_zero, neg_zero]} noncomputable instance complex.is_R_or_C : is_R_or_C ℂ := { re := ⟨complex.re, complex.zero_re, complex.add_re⟩, im := ⟨complex.im, complex.zero_im, complex.add_im⟩, conj := complex.conj, I := complex.I, I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re], I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true], re_add_im_ax := λ z, by simp only [add_monoid_hom.coe_mk, complex.re_add_im, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_re_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_im_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im, complex.coe_algebra_map, complex.of_real_eq_coe], mul_re_ax := λ z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk], mul_im_ax := λ z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im], conj_re_ax := λ z, by simp only [ring_hom.coe_mk, add_monoid_hom.coe_mk, complex.conj_re], conj_im_ax := λ z, by simp only [ring_hom.coe_mk, complex.conj_im, add_monoid_hom.coe_mk], conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk], norm_sq_eq_def_ax := λ z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq_apply, add_monoid_hom.coe_mk, complex.norm_eq_abs], mul_im_I_ax := λ z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im], inv_def_ax := λ z, by simp only [complex.inv_def, complex.norm_sq_eq_abs, complex.coe_algebra_map, complex.of_real_eq_coe, complex.norm_eq_abs], div_I_ax := complex.div_I } end instances namespace is_R_or_C section cleanup_lemmas local notation `reR` := @is_R_or_C.re ℝ _ local notation `imR` := @is_R_or_C.im ℝ _ local notation `conjR` := @is_R_or_C.conj ℝ _ local notation `IR` := @is_R_or_C.I ℝ _ local notation `absR` := @is_R_or_C.abs ℝ _ local notation `norm_sqR` := @is_R_or_C.norm_sq ℝ _ local notation `reC` := @is_R_or_C.re ℂ _ local notation `imC` := @is_R_or_C.im ℂ _ local notation `conjC` := @is_R_or_C.conj ℂ _ local notation `IC` := @is_R_or_C.I ℂ _ local notation `absC` := @is_R_or_C.abs ℂ _ local notation `norm_sqC` := @is_R_or_C.norm_sq ℂ _ @[simp] lemma re_to_real {x : ℝ} : reR x = x := rfl @[simp] lemma im_to_real {x : ℝ} : imR x = 0 := rfl @[simp] lemma conj_to_real {x : ℝ} : conjR x = x := rfl @[simp] lemma I_to_real : IR = 0 := rfl @[simp] lemma norm_sq_to_real {x : ℝ} : norm_sqR x = x*x := by simp [is_R_or_C.norm_sq] @[simp] lemma abs_to_real {x : ℝ} : absR x = _root_.abs x := by simp [is_R_or_C.abs, abs, real.sqrt_mul_self_eq_abs] @[simp] lemma coe_real_eq_id : @coe ℝ ℝ _ = id := rfl @[simp] lemma re_to_complex {x : ℂ} : reC x = x.re := rfl @[simp] lemma im_to_complex {x : ℂ} : imC x = x.im := rfl @[simp] lemma conj_to_complex {x : ℂ} : conjC x = x.conj := rfl @[simp] lemma I_to_complex : IC = complex.I := rfl @[simp] lemma norm_sq_to_complex {x : ℂ} : norm_sqC x = complex.norm_sq x := by simp [is_R_or_C.norm_sq, complex.norm_sq] @[simp] lemma abs_to_complex {x : ℂ} : absC x = complex.abs x := by simp [is_R_or_C.abs, complex.abs] end cleanup_lemmas end is_R_or_C
25a78ba1609b820ff407d70ddf4f3fda3c7264b5
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world8/level9.lean
59d2ec998771442605ef9d739d40cdd33c8ffe92
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,641
lean
import mynat.definition -- hide import mynat.add -- hide import game.world8.level8 -- hide namespace mynat -- hide /- Axiom : zero_ne_succ (a : mynat) : 0 ≠ succ(a) -/ /- Tactic : symmetry ## Summary `symmetry` turns goals of the form `⊢ A = B` to `⊢ B = A`. Also works with `≠`. Also works on hypotheses: if `h : a ≠ b` then `symmetry at h` gives `h : b ≠ a`. ## Details `symmetry` works on both goals and hypotheses. By default it works on the goal. It will turn a goal of the form `⊢ A = B` to `⊢ B = A`. More generally it will work with any symmetric binary relation (for example `≠`, or more generally any binary relation whose proof of symmetry has been tagged with the `symm` attribute). To get `symmetry` working on a hypothesis, use `symmetry at h`. ## Examples If the tactic state is ``` h : a = b ⊢ c ≠ d ``` then `symmetry` changes the goal to `⊢ d ≠ c` and `symmetry at h` changes `h` to `h : b = a`. -/ /- # Advanced Addition World ## Level 9: `succ_ne_zero` Levels 9 to 13 introduce the last axiom of Peano, namely that $0\not=\operatorname{succ}(a)$. The proof of this is called `zero_ne_succ a`. `zero_ne_succ (a : mynat) : 0 ≠ succ(a)` The `symmetry` tactic will turn any goal of the form `R x y` into `R y x`, if `R` is a symmetric binary relation (for example `=` or `≠`). In particular, you can prove `succ_ne_zero` below by first using `symmetry` and then `exact zero_ne_succ a`. -/ /- Theorem Zero is not the successor of any natural number. -/ theorem succ_ne_zero (a : mynat) : succ a ≠ 0 := begin [less_leaky] symmetry, exact zero_ne_succ a, end end mynat
cd6a6a32689343fc22c6899cf906ae22079da778
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/int/cast.lean
074add924bb8770032e7e414892b1baa4eb3d7f0
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
11,304
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.int.basic import data.nat.cast /-! # Cast of integers This file defines the *canonical* homomorphism from the integers into a type `α` with `0`, `1`, `+` and `-` (typically a `ring`). ## Main declarations * `cast`: Canonical homomorphism `ℤ → α` where `α` has a `0`, `1`, `+` and `-`. * `cast_add_hom`: `cast` bundled as an `add_monoid_hom`. * `cast_ring_hom`: `cast` bundled as a `ring_hom`. ## Implementation note Setting up the coercions priorities is tricky. See Note [coercion into rings]. -/ open nat namespace int @[simp, push_cast] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) /-- Coercion `ℕ → ℤ` as a `ring_hom`. -/ def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩ section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℤ α := ⟨int.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n : α) = n := by simp @[simp, norm_cast] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp, norm_cast] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := by simpa only [sub_eq_add_neg] using cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), begin rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add], apply congr_arg (λ x:ℕ, -(x:α)), ac_refl end @[simp, norm_cast] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm @[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp [sub_eq_add_neg] @[simp, norm_cast] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] /-- `coe : ℤ → α` as an `add_monoid_hom`. -/ def cast_add_hom (α : Type*) [add_group α] [has_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩ @[simp] lemma coe_cast_add_hom [add_group α] [has_one α] : ⇑(cast_add_hom α) = coe := rfl /-- `coe : ℤ → α` as a `ring_hom`. -/ def cast_ring_hom (α : Type*) [ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ @[simp] lemma coe_cast_ring_hom [ring α] : ⇑(cast_ring_hom α) = coe := rfl lemma cast_commute [ring α] (m : ℤ) (x : α) : commute ↑m x := int.cases_on m (λ n, n.cast_commute x) (λ n, ((n+1).cast_commute x).neg_left) lemma cast_comm [ring α] (m : ℤ) (x : α) : (m : α) * x = x * m := (cast_commute m x).eq lemma commute_cast [ring α] (x : α) (m : ℤ) : commute x m := (m.cast_commute x).symm @[simp, norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp} @[simp, norm_cast] theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp} @[simp, norm_cast] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp theorem cast_mono [ordered_ring α] : monotone (coe : ℤ → α) := begin intros m n h, rw ← sub_nonneg at h, lift n - m to ℕ using h with k, rw [← sub_nonneg, ← cast_sub, ← h_1, cast_coe_nat], exact k.cast_nonneg end @[simp] theorem cast_nonneg [ordered_ring α] [nontrivial α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := have -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one, by simpa [(neg_succ_lt_zero n).not_le, ← sub_eq_add_neg, le_neg] using this.not_le @[simp, norm_cast] theorem cast_le [ordered_ring α] [nontrivial α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] theorem cast_strict_mono [ordered_ring α] [nontrivial α] : strict_mono (coe : ℤ → α) := strict_mono_of_le_iff_le $ λ m n, cast_le.symm @[simp, norm_cast] theorem cast_lt [ordered_ring α] [nontrivial α] {m n : ℤ} : (m : α) < n ↔ m < n := cast_strict_mono.lt_iff_lt @[simp] theorem cast_nonpos [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [ordered_ring α] [nontrivial α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_min [linear_ordered_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := monotone.map_min cast_mono @[simp, norm_cast] theorem cast_max [linear_ordered_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := monotone.map_max cast_mono @[simp, norm_cast] theorem cast_abs [linear_ordered_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] lemma cast_nat_abs {R : Type*} [linear_ordered_ring R] : ∀ (n : ℤ), (n.nat_abs : R) = abs n | (n : ℕ) := by simp only [int.nat_abs_of_nat, int.cast_coe_nat, nat.abs_cast] | -[1+n] := by simp only [int.nat_abs, int.cast_neg_succ_of_nat, abs_neg, ← nat.cast_succ, nat.abs_cast] lemma coe_int_dvd [comm_ring α] (m n : ℤ) (h : m ∣ n) : (m : α) ∣ (n : α) := ring_hom.map_dvd (int.cast_ring_hom α) h end cast end int open int namespace add_monoid_hom variables {A : Type*} /-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal if `f 1 = g 1`. -/ @[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g := have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat h1, have ∀ n : ℕ, f n = g n := ext_iff.1 this, ext $ λ n, int.cases_on n this $ λ n, eq_on_neg (this $ n + 1) variables [add_group A] [has_one A] theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A := ext_int $ by simp [h1] theorem eq_int_cast (f : ℤ →+ A) (h1 : f 1 = 1) : ∀ n : ℤ, f n = n := ext_iff.1 (f.eq_int_cast_hom h1) end add_monoid_hom namespace monoid_hom variables {M : Type*} [monoid M] open multiplicative @[ext] theorem ext_mint {f g : multiplicative ℤ →* M} (h1 : f (of_add 1) = g (of_add 1)) : f = g := monoid_hom.ext $ add_monoid_hom.ext_iff.mp $ @add_monoid_hom.ext_int _ _ f.to_additive g.to_additive h1 /-- If two `monoid_hom`s agree on `-1` and the naturals then they are equal. -/ @[ext] theorem ext_int {f g : ℤ →* M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp int.of_nat_hom.to_monoid_hom = g.comp int.of_nat_hom.to_monoid_hom) : f = g := begin ext (x | x), { exact (monoid_hom.congr_fun h_nat x : _), }, { rw [int.neg_succ_of_nat_eq, ← neg_one_mul, f.map_mul, g.map_mul], congr' 1, exact_mod_cast (monoid_hom.congr_fun h_nat (x + 1) : _), } end end monoid_hom namespace monoid_with_zero_hom variables {M : Type*} [monoid_with_zero M] /-- If two `monoid_with_zero_hom`s agree on `-1` and the naturals then they are equal. -/ @[ext] theorem ext_int {f g : monoid_with_zero_hom ℤ M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp int.of_nat_hom.to_monoid_with_zero_hom = g.comp int.of_nat_hom.to_monoid_with_zero_hom) : f = g := to_monoid_hom_injective $ monoid_hom.ext_int h_neg_one $ monoid_hom.ext (congr_fun h_nat : _) /-- If two `monoid_with_zero_hom`s agree on `-1` and the _positive_ naturals then they are equal. -/ theorem ext_int' {φ₁ φ₂ : monoid_with_zero_hom ℤ M} (h_neg_one : φ₁ (-1) = φ₂ (-1)) (h_pos : ∀ n : ℕ, 0 < n → φ₁ n = φ₂ n) : φ₁ = φ₂ := ext_int h_neg_one $ ext_nat h_pos end monoid_with_zero_hom namespace ring_hom variables {α : Type*} {β : Type*} [ring α] [ring β] @[simp] lemma eq_int_cast (f : ℤ →+* α) (n : ℤ) : f n = n := f.to_add_monoid_hom.eq_int_cast f.map_one n lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α := ring_hom.ext f.eq_int_cast @[simp] lemma map_int_cast (f : α →+* β) (n : ℤ) : f n = n := (f.comp (int.cast_ring_hom α)).eq_int_cast n lemma ext_int {R : Type*} [semiring R] (f g : ℤ →+* R) : f = g := coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm instance int.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℤ →+* R) := ⟨ring_hom.ext_int⟩ end ring_hom @[simp, norm_cast] theorem int.cast_id (n : ℤ) : ↑n = n := ((ring_hom.id ℤ).eq_int_cast n).symm namespace pi variables {α β : Type*} lemma int_apply [has_zero β] [has_one β] [has_add β] [has_neg β] : ∀ (n : ℤ) (a : α), (n : α → β) a = n | (n:ℕ) a := pi.nat_apply n a | -[1+n] a := by rw [cast_neg_succ_of_nat, cast_neg_succ_of_nat, neg_apply, add_apply, one_apply, nat_apply] @[simp] lemma coe_int [has_zero β] [has_one β] [has_add β] [has_neg β] (n : ℤ) : (n : α → β) = λ _, n := by { ext, rw pi.int_apply } end pi
46539612c56d212e33e0d4c2b48f38f800b005ab
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/nateq.lean
2ca82b521c61fbdfb53cac7254c8c8f2f189ef3a
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
896
lean
open bool nat attribute nat.rec_on [reducible] definition is_eq (a b : nat) : bool := nat.rec_on a (λ b, nat.cases_on b tt (λb₁, ff)) (λ a₁ r₁ b, nat.cases_on b ff (λb₁, r₁ b₁)) b example : is_eq 3 3 = tt := rfl example : is_eq 3 5 = ff := rfl theorem eq.to_is_eq (a b : nat) (H : a = b) : is_eq a b = tt := have aux : is_eq a a = tt, from nat.induction_on a rfl (λ (a₁ : nat) (ih : is_eq a₁ a₁ = tt), ih), H ▸ aux /- theorem is_eq.to_eq (a b : nat) : is_eq a b = tt → a = b := nat.induction_on a (λb, nat.cases_on b (λh, rfl) (λb₁ H, absurd H !ff_ne_tt)) (λa₁ (ih : ∀b, is_eq a₁ b = tt → a₁ = b) (b : nat), nat.cases_on b (λ (H : is_eq (succ a₁) zero = tt), absurd H !ff_ne_tt) (λb₁ (H : is_eq (succ a₁) (succ b₁) = tt), have aux : a₁ = b₁, from ih b₁ H, aux ▸ rfl)) b -/
5a26320723327dc0b3ea16f201ab877d2b4ce51d
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/alias.lean
b76929ac82b65397e7852d444d14c3aaba19b68c
[ "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
5,508
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.buffer.parser meta.expr tactic.core /-! # The `alias` command This file defines an `alias` command, which can be used to create copies of a theorem or definition with different names. Syntax: ```lean /-- doc string -/ alias my_theorem ← alias1 alias2 ... ``` This produces defs or theorems of the form: ```lean /-- doc string -/ @[alias] theorem alias1 : <type of my_theorem> := my_theorem /-- doc string -/ @[alias] theorem alias2 : <type of my_theorem> := my_theorem ``` Iff alias syntax: ```lean alias A_iff_B ↔ B_of_A A_of_B alias A_iff_B ↔ .. ``` This gets an existing biconditional theorem `A_iff_B` and produces the one-way implications `B_of_A` and `A_of_B` (with no change in implicit arguments). A blank `_` can be used to avoid generating one direction. The `..` notation attempts to generate the 'of'-names automatically when the input theorem has the form `A_iff_B` or `A_iff_B_left` etc. -/ open lean.parser tactic interactive parser namespace tactic.alias @[user_attribute] meta def alias_attr : user_attribute := { name := `alias, descr := "This definition is an alias of another." } meta def alias_direct (d : declaration) (doc : string) (al : name) : tactic unit := do updateex_env $ λ env, env.add (match d.to_definition with | declaration.defn n ls t _ _ _ := declaration.defn al ls t (expr.const n (level.param <$> ls)) reducibility_hints.abbrev tt | declaration.thm n ls t _ := declaration.thm al ls t $ task.pure $ expr.const n (level.param <$> ls) | _ := undefined end), alias_attr.set al () tt, add_doc_string al doc meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → tactic expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := pure $ @expr.const tt iffmp [] a b (f 0) | _ f := fail "Target theorem must have the form `Π x y z, a ↔ b`" meta def alias_iff (d : declaration) (doc : string) (al : name) (iffmp : name) : tactic unit := (if al = `_ then skip else get_decl al >> skip) <|> do let ls := d.univ_params, let t := d.type, v ← mk_iff_mp_app iffmp t (λ_, expr.const d.to_name (level.param <$> ls)), t' ← infer_type v, updateex_env $ λ env, env.add (declaration.thm al ls t' $ task.pure v), alias_attr.set al () tt, add_doc_string al doc meta def make_left_right : name → tactic (name × name) | (name.mk_string s p) := do let buf : char_buffer := s.to_char_buffer, sum.inr parts ← pure $ run (sep_by1 (ch '_') (many_char (sat (≠ '_')))) s.to_char_buffer, (left, _::right) ← pure $ parts.span (≠ "iff"), let pfx (a b : string) := a.to_list.is_prefix_of b.to_list, (suffix', right') ← pure $ right.reverse.span (λ s, pfx "left" s ∨ pfx "right" s), let right := right'.reverse, let suffix := suffix'.reverse, pure (p <.> "_".intercalate (right ++ "of" :: left ++ suffix), p <.> "_".intercalate (left ++ "of" :: right ++ suffix)) | _ := failed /-- The `alias` command can be used to create copies of a theorem or definition with different names. Syntax: ```lean /-- doc string -/ alias my_theorem ← alias1 alias2 ... ``` This produces defs or theorems of the form: ```lean /-- doc string -/ @[alias] theorem alias1 : <type of my_theorem> := my_theorem /-- doc string -/ @[alias] theorem alias2 : <type of my_theorem> := my_theorem ``` Iff alias syntax: ```lean alias A_iff_B ↔ B_of_A A_of_B alias A_iff_B ↔ .. ``` This gets an existing biconditional theorem `A_iff_B` and produces the one-way implications `B_of_A` and `A_of_B` (with no change in implicit arguments). A blank `_` can be used to avoid generating one direction. The `..` notation attempts to generate the 'of'-names automatically when the input theorem has the form `A_iff_B` or `A_iff_B_left` etc. -/ @[user_command] meta def alias_cmd (meta_info : decl_meta_info) (_ : parse $ tk "alias") : lean.parser unit := do old ← ident, d ← (do old ← resolve_constant old, get_decl old) <|> fail ("declaration " ++ to_string old ++ " not found"), let doc := λ al : name, meta_info.doc_string.get_or_else $ "**Alias** of `" ++ to_string old ++ "`.", do { tk "←" <|> tk "<-", aliases ← many ident, ↑(aliases.mmap' $ λ al, alias_direct d (doc al) al) } <|> do { tk "↔" <|> tk "<->", (left, right) ← mcond ((tk "." *> tk "." >> pure tt) <|> pure ff) (make_left_right old <|> fail "invalid name for automatic name generation") (prod.mk <$> types.ident_ <*> types.ident_), alias_iff d (doc left) left `iff.mp, alias_iff d (doc right) right `iff.mpr } add_tactic_doc { name := "alias", category := doc_category.cmd, decl_names := [`tactic.alias.alias_cmd], tags := ["renaming"] } meta def get_lambda_body : expr → expr | (expr.lam _ _ _ b) := get_lambda_body b | a := a meta def get_alias_target (n : name) : tactic (option name) := do tt ← has_attribute' `alias n | pure none, d ← get_decl n, let (head, args) := (get_lambda_body d.value).get_app_fn_args, let head := if head.is_constant_of `iff.mp ∨ head.is_constant_of `iff.mpr then expr.get_app_fn (head.ith_arg 2) else head, guardb $ head.is_constant, pure $ head.const_name end tactic.alias
0429dd63c2ae96194526b3dd45febdd1af5f6116
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Data/Lsp/InitShutdown.lean
8d073fed74ebf2c5a1b26d641f6e79eb4ce8e1ed
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,931
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Lsp.Capabilities import Lean.Data.Lsp.Workspace import Lean.Data.Json /-! Functionality to do with initializing and shutting down the server ("General Messages" section of LSP spec). -/ namespace Lean namespace Lsp open Json structure ClientInfo := (name : String) (version? : Option String := none) instance : FromJson ClientInfo := ⟨fun j => do let name ← j.getObjValAs? String "name" let version? := j.getObjValAs? String "version" pure ⟨name, version?⟩⟩ inductive Trace | off | messages | verbose instance : FromJson Trace := ⟨fun j => match j.getStr? with | some "off" => Trace.off | some "messages" => Trace.messages | some "verbose" => Trace.verbose | _ => none⟩ structure InitializeParams := (processId? : Option Int := none) (clientInfo? : Option ClientInfo := none) /- We don't support the deprecated rootPath (rootPath? : Option String) -/ (rootUri? : Option String := none) (initializationOptions? : Option Json := none) (capabilities : ClientCapabilities) /- If omitted, we default to off. -/ (trace : Trace := Trace.off) (workspaceFolders? : Option (Array WorkspaceFolder) := none) instance : FromJson InitializeParams := ⟨fun j => do /- Many of these params can be null instead of not present. For ease of implementation, we're liberal: missing params, wrong json types and null all map to none, even if LSP sometimes only allows some subset of these. In cases where LSP makes a meaningful distinction between different kinds of missing values, we'll follow accordingly. -/ let processId? := j.getObjValAs? Int "processId" let clientInfo? := j.getObjValAs? ClientInfo "clientInfo" let rootUri? := j.getObjValAs? String "rootUri" let initializationOptions? := j.getObjVal? "initializationOptions" let capabilities ← j.getObjValAs? ClientCapabilities "capabilities" let trace := (j.getObjValAs? Trace "trace").getD Trace.off let workspaceFolders? := j.getObjValAs? (Array WorkspaceFolder) "workspaceFolders" pure ⟨processId?, clientInfo?, rootUri?, initializationOptions?, capabilities, trace, workspaceFolders?⟩⟩ inductive InitializedParams | mk instance : FromJson InitializedParams := ⟨fun j => InitializedParams.mk⟩ structure ServerInfo := (name : String) (version? : Option String := none) instance : ToJson ServerInfo := ⟨fun o => mkObj $ ⟨"name", o.name⟩ :: opt "version" o.version?⟩ structure InitializeResult := (capabilities : ServerCapabilities) (serverInfo? : Option ServerInfo := none) instance : ToJson InitializeResult := ⟨fun o => mkObj $ ⟨"capabilities", toJson o.capabilities⟩ :: opt "serverInfo" o.serverInfo?⟩ end Lsp end Lean
1951bb19abad376b2a82b48b0f60cf20e209b45f
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/meta/transfer.lean
699df48186d8904a7528510e0173e250b70cb64b
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,479
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 (CMU) -/ prelude import init.meta.tactic init.meta.match_tactic init.relator init.meta.mk_dec_eq_instance namespace transfer open tactic expr list monad /- Transfer rules are of the shape: rel_t : {u} Πx, R t₁ t₂ where `u` is a list of universe parameters, `x` is a list of dependent variables, and `R` is a relation. Then this rule will translate `t₁` (depending on `u` and `x`) into `t₂`. `u` and `x` will be called parameters. When `R` is a relation on functions lifted from `S` and `R` the variables bound by `S` are called arguments. `R` is generally constructed using `⇒` (i.e. `relator.lift_fun`). As example: rel_eq : (R ⇒ R ⇒ iff) eq t transfer will match this rule when it sees: (@eq α a b) and transfer it to (t a b) Here `α` is a parameter and `a` and `b` are arguments. TODO: add trace statements TODO: currently the used relation must be fixed by the matched rule or through type class inference. Maybe we want to replace this by type inference similar to Isabelle's transfer. -/ private meta structure rel_data := (in_type : expr) (out_type : expr) (relation : expr) meta instance has_to_tactic_format_rel_data : has_to_tactic_format rel_data := ⟨λr, do R ← pp r^.relation, α ← pp r^.in_type, β ← pp r^.out_type, return $ to_fmt "(" ++ R ++ ": rel (" ++ α ++ ") (" ++ β ++ "))" ⟩ private meta structure rule_data := (pr : expr) (uparams : list name) -- levels not in pat (params : list (expr × bool)) -- fst : local constant, snd = tt → param appears in pattern (uargs : list name) -- levels not in pat (args : list (expr × rel_data)) -- fst : local constant (pat : pattern) -- `R c` (out : expr) -- right-hand side `d` of rel equation `R c d` meta instance has_to_tactic_format_rule_data : has_to_tactic_format rule_data := ⟨λr, do pr ← pp r^.pr, up ← pp r^.uparams, mp ← pp r^.params, ua ← pp r^.uargs, ma ← pp r^.args, pat ← pp r^.pat^.target, out ← pp r^.out, return $ to_fmt "{ ⟨" ++ pat ++ "⟩ pr: " ++ pr ++ " → " ++ out ++ ", " ++ up ++ " " ++ mp ++ " " ++ ua ++ " " ++ ma ++ " }" ⟩ private meta def get_lift_fun : expr → tactic (list rel_data × expr) | e := do { guardb (is_constant_of (get_app_fn e) `relator.lift_fun), [α, β, γ, δ, R, S] ← return $ get_app_args e, (ps, r) ← get_lift_fun S, return (rel_data.mk α β R :: ps, r)} <|> return ([], e) private meta def mark_occurences (e : expr) : list expr → list (expr × bool) | [] := [] | (h :: t) := let xs := mark_occurences t in (h, occurs h e || any xs (λ⟨e, oc⟩, oc && occurs h e)) :: xs private meta def analyse_rule (u' : list name) (pr : expr) : tactic rule_data := do t ← infer_type pr, (params, app (app r f) g) ← mk_local_pis t, (arg_rels, R) ← get_lift_fun r, args ← monad.for (enum arg_rels) (λ⟨n, a⟩, prod.mk <$> mk_local_def (mk_simple_name ("a_" ++ to_string n)) a^.in_type <*> pure a), a_vars ← return $ fmap prod.fst args, p ← head_beta (app_of_list f a_vars), p_data ← return $ mark_occurences (app R p) params, p_vars ← return $ list.map prod.fst (list.filter (λx, ↑x.2) p_data), u ← return $ collect_univ_params (app R p) ∩ u', pat ← mk_pattern (fmap level.param u) (p_vars ++ a_vars) (app R p) (fmap level.param u) (p_vars ++ a_vars), return $ rule_data.mk pr (list.remove_all u' u) p_data u args pat g private meta def analyse_decls : list name → tactic (list rule_data) := monad.mapm (λn, do d ← get_decl n, c ← return d^.univ_params^.length, ls ← monad.for (range c) (λ_, mk_fresh_name), analyse_rule ls (const n (ls^.map level.param))) private meta def split_params_args : list (expr × bool) → list expr → list (expr × option expr) × list expr | ((lc, tt) :: ps) (e :: es) := let (ps', es') := split_params_args ps es in ((lc, some e) :: ps', es') | ((lc, ff) :: ps) es := let (ps', es') := split_params_args ps es in ((lc, none) :: ps', es') | _ es := ([], es) private meta def param_substitutions (ctxt : list expr) : list (expr × option expr) → tactic (list (name × expr) × list expr) | (((local_const n _ bi t), s) :: ps) := do (e, m) ← match s with | (some e) := return (e, []) | none := let ctxt' := list.filter (λv, occurs v t) ctxt in let ty := pis ctxt' t in if bi = binder_info.inst_implicit then do guard (bi = binder_info.inst_implicit), ty ← instantiate_mvars ty, e ← mk_instance ty, return (e, []) else do mv ← mk_meta_var ty, return (app_of_list mv ctxt', [mv]) end, sb ← return $ instantiate_local n e, ps ← return $ fmap (prod.map sb (fmap sb)) ps, (ms, vs) ← param_substitutions ps, return ((n, e) :: ms, m ++ vs) | _ := return ([], []) /- input expression a type `R a`, it finds a type `b`, s.t. there is a proof of the type `R a b`. It return (`a`, pr : `R a b`) -/ meta def compute_transfer : list rule_data → list expr → expr → tactic (expr × expr × list expr) | rds ctxt e := do -- Select matching rule (i, ps, args, ms, rd) ← first (rds^.for (λrd, do (l, m) ← match_pattern_core semireducible rd^.pat e, level_map ← monad.for rd^.uparams (λl, prod.mk l <$> mk_meta_univ), inst_univ ← return $ (λe, instantiate_univ_params e (level_map ++ zip rd^.uargs l)), (ps, args) ← return $ split_params_args (list.map (prod.map inst_univ id) rd^.params) m, (ps, ms) ← param_substitutions ctxt ps, /- this checks type class parameters -/ return (instantiate_locals ps ∘ inst_univ, ps, args, ms, rd))), (bs, hs, mss) ← monad.for (zip rd^.args args) (λ⟨⟨_, d⟩, e⟩, do -- Argument has function type (args, r) ← get_lift_fun (i d^.relation), ((a_vars, b_vars), (R_vars, bnds)) ← monad.for (enum args) (λ⟨n, arg⟩, do a ← mk_local_def (("a" ++ to_string n) : string) arg^.in_type, b ← mk_local_def (("b" ++ to_string n) : string) arg^.out_type, R ← mk_local_def (("R" ++ to_string n) : string) (arg^.relation a b), return ((a, b), (R, [a, b, R]))) >>= (return ∘ prod.map unzip unzip ∘ unzip), rds' ← monad.for R_vars (analyse_rule []), -- Transfer argument a ← return $ i e, a' ← head_beta (app_of_list a a_vars), (b, pr, ms) ← compute_transfer (rds ++ rds') (ctxt ++ a_vars) (app r a'), b' ← head_eta (lambdas b_vars b), return (b', [a, b', lambdas (list.join bnds) pr], ms)) >>= (return ∘ prod.map id unzip ∘ unzip), -- Combine b ← head_beta (app_of_list (i rd^.out) bs), pr ← return $ app_of_list (i rd^.pr) (fmap prod.snd ps ++ list.join hs), return (b, pr, ms ++ list.join mss) meta def transfer (ds : list name) : tactic unit := do rds ← analyse_decls ds, tgt ← target, (new_tgt, pr, ms) ← compute_transfer rds [] (const `iff [] tgt), new_pr ← mk_meta_var new_tgt, /- Setup final tactic state -/ exact (const `iff.mpr [] tgt new_tgt pr new_pr), ms ← monad.for ms (λm, (get_assignment m >> return []) <|> return [m]), gs ← get_goals, set_goals (list.join ms ++ new_pr :: gs) end transfer
eb2e1f50bd89ea2c39c940c9c96b04991ceb6aa5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/category/TopCommRing.lean
a1545ad6343de7f24756ba2b060a33a2c97bb1f3
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,698
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Ring.basic import topology.category.Top.basic import topology.algebra.ring.basic /-! # Category of topological commutative rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We introduce the category `TopCommRing` of topological commutative rings together with the relevant forgetful functors to topological spaces and commutative rings. -/ universes u open category_theory /-- A bundled topological commutative ring. -/ structure TopCommRing := (α : Type u) [is_comm_ring : comm_ring α] [is_topological_space : topological_space α] [is_topological_ring : topological_ring α] namespace TopCommRing instance : inhabited TopCommRing := ⟨⟨punit⟩⟩ instance : has_coe_to_sort TopCommRing (Type u) := ⟨TopCommRing.α⟩ attribute [instance] is_comm_ring is_topological_space is_topological_ring instance : category TopCommRing.{u} := { hom := λ R S, {f : R →+* S // continuous f }, id := λ R, ⟨ring_hom.id R, by obviously⟩, -- TODO remove obviously? comp := λ R S T f g, ⟨g.val.comp f.val, begin -- TODO automate cases f, cases g, dsimp, apply continuous.comp ; assumption end⟩ } instance : concrete_category TopCommRing.{u} := { forget := { obj := λ R, R, map := λ R S f, f.val }, forget_faithful := { } } /-- Construct a bundled `TopCommRing` from the underlying type and the appropriate typeclasses. -/ def of (X : Type u) [comm_ring X] [topological_space X] [topological_ring X] : TopCommRing := ⟨X⟩ @[simp] lemma coe_of (X : Type u) [comm_ring X] [topological_space X] [topological_ring X] : (of X : Type u) = X := rfl instance forget_topological_space (R : TopCommRing) : topological_space ((forget TopCommRing).obj R) := R.is_topological_space instance forget_comm_ring (R : TopCommRing) : comm_ring ((forget TopCommRing).obj R) := R.is_comm_ring instance forget_topological_ring (R : TopCommRing) : topological_ring ((forget TopCommRing).obj R) := R.is_topological_ring instance has_forget_to_CommRing : has_forget₂ TopCommRing CommRing := has_forget₂.mk' (λ R, CommRing.of R) (λ x, rfl) (λ R S f, f.val) (λ R S f, heq.rfl) instance forget_to_CommRing_topological_space (R : TopCommRing) : topological_space ((forget₂ TopCommRing CommRing).obj R) := R.is_topological_space /-- The forgetful functor to Top. -/ instance has_forget_to_Top : has_forget₂ TopCommRing Top := has_forget₂.mk' (λ R, Top.of R) (λ x, rfl) (λ R S f, ⟨⇑f.1, f.2⟩) (λ R S f, heq.rfl) instance forget_to_Top_comm_ring (R : TopCommRing) : comm_ring ((forget₂ TopCommRing Top).obj R) := R.is_comm_ring instance forget_to_Top_topological_ring (R : TopCommRing) : topological_ring ((forget₂ TopCommRing Top).obj R) := R.is_topological_ring /-- The forgetful functors to `Type` do not reflect isomorphisms, but the forgetful functor from `TopCommRing` to `Top` does. -/ instance : reflects_isomorphisms (forget₂ TopCommRing.{u} Top.{u}) := { reflects := λ X Y f _, begin resetI, -- We have an isomorphism in `Top`, let i_Top := as_iso ((forget₂ TopCommRing Top).map f), -- and a `ring_equiv`. let e_Ring : X ≃+* Y := { ..f.1, ..((forget Top).map_iso i_Top).to_equiv }, -- Putting these together we obtain the isomorphism we're after: exact ⟨⟨⟨e_Ring.symm, i_Top.inv.2⟩, ⟨by { ext x, exact e_Ring.left_inv x, }, by { ext x, exact e_Ring.right_inv x, }⟩⟩⟩ end } end TopCommRing
887705f89574cf6d1a5eda878339c530f442a315
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/topology/algebra/group.lean
31a069d603baa3a038a7d701b7f39d41b0df4286
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
7,025
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 Basic constructions for topological groups: * `topological_add_group.to_uniform_space` and `topological_add_group_is_uniform` can be used to construct a canonical uniformity for a topological add group. * `add_group_with_zero_nhd`: construct the topological structure from a group with a neighbourhood around zero. Then with `topological_add_group.to_uniform_space` one can derive a `uniform_space`. -/ import data.set.basic data.set.function import algebra.pi_instances import topology.uniform_space.completion noncomputable theory open filter universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} section topological_add_comm_group variables {G : Type u} [add_comm_group G] [topological_space G] [topological_add_group G] variable (G) def topological_add_group.to_uniform_space : uniform_space G := { uniformity := comap (λp:G×G, p.2 - p.1) (nhds 0), refl := by refine map_le_iff_le_comap.1 (le_trans _ (pure_le_nhds 0)); simp [set.subset_def] {contextual := tt}, symm := begin suffices : tendsto ((λp, -p) ∘ (λp:G×G, p.2 - p.1)) (comap (λp:G×G, p.2 - p.1) (nhds 0)) (nhds (-0)), { simpa [(∘), tendsto_comap_iff] }, exact tendsto.comp tendsto_comap (tendsto_neg tendsto_id) end, comp := begin intros D H, rw mem_lift'_sets, { rcases H with ⟨U, U_nhds, U_sub⟩, rcases exists_nhds_half U_nhds with ⟨V, ⟨V_nhds, V_sum⟩⟩, existsi ((λp:G×G, p.2 - p.1) ⁻¹' V), have H : (λp:G×G, p.2 - p.1) ⁻¹' V ∈ (comap (λp:G×G, p.2 - p.1) (nhds (0 : G))).sets, by existsi [V, V_nhds] ; refl, existsi H, have comp_rel_sub : comp_rel ((λp:G×G, p.2 - p.1) ⁻¹' V) ((λp:G×G, p.2 - p.1) ⁻¹' V) ⊆ (λp:G×G, p.2 - p.1) ⁻¹' U, begin intros p p_comp_rel, rcases p_comp_rel with ⟨z, ⟨Hz1, Hz2⟩⟩, simpa using V_sum _ _ Hz1 Hz2 end, exact set.subset.trans comp_rel_sub U_sub }, { exact monotone_comp_rel monotone_id monotone_id } end, is_open_uniformity := begin intro S, let S' := λ x, {p : G × G | p.1 = x → p.2 ∈ S}, show is_open S ↔ ∀ (x : G), x ∈ S → S' x ∈ (comap (λp:G×G, p.2 - p.1) (nhds (0 : G))).sets, rw [is_open_iff_mem_nhds], refine forall_congr (assume a, forall_congr (assume ha, _)), rw [← nhds_translation a, mem_comap_sets, mem_comap_sets], refine exists_congr (assume t, exists_congr (assume ht, _)), show (λ (y : G), y - a) ⁻¹' t ⊆ S ↔ (λ (p : G × G), p.snd - p.fst) ⁻¹' t ⊆ S' a, split, { rintros h ⟨x, y⟩ hx rfl, exact h hx }, { rintros h x hx, exact @h (a, x) hx rfl } end } section local attribute [instance] topological_add_group.to_uniform_space lemma uniformity_eq_comap_nhds_zero' : uniformity = comap (λp:G×G, p.2 - p.1) (nhds (0 : G)) := rfl variable {G} lemma topological_add_group_is_uniform : uniform_add_group G := have tendsto ((λp:(G×G), p.1 - p.2) ∘ (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1))) (comap (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((nhds 0).prod (nhds 0))) (nhds (0 - 0)) := tendsto_comap.comp (tendsto_sub tendsto_fst tendsto_snd), begin constructor, rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, uniformity_eq_comap_nhds_zero' G, tendsto_comap_iff, prod_comap_comap_eq], simpa [(∘)] end end lemma to_uniform_space_eq [u : uniform_space α] [add_comm_group α] [uniform_add_group α]: topological_add_group.to_uniform_space α = u := begin ext : 1, show @uniformity α (topological_add_group.to_uniform_space α) = uniformity, rw [uniformity_eq_comap_nhds_zero' α, uniformity_eq_comap_nhds_zero α] end end topological_add_comm_group /-- β additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (α : Type u) extends add_comm_group α := (Z : filter α) (zero_Z {} : pure 0 ≤ Z) (sub_Z {} : tendsto (λp:α×α, p.1 - p.2) (Z.prod Z) Z) namespace add_group_with_zero_nhd variables (α) [add_group_with_zero_nhd α] local notation `Z` := add_group_with_zero_nhd.Z instance : topological_space α := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z α) variables {α} lemma neg_Z : tendsto (λa:α, - a) (Z α) (Z α) := have tendsto (λa, (0:α)) (Z α) (Z α), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:α, 0 - a) (Z α) (Z α), from (tendsto.prod_mk this tendsto_id).comp sub_Z, by simpa lemma add_Z : tendsto (λp:α×α, p.1 + p.2) ((Z α).prod (Z α)) (Z α) := suffices tendsto (λp:α×α, p.1 - -p.2) ((Z α).prod (Z α)) (Z α), by simpa, (tendsto.prod_mk tendsto_fst (tendsto_snd.comp neg_Z)).comp sub_Z lemma exists_Z_half {s : set α} (hs : s ∈ (Z α).sets) : ∃ V ∈ (Z α).sets, ∀ v w ∈ V, v + w ∈ s := begin have : ((λa:α×α, a.1 + a.2) ⁻¹' s) ∈ ((Z α).prod (Z α)).sets := add_Z (by simpa using hs), rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end lemma nhds_eq (a : α) : nhds a = map (λx, x + a) (Z α) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:α) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:α, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 b t0 hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z α).sets_of_superset ht (assume x hxt, _), simpa using eqt _ _ hxt hb } end) lemma nhds_zero_eq_Z : nhds 0 = Z α := by simp [nhds_eq]; exact filter.map_id instance : topological_add_monoid α := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, (a + b) + x) ∘ (λp:α×α,p.1 + p.2)) (filter.prod (Z α) (Z α)) (map (λx:α, (a + b) + x) (Z α)), { simpa [(∘)] }, exact add_Z.comp tendsto_map end⟩ instance : topological_add_group α := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, x - a) ∘ (λx:α, -x)) (Z α) (map (λx:α, x - a) (Z α)), { simpa [(∘)] }, exact neg_Z.comp tendsto_map end⟩ end add_group_with_zero_nhd
9c02ad97ebcb7920b1a7a3b79a54c652716c91fc
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/prime_ideal.lean
5dd9538da0277d11e2708402938c0149f4abb942
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
4,822
lean
/- Copyright (c) 2021 Noam Atar. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Noam Atar -/ import order.basic import order.ideal import order.pfilter /-! # Prime ideals ## Main definitions Throughout this file, `P` is at least a preorder, but some sections require more structure, such as a bottom element, a top element, or a join-semilattice structure. - `order.ideal.prime_pair`: A pair of an `ideal` and a `pfilter` which form a partition of `P`. This is useful as giving the data of a prime ideal is the same as giving the data of a prime filter. - `order.ideal.is_prime`: a predicate for prime ideals. Dual to the notion of a prime filter. - `order.pfilter.is_prime`: a predicate for prime filters. Dual to the notion of a prime ideal. ## References - <https://en.wikipedia.org/wiki/Ideal_(order_theory)> ## Tags ideal, prime -/ open order.pfilter namespace order variables {P : Type*} namespace ideal /-- A pair of an `ideal` and a `pfilter` which form a partition of `P`. -/ @[nolint has_inhabited_instance] structure prime_pair (P : Type*) [preorder P] := (I : ideal P) (F : pfilter P) (is_compl_I_F : is_compl (I : set P) F) namespace prime_pair variables [preorder P] (IF : prime_pair P) lemma compl_I_eq_F : (IF.I : set P)ᶜ = IF.F := IF.is_compl_I_F.compl_eq lemma compl_F_eq_I : (IF.F : set P)ᶜ = IF.I := IF.is_compl_I_F.eq_compl.symm lemma I_is_proper : is_proper IF.I := begin cases IF.F.nonempty, apply is_proper_of_not_mem (_ : w ∉ IF.I), rwa ← IF.compl_I_eq_F at h, end lemma disjoint : disjoint (IF.I : set P) IF.F := IF.is_compl_I_F.disjoint lemma I_union_F : (IF.I : set P) ∪ IF.F = set.univ := IF.is_compl_I_F.sup_eq_top lemma F_union_I : (IF.F : set P) ∪ IF.I = set.univ := IF.is_compl_I_F.symm.sup_eq_top end prime_pair /-- An ideal `I` is prime if its complement is a filter. -/ @[mk_iff] class is_prime [preorder P] (I : ideal P) extends is_proper I : Prop := (compl_filter : is_pfilter (I : set P)ᶜ) section preorder variable [preorder P] /-- Create an element of type `order.ideal.prime_pair` from an ideal satisfying the predicate `order.ideal.is_prime`. -/ def is_prime.to_prime_pair {I : ideal P} (h : is_prime I) : prime_pair P := { I := I, F := h.compl_filter.to_pfilter, is_compl_I_F := is_compl_compl } lemma prime_pair.I_is_prime (IF : prime_pair P) : is_prime IF.I := { compl_filter := by { rw IF.compl_I_eq_F, exact IF.F.is_pfilter }, ..IF.I_is_proper } end preorder section semilattice_inf variables [semilattice_inf P] {x y : P} {I : ideal P} lemma is_prime.mem_or_mem (hI : is_prime I) {x y : P} : x ⊓ y ∈ I → x ∈ I ∨ y ∈ I := begin contrapose!, let F := hI.compl_filter.to_pfilter, show x ∈ F ∧ y ∈ F → x ⊓ y ∈ F, exact λ h, inf_mem _ _ h.1 h.2, end lemma is_prime.of_mem_or_mem [is_proper I] (hI : ∀ {x y : P}, x ⊓ y ∈ I → x ∈ I ∨ y ∈ I) : is_prime I := begin rw is_prime_iff, use ‹_›, apply is_pfilter.of_def, { exact set.nonempty_compl.2 (I.is_proper_iff.1 ‹_›) }, { intros x _ y _, refine ⟨x ⊓ y, _, inf_le_left, inf_le_right⟩, have := mt hI, tauto! }, { exact @mem_compl_of_ge _ _ _ } end lemma is_prime_iff_mem_or_mem [is_proper I] : is_prime I ↔ ∀ {x y : P}, x ⊓ y ∈ I → x ∈ I ∨ y ∈ I := ⟨is_prime.mem_or_mem, is_prime.of_mem_or_mem⟩ end semilattice_inf section distrib_lattice variables [distrib_lattice P] {I : ideal P} @[priority 100] instance is_maximal.is_prime [is_maximal I] : is_prime I := begin rw is_prime_iff_mem_or_mem, intros x y, contrapose!, rintro ⟨hx, hynI⟩ hxy, apply hynI, let J := I ⊔ principal x, have hJuniv : (J : set P) = set.univ := is_maximal.maximal_proper (lt_sup_principal_of_not_mem ‹_›), have hyJ : y ∈ ↑J := set.eq_univ_iff_forall.mp hJuniv y, rw coe_sup_eq at hyJ, rcases hyJ with ⟨a, ha, b, hb, hy⟩, rw hy, apply sup_mem _ _ ha, refine I.mem_of_le (le_inf hb _) hxy, rw hy, exact le_sup_right end end distrib_lattice end ideal namespace pfilter variable [preorder P] /-- A filter `F` is prime if its complement is an ideal. -/ @[mk_iff] class is_prime (F : pfilter P) : Prop := (compl_ideal : is_ideal (F : set P)ᶜ) /-- Create an element of type `order.ideal.prime_pair` from a filter satisfying the predicate `order.pfilter.is_prime`. -/ def is_prime.to_prime_pair {F : pfilter P} (h : is_prime F) : ideal.prime_pair P := { I := h.compl_ideal.to_ideal, F := F, is_compl_I_F := is_compl_compl.symm } lemma _root_.order.ideal.prime_pair.F_is_prime (IF : ideal.prime_pair P) : is_prime IF.F := { compl_ideal := by { rw IF.compl_F_eq_I, exact IF.I.is_ideal } } end pfilter end order
af128a84b40facecf3d9bfa9a75c9cdf77b8a3e1
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/topology/bases.lean
0c124ff585c60bb338ead5b38434c9eca63cf211
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
14,878
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 Bases of topologies. Countability axioms. -/ import topology.constructions data.set.countable open set filter lattice classical open_locale topological_space namespace filter universe u variables {α : Type u} /-- A filter has a countable basis iff it is generated by a countable collection of subsets of α. (A filter is a generated by a collection of sets iff it is the infimum of the principal filters.) Note: we do not require the collection to be closed under finite intersections. -/ def has_countable_basis (f : filter α) : Prop := ∃ s : set (set α), countable s ∧ f = ⨅ t ∈ s, principal t lemma has_countable_basis_of_seq (f : filter α) (x : ℕ → set α) (h : f = ⨅ i, principal (x i)) : f.has_countable_basis := ⟨range x, countable_range _, by rwa infi_range⟩ lemma seq_of_has_countable_basis (f : filter α) (cblb : f.has_countable_basis) : ∃ x : ℕ → set α, f = ⨅ i, principal (x i) := begin rcases cblb with ⟨B, Bcbl, gen⟩, subst gen, classical, by_cases Bnonempty : B = ∅, { use λ n, set.univ, simp [principal_univ, *] }, rw countable_iff_exists_surjective_to_subtype Bnonempty at Bcbl, rcases Bcbl with ⟨g, gsurj⟩, rw lattice.infi_subtype', use (λ n, g n), apply le_antisymm; rw le_infi_iff, { intro i, apply infi_le_of_le (g i) _, apply le_refl _ }, { intros a, rcases gsurj a with i, apply infi_le_of_le i _, subst h, apply le_refl _ } end /-- Different characterization of countable basis. A filter has a countable basis iff it is generated by a sequence of sets. -/ lemma has_countable_basis_iff_seq (f : filter α) : f.has_countable_basis ↔ ∃ x : ℕ → set α, f = ⨅ i, principal (x i) := ⟨seq_of_has_countable_basis _, λ ⟨x, xgen⟩, has_countable_basis_of_seq _ x xgen⟩ lemma mono_seq_of_has_countable_basis (f : filter α) (cblb : f.has_countable_basis) : ∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ f = ⨅ i, principal (x i) := begin rcases (seq_of_has_countable_basis f cblb) with ⟨x', hx'⟩, let x := λ n, ⋂ m ≤ n, x' m, use x, split, { intros i j hij a, simp [x], intros h i' hi'i, apply h, transitivity; assumption }, subst hx', apply le_antisymm; rw le_infi_iff; intro i, { rw le_principal_iff, apply Inter_mem_sets (finite_le_nat _), intros j hji, rw ← le_principal_iff, apply infi_le_of_le j _, apply le_refl _ }, { apply infi_le_of_le i _, rw principal_mono, intro a, simp [x], intro h, apply h, refl }, end /-- Different characterization of countable basis. A filter has a countable basis iff it is generated by a monotonically decreasing sequence of sets. -/ lemma has_countable_basis_iff_mono_seq (f : filter α) : f.has_countable_basis ↔ ∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ f = ⨅ i, principal (x i) := ⟨mono_seq_of_has_countable_basis _, λ ⟨x, _, xgen⟩, has_countable_basis_of_seq _ x xgen⟩ end filter namespace topological_space /- countability axioms For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. -/ universe u variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ def is_topological_basis (s : set (set α)) : Prop := (∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧ (⋃₀ s) = univ ∧ t = generate_from s lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅}) := let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅} in ⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩, have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union, eq₁ ▸ eq₂ ▸ assume x h, ⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b, by simpa only [ie] using ne_empty_of_mem h⟩, ie⟩, h, subset.refl _⟩, eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, ⟨finite_empty, empty_subset _, by rw sInter_empty; exact nonempty_iff_univ_ne_empty.1 ⟨a⟩⟩, sInter_empty⟩, mem_univ _⟩, have generate_from s = generate_from b', from le_antisymm (le_generate_from $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩, eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)) (le_generate_from $ assume s hs, by_cases (assume : s = ∅, by rw [this]; apply @is_open_empty _ _) (assume : s ≠ ∅, generate_open.basic _ ⟨{s}, ⟨finite_singleton s, singleton_subset_iff.2 hs, by rwa [sInter_singleton]⟩, sInter_singleton s⟩)), this ▸ hs⟩ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, _root_.is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → _root_.is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := ⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩, h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩ (is_open_inter _ _ _ (h_open _ ht₁) (h_open _ ht₂)), eq_univ_iff_forall.2 $ assume a, let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial (is_open_univ _) in ⟨u, h₁, h₂⟩, le_antisymm (le_generate_from h_open) (assume u hu, (@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau, let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ le_principal_iff.2 hvu))⟩ lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ 𝓝 a ↔ ∃t∈b, a ∈ t ∧ t ⊆ s := begin change s ∈ (𝓝 a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s, rw [hb.2.2, nhds_generate_from, infi_sets_eq'], { simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm], refl }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)), le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ }, { rcases eq_univ_iff_forall.1 hb.2.1 a with ⟨i, h1, h2⟩, exact ⟨i, h2, h1⟩ } end lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : _root_.is_open s := is_open_iff_mem_nhds.2 $ λ a as, (mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩ lemma mem_basis_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u) (ou : _root_.is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := (mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au lemma sUnion_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a, ⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in ⟨b, ⟨hb, bu⟩, ab⟩, λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩ lemma Union_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B := let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in ⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩ variables (α) /-- A separable space is one with a countable dense subset. -/ class separable_space : Prop := (exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ) /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, (𝓝 a).has_countable_basis) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b) instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in ⟨assume a, ⟨{s | a ∈ s ∧ s ∈ b}, countable_subset (assume x ⟨_, hx⟩, hx) hb, by rw [eq, nhds_generate_from]⟩⟩ lemma second_countable_topology_induced (β) [t : topological_space β] [second_countable_topology β] (f : α → β) : @second_countable_topology α (t.induced f) := begin rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩, refine { is_open_generated_countable := ⟨preimage f '' b, countable_image _ hb, _⟩ }, rw [eq, induced_generate_from_eq] end instance subtype.second_countable_topology (s : set α) [second_countable_topology α] : second_countable_topology s := second_countable_topology_induced s α coe lemma is_open_generated_countable_inter [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ ⋂₀ s ≠ ∅} in ⟨b', countable_image _ $ countable_subset (by simp only [(and_assoc _ _).symm]; exact inter_subset_left _ _) (countable_set_of_finite_subset hb₁), assume ⟨s, ⟨_, _, hn⟩, hp⟩, hn hp, is_topological_basis_of_subbasis hb₂⟩ /- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/ instance {β : Type*} [topological_space β] [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) := ⟨let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := is_open_generated_countable_inter α in let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := is_open_generated_countable_inter β in ⟨{g | ∃u∈a, ∃v∈b, g = set.prod u v}, have {g | ∃u∈a, ∃v∈b, g = set.prod u v} = (⋃u∈a, ⋃v∈b, {set.prod u v}), by apply set.ext; simp, by rw [this]; exact (countable_bUnion ha₁ $ assume u hu, countable_bUnion hb₁ $ by simp), by rw [ha₅, hb₅, prod_generate_from_generate_from_eq ha₄ hb₄]⟩⟩ instance second_countable_topology_fintype {ι : Type*} {π : ι → Type*} [fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := have ∀i, ∃b : set (set (π i)), countable b ∧ ∅ ∉ b ∧ is_topological_basis b, from assume a, @is_open_generated_countable_inter (π a) _ (sc a), let ⟨g, hg⟩ := classical.axiom_of_choice this in have t = (λa, generate_from (g a)), from funext $ assume a, (hg a).2.2.2.2, begin constructor, refine ⟨pi univ '' pi univ g, countable_image _ _, _⟩, { suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ g a}, { simpa [pi] }, exact countable_pi (assume i, (hg i).1), }, rw [this, pi_generate_from_eq_fintype], { congr' 1, ext f, simp [pi, eq_comm] }, exact assume a, (hg a).2.2.2.1 end instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in have nhds_eq : ∀a, 𝓝 a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val), by intro a; rw [eq, nhds_generate_from, infi_subtype]; refl, have ∀s∈b, ∃a, a ∈ s, from assume s hs, exists_mem_of_ne_empty $ assume eq, hb₂ $ eq ▸ hs, have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simp only [skolem] at this; exact this, let ⟨f, hf⟩ := this in ⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}), countable_bUnion hb₁ (λ _ _, countable_Union_Prop $ λ _, countable_singleton _), set.ext $ assume a, have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial, let ⟨t, ht₁, ht₂⟩ := this in have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩, suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥, by simpa only [closure_eq_nhds, nhds_eq, infi_inf w, inf_principal, mem_set_of_eq, mem_univ, iff_true], infi_neq_bot_of_directed ⟨a⟩ (assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩, have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩, let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in ⟨⟨s₃, has₃, hs₃⟩, begin simp only [le_principal_iff, mem_principal_sets, (≥)], simp only [subset_inter_iff] at hs, split; apply inter_subset_inter_left; simp only [hs] end⟩) (assume ⟨s, has, hs⟩, have s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h}) ≠ ∅, from ne_empty_of_mem ⟨hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, mem_singleton _⟩⟩, mt principal_eq_bot_iff.1 this) ⟩⟩ variables {α} lemma is_open_Union_countable [second_countable_topology α] {ι} (s : ι → set α) (H : ∀ i, _root_.is_open (s i)) : ∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i := let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in begin let B' := {b ∈ B | ∃ i, b ⊆ s i}, choose f hf using λ b:B', b.2.2, haveI : encodable B' := (countable_subset (sep_subset _ _) cB).to_encodable, refine ⟨_, countable_range f, subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩, rintro _ ⟨i, rfl⟩ x xs, rcases mem_basis_subset_of_mem_open bB xs (H _) with ⟨b, hb, xb, bs⟩, exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩ end lemma is_open_sUnion_countable [second_countable_topology α] (S : set (set α)) (H : ∀ s ∈ S, _root_.is_open s) : ∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in ⟨subtype.val '' T, countable_image _ cT, image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs, by rwa [sUnion_image, sUnion_eq_Union]⟩ end topological_space
36ebcaf4dbf9fd5c3cb49682f1ddf7d252515e77
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/category/Top/basic.lean
504799dc5b18f5893abc0cb5e5c4456b978eaa1a
[ "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
1,597
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison, Mario Carneiro -/ import category_theory.concrete_category.unbundled_hom import topology.continuous_map import topology.opens open category_theory open topological_space universe u /-- The category of topological spaces and continuous maps. -/ def Top : Type (u+1) := bundled topological_space namespace Top instance bundled_hom : bundled_hom @continuous_map := ⟨@continuous_map.to_fun, @continuous_map.id, @continuous_map.comp, @continuous_map.coe_inj⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] Top instance topological_space_unbundled (x : Top) : topological_space x := x.str @[simp] lemma id_app (X : Top.{u}) (x : X) : (𝟙 X : X → X) x = x := rfl @[simp] lemma comp_app {X Y Z : Top.{u}} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g : X → Z) x = g (f x) := rfl /-- Construct a bundled `Top` from the underlying type and the typeclass. -/ def of (X : Type u) [topological_space X] : Top := ⟨X⟩ instance (X : Top) : topological_space X := X.str instance : inhabited Top := ⟨Top.of empty⟩ /-- The discrete topology on any type. -/ def discrete : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊥⟩, map := λ X Y f, { to_fun := f, continuous_to_fun := continuous_bot } } /-- The trivial topology on any type. -/ def trivial : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊤⟩, map := λ X Y f, { to_fun := f, continuous_to_fun := continuous_top } } end Top
1a8b3e084eb81d57068a672cd8b16c5578cf329e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/qpf/multivariate/constructions/prj.lean
d3f0500d33ea813326dd8b152c27671bdf77f3f6
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
1,525
lean
/- Copyright (c) 2020 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.functor.multivariate import data.qpf.multivariate.basic /-! Projection functors are QPFs. The `n`-ary projection functors on `i` is an `n`-ary functor `F` such that `F (α₀..αᵢ₋₁, αᵢ, αᵢ₊₁..αₙ₋₁) = αᵢ` -/ universes u v namespace mvqpf open_locale mvfunctor variables {n : ℕ} (i : fin2 n) /-- The projection `i` functor -/ def prj (v : typevec.{u} n) : Type u := v i instance prj.inhabited {v : typevec.{u} n} [inhabited (v i)] : inhabited (prj i v) := ⟨ (default _ : v i) ⟩ /-- `map` on functor `prj i` -/ def prj.map ⦃α β : typevec n⦄ (f : α ⟹ β) : prj i α → prj i β := f _ instance prj.mvfunctor : mvfunctor (prj i) := { map := prj.map i } /-- Polynomial representation of the projection functor -/ def prj.P : mvpfunctor.{u} n := { A := punit, B := λ _ j, ulift $ plift $ i = j } /-- Abstraction function of the `qpf` instance -/ def prj.abs ⦃α : typevec n⦄ : (prj.P i).obj α → prj i α | ⟨x, f⟩ := f _ ⟨⟨rfl⟩⟩ /-- Representation function of the `qpf` instance -/ def prj.repr ⦃α : typevec n⦄ : prj i α → (prj.P i).obj α := λ x : α i, ⟨ ⟨ ⟩, λ j ⟨⟨h⟩⟩, (h.rec x : α j) ⟩ instance prj.mvqpf : mvqpf (prj i) := { P := prj.P i, abs := prj.abs i, repr := prj.repr i, abs_repr := by intros; refl, abs_map := by intros; cases p; refl } end mvqpf
1dada3fb98e0827a3813474da037265804a1c2ea
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/logic/function/basic.lean
07d5e77d78e6ea9d69f6d81b8a7c6f6edffce3a9
[ "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,784
lean
/- Copyright (c) 2016 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 logic.basic import data.option.defs /-! # Miscellaneous function constructions and lemmas -/ universes u v w namespace function section variables {α β γ : Sort*} {f : α → β} /-- Evaluate a function at an argument. Useful if you want to talk about the partially applied `function.eval x : (Π x, β x) → β x`. -/ @[reducible] def eval {β : α → Sort*} (x : α) (f : Π x, β x) : β x := f x @[simp] lemma eval_apply {β : α → Sort*} (x : α) (f : Π x, β x) : eval x f = f x := rfl lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl lemma const_def {y : β} : (λ x : α, y) = const α y := rfl @[simp] lemma const_apply {y : β} {x : α} : const α y x = y := rfl @[simp] lemma const_comp {f : α → β} {c : γ} : const β c ∘ f = const α c := rfl @[simp] lemma comp_const {f : β → γ} {b : β} : f ∘ const α b = const α (f b) := rfl lemma id_def : @id α = λ x, x := rfl lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : Πa, β a} {f' : Πa, β' a} (hα : α = α') (h : ∀a a', a == a' → f a == f' a') : f == f' := begin subst hα, have : ∀a, f a == f' a, { intro a, exact h a a (heq.refl a) }, have : β = β', { funext a, exact type_eq_of_heq (this a) }, subst this, apply heq_of_eq, funext a, exact eq_of_heq (this a) end lemma funext_iff {β : α → Sort*} {f₁ f₂ : Π (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) := iff.intro (assume h a, h ▸ rfl) funext protected lemma bijective.injective {f : α → β} (hf : bijective f) : injective f := hf.1 protected lemma bijective.surjective {f : α → β} (hf : bijective f) : surjective f := hf.2 theorem injective.eq_iff (I : injective f) {a b : α} : f a = f b ↔ a = b := ⟨@I _ _, congr_arg f⟩ theorem injective.eq_iff' (I : injective f) {a b : α} {c : β} (h : f b = c) : f a = c ↔ a = b := h ▸ I.eq_iff lemma injective.ne (hf : injective f) {a₁ a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ := mt (assume h, hf h) lemma injective.ne_iff (hf : injective f) {x y : α} : f x ≠ f y ↔ x ≠ y := ⟨mt $ congr_arg f, hf.ne⟩ lemma injective.ne_iff' (hf : injective f) {x y : α} {z : β} (h : f y = z) : f x ≠ z ↔ x ≠ y := h ▸ hf.ne_iff /-- If the co-domain `β` of an injective function `f : α → β` has decidable equality, then the domain `α` also has decidable equality. -/ def injective.decidable_eq [decidable_eq β] (I : injective f) : decidable_eq α := λ a b, decidable_of_iff _ I.eq_iff lemma injective.of_comp {g : γ → α} (I : injective (f ∘ g)) : injective g := λ x y h, I $ show f (g x) = f (g y), from congr_arg f h lemma injective.of_comp_iff {f : α → β} (hf : injective f) (g : γ → α) : injective (f ∘ g) ↔ injective g := ⟨injective.of_comp, hf.comp⟩ lemma injective.of_comp_iff' (f : α → β) {g : γ → α} (hg : bijective g) : injective (f ∘ g) ↔ injective f := ⟨ λ h x y, let ⟨x', hx⟩ := hg.surjective x, ⟨y', hy⟩ := hg.surjective y in hx ▸ hy ▸ λ hf, h hf ▸ rfl, λ h, h.comp hg.injective⟩ lemma injective_of_subsingleton [subsingleton α] (f : α → β) : injective f := λ a b ab, subsingleton.elim _ _ lemma injective.dite (p : α → Prop) [decidable_pred p] {f : {a : α // p a} → β} {f' : {a : α // ¬ p a} → β} (hf : injective f) (hf' : injective f') (im_disj : ∀ {x x' : α} {hx : p x} {hx' : ¬ p x'}, f ⟨x, hx⟩ ≠ f' ⟨x', hx'⟩) : function.injective (λ x, if h : p x then f ⟨x, h⟩ else f' ⟨x, h⟩) := λ x₁ x₂ h, begin dsimp only at h, by_cases h₁ : p x₁; by_cases h₂ : p x₂, { rw [dif_pos h₁, dif_pos h₂] at h, injection (hf h), }, { rw [dif_pos h₁, dif_neg h₂] at h, exact (im_disj h).elim, }, { rw [dif_neg h₁, dif_pos h₂] at h, exact (im_disj h.symm).elim, }, { rw [dif_neg h₁, dif_neg h₂] at h, injection (hf' h), }, end lemma surjective.of_comp {g : γ → α} (S : surjective (f ∘ g)) : surjective f := λ y, let ⟨x, h⟩ := S y in ⟨g x, h⟩ lemma surjective.of_comp_iff (f : α → β) {g : γ → α} (hg : surjective g) : surjective (f ∘ g) ↔ surjective f := ⟨surjective.of_comp, λ h, h.comp hg⟩ lemma surjective.of_comp_iff' {f : α → β} (hf : bijective f) (g : γ → α) : surjective (f ∘ g) ↔ surjective g := ⟨λ h x, let ⟨x', hx'⟩ := h (f x) in ⟨x', hf.injective hx'⟩, hf.surjective.comp⟩ instance decidable_eq_pfun (p : Prop) [decidable p] (α : p → Type*) [Π hp, decidable_eq (α hp)] : decidable_eq (Π hp, α hp) | f g := decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm theorem surjective.forall {f : α → β} (hf : surjective f) {p : β → Prop} : (∀ y, p y) ↔ ∀ x, p (f x) := ⟨λ h x, h (f x), λ h y, let ⟨x, hx⟩ := hf y in hx ▸ h x⟩ theorem surjective.forall₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∀ y₁ y₂, p y₁ y₂) ↔ ∀ x₁ x₂, p (f x₁) (f x₂) := hf.forall.trans $ forall_congr $ λ x, hf.forall theorem surjective.forall₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∀ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∀ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.forall.trans $ forall_congr $ λ x, hf.forall₂ theorem surjective.exists {f : α → β} (hf : surjective f) {p : β → Prop} : (∃ y, p y) ↔ ∃ x, p (f x) := ⟨λ ⟨y, hy⟩, let ⟨x, hx⟩ := hf y in ⟨x, hx.symm ▸ hy⟩, λ ⟨x, hx⟩, ⟨f x, hx⟩⟩ theorem surjective.exists₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∃ y₁ y₂, p y₁ y₂) ↔ ∃ x₁ x₂, p (f x₁) (f x₂) := hf.exists.trans $ exists_congr $ λ x, hf.exists theorem surjective.exists₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∃ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∃ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.exists.trans $ exists_congr $ λ x, hf.exists₂ lemma bijective_iff_exists_unique (f : α → β) : bijective f ↔ ∀ b : β, ∃! (a : α), f a = b := ⟨ λ hf b, let ⟨a, ha⟩ := hf.surjective b in ⟨a, ha, λ a' ha', hf.injective (ha'.trans ha.symm)⟩, λ he, ⟨ λ a a' h, unique_of_exists_unique (he (f a')) h rfl, λ b, exists_of_exists_unique (he b) ⟩⟩ /-- Shorthand for using projection notation with `function.bijective_iff_exists_unique`. -/ lemma bijective.exists_unique {f : α → β} (hf : bijective f) (b : β) : ∃! (a : α), f a = b := (bijective_iff_exists_unique f).mp hf b lemma bijective.of_comp_iff (f : α → β) {g : γ → α} (hg : bijective g) : bijective (f ∘ g) ↔ bijective f := and_congr (injective.of_comp_iff' _ hg) (surjective.of_comp_iff _ hg.surjective) lemma bijective.of_comp_iff' {f : α → β} (hf : bijective f) (g : γ → α) : function.bijective (f ∘ g) ↔ function.bijective g := and_congr (injective.of_comp_iff hf.injective _) (surjective.of_comp_iff' hf _) /-- **Cantor's diagonal argument** implies that there are no surjective functions from `α` to `set α`. -/ theorem cantor_surjective {α} (f : α → set α) : ¬ function.surjective f | h := let ⟨D, e⟩ := h (λ a, ¬ f a a) in (iff_not_self (f D D)).1 $ iff_of_eq (congr_fun e D) /-- **Cantor's diagonal argument** implies that there are no injective functions from `set α` to `α`. -/ theorem cantor_injective {α : Type*} (f : (set α) → α) : ¬ function.injective f | i := cantor_surjective (λ a b, ∀ U, a = f U → U b) $ right_inverse.surjective (λ U, funext $ λ a, propext ⟨λ h, h U rfl, λ h' U' e, i e ▸ h'⟩) /-- `g` is a partial inverse to `f` (an injective but not necessarily surjective function) if `g y = some x` implies `f x = y`, and `g y = none` implies that `y` is not in the range of `f`. -/ def is_partial_inv {α β} (f : α → β) (g : β → option α) : Prop := ∀ x y, g y = some x ↔ f x = y theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x := (H _ _).2 rfl theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f := λ a b h, option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl) theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g) (x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y := ((H _ _).1 h₁).symm.trans ((H _ _).1 h₂) theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id := funext h theorem left_inverse_iff_comp {f : α → β} {g : β → α} : left_inverse f g ↔ f ∘ g = id := ⟨left_inverse.comp_eq_id, congr_fun⟩ theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id := funext h theorem right_inverse_iff_comp {f : α → β} {g : β → α} : right_inverse f g ↔ g ∘ f = id := ⟨right_inverse.comp_eq_id, congr_fun⟩ theorem left_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) := assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a] theorem right_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) := left_inverse.comp hh hf theorem left_inverse.right_inverse {f : α → β} {g : β → α} (h : left_inverse g f) : right_inverse f g := h theorem right_inverse.left_inverse {f : α → β} {g : β → α} (h : right_inverse g f) : left_inverse f g := h theorem left_inverse.surjective {f : α → β} {g : β → α} (h : left_inverse f g) : surjective f := h.right_inverse.surjective theorem right_inverse.injective {f : α → β} {g : β → α} (h : right_inverse f g) : injective f := h.left_inverse.injective theorem left_inverse.right_inverse_of_injective {f : α → β} {g : β → α} (h : left_inverse f g) (hf : injective f) : right_inverse f g := λ x, hf $ h (f x) theorem left_inverse.right_inverse_of_surjective {f : α → β} {g : β → α} (h : left_inverse f g) (hg : surjective g) : right_inverse f g := λ x, let ⟨y, hy⟩ := hg x in hy ▸ congr_arg g (h y) theorem left_inverse.eq_right_inverse {f : α → β} {g₁ g₂ : β → α} (h₁ : left_inverse g₁ f) (h₂ : right_inverse g₂ f) : g₁ = g₂ := calc g₁ = g₁ ∘ f ∘ g₂ : by rw [h₂.comp_eq_id, comp.right_id] ... = g₂ : by rw [← comp.assoc, h₁.comp_eq_id, comp.left_id] local attribute [instance, priority 10] classical.prop_decidable /-- We can use choice to construct explicitly a partial inverse for a given injective function `f`. -/ noncomputable def partial_inv {α β} (f : α → β) (b : β) : option α := if h : ∃ a, f a = b then some (classical.some h) else none theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) : is_partial_inv f (partial_inv f) | a b := ⟨λ h, if h' : ∃ a, f a = b then begin rw [partial_inv, dif_pos h'] at h, injection h with h, subst h, apply classical.some_spec h' end else by rw [partial_inv, dif_neg h'] at h; contradiction, λ e, e ▸ have h : ∃ a', f a' = f a, from ⟨_, rfl⟩, (dif_pos h).trans (congr_arg _ (I $ classical.some_spec h))⟩ theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x := is_partial_inv_left (partial_inv_of_injective I) end section inv_fun variables {α : Type u} [n : nonempty α] {β : Sort v} {f : α → β} {s : set α} {a : α} {b : β} include n local attribute [instance, priority 10] classical.prop_decidable /-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f` on `f '' s`. For a computable version, see `function.injective.inv_of_mem_range`. -/ noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then classical.some h else classical.choice n theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_eq' (h : ∀ (x ∈ s) (y ∈ s), f x = f y → x = y) (ha : a ∈ s) : inv_fun_on f s (f a) = a := have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩, h _ (inv_fun_on_mem this) _ ha (inv_fun_on_eq this) theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = classical.choice n := by rw [bex_def] at h; rw [inv_fun_on, dif_neg h] /-- The inverse of a function (which is a left inverse if `f` is injective and a right inverse if `f` is surjective). -/ noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b := inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩ lemma inv_fun_neg (h : ¬ ∃ a, f a = b) : inv_fun f b = classical.choice n := by refine inv_fun_on_neg (mt _ h); exact assume ⟨a, _, ha⟩, ⟨a, ha⟩ theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g := funext $ assume b, hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f := assume b, inv_fun_eq $ hf b lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f := assume b, have f (inv_fun f (f b)) = f b, from inv_fun_eq ⟨b, rfl⟩, hf this lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) := (left_inverse_inv_fun hf).surjective lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf end inv_fun section inv_fun variables {α : Type u} [nonempty α] {β : Sort v} {f : α → β} lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f := ⟨inv_fun f, left_inverse_inv_fun hf⟩ lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f := ⟨injective.has_left_inverse, has_left_inverse.injective⟩ end inv_fun section surj_inv variables {α : Sort u} {β : Sort v} {f : α → β} /-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require `α` to be inhabited.) -/ noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b) lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := classical.some_spec (h b) lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f := surj_inv_eq hf lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f := right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2) lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f := ⟨_, right_inverse_surj_inv hf⟩ lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f := ⟨surjective.has_right_inverse, has_right_inverse.surjective⟩ lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f := ⟨λ hf, ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩, λ ⟨g, gl, gr⟩, ⟨gl.injective, gr.surjective⟩⟩ lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) := (right_inverse_surj_inv h).injective lemma surjective_to_subsingleton [na : nonempty α] [subsingleton β] (f : α → β) : surjective f := λ y, let ⟨a⟩ := na in ⟨a, subsingleton.elim _ _⟩ end surj_inv section update variables {α : Sort u} {β : α → Sort v} {α' : Sort w} [decidable_eq α] [decidable_eq α'] /-- Replacing the value of a function at a given point by a given value. -/ def update (f : Πa, β a) (a' : α) (v : β a') (a : α) : β a := if h : a = a' then eq.rec v h.symm else f a /-- On non-dependent functions, `function.update` can be expressed as an `ite` -/ lemma update_apply {β : Sort*} (f : α → β) (a' : α) (b : β) (a : α) : update f a' b a = if a = a' then b else f a := begin dunfold update, congr, funext, rw eq_rec_constant, end @[simp] lemma update_same (a : α) (v : β a) (f : Πa, β a) : update f a v a = v := dif_pos rfl lemma surjective_eval {α : Sort u} {β : α → Sort v} [h : Π a, nonempty (β a)] (a : α) : surjective (eval a : (Π a, β a) → β a) := λ b, ⟨@update _ _ (classical.dec_eq α) (λ a, (h a).some) a b, @update_same _ _ (classical.dec_eq α) _ _ _⟩ lemma update_injective (f : Πa, β a) (a' : α) : injective (update f a') := λ v v' h, have _ := congr_fun h a', by rwa [update_same, update_same] at this @[simp] lemma update_noteq {a a' : α} (h : a ≠ a') (v : β a') (f : Πa, β a) : update f a' v a = f a := dif_neg h lemma forall_update_iff (f : Π a, β a) {a : α} {b : β a} (p : Π a, β a → Prop) : (∀ x, p x (update f a b x)) ↔ p a b ∧ ∀ x ≠ a, p x (f x) := by { rw [← and_forall_ne a, update_same], simp { contextual := tt } } lemma exists_update_iff (f : Π a, β a) {a : α} {b : β a} (p : Π a, β a → Prop) : (∃ x, p x (update f a b x)) ↔ p a b ∨ ∃ x ≠ a, p x (f x) := by { rw [← not_forall_not, forall_update_iff f (λ a b, ¬p a b)], simp [not_and_distrib] } lemma update_eq_iff {a : α} {b : β a} {f g : Π a, β a} : update f a b = g ↔ b = g a ∧ ∀ x ≠ a, f x = g x := funext_iff.trans $ forall_update_iff _ (λ x y, y = g x) lemma eq_update_iff {a : α} {b : β a} {f g : Π a, β a} : g = update f a b ↔ g a = b ∧ ∀ x ≠ a, g x = f x := funext_iff.trans $ forall_update_iff _ (λ x y, g x = y) @[simp] lemma update_eq_self (a : α) (f : Πa, β a) : update f a (f a) = f := update_eq_iff.2 ⟨rfl, λ _ _, rfl⟩ lemma update_comp_eq_of_forall_ne' {α'} (g : Π a, β a) {f : α' → α} {i : α} (a : β i) (h : ∀ x, f x ≠ i) : (λ j, (update g i a) (f j)) = (λ j, g (f j)) := funext $ λ x, update_noteq (h _) _ _ /-- Non-dependent version of `function.update_comp_eq_of_forall_ne'` -/ lemma update_comp_eq_of_forall_ne {α β : Sort*} (g : α' → β) {f : α → α'} {i : α'} (a : β) (h : ∀ x, f x ≠ i) : (update g i a) ∘ f = g ∘ f := update_comp_eq_of_forall_ne' g a h lemma update_comp_eq_of_injective' (g : Π a, β a) {f : α' → α} (hf : function.injective f) (i : α') (a : β (f i)) : (λ j, update g (f i) a (f j)) = update (λ i, g (f i)) i a := eq_update_iff.2 ⟨update_same _ _ _, λ j hj, update_noteq (hf.ne hj) _ _⟩ /-- Non-dependent version of `function.update_comp_eq_of_injective'` -/ lemma update_comp_eq_of_injective {β : Sort*} (g : α' → β) {f : α → α'} (hf : function.injective f) (i : α) (a : β) : (function.update g (f i) a) ∘ f = function.update (g ∘ f) i a := update_comp_eq_of_injective' g hf i a lemma apply_update {ι : Sort*} [decidable_eq ι] {α β : ι → Sort*} (f : Π i, α i → β i) (g : Π i, α i) (i : ι) (v : α i) (j : ι) : f j (update g i v j) = update (λ k, f k (g k)) i (f i v) j := begin by_cases h : j = i, { subst j, simp }, { simp [h] } end lemma apply_update₂ {ι : Sort*} [decidable_eq ι] {α β γ : ι → Sort*} (f : Π i, α i → β i → γ i) (g : Π i, α i) (h : Π i, β i) (i : ι) (v : α i) (w : β i) (j : ι) : f j (update g i v j) (update h i w j) = update (λ k, f k (g k) (h k)) i (f i v w) j := begin by_cases h : j = i, { subst j, simp }, { simp [h] } end lemma comp_update {α' : Sort*} {β : Sort*} (f : α' → β) (g : α → α') (i : α) (v : α') : f ∘ (update g i v) = update (f ∘ g) i (f v) := funext $ apply_update _ _ _ _ theorem update_comm {α} [decidable_eq α] {β : α → Sort*} {a b : α} (h : a ≠ b) (v : β a) (w : β b) (f : Πa, β a) : update (update f a v) b w = update (update f b w) a v := begin funext c, simp only [update], by_cases h₁ : c = b; by_cases h₂ : c = a; try {simp [h₁, h₂]}, cases h (h₂.symm.trans h₁), end @[simp] theorem update_idem {α} [decidable_eq α] {β : α → Sort*} {a : α} (v w : β a) (f : Πa, β a) : update (update f a v) a w = update f a w := by {funext b, by_cases b = a; simp [update, h]} end update section extend noncomputable theory local attribute [instance, priority 10] classical.prop_decidable variables {α β γ : Sort*} {f : α → β} /-- `extend f g e'` extends a function `g : α → γ` along a function `f : α → β` to a function `β → γ`, by using the values of `g` on the range of `f` and the values of an auxiliary function `e' : β → γ` elsewhere. Mostly useful when `f` is injective. -/ def extend (f : α → β) (g : α → γ) (e' : β → γ) : β → γ := λ b, if h : ∃ a, f a = b then g (classical.some h) else e' b lemma extend_def (f : α → β) (g : α → γ) (e' : β → γ) (b : β) [decidable (∃ a, f a = b)] : extend f g e' b = if h : ∃ a, f a = b then g (classical.some h) else e' b := by { unfold extend, congr } @[simp] lemma extend_apply (hf : injective f) (g : α → γ) (e' : β → γ) (a : α) : extend f g e' (f a) = g a := begin simp only [extend_def, dif_pos, exists_apply_eq_apply], exact congr_arg g (hf $ classical.some_spec (exists_apply_eq_apply f a)) end @[simp] lemma extend_apply' (g : α → γ) (e' : β → γ) (b : β) (hb : ¬∃ a, f a = b) : extend f g e' b = e' b := by simp [function.extend_def, hb] lemma extend_injective (hf : injective f) (e' : β → γ) : injective (λ g, extend f g e') := begin intros g₁ g₂ hg, refine funext (λ x, _), have H := congr_fun hg (f x), simp only [hf, extend_apply] at H, exact H end @[simp] lemma extend_comp (hf : injective f) (g : α → γ) (e' : β → γ) : extend f g e' ∘ f = g := funext $ λ a, extend_apply hf g e' a end extend lemma uncurry_def {α β γ} (f : α → β → γ) : uncurry f = (λp, f p.1 p.2) := rfl @[simp] lemma uncurry_apply_pair {α β γ} (f : α → β → γ) (x : α) (y : β) : uncurry f (x, y) = f x y := rfl @[simp] lemma curry_apply {α β γ} (f : α × β → γ) (x : α) (y : β) : curry f x y = f (x, y) := rfl section bicomp variables {α β γ δ ε : Type*} /-- Compose a binary function `f` with a pair of unary functions `g` and `h`. If both arguments of `f` have the same type and `g = h`, then `bicompl f g g = f on g`. -/ def bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a b) := f (g a) (h b) /-- Compose an unary function `f` with a binary function `g`. -/ def bicompr (f : γ → δ) (g : α → β → γ) (a b) := f (g a b) -- Suggested local notation: local notation f `∘₂` g := bicompr f g lemma uncurry_bicompr (f : α → β → γ) (g : γ → δ) : uncurry (g ∘₂ f) = (g ∘ uncurry f) := rfl lemma uncurry_bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) : uncurry (bicompl f g h) = (uncurry f) ∘ (prod.map g h) := rfl end bicomp section uncurry variables {α β γ δ : Type*} /-- Records a way to turn an element of `α` into a function from `β` to `γ`. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/ class has_uncurry (α : Type*) (β : out_param Type*) (γ : out_param Type*) := (uncurry : α → (β → γ)) /-- Uncurrying operator. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps.-/ add_decl_doc has_uncurry.uncurry notation `↿`:max x:max := has_uncurry.uncurry x instance has_uncurry_base : has_uncurry (α → β) α β := ⟨id⟩ instance has_uncurry_induction [has_uncurry β γ δ] : has_uncurry (α → β) (α × γ) δ := ⟨λ f p, ↿(f p.1) p.2⟩ end uncurry /-- A function is involutive, if `f ∘ f = id`. -/ def involutive {α} (f : α → α) : Prop := ∀ x, f (f x) = x lemma involutive_iff_iter_2_eq_id {α} {f : α → α} : involutive f ↔ (f^[2] = id) := funext_iff.symm namespace involutive variables {α : Sort u} {f : α → α} (h : involutive f) include h @[simp] lemma comp_self : f ∘ f = id := funext h protected lemma left_inverse : left_inverse f f := h protected lemma right_inverse : right_inverse f f := h protected lemma injective : injective f := h.left_inverse.injective protected lemma surjective : surjective f := λ x, ⟨f x, h x⟩ protected lemma bijective : bijective f := ⟨h.injective, h.surjective⟩ /-- Involuting an `ite` of an involuted value `x : α` negates the `Prop` condition in the `ite`. -/ protected lemma ite_not (P : Prop) [decidable P] (x : α) : f (ite P x (f x)) = ite (¬ P) x (f x) := by rw [apply_ite f, h, ite_not] /-- An involution commutes across an equality. Compare to `function.injective.eq_iff`. -/ protected lemma eq_iff {x y : α} : f x = y ↔ x = f y := h.injective.eq_iff' (h y) end involutive /-- The property of a binary function `f : α → β → γ` being injective. Mathematically this should be thought of as the corresponding function `α × β → γ` being injective. -/ @[reducible] def injective2 {α β γ} (f : α → β → γ) : Prop := ∀ ⦃a₁ a₂ b₁ b₂⦄, f a₁ b₁ = f a₂ b₂ → a₁ = a₂ ∧ b₁ = b₂ namespace injective2 variables {α β γ : Type*} (f : α → β → γ) protected lemma left (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : a₁ = a₂ := (hf h).1 protected lemma right (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : b₁ = b₂ := (hf h).2 lemma eq_iff (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ : f a₁ b₁ = f a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ h, hf h, λ⟨h1, h2⟩, congr_arg2 f h1 h2⟩ end injective2 section sometimes local attribute [instance, priority 10] classical.prop_decidable /-- `sometimes f` evaluates to some value of `f`, if it exists. This function is especially interesting in the case where `α` is a proposition, in which case `f` is necessarily a constant function, so that `sometimes f = f a` for all `a`. -/ noncomputable def sometimes {α β} [nonempty β] (f : α → β) : β := if h : nonempty α then f (classical.choice h) else classical.choice ‹_› theorem sometimes_eq {p : Prop} {α} [nonempty α] (f : p → α) (a : p) : sometimes f = f a := dif_pos ⟨a⟩ theorem sometimes_spec {p : Prop} {α} [nonempty α] (P : α → Prop) (f : p → α) (a : p) (h : P (f a)) : P (sometimes f) := by rwa sometimes_eq end sometimes end function /-- `s.piecewise f g` is the function equal to `f` on the set `s`, and to `g` on its complement. -/ def set.piecewise {α : Type u} {β : α → Sort v} (s : set α) (f g : Πi, β i) [∀j, decidable (j ∈ s)] : Πi, β i := λi, if i ∈ s then f i else g i /-! ### Bijectivity of `eq.rec`, `eq.mp`, `eq.mpr`, and `cast` -/ lemma eq_rec_on_bijective {α : Sort*} {C : α → Sort*} : ∀ {a a' : α} (h : a = a'), function.bijective (@eq.rec_on _ _ C _ h) | _ _ rfl := ⟨λ x y, id, λ x, ⟨x, rfl⟩⟩ lemma eq_mp_bijective {α β : Sort*} (h : α = β) : function.bijective (eq.mp h) := eq_rec_on_bijective h lemma eq_mpr_bijective {α β : Sort*} (h : α = β) : function.bijective (eq.mpr h) := eq_rec_on_bijective h.symm lemma cast_bijective {α β : Sort*} (h : α = β) : function.bijective (cast h) := eq_rec_on_bijective h /-! Note these lemmas apply to `Type*` not `Sort*`, as the latter interferes with `simp`, and is trivial anyway.-/ @[simp] lemma eq_rec_inj {α : Sort*} {a a' : α} (h : a = a') {C : α → Type*} (x y : C a) : (eq.rec x h : C a') = eq.rec y h ↔ x = y := (eq_rec_on_bijective h).injective.eq_iff @[simp] lemma cast_inj {α β : Type*} (h : α = β) {x y : α} : cast h x = cast h y ↔ x = y := (cast_bijective h).injective.eq_iff /-- A set of functions "separates points" if for each pair of distinct points there is a function taking different values on them. -/ def set.separates_points {α β : Type*} (A : set (α → β)) : Prop := ∀ ⦃x y : α⦄, x ≠ y → ∃ f ∈ A, (f x : β) ≠ f y lemma is_symm_op.flip_eq {α β} (op) [is_symm_op α β op] : flip op = op := funext $ λ a, funext $ λ b, (is_symm_op.symm_op a b).symm
56c15a499373da4cdfb3371e783a891934a6c9a0
83bd63fd58ebbb33f769cbf6d6a67463ba1bc637
/src/day_1/intro_test.lean
45dc9d4721e83ff67d109ad3df680e30d0ef308f
[]
no_license
Wornbard/mbl_lean_workshop
6ebdafebac74f1b1148f67a528242a3687af17e1
6b68ce25fdc49043fd5ab409de8e4a2987def22e
refs/heads/main
1,690,205,591,845
1,630,953,271,000
1,630,953,271,000
403,417,180
0
0
null
null
null
null
UTF-8
Lean
false
false
863
lean
import tactic --If the above returns an error, you probably didn't install mathlib correctly. Consult the instruction in README carefully --If you think you did everything correctly, consult me (Jakub Wornbard) on Facebook or however else you like --You should see the `Lean Infoview` window on the right of the screen. --If you don't, you may try `ctrl+shift+enter` --If you still don't see it, something is probably wrong. Make sure you installed the Lean extension in VS Code #eval 2+2 --If you put the cursor at the end of the line above, you should see the result in the Infoview variable (P : Prop) example : P→P := begin --the state of the Infoview should change as you move the cursor down the next few lines. --after the last comma, it should say `goals accompished` intro hP, assumption, end --If all of that works you're good to go
78ae5e9d2e149111629f3ad7d39e1c8f5854c9aa
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/group_theory/dihedral_auto.lean
2b3cad7cec2938c17b5c0bc85e32649bcea38005
[]
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
3,357
lean
/- Copyright (c) 2020 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.zmod.basic import Mathlib.group_theory.order_of_element import Mathlib.PostPort universes l namespace Mathlib /-! # Dihedral Groups We define the dihedral groups `dihedral n`, with elements `r i` and `sr i` for `i : zmod n`. For `n ≠ 0`, `dihedral n` represents the symmetry group of the regular `n`-gon. `r i` represents the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon. `dihedral 0` corresponds to the infinite dihedral group. -/ /-- For `n ≠ 0`, `dihedral n` represents the symmetry group of the regular `n`-gon. `r i` represents the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon. `dihedral 0` corresponds to the infinite dihedral group. -/ inductive dihedral (n : ℕ) where | r : zmod n → dihedral n | sr : zmod n → dihedral n namespace dihedral /-- Multiplication of the dihedral group. -/ /-- The identity `1` is the rotation by `0`. -/ protected instance inhabited {n : ℕ} : Inhabited (dihedral n) := { default := one } /-- The inverse of a an element of the dihedral group. -/ /-- The group structure on `dihedral n`. -/ protected instance group {n : ℕ} : group (dihedral n) := group.mk mul sorry one sorry sorry inv (div_inv_monoid.div._default mul sorry one sorry sorry inv) sorry @[simp] theorem r_mul_r {n : ℕ} (i : zmod n) (j : zmod n) : r i * r j = r (i + j) := rfl @[simp] theorem r_mul_sr {n : ℕ} (i : zmod n) (j : zmod n) : r i * sr j = sr (j - i) := rfl @[simp] theorem sr_mul_r {n : ℕ} (i : zmod n) (j : zmod n) : sr i * r j = sr (i + j) := rfl @[simp] theorem sr_mul_sr {n : ℕ} (i : zmod n) (j : zmod n) : sr i * sr j = r (j - i) := rfl theorem one_def {n : ℕ} : 1 = r 0 := rfl /-- If `0 < n`, then `dihedral n` is a finite group. -/ protected instance fintype {n : ℕ} [fact (0 < n)] : fintype (dihedral n) := fintype.of_equiv (zmod n ⊕ zmod n) fintype_helper protected instance nontrivial {n : ℕ} : nontrivial (dihedral n) := nontrivial.mk (Exists.intro (r 0) (Exists.intro (sr 0) (of_as_true trivial))) /-- If `0 < n`, then `dihedral n` has `2n` elements. -/ theorem card {n : ℕ} [fact (0 < n)] : fintype.card (dihedral n) = bit0 1 * n := sorry @[simp] theorem r_one_pow {n : ℕ} (k : ℕ) : r 1 ^ k = r ↑k := sorry @[simp] theorem r_one_pow_n {n : ℕ} : r 1 ^ n = 1 := sorry @[simp] theorem sr_mul_self {n : ℕ} (i : zmod n) : sr i * sr i = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (sr i * sr i = 1)) (sr_mul_sr i i))) (eq.mpr (id (Eq._oldrec (Eq.refl (r (i - i) = 1)) (sub_self i))) (eq.mpr (id (Eq._oldrec (Eq.refl (r 0 = 1)) one_def)) (Eq.refl (r 0)))) /-- If `0 < n`, then `sr i` has order 2. -/ @[simp] theorem order_of_sr {n : ℕ} [fact (0 < n)] (i : zmod n) : order_of (sr i) = bit0 1 := sorry /-- If `0 < n`, then `r 1` has order `n`. -/ @[simp] theorem order_of_r_one {n : ℕ} [hnpos : fact (0 < n)] : order_of (r 1) = n := sorry /-- If `0 < n`, then `i : zmod n` has order `n / gcd n i` -/ theorem order_of_r {n : ℕ} [fact (0 < n)] (i : zmod n) : order_of (r i) = n / nat.gcd n (zmod.val i) := sorry end Mathlib
0384f54264e161785aab254cfbefc00f4a1a9210
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/algebra/iterate_hom.lean
a465d5f1e84727cdf944f8c5038f26d0f6f71a11
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,841
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov -/ import algebra.group_power import logic.function.iterate import group_theory.perm.basic /-! # Iterates of monoid and ring homomorphisms Iterate of a monoid/ring homomorphism is a monoid/ring homomorphism but it has a wrong type, so Lean can't apply lemmas like `monoid_hom.map_one` to `f^[n] 1`. Though it is possible to define a monoid structure on the endomorphisms, quite often we do not want to convert from `M →* M` to (not yet defined) `monoid.End M` and from `f^[n]` to `f^n` just to apply a simple lemma. So, we restate standard `*_hom.map_*` lemmas under names `*_hom.iterate_map_*`. We also prove formulas for iterates of add/mul left/right. ## Tags homomorphism, iterate -/ open function variables {M : Type*} {N : Type*} {G : Type*} {H : Type*} /-- An auxiliary lemma that can be used to prove `⇑(f ^ n) = (⇑f^[n])`. -/ lemma hom_coe_pow {F : Type*} [monoid F] (c : F → M → M) (h1 : c 1 = id) (hmul : ∀ f g, c (f * g) = c f ∘ c g) (f : F) : ∀ n, c (f ^ n) = (c f^[n]) | 0 := h1 | (n + 1) := by rw [pow_succ, iterate_succ', hmul, hom_coe_pow] namespace monoid_hom variables [monoid M] [monoid N] [group G] [group H] @[simp, to_additive] theorem iterate_map_one (f : M →* M) (n : ℕ) : f^[n] 1 = 1 := iterate_fixed f.map_one n @[simp, to_additive] theorem iterate_map_mul (f : M →* M) (n : ℕ) (x y) : f^[n] (x * y) = (f^[n] x) * (f^[n] y) := semiconj₂.iterate f.map_mul n x y @[simp, to_additive] theorem iterate_map_inv (f : G →* G) (n : ℕ) (x) : f^[n] (x⁻¹) = (f^[n] x)⁻¹ := commute.iterate_left f.map_inv n x theorem iterate_map_pow (f : M →* M) (a) (n m : ℕ) : f^[n] (a^m) = (f^[n] a)^m := commute.iterate_left (λ x, f.map_pow x m) n a theorem iterate_map_gpow (f : G →* G) (a) (n : ℕ) (m : ℤ) : f^[n] (a^m) = (f^[n] a)^m := commute.iterate_left (λ x, f.map_gpow x m) n a lemma coe_pow {M} [comm_monoid M] (f : monoid.End M) (n : ℕ) : ⇑(f^n) = (f^[n]) := hom_coe_pow _ rfl (λ f g, rfl) _ _ end monoid_hom namespace add_monoid_hom variables [add_monoid M] [add_monoid N] [add_group G] [add_group H] @[simp] theorem iterate_map_sub (f : G →+ G) (n : ℕ) (x y) : f^[n] (x - y) = (f^[n] x) - (f^[n] y) := semiconj₂.iterate f.map_sub n x y theorem iterate_map_smul (f : M →+ M) (n m : ℕ) (x : M) : f^[n] (m •ℕ x) = m •ℕ (f^[n] x) := f.to_multiplicative.iterate_map_pow x n m theorem iterate_map_gsmul (f : G →+ G) (n : ℕ) (m : ℤ) (x : G) : f^[n] (m •ℤ x) = m •ℤ (f^[n] x) := f.to_multiplicative.iterate_map_gpow x n m end add_monoid_hom namespace ring_hom section semiring variables {R : Type*} [semiring R] (f : R →+* R) (n : ℕ) (x y : R) lemma coe_pow (n : ℕ) : ⇑(f^n) = (f^[n]) := hom_coe_pow _ rfl (λ f g, rfl) f n theorem iterate_map_one : f^[n] 1 = 1 := f.to_monoid_hom.iterate_map_one n theorem iterate_map_zero : f^[n] 0 = 0 := f.to_add_monoid_hom.iterate_map_zero n theorem iterate_map_add : f^[n] (x + y) = (f^[n] x) + (f^[n] y) := f.to_add_monoid_hom.iterate_map_add n x y theorem iterate_map_mul : f^[n] (x * y) = (f^[n] x) * (f^[n] y) := f.to_monoid_hom.iterate_map_mul n x y theorem iterate_map_pow (a) (n m : ℕ) : f^[n] (a^m) = (f^[n] a)^m := f.to_monoid_hom.iterate_map_pow a n m theorem iterate_map_smul (n m : ℕ) (x : R) : f^[n] (m •ℕ x) = m •ℕ (f^[n] x) := f.to_add_monoid_hom.iterate_map_smul n m x end semiring variables {R : Type*} [ring R] (f : R →+* R) (n : ℕ) (x y : R) theorem iterate_map_sub : f^[n] (x - y) = (f^[n] x) - (f^[n] y) := f.to_add_monoid_hom.iterate_map_sub n x y theorem iterate_map_neg : f^[n] (-x) = -(f^[n] x) := f.to_add_monoid_hom.iterate_map_neg n x theorem iterate_map_gsmul (n : ℕ) (m : ℤ) (x : R) : f^[n] (m •ℤ x) = m •ℤ (f^[n] x) := f.to_add_monoid_hom.iterate_map_gsmul n m x end ring_hom lemma equiv.perm.coe_pow {α : Type*} (f : equiv.perm α) (n : ℕ) : ⇑(f ^ n) = (f^[n]) := hom_coe_pow _ rfl (λ _ _, rfl) _ _ @[simp] lemma mul_left_iterate [monoid M] (a : M) (n : ℕ) : ((*) a)^[n] = (*) (a^n) := nat.rec_on n (funext $ λ x, by simp) $ λ n ihn, funext $ λ x, by simp [iterate_succ, ihn, pow_succ', mul_assoc] @[simp] lemma add_left_iterate [add_monoid M] (a : M) (n : ℕ) : ((+) a)^[n] = (+) (n •ℕ a) := @mul_left_iterate (multiplicative M) _ a n @[simp] lemma mul_right_iterate [monoid M] (a : M) (n : ℕ) : (λ x, x * a)^[n] = (λ x, x * a^n) := nat.rec_on n (funext $ λ x, by simp) $ λ n ihn, funext $ λ x, by simp [iterate_succ, ihn, pow_succ, mul_assoc] @[simp] lemma add_right_iterate [add_monoid M] (a : M) (n : ℕ) : (λ x, x + a)^[n] = λ x, x + (n •ℕ a) := @mul_right_iterate (multiplicative M) _ a n
6ce3a88f089a13f6dec2e2c9a7e32907b9df2085
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed_space/star/gelfand_duality.lean
b7096eee0179c11764e432b6efecc9355dfd6d89
[ "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
10,705
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Reeased under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.star.spectrum import analysis.normed.group.quotient import analysis.normed_space.algebra import topology.continuous_function.units import topology.continuous_function.compact import topology.algebra.algebra import topology.continuous_function.stone_weierstrass /-! # Gelfand Duality The `gelfand_transform` is an algebra homomorphism from a topological `𝕜`-algebra `A` to `C(character_space 𝕜 A, 𝕜)`. In the case where `A` is a commutative complex Banach algebra, then the Gelfand transform is actually spectrum-preserving (`spectrum.gelfand_transform_eq`). Moreover, when `A` is a commutative C⋆-algebra over `ℂ`, then the Gelfand transform is a surjective isometry, and even an equivalence between C⋆-algebras. ## Main definitions * `ideal.to_character_space` : constructs an element of the character space from a maximal ideal in a commutative complex Banach algebra * `weak_dual.character_space.comp_continuous_map`: The functorial map taking `ψ : A →⋆ₐ[ℂ] B` to a continuous function `character_space ℂ B → character_space ℂ A` given by pre-composition with `ψ`. ## Main statements * `spectrum.gelfand_transform_eq` : the Gelfand transform is spectrum-preserving when the algebra is a commutative complex Banach algebra. * `gelfand_transform_isometry` : the Gelfand transform is an isometry when the algebra is a commutative (unital) C⋆-algebra over `ℂ`. * `gelfand_transform_bijective` : the Gelfand transform is bijective when the algebra is a commutative (unital) C⋆-algebra over `ℂ`. ## TODO * After `star_alg_equiv` is defined, realize `gelfand_transform` as a `star_alg_equiv`. * Prove that if `A` is the unital C⋆-algebra over `ℂ` generated by a fixed normal element `x` in a larger C⋆-algebra `B`, then `character_space ℂ A` is homeomorphic to `spectrum ℂ x`. * From the previous result, construct the **continuous functional calculus**. * Show that if `X` is a compact Hausdorff space, then `X` is (canonically) homeomorphic to `character_space ℂ C(X, ℂ)`. * Conclude using the previous fact that the functors `C(⬝, ℂ)` and `character_space ℂ ⬝` along with the canonical homeomorphisms described above constitute a natural contravariant equivalence of the categories of compact Hausdorff spaces (with continuous maps) and commutative unital C⋆-algebras (with unital ⋆-algebra homomoprhisms); this is known as **Gelfand duality**. ## Tags Gelfand transform, character space, C⋆-algebra -/ open weak_dual open_locale nnreal section complex_banach_algebra open ideal variables {A : Type*} [normed_comm_ring A] [normed_algebra ℂ A] [complete_space A] (I : ideal A) [ideal.is_maximal I] /-- Every maximal ideal in a commutative complex Banach algebra gives rise to a character on that algebra. In particular, the character, which may be identified as an algebra homomorphism due to `weak_dual.character_space.equiv_alg_hom`, is given by the composition of the quotient map and the Gelfand-Mazur isomorphism `normed_ring.alg_equiv_complex_of_complete`. -/ noncomputable def ideal.to_character_space : character_space ℂ A := character_space.equiv_alg_hom.symm $ ((@normed_ring.alg_equiv_complex_of_complete (A ⧸ I) _ _ (by { letI := quotient.field I, exact @is_unit_iff_ne_zero (A ⧸ I) _ }) _).symm : A ⧸ I →ₐ[ℂ] ℂ).comp (quotient.mkₐ ℂ I) lemma ideal.to_character_space_apply_eq_zero_of_mem {a : A} (ha : a ∈ I) : I.to_character_space a = 0 := begin unfold ideal.to_character_space, simpa only [character_space.equiv_alg_hom_symm_coe, alg_hom.coe_comp, alg_equiv.coe_alg_hom, quotient.mkₐ_eq_mk, function.comp_app, quotient.eq_zero_iff_mem.mpr ha, spectrum.zero_eq, normed_ring.alg_equiv_complex_of_complete_symm_apply] using set.eq_of_mem_singleton (set.singleton_nonempty (0 : ℂ)).some_mem, end /-- If `a : A` is not a unit, then some character takes the value zero at `a`. This is equivlaent to `gelfand_transform ℂ A a` takes the value zero at some character. -/ lemma weak_dual.character_space.exists_apply_eq_zero {a : A} (ha : ¬ is_unit a) : ∃ f : character_space ℂ A, f a = 0 := begin unfreezingI { obtain ⟨M, hM, haM⟩ := (span {a}).exists_le_maximal (span_singleton_ne_top ha) }, exact ⟨M.to_character_space, M.to_character_space_apply_eq_zero_of_mem (haM (mem_span_singleton.mpr ⟨1, (mul_one a).symm⟩))⟩, end /-- The Gelfand transform is spectrum-preserving. -/ lemma spectrum.gelfand_transform_eq (a : A) : spectrum ℂ (gelfand_transform ℂ A a) = spectrum ℂ a := begin refine set.subset.antisymm (alg_hom.spectrum_apply_subset (gelfand_transform ℂ A) a) (λ z hz, _), obtain ⟨f, hf⟩ := weak_dual.character_space.exists_apply_eq_zero hz, simp only [map_sub, sub_eq_zero, alg_hom_class.commutes, algebra.id.map_eq_id, ring_hom.id_apply] at hf, exact (continuous_map.spectrum_eq_range (gelfand_transform ℂ A a)).symm ▸ ⟨f, hf.symm⟩, end instance [nontrivial A] : nonempty (character_space ℂ A) := ⟨classical.some $ weak_dual.character_space.exists_apply_eq_zero $ zero_mem_nonunits.2 zero_ne_one⟩ end complex_banach_algebra section complex_cstar_algebra variables {A : Type*} [normed_comm_ring A] [normed_algebra ℂ A] [complete_space A] variables [star_ring A] [cstar_ring A] [star_module ℂ A] lemma gelfand_transform_map_star (a : A) : gelfand_transform ℂ A (star a) = star (gelfand_transform ℂ A a) := continuous_map.ext $ λ φ, map_star φ a variable (A) /-- The Gelfand transform is an isometry when the algebra is a C⋆-algebra over `ℂ`. -/ lemma gelfand_transform_isometry : isometry (gelfand_transform ℂ A) := begin nontriviality A, refine add_monoid_hom_class.isometry_of_norm (gelfand_transform ℂ A) (λ a, _), /- By `spectrum.gelfand_transform_eq`, the spectra of `star a * a` and its `gelfand_transform` coincide. Therefore, so do their spectral radii, and since they are self-adjoint, so also do their norms. Applying the C⋆-property of the norm and taking square roots shows that the norm is preserved. -/ have : spectral_radius ℂ (gelfand_transform ℂ A (star a * a)) = spectral_radius ℂ (star a * a), { unfold spectral_radius, rw spectrum.gelfand_transform_eq, }, simp only [map_mul, (is_self_adjoint.star_mul_self _).spectral_radius_eq_nnnorm, gelfand_transform_map_star a, ennreal.coe_eq_coe, cstar_ring.nnnorm_star_mul_self, ←sq] at this, simpa only [function.comp_app, nnreal.sqrt_sq] using congr_arg ((coe : ℝ≥0 → ℝ) ∘ ⇑nnreal.sqrt) this, end /-- The Gelfand transform is bijective when the algebra is a C⋆-algebra over `ℂ`. -/ lemma gelfand_transform_bijective : function.bijective (gelfand_transform ℂ A) := begin refine ⟨(gelfand_transform_isometry A).injective, _⟩, suffices : (gelfand_transform ℂ A).range = ⊤, { exact λ x, this.symm ▸ (gelfand_transform ℂ A).mem_range.mp (this.symm ▸ algebra.mem_top) }, /- Because the `gelfand_transform ℂ A` is an isometry, it has closed range, and so by the Stone-Weierstrass theorem, it suffices to show that the image of the Gelfand transform separates points in `C(character_space ℂ A, ℂ)` and is closed under `star`. -/ have h : (gelfand_transform ℂ A).range.topological_closure = (gelfand_transform ℂ A).range, from le_antisymm (subalgebra.topological_closure_minimal _ le_rfl (gelfand_transform_isometry A).closed_embedding.closed_range) (subalgebra.subalgebra_topological_closure _), refine h ▸ continuous_map.subalgebra_is_R_or_C_topological_closure_eq_top_of_separates_points _ (λ _ _, _) (λ f hf, _), /- Separating points just means that elements of the `character_space` which agree at all points of `A` are the same functional, which is just extensionality. -/ { contrapose!, exact λ h, subtype.ext (continuous_linear_map.ext $ λ a, h (gelfand_transform ℂ A a) ⟨gelfand_transform ℂ A a, ⟨a, rfl⟩, rfl⟩), }, /- If `f = gelfand_transform ℂ A a`, then `star f` is also in the range of `gelfand_transform ℂ A` using the argument `star a`. The key lemma below may be hard to spot; it's `map_star` coming from `weak_dual.star_hom_class`, which is a nontrivial result. -/ { obtain ⟨f, ⟨a, rfl⟩, rfl⟩ := subalgebra.mem_map.mp hf, refine ⟨star a, continuous_map.ext $ λ ψ, _⟩, simpa only [gelfand_transform_map_star a, alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom] } end /-- The Gelfand transform as a `star_alg_equiv` between a commutative unital C⋆-algebra over `ℂ` and the continuous functions on its `character_space`. -/ @[simps] noncomputable def gelfand_star_transform : A ≃⋆ₐ[ℂ] C(character_space ℂ A, ℂ) := star_alg_equiv.of_bijective (show A →⋆ₐ[ℂ] C(character_space ℂ A, ℂ), from { map_star' := λ x, gelfand_transform_map_star x, .. gelfand_transform ℂ A }) (gelfand_transform_bijective A) end complex_cstar_algebra section functoriality namespace weak_dual namespace character_space variables {A B C : Type*} variables [normed_ring A] [normed_algebra ℂ A] [complete_space A] [star_ring A] variables [normed_ring B] [normed_algebra ℂ B] [complete_space B] [star_ring B] variables [normed_ring C] [normed_algebra ℂ C] [complete_space C] [star_ring C] /-- The functorial map taking `ψ : A →⋆ₐ[ℂ] B` to a continuous function `character_space ℂ B → character_space ℂ A` obtained by pre-composition with `ψ`. -/ @[simps] noncomputable def comp_continuous_map (ψ : A →⋆ₐ[ℂ] B) : C(character_space ℂ B, character_space ℂ A) := { to_fun := λ φ, equiv_alg_hom.symm ((equiv_alg_hom φ).comp (ψ.to_alg_hom)), continuous_to_fun := continuous.subtype_mk (continuous_of_continuous_eval $ λ a, map_continuous $ gelfand_transform ℂ B (ψ a)) _ } variables (A) /-- `weak_dual.character_space.comp_continuous_map` sends the identity to the identity. -/ @[simp] lemma comp_continuous_map_id : comp_continuous_map (star_alg_hom.id ℂ A) = continuous_map.id (character_space ℂ A) := continuous_map.ext $ λ a, ext $ λ x, rfl variables {A} /-- `weak_dual.character_space.comp_continuous_map` is functorial. -/ @[simp] lemma comp_continuous_map_comp (ψ₂ : B →⋆ₐ[ℂ] C) (ψ₁ : A →⋆ₐ[ℂ] B) : comp_continuous_map (ψ₂.comp ψ₁) = (comp_continuous_map ψ₁).comp (comp_continuous_map ψ₂) := continuous_map.ext $ λ a, ext $ λ x, rfl end character_space end weak_dual end functoriality
cec866477bbe05128e2f58d1691a14bbd31e962a
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/algebra/group_theory.hlean
f32eb8a7a41bf05e443ea37c79b9b2da969535ec
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
19,346
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Basic group theory -/ import algebra.category.category algebra.bundled .homomorphism open eq algebra pointed function is_trunc pi equiv is_equiv set_option class.force_new true namespace group definition pointed_Group [instance] [constructor] (G : Group) : pointed G := pointed.mk 1 definition Group.struct' [instance] [reducible] (G : Group) : group G := Group.struct G definition ab_group_Group_of_AbGroup [instance] [constructor] [priority 900] (G : AbGroup) : ab_group (Group_of_AbGroup G) := begin esimp, exact _ end definition ab_group_pSet_of_Group [instance] (G : AbGroup) : ab_group (pSet_of_Group G) := AbGroup.struct G definition group_pSet_of_Group [instance] [priority 900] (G : Group) : group (pSet_of_Group G) := Group.struct G /- group homomorphisms -/ /- definition is_homomorphism [class] [reducible] {G₁ G₂ : Type} [has_mul G₁] [has_mul G₂] (φ : G₁ → G₂) : Type := Π(g h : G₁), φ (g * h) = φ g * φ h section variables {G G₁ G₂ G₃ : Type} {g h : G₁} (ψ : G₂ → G₃) {φ₁ φ₂ : G₁ → G₂} (φ : G₁ → G₂) [group G] [group G₁] [group G₂] [group G₃] [is_homomorphism ψ] [is_homomorphism φ₁] [is_homomorphism φ₂] [is_homomorphism φ] definition respect_mul {G₁ G₂ : Type} [has_mul G₁] [has_mul G₂] (φ : G₁ → G₂) [is_homomorphism φ] : Π(g h : G₁), φ (g * h) = φ g * φ h := by assumption theorem respect_one /- φ -/ : φ 1 = 1 := mul.right_cancel (calc φ 1 * φ 1 = φ (1 * 1) : respect_mul φ ... = φ 1 : ap φ !one_mul ... = 1 * φ 1 : one_mul) theorem respect_inv /- φ -/ (g : G₁) : φ g⁻¹ = (φ g)⁻¹ := eq_inv_of_mul_eq_one (!respect_mul⁻¹ ⬝ ap φ !mul.left_inv ⬝ !respect_one) definition is_embedding_homomorphism /- φ -/ (H : Π{g}, φ g = 1 → g = 1) : is_embedding φ := begin apply function.is_embedding_of_is_injective, intro g g' p, apply eq_of_mul_inv_eq_one, apply H, refine !respect_mul ⬝ _, rewrite [respect_inv φ, p], apply mul.right_inv end definition is_homomorphism_compose {ψ : G₂ → G₃} {φ : G₁ → G₂} (H1 : is_homomorphism ψ) (H2 : is_homomorphism φ) : is_homomorphism (ψ ∘ φ) := λg h, ap ψ !respect_mul ⬝ !respect_mul definition is_homomorphism_id (G : Type) [group G] : is_homomorphism (@id G) := λg h, idp end section additive definition is_add_homomorphism [class] [reducible] {G₁ G₂ : Type} [has_add G₁] [has_add G₂] (φ : G₁ → G₂) : Type := Π(g h : G₁), φ (g + h) = φ g + φ h variables {G₁ G₂ : Type} (φ : G₁ → G₂) [add_group G₁] [add_group G₂] [is_add_homomorphism φ] definition respect_add /- φ -/ : Π(g h : G₁), φ (g + h) = φ g + φ h := by assumption theorem respect_zero /- φ -/ : φ 0 = 0 := add.right_cancel (calc φ 0 + φ 0 = φ (0 + 0) : respect_add φ ... = φ 0 : ap φ !zero_add ... = 0 + φ 0 : zero_add) theorem respect_neg /- φ -/ (g : G₁) : φ (-g) = -(φ g) := eq_neg_of_add_eq_zero (!respect_add⁻¹ ⬝ ap φ !add.left_inv ⬝ !respect_zero) end additive -/ structure homomorphism (G₁ G₂ : Group) : Type := (φ : G₁ → G₂) (p : is_mul_hom φ) infix ` →g `:55 := homomorphism definition group_fun [unfold 3] [coercion] := @homomorphism.φ definition homomorphism.struct [unfold 3] [instance] [priority 900] {G₁ G₂ : Group} (φ : G₁ →g G₂) : is_mul_hom φ := homomorphism.p φ definition homomorphism.mulstruct [instance] [priority 2000] {G₁ G₂ : Group} (φ : G₁ →g G₂) : is_mul_hom φ := homomorphism.p φ definition homomorphism.addstruct [instance] [priority 2000] {G₁ G₂ : AddGroup} (φ : G₁ →g G₂) : is_add_hom φ := homomorphism.p φ variables {G G₁ G₂ G₃ : Group} {g h : G₁} {ψ : G₂ →g G₃} {φ₁ φ₂ : G₁ →g G₂} (φ : G₁ →g G₂) definition to_respect_mul /- φ -/ (g h : G₁) : φ (g * h) = φ g * φ h := respect_mul φ g h theorem to_respect_one /- φ -/ : φ 1 = 1 := respect_one φ theorem to_respect_inv /- φ -/ (g : G₁) : φ g⁻¹ = (φ g)⁻¹ := respect_inv φ g definition to_is_embedding_homomorphism /- φ -/ (H : Π{g}, φ g = 1 → g = 1) : is_embedding φ := is_embedding_of_is_mul_hom φ @H variables (G₁ G₂) definition is_set_homomorphism [instance] : is_set (G₁ →g G₂) := begin have H : G₁ →g G₂ ≃ Σ(f : G₁ → G₂), Π(g₁ g₂ : G₁), f (g₁ * g₂) = f g₁ * f g₂, begin fapply equiv.MK, { intro φ, induction φ, constructor, exact (respect_mul φ)}, { intro v, induction v with f H, constructor, exact H}, { intro v, induction v, reflexivity}, { intro φ, induction φ, reflexivity} end, apply is_trunc_equiv_closed_rev, exact H end variables {G₁ G₂} definition pmap_of_homomorphism [constructor] /- φ -/ : G₁ →* G₂ := pmap.mk φ begin esimp, exact respect_one φ end definition homomorphism_change_fun [constructor] {G₁ G₂ : Group} (φ : G₁ →g G₂) (f : G₁ → G₂) (p : φ ~ f) : G₁ →g G₂ := homomorphism.mk f (λg h, (p (g * h))⁻¹ ⬝ to_respect_mul φ g h ⬝ ap011 mul (p g) (p h)) definition homomorphism_eq (p : group_fun φ₁ ~ group_fun φ₂) : φ₁ = φ₂ := begin induction φ₁ with φ₁ q₁, induction φ₂ with φ₂ q₂, esimp at p, induction p, exact ap (homomorphism.mk φ₁) !is_prop.elim end section additive variables {H₁ H₂ : AddGroup} (χ : H₁ →g H₂) definition to_respect_add /- χ -/ (g h : H₁) : χ (g + h) = χ g + χ h := respect_add χ g h theorem to_respect_zero /- χ -/ : χ 0 = 0 := respect_zero χ theorem to_respect_neg /- χ -/ (g : H₁) : χ (-g) = -(χ g) := respect_neg χ g end additive section add_mul variables {H₁ : AddGroup} {H₂ : Group} (χ : H₁ →g H₂) definition to_respect_add_mul /- χ -/ (g h : H₁) : χ (g + h) = χ g * χ h := to_respect_mul χ g h theorem to_respect_zero_one /- χ -/ : χ 0 = 1 := to_respect_one χ theorem to_respect_neg_inv /- χ -/ (g : H₁) : χ (-g) = (χ g)⁻¹ := to_respect_inv χ g end add_mul section mul_add variables {H₁ : Group} {H₂ : AddGroup} (χ : H₁ →g H₂) definition to_respect_mul_add /- χ -/ (g h : H₁) : χ (g * h) = χ g + χ h := to_respect_mul χ g h theorem to_respect_one_zero /- χ -/ : χ 1 = 0 := to_respect_one χ theorem to_respect_inv_neg /- χ -/ (g : H₁) : χ g⁻¹ = -(χ g) := to_respect_inv χ g end mul_add /- categorical structure of groups + homomorphisms -/ definition homomorphism_compose [constructor] [trans] (ψ : G₂ →g G₃) (φ : G₁ →g G₂) : G₁ →g G₃ := homomorphism.mk (ψ ∘ φ) (is_mul_hom_compose _ _) variable (G) definition homomorphism_id [constructor] [refl] : G →g G := homomorphism.mk (@id G) (is_mul_hom_id G) variable {G} abbreviation gid [constructor] := @homomorphism_id infixr ` ∘g `:75 := homomorphism_compose notation 1 := homomorphism_id _ structure isomorphism (A B : Group) := (to_hom : A →g B) (is_equiv_to_hom : is_equiv to_hom) infix ` ≃g `:25 := isomorphism attribute isomorphism.to_hom [coercion] attribute isomorphism.is_equiv_to_hom [instance] attribute isomorphism._trans_of_to_hom [unfold 3] definition equiv_of_isomorphism [constructor] (φ : G₁ ≃g G₂) : G₁ ≃ G₂ := equiv.mk φ _ definition pequiv_of_isomorphism [constructor] (φ : G₁ ≃g G₂) : G₁ ≃* G₂ := pequiv.mk φ begin esimp, exact _ end begin esimp, exact respect_one φ end definition isomorphism_of_equiv [constructor] (φ : G₁ ≃ G₂) (p : Πg₁ g₂, φ (g₁ * g₂) = φ g₁ * φ g₂) : G₁ ≃g G₂ := isomorphism.mk (homomorphism.mk φ p) !to_is_equiv definition isomorphism_of_eq [constructor] {G₁ G₂ : Group} (φ : G₁ = G₂) : G₁ ≃g G₂ := isomorphism_of_equiv (equiv_of_eq (ap Group.carrier φ)) begin intros, induction φ, reflexivity end definition pequiv_of_isomorphism_of_eq {G₁ G₂ : Group} (p : G₁ = G₂) : pequiv_of_isomorphism (isomorphism_of_eq p) = pequiv_of_eq (ap pType_of_Group p) := begin induction p, apply pequiv_eq, fapply pmap_eq, { intro g, reflexivity}, { apply is_prop.elim} end definition to_ginv [constructor] (φ : G₁ ≃g G₂) : G₂ →g G₁ := homomorphism.mk φ⁻¹ abstract begin intro g₁ g₂, apply eq_of_fn_eq_fn' φ, rewrite [respect_mul φ, +right_inv φ] end end variable (G) definition isomorphism.refl [refl] [constructor] : G ≃g G := isomorphism.mk 1 !is_equiv_id variable {G} definition isomorphism.symm [symm] [constructor] (φ : G₁ ≃g G₂) : G₂ ≃g G₁ := isomorphism.mk (to_ginv φ) !is_equiv_inv definition isomorphism.trans [trans] [constructor] (φ : G₁ ≃g G₂) (ψ : G₂ ≃g G₃) : G₁ ≃g G₃ := isomorphism.mk (ψ ∘g φ) !is_equiv_compose definition isomorphism.eq_trans [trans] [constructor] {G₁ G₂ : Group} {G₃ : Group} (φ : G₁ = G₂) (ψ : G₂ ≃g G₃) : G₁ ≃g G₃ := proof isomorphism.trans (isomorphism_of_eq φ) ψ qed definition isomorphism.trans_eq [trans] [constructor] {G₁ : Group} {G₂ G₃ : Group} (φ : G₁ ≃g G₂) (ψ : G₂ = G₃) : G₁ ≃g G₃ := isomorphism.trans φ (isomorphism_of_eq ψ) postfix `⁻¹ᵍ`:(max + 1) := isomorphism.symm infixl ` ⬝g `:75 := isomorphism.trans infixl ` ⬝gp `:75 := isomorphism.trans_eq infixl ` ⬝pg `:75 := isomorphism.eq_trans definition pmap_of_isomorphism [constructor] (φ : G₁ ≃g G₂) : G₁ →* G₂ := pequiv_of_isomorphism φ /- category of groups -/ section open category definition precategory_group [constructor] : precategory Group := precategory.mk homomorphism @homomorphism_compose @homomorphism_id (λG₁ G₂ G₃ G₄ φ₃ φ₂ φ₁, homomorphism_eq (λg, idp)) (λG₁ G₂ φ, homomorphism_eq (λg, idp)) (λG₁ G₂ φ, homomorphism_eq (λg, idp)) end -- TODO -- definition category_group : category Group := -- category.mk precategory_group -- begin -- intro G₁ G₂, -- fapply adjointify, -- { intro φ, fapply Group_eq, }, -- { }, -- { } -- end /- given an equivalence A ≃ B we can transport a group structure on A to a group structure on B -/ section parameters {A B : Type} (f : A ≃ B) [group A] definition group_equiv_mul (b b' : B) : B := f (f⁻¹ᶠ b * f⁻¹ᶠ b') definition group_equiv_one : B := f one definition group_equiv_inv (b : B) : B := f (f⁻¹ᶠ b)⁻¹ local infix * := group_equiv_mul local postfix ^ := group_equiv_inv local notation 1 := group_equiv_one theorem group_equiv_mul_assoc (b₁ b₂ b₃ : B) : (b₁ * b₂) * b₃ = b₁ * (b₂ * b₃) := by rewrite [↑group_equiv_mul, +left_inv f, mul.assoc] theorem group_equiv_one_mul (b : B) : 1 * b = b := by rewrite [↑group_equiv_mul, ↑group_equiv_one, left_inv f, one_mul, right_inv f] theorem group_equiv_mul_one (b : B) : b * 1 = b := by rewrite [↑group_equiv_mul, ↑group_equiv_one, left_inv f, mul_one, right_inv f] theorem group_equiv_mul_left_inv (b : B) : b^ * b = 1 := by rewrite [↑group_equiv_mul, ↑group_equiv_one, ↑group_equiv_inv, +left_inv f, mul.left_inv] definition group_equiv_closed : group B := ⦃group, mul := group_equiv_mul, mul_assoc := group_equiv_mul_assoc, one := group_equiv_one, one_mul := group_equiv_one_mul, mul_one := group_equiv_mul_one, inv := group_equiv_inv, mul_left_inv := group_equiv_mul_left_inv, is_set_carrier := is_trunc_equiv_closed 0 f⦄ end variable (G) /- the trivial group -/ open unit --rename: group_unit definition trivial_group [constructor] : group unit := group.mk _ (λx y, star) (λx y z, idp) star (unit.rec idp) (unit.rec idp) (λx, star) (λx, idp) --rename trivial_group definition Trivial_group [constructor] : Group := Group.mk _ trivial_group abbreviation G0 := Trivial_group definition trivial_group_of_is_contr [H : is_contr G] : G ≃g G0 := begin fapply isomorphism_of_equiv, { apply equiv_unit_of_is_contr}, { intros, reflexivity} end variable {G} /- A group where the point in the pointed type corresponds with 1 in the group. We need this structure when we are given a pointed type, and want to say that there is a group structure on it which is compatible with the point. This is used in chain complexes. -/ structure pgroup [class] (X : Type*) extends semigroup X, has_inv X := (pt_mul : Πa, mul pt a = a) (mul_pt : Πa, mul a pt = a) (mul_left_inv_pt : Πa, mul (inv a) a = pt) definition group_of_pgroup [reducible] [instance] (X : Type*) [H : pgroup X] : group X := ⦃group, H, one := pt, one_mul := pgroup.pt_mul , mul_one := pgroup.mul_pt, mul_left_inv := pgroup.mul_left_inv_pt⦄ definition pgroup_of_group (X : Type*) [H : group X] (p : one = pt :> X) : pgroup X := begin cases X with X x, esimp at *, induction p, exact ⦃pgroup, H, pt_mul := one_mul, mul_pt := mul_one, mul_left_inv_pt := mul.left_inv⦄ end definition Group_of_pgroup (G : Type*) [pgroup G] : Group := Group.mk G _ definition pgroup_Group [instance] (G : Group) : pgroup G := ⦃ pgroup, Group.struct G, pt_mul := one_mul, mul_pt := mul_one, mul_left_inv_pt := mul.left_inv ⦄ -- infinity pgroups structure inf_pgroup [class] (X : Type*) extends inf_semigroup X, has_inv X := (pt_mul : Πa, mul pt a = a) (mul_pt : Πa, mul a pt = a) (mul_left_inv_pt : Πa, mul (inv a) a = pt) definition inf_group_of_inf_pgroup [reducible] [instance] (X : Type*) [H : inf_pgroup X] : inf_group X := ⦃inf_group, H, one := pt, one_mul := inf_pgroup.pt_mul , mul_one := inf_pgroup.mul_pt, mul_left_inv := inf_pgroup.mul_left_inv_pt⦄ definition inf_pgroup_of_inf_group (X : Type*) [H : inf_group X] (p : one = pt :> X) : inf_pgroup X := begin cases X with X x, esimp at *, induction p, exact ⦃inf_pgroup, H, pt_mul := one_mul, mul_pt := mul_one, mul_left_inv_pt := mul.left_inv⦄ end definition inf_Group_of_inf_pgroup (G : Type*) [inf_pgroup G] : InfGroup := InfGroup.mk G _ definition inf_pgroup_InfGroup [instance] (G : InfGroup) : inf_pgroup G := ⦃ inf_pgroup, InfGroup.struct G, pt_mul := one_mul, mul_pt := mul_one, mul_left_inv_pt := mul.left_inv ⦄ /- equality of groups and abelian groups -/ definition group.to_has_mul {A : Type} (H : group A) : has_mul A := _ definition group.to_has_inv {A : Type} (H : group A) : has_inv A := _ definition group.to_has_one {A : Type} (H : group A) : has_one A := _ local attribute group.to_has_mul group.to_has_inv [coercion] universe variable l variables {A B : Type.{l}} definition group_eq {G H : group A} (same_mul' : Π(g h : A), @mul A G g h = @mul A H g h) : G = H := begin have foo : Π(g : A), @inv A G g = (@inv A G g * g) * @inv A H g, from λg, !mul_inv_cancel_right⁻¹, cases G with Gs Gm Gh1 G1 Gh2 Gh3 Gi Gh4, cases H with Hs Hm Hh1 H1 Hh2 Hh3 Hi Hh4, have same_mul : Gm = Hm, from eq_of_homotopy2 same_mul', cases same_mul, have same_one : G1 = H1, from calc G1 = Hm G1 H1 : Hh3 ... = H1 : Gh2, have same_inv : Gi = Hi, from eq_of_homotopy (take g, calc Gi g = Hm (Hm (Gi g) g) (Hi g) : foo ... = Hm G1 (Hi g) : by rewrite Gh4 ... = Hi g : Gh2), cases same_one, cases same_inv, have ps : Gs = Hs, from !is_prop.elim, have ph1 : Gh1 = Hh1, from !is_prop.elim, have ph2 : Gh2 = Hh2, from !is_prop.elim, have ph3 : Gh3 = Hh3, from !is_prop.elim, have ph4 : Gh4 = Hh4, from !is_prop.elim, cases ps, cases ph1, cases ph2, cases ph3, cases ph4, reflexivity end definition group_pathover {G : group A} {H : group B} {p : A = B} (resp_mul : Π(g h : A), cast p (g * h) = cast p g * cast p h) : G =[p] H := begin induction p, apply pathover_idp_of_eq, exact group_eq (resp_mul) end definition Group_eq_of_eq {G H : Group} (p : Group.carrier G = Group.carrier H) (resp_mul : Π(g h : G), cast p (g * h) = cast p g * cast p h) : G = H := begin cases G with Gc G, cases H with Hc H, apply (apd011 Group.mk p), exact group_pathover resp_mul end definition Group_eq {G H : Group} (f : Group.carrier G ≃ Group.carrier H) (resp_mul : Π(g h : G), f (g * h) = f g * f h) : G = H := Group_eq_of_eq (ua f) (λg h, !cast_ua ⬝ resp_mul g h ⬝ ap011 mul !cast_ua⁻¹ !cast_ua⁻¹) definition eq_of_isomorphism {G₁ G₂ : Group} (φ : G₁ ≃g G₂) : G₁ = G₂ := Group_eq (equiv_of_isomorphism φ) (respect_mul φ) definition ab_group.to_has_mul {A : Type} (H : ab_group A) : has_mul A := _ local attribute ab_group.to_has_mul [coercion] definition ab_group_eq {A : Type} {G H : ab_group A} (same_mul : Π(g h : A), @mul A G g h = @mul A H g h) : G = H := begin have g_eq : @ab_group.to_group A G = @ab_group.to_group A H, from group_eq same_mul, cases G with Gs Gm Gh1 G1 Gh2 Gh3 Gi Gh4 Gh5, cases H with Hs Hm Hh1 H1 Hh2 Hh3 Hi Hh4 Hh5, have pm : Gm = Hm, from ap (@mul _ ∘ group.to_has_mul) g_eq, have pi : Gi = Hi, from ap (@inv _ ∘ group.to_has_inv) g_eq, have p1 : G1 = H1, from ap (@one _ ∘ group.to_has_one) g_eq, induction pm, induction pi, induction p1, have ps : Gs = Hs, from !is_prop.elim, have ph1 : Gh1 = Hh1, from !is_prop.elim, have ph2 : Gh2 = Hh2, from !is_prop.elim, have ph3 : Gh3 = Hh3, from !is_prop.elim, have ph4 : Gh4 = Hh4, from !is_prop.elim, have ph5 : Gh5 = Hh5, from !is_prop.elim, induction ps, induction ph1, induction ph2, induction ph3, induction ph4, induction ph5, reflexivity end definition ab_group_pathover {A B : Type} {G : ab_group A} {H : ab_group B} {p : A = B} (resp_mul : Π(g h : A), cast p (g * h) = cast p g * cast p h) : G =[p] H := begin induction p, apply pathover_idp_of_eq, exact ab_group_eq (resp_mul) end definition AbGroup_eq_of_isomorphism {G₁ G₂ : AbGroup} (φ : G₁ ≃g G₂) : G₁ = G₂ := begin induction G₁, induction G₂, apply apd011 AbGroup.mk (ua (equiv_of_isomorphism φ)), apply ab_group_pathover, intro g h, exact !cast_ua ⬝ respect_mul φ g h ⬝ ap011 mul !cast_ua⁻¹ !cast_ua⁻¹ end definition trivial_group_of_is_contr' (G : Group) [H : is_contr G] : G = G0 := eq_of_isomorphism (trivial_group_of_is_contr G) end group
df72ecb255bfb452ad1cdd539bfe247a727d761f
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/quadratic_discriminant.lean
69ed59101863a9399a6eef749272eb5fe59fc8fd
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
5,778
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import algebra.invertible import tactic.linarith import order.filter.at_top_bot /-! # Quadratic discriminants and roots of a quadratic This file defines the discriminant of a quadratic and gives the solution to a quadratic equation. ## Main definition - `discrim a b c`: the discriminant of a quadratic `a * x * x + b * x + c` is `b * b - 4 * a * c`. ## Main statements - `quadratic_eq_zero_iff`: roots of a quadratic can be written as `(-b + s) / (2 * a)` or `(-b - s) / (2 * a)`, where `s` is a square root of the discriminant. - `quadratic_ne_zero_of_discrim_ne_square`: if the discriminant has no square root, then the corresponding quadratic has no root. - `discrim_le_zero`: if a quadratic is always non-negative, then its discriminant is non-positive. ## Tags polynomial, quadratic, discriminant, root -/ open filter section ring variables {R : Type*} /-- Discriminant of a quadratic -/ def discrim [ring R] (a b c : R) : R := b^2 - 4 * a * c variables [integral_domain R] {a b c : R} /-- A quadratic has roots if and only if its discriminant equals some square. -/ lemma quadratic_eq_zero_iff_discrim_eq_square (h2 : (2 : R) ≠ 0) (ha : a ≠ 0) (x : R) : a * x * x + b * x + c = 0 ↔ discrim a b c = (2 * a * x + b) ^ 2 := begin split, { assume h, calc discrim a b c = 4 * a * (a * x * x + b * x + c) + b * b - 4 * a * c : by { rw [h, discrim], ring } ... = (2*a*x + b)^2 : by ring }, { assume h, have ha : 2 * 2 * a ≠ 0 := mul_ne_zero (mul_ne_zero h2 h2) ha, apply mul_left_cancel' ha, calc 2 * 2 * a * (a * x * x + b * x + c) = (2 * a * x + b) ^ 2 - (b ^ 2 - 4 * a * c) : by ring ... = 0 : by { rw [← h, discrim], ring } ... = 2*2*a*0 : by ring } end /-- A quadratic has no root if its discriminant has no square root. -/ lemma quadratic_ne_zero_of_discrim_ne_square (h2 : (2 : R) ≠ 0) (ha : a ≠ 0) (h : ∀ s : R, discrim a b c ≠ s * s) (x : R) : a * x * x + b * x + c ≠ 0 := begin assume h', rw [quadratic_eq_zero_iff_discrim_eq_square h2 ha, pow_two] at h', exact h _ h' end end ring section field variables {K : Type*} [field K] [invertible (2 : K)] {a b c x : K} /-- Roots of a quadratic -/ lemma quadratic_eq_zero_iff (ha : a ≠ 0) {s : K} (h : discrim a b c = s * s) (x : K) : a * x * x + b * x + c = 0 ↔ x = (-b + s) / (2 * a) ∨ x = (-b - s) / (2 * a) := begin have h2 : (2 : K) ≠ 0 := nonzero_of_invertible 2, rw [quadratic_eq_zero_iff_discrim_eq_square h2 ha, h, pow_two, mul_self_eq_mul_self_iff], have ne : 2 * a ≠ 0 := mul_ne_zero h2 ha, have : x = 2 * a * x / (2 * a) := (mul_div_cancel_left x ne).symm, have h₁ : 2 * a * ((-b + s) / (2 * a)) = -b + s := mul_div_cancel' _ ne, have h₂ : 2 * a * ((-b - s) / (2 * a)) = -b - s := mul_div_cancel' _ ne, split, { intro h', rcases h', { left, rw h', simpa [add_comm] }, { right, rw h', simpa [add_comm, sub_eq_add_neg] } }, { intro h', rcases h', { left, rw [h', h₁], ring }, { right, rw [h', h₂], ring } } end /-- A quadratic has roots if its discriminant has square roots -/ lemma exists_quadratic_eq_zero (ha : a ≠ 0) (h : ∃ s, discrim a b c = s * s) : ∃ x, a * x * x + b * x + c = 0 := begin rcases h with ⟨s, hs⟩, use (-b + s) / (2 * a), rw quadratic_eq_zero_iff ha hs, simp end /-- Root of a quadratic when its discriminant equals zero -/ lemma quadratic_eq_zero_iff_of_discrim_eq_zero (ha : a ≠ 0) (h : discrim a b c = 0) (x : K) : a * x * x + b * x + c = 0 ↔ x = -b / (2 * a) := begin have : discrim a b c = 0 * 0, by rw [h, mul_zero], rw [quadratic_eq_zero_iff ha this, add_zero, sub_zero, or_self] end end field section linear_ordered_field variables {K : Type*} [linear_ordered_field K] {a b c : K} /-- If a polynomial of degree 2 is always nonnegative, then its discriminant is nonpositive -/ lemma discrim_le_zero (h : ∀ x : K, 0 ≤ a * x * x + b * x + c) : discrim a b c ≤ 0 := begin rw [discrim, pow_two], obtain ha|rfl|ha : a < 0 ∨ a = 0 ∨ 0 < a := lt_trichotomy a 0, -- if a < 0 { have : tendsto (λ x, (a * x + b) * x + c) at_top at_bot := tendsto_at_bot_add_const_right _ c ((tendsto_at_bot_add_const_right _ b (tendsto_id.neg_const_mul_at_top ha)).at_bot_mul_at_top tendsto_id), rcases (this.eventually (eventually_lt_at_bot 0)).exists with ⟨x, hx⟩, exact false.elim ((h x).not_lt $ by rwa ← add_mul) }, -- if a = 0 { rcases em (b = 0) with (rfl|hb), { simp }, { have := h ((-c - 1) / b), rw [mul_div_cancel' _ hb] at this, linarith } }, -- if a > 0 { have := calc 4 * a * (a * (-(b / a) * (1 / 2)) * (-(b / a) * (1 / 2)) + b * (-(b / a) * (1 / 2)) + c) = (a * (b / a)) * (a * (b / a)) - 2 * (a * (b / a)) * b + 4 * a * c : by ring ... = -(b * b - 4 * a * c) : by { simp only [mul_div_cancel' b (ne_of_gt ha)], ring }, have ha' : 0 ≤ 4 * a, by linarith, have h := (mul_nonneg ha' (h (-(b / a) * (1 / 2)))), rw this at h, rwa ← neg_nonneg } end /-- If a polynomial of degree 2 is always positive, then its discriminant is negative, at least when the coefficient of the quadratic term is nonzero. -/ lemma discrim_lt_zero (ha : a ≠ 0) (h : ∀ x : K, 0 < a * x * x + b * x + c) : discrim a b c < 0 := begin have : ∀ x : K, 0 ≤ a*x*x + b*x + c := assume x, le_of_lt (h x), refine lt_of_le_of_ne (discrim_le_zero this) _, assume h', have := h (-b / (2 * a)), have : a * (-b / (2 * a)) * (-b / (2 * a)) + b * (-b / (2 * a)) + c = 0, { rw [quadratic_eq_zero_iff_of_discrim_eq_zero ha h' (-b / (2 * a))] }, linarith end end linear_ordered_field
3854763cce02e04e14ded806e9743bcff80281d0
76df16d6c3760cb415f1294caee997cc4736e09b
/lean/src/op/basic.lean
458efd3a32fea3dcd854636bc0d293aa7ef87edd
[ "MIT" ]
permissive
uw-unsat/leanette-popl22-artifact
70409d9cbd8921d794d27b7992bf1d9a4087e9fe
80fea2519e61b45a283fbf7903acdf6d5528dbe7
refs/heads/master
1,681,592,449,670
1,637,037,431,000
1,637,037,431,000
414,331,908
6
1
null
null
null
null
UTF-8
Lean
false
false
3,431
lean
import .sym import ..cs.sym import ..cs.lib import ..tactic.all open op.sym lemma int.evals_to_int {m : model} {t : term type.int} {w : op.lang.val} (h : (val_atom.term t).eval m = w) : ∃ {i : ℤ}, w = lang.val.datum (op.lang.datum.int i) := begin simp only [val_atom.eval] at h, cases t.eval m with _ i, simp only [lit.to_val] at h, use i, simp [h], end lemma bool.evals_to_bool {m : model} {t : term type.bool} {w : op.lang.val} (h : (val_atom.term t).eval m = w) : ∃ {b : bool}, w = (lang.val.bool b) := begin simp only [val_atom.eval] at h, cases t.eval m with b, simp only [lit.to_val] at h, use b, simp [h], end lemma env.eval_lift {m : model} {ε : env} : vals.eval ε m = sym.env.eval ev m ε := begin induction ε with hd tl ih, case nil { simp [sym.env.eval, vals.eval] }, case cons { simp [sym.env.eval, vals.eval, ih, ev, evalV, list.map] }, end lemma clos.eval_lift {m : model} {x : ℕ} {e : op.lang.exp} {ε : list val} : (val_atom.clos x e ε).eval m = sym.clos.eval ev m ⟨x, e, ε⟩ := by simp [sym.clos.eval, val_atom.eval, env.eval_lift] lemma choices.eval_lift {m : model} {gvs : choices' val_atom} : choices.eval gvs m = gvs.eval ev.atom m op.lang.undef := begin induction gvs with hd tl ih, case nil { simp [choices.eval, sym.choices.eval] }, case cons { cases hd with g va, simp only [choices.eval, sym.choices.eval, ev.atom, evalB], split_ifs, case_c { simp [evalVA] }, case_c { assumption }, }, end lemma clos.evals_to_clos {m : model} {w : op.lang.val} {x : ℕ} {e : op.lang.exp} {ε : op.sym.env} (h : (val_atom.clos x e ε).eval m = w) : w.is_clos := begin apply_c sym.clos.evals_to_clos, case ev { exact ev }, case c { exact ⟨x, e, ε⟩ }, case_c { simpa [← clos.eval_lift] }, end lemma list.evals_to_list {m : model} {w : op.lang.val} {vs : list val} (h : (val_atom.list vs).eval m = w) : w.is_list := begin cases vs, case nil { simp only [val_atom.eval] at h, simp [← h], }, case cons : hd tl { simp [← h, val_atom.eval] }, end lemma list.evals_cons {m : model} {w : op.lang.val} {v : val} {vs : list val} (h : (val_atom.list (v :: vs)).eval m = w) : ∃ w' ws', v.eval m = w' ∧ (val_atom.list vs).eval m = lang.val.list ws' ∧ w = lang.val.list (w' :: ws') := begin simp only [val_atom.eval, vals.eval] at h, use [v.eval m, vals.eval vs m], simp [val_atom.eval, h], end lemma choices.none_changes_eval {SymV_0 SymV SymV' SymR SymR' : Type} {m : model} {gvs : sym.choices (term type.bool) SymV_0} {evalV : model → SymV → SymR} (evalV' : model → SymV' → SymR') : sym.choices.none (make_ev evalV) m gvs ↔ sym.choices.none (make_ev evalV') m gvs := by simp [sym.choices.none, sym.choices.true] lemma val_atom.evals_no_undef {va : val_atom} {m : model} : va.eval m ≠ op.lang.undef := begin generalize h : va.eval m = w, cases va, case term : τ t { cases τ, case bool { cases bool.evals_to_bool h with _ h', subst h', simp [op.lang.undef], }, case int { cases int.evals_to_int h with _ h', subst h', simp [op.lang.undef], }, }, case clos { replace h := clos.evals_to_clos h, cases w, all_goals { contradiction }, }, case list { replace h := list.evals_to_list h, cases w, all_goals { contradiction }, }, end
75c7f8baf8cbffa5f366849db87dfe37b40c65a3
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/tactic2.lean
007ff3c8d3981c3b057c74357db22ac8d987ac94
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
797
lean
(* import("tactic.lua") *) variables p q r : Bool theorem T1 : p → q → p /\ q := (fun H1 H2, let H1 : p := _, H2 : q := _ in and_intro H1 H2 ). exact -- solve first metavar done exact -- solve second metavar done (* simple_tac = Repeat(conj_tac() ^ assumption_tac()) *) theorem T2 : p → q → p /\ q /\ p := _. simple_tac done print environment 1 theorem T3 : p → p /\ q → r → q /\ r /\ p := _. (* Repeat(OrElse(conj_tac(), conj_hyp_tac(), assumption_tac())) *) done -- Display proof term generated by previous tac print environment 1 theorem T4 : p → p /\ q → r → q /\ r /\ p := _. Repeat (OrElse (apply and_intro) conj_hyp exact) done -- Display proof term generated by previous tac -- print environment 1
4b67c4f26ceb834fe8565ffe63865433dc916e00
dc06cc9775d64d571bf4778459ec6fde1f344116
/src/analysis/calculus/times_cont_diff.lean
88e6bf4a812757b8cd62a8caed3442266f61ab8d
[ "Apache-2.0" ]
permissive
mgubi/mathlib
8c1ea39035776ad52cf189a7af8cc0eee7dea373
7c09ed5eec8434176fbc493e0115555ccc4c8f99
refs/heads/master
1,642,222,572,514
1,563,782,424,000
1,563,782,424,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,680
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 # Higher differentiabiliity A function is `C^1` on a domain if it is differentiable there, and its derivative is continuous. By induction, it is `C^n` if it is `C^{n-1}` and its (n-1)-th derivative is `C^1` there or, equivalently, if it is `C^1` and its derivative is `C^{n-1}`. Finally, it is `C^∞` if it is `C^n` for all n. We formalize these notions by defining iteratively the n-th derivative of a function at the (n-1)-th derivative of the derivative. It is called `iterated_fderiv k n f x` where `k` is the field, `n` is the number of iterations, `f` is the function and `x` is the point. We also define a version `iterated_fderiv_within` relative to a domain, as well as predicates `times_cont_diff k n f` and `times_cont_diff_on k n f s` saying that the function is `C^n`, respectively in the whole space or on the set `s`. We prove basic properties of these notions. ## Implementation notes The n-th derivative of a function belongs to the space E →L[k] (E →L[k] (E ... F)...))), where there are n iterations of `E →L[k]`. We define this space inductively, call it `iterated_continuous_linear_map k n E F`, and denote it by `E [×n]→L[k] F`. We can define it inductively either from the left (i.e., saying that the (n+1)-th space S_{n+1} is E →L[k] S_n) or from the right (i.e., saying that the (n+1)-th space associated to F, denoted by S_{n+1} (F), is equal to S_n (E →L[k] F)). For proofs, it turns out to be more convenient to use the latter approach (from the right), as it means to prove things at the (n+1)-th step we only need to understand well enough the derivative in E →L[k] F (contrary to the approach from the left, where one would need to know enough on the n-th derivative to deduce things on the (n+1)-th derivative). In other words, one could define the (n+1)-th derivative either as the derivative of the n-th derivative, or as the n-th derivative of the derivative. We use the latter definition. A difficulty is related to universes: the first and second spaces in the sequence, for n=0 and 1, are F and E →L[k] F. If E has universe u and F has universe v, then the first one lives in v and the second one in max v u. Since they should live in the same universe (as all the other spaces in the construction), it means that at the 0-th step we should not use F, but ulift it to universe max v u. But we should also ulift its vector space structure and its normed space structure. This can certainly be done, but I decided it was not worth it for now. Therefore, the definition is only made when E and F live in the same universe. Regarding the definition of `C^n` functions, there are two equivalent definitions: * require by induction that the function is differentiable, and that its derivative is C^{n-1} * or require that, for all m ≤ n, the m-th derivative is continuous, and for all m < n the m-th derivative is differentiable. The first definition is more efficient for many proofs by induction. The second definition is more satisfactory as it gives concrete information about the n-th derivative (contrary to the first point of view), and moreover it also makes sense for n = ∞. Therefore, we give (and use) both definitions, named respectively `times_cont_diff_rec` and `times_cont_diff` (as well as relativized versions on a set). We show that they are equivalent. The first one is mainly auxiliary: in applications, one should always use `times_cont_diff` (but the proofs below use heavily the equivalence to show that `times_cont_diff` is well behaved). -/ import analysis.calculus.deriv noncomputable theory local attribute [instance, priority 0] classical.decidable_inhabited classical.prop_decidable universes u v w open set variables {k : Type*} [nondiscrete_normed_field k] {E : Type u} [normed_group E] [normed_space k E] {F : Type u} [normed_group F] [normed_space k F] {G : Type u} [normed_group G] [normed_space k G] {s s₁ u : set E} {f f₁ : E → F} {f' f₁' : E →L[k] F} {f₂ : E → G} {f₂' : E →L[k] G} {g : F → G} {x : E} {c : F} {L : filter E} {t : set F} {b : E × F → G} {sb : set (E × F)} {p : E × F} {n : ℕ} include k /-- The space `iterated_continuous_linear_map k n E F` is the space E →L[k] (E →L[k] (E ... F)...))), defined inductively over `n`. This is the space to which the `n`-th derivative of a function naturally belongs. It is only defined when `E` and `F` live in the same universe. -/ def iterated_continuous_linear_map (k : Type w) [nondiscrete_normed_field k] : Π (n : ℕ) (E : Type u) [gE : normed_group E] [@normed_space k E _ gE] (F : Type u) [gF : normed_group F] [@normed_space k F _ gF], Type u | 0 E _ _ F _ _ := F | (n+1) E _ _ F _ _ := by { resetI, exact iterated_continuous_linear_map n E (E →L[k] F) } notation E `[×`:25 n `]→L[`:25 k `] ` F := iterated_continuous_linear_map k n E F /-- Define by induction a normed group structure on the space of iterated continuous linear maps. To avoid `resetI` in the statement, use the @ version with all parameters. As the equation compiler chokes on this one, we use the `nat.rec_on` version. -/ def iterated_continuous_linear_map.normed_group_rec (k : Type w) [hk : nondiscrete_normed_field k] (n : ℕ) (E : Type u) [gE : normed_group E] [sE : normed_space k E] : ∀(F : Type u) [nF : normed_group F] [sF : @normed_space k F _ nF], normed_group (@iterated_continuous_linear_map k hk n E gE sE F nF sF) := nat.rec_on n (λF nF sF, nF) (λn aux_n F nF sF, by { resetI, apply aux_n }) /-- Define by induction a normed space structure on the space of iterated continuous linear maps. To avoid `resetI` in the statement, use the @ version with all parameters. As the equation compiler chokes on this one, we use the `nat.rec_on` version. -/ def iterated_continuous_linear_map.normed_space_rec (k : Type w) [hk : nondiscrete_normed_field k] (n : ℕ) (E : Type u) [gE : normed_group E] [sE : normed_space k E] : ∀(F : Type u) [nF : normed_group F] [sF : @normed_space k F _ nF], @normed_space k (@iterated_continuous_linear_map k hk n E gE sE F nF sF) _ (@iterated_continuous_linear_map.normed_group_rec k hk n E gE sE F nF sF) := nat.rec_on n (λF nF sF, sF) (λn aux_n F nF sF, by { resetI, apply aux_n }) /-- Explicit normed group structure on the space of iterated continuous linear maps. -/ instance iterated_continuous_linear_map.normed_group (n : ℕ) (k : Type w) [hk : nondiscrete_normed_field k] (E : Type u) [gE : normed_group E] [sE : normed_space k E] (F : Type u) [gF : normed_group F] [sF : normed_space k F] : normed_group (E [×n]→L[k] F) := iterated_continuous_linear_map.normed_group_rec k n E F /-- Explicit normed space structure on the space of iterated continuous linear maps. -/ instance iterated_continuous_linear_map.normed_space (n : ℕ) (k : Type w) [hk : nondiscrete_normed_field k] (E : Type u) [gE : normed_group E] [sE : normed_space k E] (F : Type u) [gF : normed_group F] [sF : normed_space k F] : normed_space k (E [×n]→L[k] F) := iterated_continuous_linear_map.normed_space_rec k n E F /-- The n-th derivative of a function, defined inductively by saying that the (n+1)-th derivative of f is the n-th derivative of the derivative of f. -/ def iterated_fderiv (k : Type w) [hk : nondiscrete_normed_field k] (n : ℕ) {E : Type u} [gE : normed_group E] [sE : normed_space k E] : ∀{F : Type u} [gF : normed_group F] [sF : @normed_space k F _ gF] (f : E → F), E → @iterated_continuous_linear_map k hk n E gE sE F gF sF := nat.rec_on n (λF gF sF f, f) (λn rec F gF sF f, by { resetI, exact rec (fderiv k f) }) @[simp] lemma iterated_fderiv_zero : iterated_fderiv k 0 f = f := rfl @[simp] lemma iterated_fderiv_succ : iterated_fderiv k (n+1) f = (iterated_fderiv k n (λx, fderiv k f x) : _) := rfl /-- The n-th derivative of a function along a set, defined inductively by saying that the (n+1)-th derivative of f is the n-th derivative of the derivative of f. -/ def iterated_fderiv_within (k : Type w) [hk :nondiscrete_normed_field k] (n : ℕ) {E : Type u} [gE : normed_group E] [sE : normed_space k E] : ∀{F : Type u} [gF : normed_group F] [sF : @normed_space k F _ gF] (f : E → F) (s : set E), E → @iterated_continuous_linear_map k hk n E gE sE F gF sF := nat.rec_on n (λF gF sF f s, f) (λn rec F gF sF f s, by { resetI, exact rec (fderiv_within k f s) s}) @[simp] lemma iterated_fderiv_within_zero : iterated_fderiv_within k 0 f s = f := rfl @[simp] lemma iterated_fderiv_within_succ : iterated_fderiv_within k (n+1) f s = (iterated_fderiv_within k n (λx, fderiv_within k f s x) s : _) := rfl theorem iterated_fderiv_within_univ {n : ℕ} : iterated_fderiv_within k n f univ = iterated_fderiv k n f := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F, { refl }, { simp [IH] } end /-- If two functions coincide on a set `s` of unique differentiability, then their iterated differentials within this set coincide. -/ lemma iterated_fderiv_within_congr (hs : unique_diff_on k s) (hL : ∀y∈s, f₁ y = f y) (hx : x ∈ s) : iterated_fderiv_within k n f₁ s x = iterated_fderiv_within k n f s x := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f x, { simp [hL x hx] }, { simp only [iterated_fderiv_within_succ], refine IH (λy hy, _) hx, apply fderiv_within_congr (hs y hy) hL (hL y hy) } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with an open set containing `x`. -/ lemma iterated_fderiv_within_inter_open (xu : x ∈ u) (hu : is_open u) (xs : x ∈ s) (hs : unique_diff_on k (s ∩ u)) : iterated_fderiv_within k n f (s ∩ u) x = iterated_fderiv_within k n f s x := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { simp }, { simp, rw ← IH, apply iterated_fderiv_within_congr hs (λy hy, _) ⟨xs, xu⟩, apply fderiv_within_inter (mem_nhds_sets hu hy.2), have := hs y hy, rwa unique_diff_within_at_inter (mem_nhds_sets hu hy.2) at this } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x`. -/ lemma iterated_fderiv_within_inter (hu : u ∈ nhds x) (xs : x ∈ s) (hs : unique_diff_on k s) : iterated_fderiv_within k n f (s ∩ u) x = iterated_fderiv_within k n f s x := begin rcases mem_nhds_sets_iff.1 hu with ⟨v, vu, v_open, xv⟩, have A : (s ∩ u) ∩ v = s ∩ v, { apply subset.antisymm (inter_subset_inter (inter_subset_left _ _) (subset.refl _)), exact λ y ⟨ys, yv⟩, ⟨⟨ys, vu yv⟩, yv⟩ }, have : iterated_fderiv_within k n f (s ∩ v) x = iterated_fderiv_within k n f s x := iterated_fderiv_within_inter_open xv v_open xs (unique_diff_on_inter hs v_open), rw ← this, have : iterated_fderiv_within k n f ((s ∩ u) ∩ v) x = iterated_fderiv_within k n f (s ∩ u) x, { refine iterated_fderiv_within_inter_open xv v_open ⟨xs, mem_of_nhds hu⟩ _, rw A, exact unique_diff_on_inter hs v_open }, rw A at this, rw ← this end /-- Auxiliary definition defining `C^n` functions by induction over `n`. In applications, use `times_cont_diff` instead. -/ def times_cont_diff_rec (k : Type w) [nondiscrete_normed_field k] : Π (n : ℕ) {E : Type u} [gE : normed_group E] [@normed_space k E _ gE] {F : Type u} [gF : normed_group F] [@normed_space k F _ gF] (f : E → F), Prop | 0 E _ _ F _ _ f := by { resetI, exact continuous f } | (n+1) E _ _ F _ _ f := by { resetI, exact differentiable k f ∧ times_cont_diff_rec n (fderiv k f) } @[simp] lemma times_cont_diff_rec_zero : times_cont_diff_rec k 0 f ↔ continuous f := by refl @[simp] lemma times_cont_diff_rec_succ : times_cont_diff_rec k n.succ f ↔ differentiable k f ∧ times_cont_diff_rec k n (λx, fderiv k f x) := by refl lemma times_cont_diff_rec.of_succ (h : times_cont_diff_rec k n.succ f) : times_cont_diff_rec k n f := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F, { exact h.1.continuous }, { rw times_cont_diff_rec_succ at h ⊢, exact ⟨h.1, IH h.2⟩ } end lemma times_cont_diff_rec.continuous (h : times_cont_diff_rec k n f) : continuous (iterated_fderiv k n f) := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { exact h }, { rw iterated_fderiv_succ, exact IH (times_cont_diff_rec_succ.1 h).2 } end lemma times_cont_diff_rec.differentiable (h : times_cont_diff_rec k (n+1) f) : differentiable k (iterated_fderiv k n f) := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { exact h.1 }, { rw iterated_fderiv_succ, apply IH h.2 } end /-- Auxiliary definition defining `C^n` functions on a set by induction over `n`. In applications, use `times_cont_diff_on` instead. -/ def times_cont_diff_on_rec (k : Type w) [nondiscrete_normed_field k] : Π (n : ℕ) {E : Type u} [gE : normed_group E] [@normed_space k E _ gE] {F : Type u} [gF : normed_group F] [@normed_space k F _ gF] (f : E → F) (s : set E), Prop | 0 E _ _ F _ _ f s := by { resetI, exact continuous_on f s } | (n+1) E _ _ F _ _ f s := by { resetI, exact differentiable_on k f s ∧ times_cont_diff_on_rec n (fderiv_within k f s) s} @[simp] lemma times_cont_diff_on_rec_zero : times_cont_diff_on_rec k 0 f s ↔ continuous_on f s := by refl @[simp] lemma times_cont_diff_on_rec_succ : times_cont_diff_on_rec k n.succ f s ↔ differentiable_on k f s ∧ times_cont_diff_on_rec k n (λx, fderiv_within k f s x) s := by refl lemma times_cont_diff_on_rec.of_succ (h : times_cont_diff_on_rec k n.succ f s) : times_cont_diff_on_rec k n f s := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F, { exact h.1.continuous_on }, { rw times_cont_diff_on_rec_succ at h ⊢, exact ⟨h.1, IH h.2⟩ } end lemma times_cont_diff_on_rec.continuous_on_iterated_fderiv_within (h : times_cont_diff_on_rec k n f s) : continuous_on (iterated_fderiv_within k n f s) s := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { exact h }, { rw iterated_fderiv_within_succ, exact IH (times_cont_diff_on_rec_succ.1 h).2 } end lemma times_cont_diff_on_rec.differentiable_on (h : times_cont_diff_on_rec k (n+1) f s) : differentiable_on k (iterated_fderiv_within k n f s) s := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { exact h.1 }, { rw iterated_fderiv_within_succ, apply IH h.2 } end lemma times_cont_diff_on_rec_univ : times_cont_diff_on_rec k n f univ ↔ times_cont_diff_rec k n f := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { rw [times_cont_diff_on_rec_zero, times_cont_diff_rec_zero, continuous_iff_continuous_on_univ] }, { rw [times_cont_diff_on_rec_succ, times_cont_diff_rec_succ, differentiable_on_univ, fderiv_within_univ, IH] } end /-- A function is `C^n` on a set, for `n : with_top ℕ`, if its derivatives of order at most `n` are all well defined and continuous. -/ def times_cont_diff_on (k : Type w) [nondiscrete_normed_field k] (n : with_top ℕ) {E F : Type u} [normed_group E] [normed_space k E] [normed_group F] [normed_space k F] (f : E → F) (s : set E) := (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous_on (iterated_fderiv_within k m f s) s) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable_on k (iterated_fderiv_within k m f s) s) @[simp] lemma times_cont_diff_on_zero : times_cont_diff_on k 0 f s ↔ continuous_on f s := by simp [times_cont_diff_on] /-- The two definitions of `C^n` functions on domains, directly in terms of continuity of all derivatives, or by induction, are equivalent. -/ theorem times_cont_diff_on_iff_times_cont_diff_on_rec : times_cont_diff_on k n f s ↔ times_cont_diff_on_rec k n f s := begin tactic.unfreeze_local_instances, induction n with n IH generalizing F f, { rw [with_top.coe_zero, times_cont_diff_on_rec_zero, times_cont_diff_on_zero] }, { split, { assume H, rw times_cont_diff_on_rec_succ, refine ⟨H.2 0 (by simp only [with_top.zero_lt_coe, with_top.coe_zero, nat.succ_pos n]), _⟩, rw ← IH, split, { assume m hm, have : (m.succ : with_top nat) ≤ n.succ := with_top.coe_le_coe.2 (nat.succ_le_succ (with_top.coe_le_coe.1 hm)), exact H.1 _ this }, { assume m hm, have : (m.succ : with_top nat) < n.succ := with_top.coe_lt_coe.2 (nat.succ_le_succ (with_top.coe_lt_coe.1 hm)), exact H.2 _ this } }, { assume H, split, { assume m hm, simp only [with_top.coe_le_coe] at hm, cases nat.of_le_succ hm with h h, { have := H.of_succ, rw ← IH at this, exact this.1 _ (with_top.coe_le_coe.2 h) }, { rw h, simp at H, exact H.2.continuous_on_iterated_fderiv_within } }, { assume m hm, simp only [with_top.coe_lt_coe] at hm, cases nat.of_le_succ hm with h h, { have := H.of_succ, rw ← IH at this, exact this.2 _ (with_top.coe_lt_coe.2 h) }, { rw nat.succ_inj h, exact H.differentiable_on } } } }, end /- Next lemma is marked as a simp lemma as `C^(n+1)` functions appear mostly in inductions. -/ @[simp] lemma times_cont_diff_on_succ : times_cont_diff_on k n.succ f s ↔ differentiable_on k f s ∧ times_cont_diff_on k n (λx, fderiv_within k f s x) s := by simp [times_cont_diff_on_iff_times_cont_diff_on_rec] lemma times_cont_diff_on.of_le {m n : with_top ℕ} (h : times_cont_diff_on k n f s) (le : m ≤ n) : times_cont_diff_on k m f s := ⟨λp hp, h.1 p (le_trans hp le), λp hp, h.2 p (lt_of_lt_of_le hp le)⟩ lemma times_cont_diff_on.of_succ (h : times_cont_diff_on k n.succ f s) : times_cont_diff_on k n f s := h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)) lemma times_cont_diff_on.continuous_on {n : with_top ℕ} (h : times_cont_diff_on k n f s) : continuous_on f s := h.1 0 (by simp) lemma times_cont_diff_on.continuous_on_fderiv_within {n : with_top ℕ} (h : times_cont_diff_on k n f s) (hn : 1 ≤ n) : continuous_on (fderiv_within k f s) s := h.1 1 hn set_option class.instance_max_depth 50 /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff_on.continuous_on_fderiv_within_apply {n : with_top ℕ} (h : times_cont_diff_on k n f s) (hn : 1 ≤ n) : continuous_on (λp : E × E, (fderiv_within k f s p.1 : E → F) p.2) (set.prod s univ) := begin have A : continuous (λq : (E →L[k] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous_on (λp : E × E, (fderiv_within k f s p.1, p.2)) (set.prod s univ), { apply continuous_on.prod _ continuous_snd.continuous_on, refine continuous_on.comp (h.continuous_on_fderiv_within hn) continuous_fst.continuous_on (λx hx, _), simp at hx, rcases hx with ⟨y, hy⟩, exact hy }, exact A.comp_continuous_on B end lemma times_cont_diff_on_top : times_cont_diff_on k ⊤ f s ↔ (∀n:ℕ, times_cont_diff_on k n f s) := begin split, { assume h n, exact h.of_le lattice.le_top }, { assume h, split, { exact λm hm, (h m).1 m (le_refl _) }, { exact λ m hm, (h m.succ).2 m (with_top.coe_lt_coe.2 (lt_add_one m)) } } end lemma times_cont_diff_on_fderiv_within_nat {m n : ℕ} (hf : times_cont_diff_on k n f s) (h : m + 1 ≤ n) : times_cont_diff_on k m (λx, fderiv_within k f s x) s := begin have : times_cont_diff_on k m.succ f s := hf.of_le (with_top.coe_le_coe.2 h), exact (times_cont_diff_on_succ.1 this).2 end lemma times_cont_diff_on_fderiv_within {m n : with_top ℕ} (hf : times_cont_diff_on k n f s) (h : m + 1 ≤ n) : times_cont_diff_on k m (λx, fderiv_within k f s x) s := begin cases m, { change ⊤ + 1 ≤ n at h, have : n = ⊤, by simpa using h, rw this at hf, change times_cont_diff_on k ⊤ (λ (x : E), fderiv_within k f s x) s, rw times_cont_diff_on_top at ⊢ hf, exact λm, times_cont_diff_on_fderiv_within_nat (hf (m + 1)) (le_refl _) }, { have : times_cont_diff_on k (m + 1) f s := hf.of_le h, exact times_cont_diff_on_fderiv_within_nat this (le_refl _) } end lemma times_cont_diff_on.congr_mono {n : with_top ℕ} (H : times_cont_diff_on k n f s) (hs : unique_diff_on k s₁) (h : ∀x ∈ s₁, f₁ x = f x) (h₁ : s₁ ⊆ s) : times_cont_diff_on k n f₁ s₁ := begin tactic.unfreeze_local_instances, induction n using with_top.nat_induction with n IH Itop generalizing F, { rw times_cont_diff_on_zero at H ⊢, exact continuous_on.congr_mono H h h₁ }, { rw times_cont_diff_on_succ at H ⊢, refine ⟨differentiable_on.congr_mono H.1 h h₁, IH H.2 (λx hx, _)⟩, apply differentiable_within_at.fderiv_within_congr_mono (H.1 x (h₁ hx)) h (h x hx) (hs x hx) h₁ }, { rw times_cont_diff_on_top at H ⊢, assume n, exact Itop n (H n) h } end lemma times_cont_diff_on.congr {n : with_top ℕ} {s : set E} (H : times_cont_diff_on k n f s) (hs : unique_diff_on k s) (h : ∀x ∈ s, f₁ x = f x) : times_cont_diff_on k n f₁ s := times_cont_diff_on.congr_mono H hs h (subset.refl _) lemma times_cont_diff_on.congr_mono' {n m : with_top ℕ} {s : set E} (H : times_cont_diff_on k n f s) (hs : unique_diff_on k s₁) (h : ∀x ∈ s₁, f₁ x = f x) (h₁ : s₁ ⊆ s) (le : m ≤ n) : times_cont_diff_on k m f₁ s₁ := times_cont_diff_on.of_le (H.congr_mono hs h h₁) le lemma times_cont_diff_on.mono {n : with_top ℕ} {s t : set E} (h : times_cont_diff_on k n f t) (hst : s ⊆ t) (hs : unique_diff_on k s) : times_cont_diff_on k n f s := times_cont_diff_on.congr_mono h hs (λx hx, rfl) hst /-- Being `C^n` is a local property. -/ lemma times_cont_diff_on_of_locally_times_cont_diff_on {n : with_top ℕ} {s : set E} (hs : unique_diff_on k s) (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ times_cont_diff_on k n f (s ∩ u)) : times_cont_diff_on k n f s := begin split, { assume m hm, apply continuous_on_of_locally_continuous_on (λx hx, _), rcases h x hx with ⟨u, u_open, xu, hu⟩, refine ⟨u, u_open, xu,_⟩, apply continuous_on.congr_mono (hu.1 m hm) (λy hy, _) (subset.refl _), symmetry, exact iterated_fderiv_within_inter_open hy.2 u_open hy.1 (unique_diff_on_inter hs u_open) }, { assume m hm, apply differentiable_on_of_locally_differentiable_on (λx hx, _), rcases h x hx with ⟨u, u_open, xu, hu⟩, refine ⟨u, u_open, xu,_⟩, apply differentiable_on.congr_mono (hu.2 m hm) (λy hy, _) (subset.refl _), symmetry, exact iterated_fderiv_within_inter_open hy.2 u_open hy.1 (unique_diff_on_inter hs u_open) } end /-- A function is `C^n`, for `n : with_top ℕ`, if its derivatives of order at most `n` are all well defined and continuous. -/ def times_cont_diff (k : Type w) [nondiscrete_normed_field k] (n : with_top ℕ) {E F : Type u} [normed_group E] [normed_space k E] [normed_group F] [normed_space k F] (f : E → F) := (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous (iterated_fderiv k m f )) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable k (iterated_fderiv k m f)) lemma times_cont_diff_on_univ {n : with_top ℕ} : times_cont_diff_on k n f univ ↔ times_cont_diff k n f := by simp [times_cont_diff_on, times_cont_diff, iterated_fderiv_within_univ, continuous_iff_continuous_on_univ, differentiable_on_univ] @[simp] lemma times_cont_diff_zero : times_cont_diff k 0 f ↔ continuous f := by simp [times_cont_diff] theorem times_cont_diff_iff_times_cont_diff_rec : times_cont_diff k n f ↔ times_cont_diff_rec k n f := by simp [times_cont_diff_on_univ.symm, times_cont_diff_on_rec_univ.symm, times_cont_diff_on_iff_times_cont_diff_on_rec] @[simp] lemma times_cont_diff_succ : times_cont_diff k n.succ f ↔ differentiable k f ∧ times_cont_diff k n (λx, fderiv k f x) := by simp [times_cont_diff_iff_times_cont_diff_rec] lemma times_cont_diff.of_le {m n : with_top ℕ} (h : times_cont_diff k n f) (le : m ≤ n) : times_cont_diff k m f := ⟨λp hp, h.1 p (le_trans hp le), λp hp, h.2 p (lt_of_lt_of_le hp le)⟩ lemma times_cont_diff.of_succ (h : times_cont_diff k n.succ f) : times_cont_diff k n f := h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)) lemma times_cont_diff.continuous {n : with_top ℕ} (h : times_cont_diff k n f) : continuous f := h.1 0 (by simp) lemma times_cont_diff.continuous_fderiv {n : with_top ℕ} (h : times_cont_diff k n f) (hn : 1 ≤ n) : continuous (fderiv k f) := h.1 1 hn lemma times_cont_diff.continuous_fderiv_apply {n : with_top ℕ} (h : times_cont_diff k n f) (hn : 1 ≤ n) : continuous (λp : E × E, (fderiv k f p.1 : E → F) p.2) := begin have A : continuous (λq : (E →L[k] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous (λp : E × E, (fderiv k f p.1, p.2)), { apply continuous.prod_mk _ continuous_snd, exact continuous.comp (h.continuous_fderiv hn) continuous_fst }, exact A.comp B end lemma times_cont_diff_top : times_cont_diff k ⊤ f ↔ (∀n:ℕ, times_cont_diff k n f) := by simp [times_cont_diff_on_univ.symm, times_cont_diff_on_rec_univ.symm, times_cont_diff_on_top] lemma times_cont_diff.times_cont_diff_on {n : with_top ℕ} {s : set E} (h : times_cont_diff k n f) (hs : unique_diff_on k s) : times_cont_diff_on k n f s := by { rw ← times_cont_diff_on_univ at h, apply times_cont_diff_on.mono h (subset_univ _) hs } /-- Constants are C^∞. -/ lemma times_cont_diff_const {n : with_top ℕ} {c : F} : times_cont_diff k n (λx : E, c) := begin tactic.unfreeze_local_instances, induction n using with_top.nat_induction with n IH Itop generalizing F, { rw times_cont_diff_zero, apply continuous_const }, { refine times_cont_diff_succ.2 ⟨differentiable_const _, _⟩, simp [fderiv_const], exact IH }, { rw times_cont_diff_top, assume n, apply Itop } end /-- Linear functions are C^∞. -/ lemma is_bounded_linear_map.times_cont_diff {n : with_top ℕ} (hf : is_bounded_linear_map k f) : times_cont_diff k n f := begin induction n using with_top.nat_induction with n IH Itop, { rw times_cont_diff_zero, exact hf.continuous }, { refine times_cont_diff_succ.2 ⟨hf.differentiable, _⟩, simp [hf.fderiv], exact times_cont_diff_const }, { rw times_cont_diff_top, apply Itop } end /-- The first projection in a product is C^∞. -/ lemma times_cont_diff_fst {n : with_top ℕ} : times_cont_diff k n (prod.fst : E × F → E) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.fst /-- The second projection in a product is C^∞. -/ lemma times_cont_diff_snd {n : with_top ℕ} : times_cont_diff k n (prod.snd : E × F → F) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.snd /-- The identity is C^∞. -/ lemma times_cont_diff_id {n : with_top ℕ} : times_cont_diff k n (id : E → E) := is_bounded_linear_map.id.times_cont_diff /-- Bilinear functions are C^∞. -/ lemma is_bounded_bilinear_map.times_cont_diff {n : with_top ℕ} (hb : is_bounded_bilinear_map k b) : times_cont_diff k n b := begin induction n using with_top.nat_induction with n IH Itop, { rw times_cont_diff_zero, exact hb.continuous }, { refine times_cont_diff_succ.2 ⟨hb.differentiable, _⟩, simp [hb.fderiv], exact hb.is_bounded_linear_map_deriv.times_cont_diff }, { rw times_cont_diff_top, apply Itop } end /-- Composition by bounded linear maps preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.comp_is_bounded_linear {n : with_top ℕ} {s : set E} {f : E → F} {g : F → G} (hf : times_cont_diff_on k n f s) (hg : is_bounded_linear_map k g) (hs : unique_diff_on k s) : times_cont_diff_on k n (λx, g (f x)) s := begin tactic.unfreeze_local_instances, induction n using with_top.nat_induction with n IH Itop generalizing F G, { have : continuous_on g univ := hg.continuous.continuous_on, rw times_cont_diff_on_zero at hf ⊢, apply continuous_on.comp this hf (subset_univ _) }, { rw times_cont_diff_on_succ at hf ⊢, refine ⟨differentiable_on.comp hg.differentiable_on hf.1 (subset_univ _), _⟩, let Φ : (E →L[k] F) → (E →L[k] G) := λu, continuous_linear_map.comp (hg.to_continuous_linear_map) u, have : ∀x∈s, fderiv_within k (g ∘ f) s x = Φ (fderiv_within k f s x), { assume x hx, rw [fderiv_within.comp x _ (hf.1 x hx) (subset_univ _) (hs x hx), fderiv_within_univ, hg.fderiv], rw differentiable_within_at_univ, exact hg.differentiable_at }, apply times_cont_diff_on.congr_mono _ hs this (subset.refl _), simp only [times_cont_diff_on_succ] at hf, exact IH hf.2 hg.to_continuous_linear_map.is_bounded_linear_map_comp_left }, { rw times_cont_diff_on_top at hf ⊢, assume n, apply Itop n (hf n) hg } end /-- Composition by bounded linear maps preserves `C^n` functions. -/ lemma times_cont_diff.comp_is_bounded_linear {n : with_top ℕ} {f : E → F} {g : F → G} (hf : times_cont_diff k n f) (hg : is_bounded_linear_map k g) : times_cont_diff k n (λx, g (f x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp_is_bounded_linear (times_cont_diff_on_univ.2 hf) hg is_open_univ.unique_diff_on /-- The cartesian product of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G} (hf : times_cont_diff_on k n f s) (hg : times_cont_diff_on k n g s) (hs : unique_diff_on k s) : times_cont_diff_on k n (λx:E, (f x, g x)) s := begin tactic.unfreeze_local_instances, induction n using with_top.nat_induction with n IH Itop generalizing F G, { rw times_cont_diff_on_zero at hf hg ⊢, exact continuous_on.prod hf hg }, { rw times_cont_diff_on_succ at hf hg ⊢, refine ⟨differentiable_on.prod hf.1 hg.1, _⟩, let F₁ := λx : E, (fderiv_within k f s x, fderiv_within k g s x), let Φ : ((E →L[k] F) × (E →L[k] G)) → (E →L[k] (F × G)) := λp, continuous_linear_map.prod p.1 p.2, have : times_cont_diff_on k n (Φ ∘ F₁) s := times_cont_diff_on.comp_is_bounded_linear (IH hf.2 hg.2) is_bounded_linear_map_prod_iso hs, apply times_cont_diff_on.congr_mono this hs (λx hx, _) (subset.refl _), apply differentiable_at.fderiv_within_prod (hf.1 x hx) (hg.1 x hx) (hs x hx) }, { rw times_cont_diff_on_top at hf hg ⊢, assume n, apply Itop n (hf n) (hg n) } end /-- The cartesian product of `C^n` functions is `C^n`. -/ lemma times_cont_diff.prod {n : with_top ℕ} {f : E → F} {g : E → G} (hf : times_cont_diff k n f) (hg : times_cont_diff k n g) : times_cont_diff k n (λx:E, (f x, g x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.prod (times_cont_diff_on_univ.2 hf) (times_cont_diff_on_univ.2 hg) is_open_univ.unique_diff_on /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.comp {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : times_cont_diff_on k n g t) (hf : times_cont_diff_on k n f s) (hs : unique_diff_on k s) (st : f '' s ⊆ t) : times_cont_diff_on k n (g ∘ f) s := begin tactic.unfreeze_local_instances, induction n using with_top.nat_induction with n IH Itop generalizing E F G, { rw times_cont_diff_on_zero at hf hg ⊢, exact continuous_on.comp hg hf st }, { rw times_cont_diff_on_succ at hf hg ⊢, /- We have to show that the derivative of g ∘ f is C^n, given that g and f are C^(n+1). By the chain rule, this derivative is Dg(f x) ⬝ Df(x). This is the composition of x ↦ (Dg (f x), Df (x)) with the product of bounded linear maps, which is bilinear and therefore C^∞. By the induction assumption, it suffices to show that x ↦ (Dg (f x), Df (x)) is C^n. It is even enough to show that each component is C^n. This follows from the assumptions on f and g, and the inductive assumption. -/ refine ⟨differentiable_on.comp hg.1 hf.1 st, _⟩, have : ∀x∈s, fderiv_within k (g ∘ f) s x = continuous_linear_map.comp (fderiv_within k g t (f x)) (fderiv_within k f s x), { assume x hx, apply fderiv_within.comp x _ (hf.1 x hx) st (hs x hx), exact hg.1 _ (st (mem_image_of_mem _ hx)) }, apply times_cont_diff_on.congr _ hs this, have A : times_cont_diff_on k n (λx, fderiv_within k g t (f x)) s := IH hg.2 (times_cont_diff_on_succ.2 hf).of_succ hs st, have B : times_cont_diff_on k n (λx, fderiv_within k f s x) s := hf.2, have C : times_cont_diff_on k n (λx:E, (fderiv_within k f s x, fderiv_within k g t (f x))) s := times_cont_diff_on.prod B A hs, have D : times_cont_diff_on k n (λ(p : (E →L[k] F) × (F →L[k] G)), p.2.comp p.1) univ := is_bounded_bilinear_map_comp.times_cont_diff.times_cont_diff_on is_open_univ.unique_diff_on, exact IH D C hs (subset_univ _) }, { rw times_cont_diff_on_top at hf hg ⊢, assume n, apply Itop n (hg n) (hf n) hs st } end /-- The composition of `C^n` functions is `C^n`. -/ lemma times_cont_diff.comp {n : with_top ℕ} {g : F → G} {f : E → F} (hg : times_cont_diff k n g) (hf : times_cont_diff k n f) : times_cont_diff k n (g ∘ f) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp (times_cont_diff_on_univ.2 hg) (times_cont_diff_on_univ.2 hf) is_open_univ.unique_diff_on (subset_univ _) /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff_on_fderiv_within_apply {m n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on k n f s) (hs : unique_diff_on k s) (hmn : m + 1 ≤ n) : times_cont_diff_on k m (λp : E × E, (fderiv_within k f s p.1 : E →L[k] F) p.2) (set.prod s (univ : set E)) := begin have U : unique_diff_on k (set.prod s (univ : set E)) := hs.prod unique_diff_on_univ, have A : times_cont_diff_on k m (λp : (E →L[k] F) × E, p.1 p.2) univ, { rw times_cont_diff_on_univ, apply is_bounded_bilinear_map.times_cont_diff, exact is_bounded_bilinear_map_apply }, have B : times_cont_diff_on k m (λ (p : E × E), ((fderiv_within k f s p.fst), p.snd)) (set.prod s univ), { apply times_cont_diff_on.prod _ _ U, { have I : times_cont_diff_on k m (λ (x : E), fderiv_within k f s x) s := times_cont_diff_on_fderiv_within hf hmn, have J : times_cont_diff_on k m (λ (x : E × E), x.1) (set.prod s univ), { apply times_cont_diff.times_cont_diff_on _ U, apply is_bounded_linear_map.times_cont_diff, apply is_bounded_linear_map.fst }, exact times_cont_diff_on.comp I J U (fst_image_prod_subset _ _) }, { apply times_cont_diff.times_cont_diff_on _ U, apply is_bounded_linear_map.times_cont_diff, apply is_bounded_linear_map.snd } }, apply times_cont_diff_on.comp A B U (subset_univ _), end /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff.times_cont_diff_fderiv_apply {n m : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff k n f) (hmn : m + 1 ≤ n) : times_cont_diff k m (λp : E × E, (fderiv k f p.1 : E →L[k] F) p.2) := begin rw ← times_cont_diff_on_univ at ⊢ hf, rw [← fderiv_within_univ, ← univ_prod_univ], exact times_cont_diff_on_fderiv_within_apply hf unique_diff_on_univ hmn end
14fadffffc99a926546154dd48a5ab157d214061
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/rbmap/default.lean
287a1f86cfc21f1de749b3da988c8457f2a6a212
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,109
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.rbtree import data.rbmap.basic universes u v namespace rbmap variables {α : Type u} {β : Type v} {lt : α → α → Prop} /- Auxiliary instances -/ private def rbmap_lt_is_swo {α : Type u} {β : Type v} {lt : α → α → Prop} [is_strict_weak_order α lt] : is_strict_weak_order (α × β) (rbmap_lt lt) := { irrefl := λ _, irrefl_of lt _, trans := λ _ _ _ h₁ h₂, trans_of lt h₁ h₂, incomp_trans := λ _ _ _ h₁ h₂, incomp_trans_of lt h₁ h₂ } private def rbmap_lt_dec {α : Type u} {β : Type v} {lt : α → α → Prop} [h : decidable_rel lt] : decidable_rel (@rbmap_lt α β lt) := λ a b, h a.1 b.1 local attribute [instance] rbmap_lt_is_swo rbmap_lt_dec /- Helper lemmas for reusing rbtree results. -/ private lemma to_rbtree_mem {k : α} {m : rbmap α β lt} : k ∈ m → ∃ v : β, rbtree.mem (k, v) m := begin cases m with n p; cases n; intros h, { exact false.elim h }, all_goals { existsi n_val.2, exact h } end private lemma eqv_entries_of_eqv_keys {k₁ k₂ : α} (v₁ v₂ : β) : k₁ ≈[lt] k₂ → (k₁, v₁) ≈[rbmap_lt lt] (k₂, v₂) := id private lemma eqv_keys_of_eqv_entries {k₁ k₂ : α} {v₁ v₂ : β} : (k₁, v₁) ≈[rbmap_lt lt] (k₂, v₂) → k₁ ≈[lt] k₂ := id private lemma eqv_entries [is_irrefl α lt] (k : α) (v₁ v₂ : β) : (k, v₁) ≈[rbmap_lt lt] (k, v₂) := and.intro (irrefl_of lt k) (irrefl_of lt k) private lemma to_rbmap_mem [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : rbtree.mem (k, v) m → k ∈ m := begin cases m with n p; cases n; intros h, { exact false.elim h }, { simp [has_mem.mem, rbmap.mem], exact @rbtree.mem_of_mem_of_eqv _ _ _ ⟨rbnode.red_node n_lchild n_val n_rchild, p⟩ _ _ h (eqv_entries _ _ _) }, { simp [has_mem.mem, rbmap.mem], exact @rbtree.mem_of_mem_of_eqv _ _ _ ⟨rbnode.black_node n_lchild n_val n_rchild, p⟩ _ _ h (eqv_entries _ _ _) } end private lemma to_rbtree_mem' [is_strict_weak_order α lt] {k : α} {m : rbmap α β lt} (v : β) : k ∈ m → rbtree.mem (k, v) m := begin intro h, cases to_rbtree_mem h with v' hm, apply rbtree.mem_of_mem_of_eqv hm, apply eqv_entries end lemma eq_some_of_to_value_eq_some {e : option (α × β)} {v : β} : to_value e = some v → ∃ k, e = some (k, v) := begin cases e with val; simp [to_value, false_implies_iff], { cases val, simp, intro h, subst v, constructor, refl } end lemma eq_none_of_to_value_eq_none {e : option (α × β)} : to_value e = none → e = none := by cases e; simp [to_value, false_implies_iff] /- Lemmas -/ lemma not_mem_mk_rbmap : ∀ (k : α), k ∉ mk_rbmap α β lt := by simp [has_mem.mem, mk_rbmap, mk_rbtree, rbmap.mem] lemma not_mem_of_empty {m : rbmap α β lt} (k : α) : m.empty = tt → k ∉ m := by cases m with n p; cases n; simp [has_mem.mem, mk_rbmap, mk_rbtree, rbmap.mem, rbmap.empty, rbtree.empty, false_implies_iff] lemma mem_of_mem_of_eqv [is_strict_weak_order α lt] {m : rbmap α β lt} {k₁ k₂ : α} : k₁ ∈ m → k₁ ≈[lt] k₂ → k₂ ∈ m := begin intros h₁ h₂, have h₁ := to_rbtree_mem h₁, cases h₁ with v h₁, exact to_rbmap_mem (rbtree.mem_of_mem_of_eqv h₁ (eqv_entries_of_eqv_keys v v h₂)) end section decidable variables [decidable_rel lt] lemma not_mem_of_find_entry_none [is_strict_weak_order α lt] {k : α} {m : rbmap α β lt} : m.find_entry k = none → k ∉ m := begin cases m with t p, cases t; simp [find_entry], { intros, simp [has_mem.mem, rbmap.mem] }, all_goals { intro h, exact rbtree.not_mem_of_find_none h, } end lemma not_mem_of_find_none [is_strict_weak_order α lt] {k : α} {m : rbmap α β lt} : m.find k = none → k ∉ m := begin simp [find], intro h, have := eq_none_of_to_value_eq_none h, exact not_mem_of_find_entry_none this end lemma mem_of_find_entry_some [is_strict_weak_order α lt] {k₁ : α} {e : α × β} {m : rbmap α β lt} : m.find_entry k₁ = some e → k₁ ∈ m := begin cases m with t p, cases t; simp [find_entry, false_implies_iff], all_goals { intro h, exact rbtree.mem_of_find_some h } end lemma mem_of_find_some [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.find k = some v → k ∈ m := begin simp [find], intro h, have := eq_some_of_to_value_eq_some h, cases this with _ he, exact mem_of_find_entry_some he end lemma find_entry_eq_find_entry_of_eqv [is_strict_weak_order α lt] {m : rbmap α β lt} {k₁ k₂ : α} : k₁ ≈[lt] k₂ → m.find_entry k₁ = m.find_entry k₂ := begin intro h, cases m with t p, cases t; simp [find_entry], all_goals { apply rbtree.find_eq_find_of_eqv, apply eqv_entries_of_eqv_keys, assumption } end lemma find_eq_find_of_eqv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) : k₁ ≈[lt] k₂ → m.find k₁ = m.find k₂ := begin intro h, simp [find], apply congr_arg, apply find_entry_eq_find_entry_of_eqv, assumption end lemma find_entry_correct [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) : k ∈ m ↔ (∃ e, m.find_entry k = some e ∧ k ≈[lt] e.1) := begin apply iff.intro; cases m with t p, { intro h, have h := to_rbtree_mem h, cases h with v h₁, have hex := iff.mp (rbtree.find_correct _ _) h₁, cases hex with e h₂, existsi e, cases t; simp [find_entry] at ⊢ h₂, { simp [rbtree.find, rbnode.find] at h₂, cases h₂ }, { cases h₂ with h₂₁ h₂₂, split, { have := rbtree.find_eq_find_of_eqv ⟨rbnode.red_node t_lchild t_val t_rchild, p⟩ (eqv_entries k v t_val.2), rw [←this], exact h₂₁ }, { cases e, apply eqv_keys_of_eqv_entries h₂₂ } }, { cases h₂ with h₂₁ h₂₂, split, { have := rbtree.find_eq_find_of_eqv ⟨rbnode.black_node t_lchild t_val t_rchild, p⟩ (eqv_entries k v t_val.2), rw [←this], exact h₂₁ }, { cases e, apply eqv_keys_of_eqv_entries h₂₂ } } }, { intro h, cases h with e h, cases h with h₁ h₂, cases t; simp [find_entry] at h₁, { contradiction }, all_goals { exact to_rbmap_mem (rbtree.mem_of_find_some h₁) } } end lemma eqv_of_find_entry_some [is_strict_weak_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : m.find_entry k₁ = some (k₂, v) → k₁ ≈[lt] k₂ := begin cases m with t p, cases t; simp [find_entry, false_implies_iff], all_goals { intro h, exact eqv_keys_of_eqv_entries (rbtree.eqv_of_find_some h) } end lemma eq_of_find_entry_some [is_strict_total_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : m.find_entry k₁ = some (k₂, v) → k₁ = k₂ := λ h, suffices k₁ ≈[lt] k₂, from eq_of_eqv_lt this, eqv_of_find_entry_some h lemma find_correct [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) : k ∈ m ↔ ∃ v, m.find k = some v := begin apply iff.intro, { intro h, have := iff.mp (find_entry_correct k m) h, cases this with e h, cases h with h₁ h₂, existsi e.2, simp [find, h₁, to_value] }, { intro h, cases h with v h, simp [find] at h, have h := eq_some_of_to_value_eq_some h, cases h with k' h, have heqv := eqv_of_find_entry_some h, exact iff.mpr (find_entry_correct k m) ⟨(k', v), ⟨h, heqv⟩⟩ } end lemma constains_correct [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) : k ∈ m ↔ m.contains k = tt := begin apply iff.intro, { intro h, have h := iff.mp (find_entry_correct k m) h, cases h with e h, cases h with h₁ h₂, simp [contains, h₁, option.is_some] }, { simp [contains], intro h, generalize he : find_entry m k = e, cases e, { simp [he, option.is_some] at h, contradiction }, { exact mem_of_find_entry_some he } } end lemma mem_insert_of_incomp [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : (¬ lt k₁ k₂ ∧ ¬ lt k₂ k₁) → k₁ ∈ m.insert k₂ v := λ h, to_rbmap_mem (rbtree.mem_insert_of_incomp m (eqv_entries_of_eqv_keys v v h)) lemma mem_insert [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) (v : β) : k ∈ m.insert k v := to_rbmap_mem (rbtree.mem_insert (k, v) m) lemma mem_insert_of_equiv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : k₁ ≈[lt] k₂ → k₁ ∈ m.insert k₂ v := mem_insert_of_incomp m v lemma mem_insert_of_mem [is_strict_weak_order α lt] {k₁ : α} {m : rbmap α β lt} (k₂ : α) (v : β) : k₁ ∈ m → k₁ ∈ m.insert k₂ v := λ h, to_rbmap_mem (rbtree.mem_insert_of_mem (k₂, v) (to_rbtree_mem' v h)) lemma equiv_or_mem_of_mem_insert [is_strict_weak_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : k₁ ∈ m.insert k₂ v → k₁ ≈[lt] k₂ ∨ k₁ ∈ m := λ h, or.elim (rbtree.equiv_or_mem_of_mem_insert (to_rbtree_mem' v h)) (λ h, or.inl (eqv_keys_of_eqv_entries h)) (λ h, or.inr (to_rbmap_mem h)) lemma incomp_or_mem_of_mem_ins [is_strict_weak_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : k₁ ∈ m.insert k₂ v → (¬ lt k₁ k₂ ∧ ¬ lt k₂ k₁) ∨ k₁ ∈ m := equiv_or_mem_of_mem_insert lemma eq_or_mem_of_mem_ins [is_strict_total_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : k₁ ∈ m.insert k₂ v → k₁ = k₂ ∨ k₁ ∈ m := λ h, suffices k₁ ≈[lt] k₂ ∨ k₁ ∈ m, by simp [eqv_lt_iff_eq] at this; assumption, incomp_or_mem_of_mem_ins h lemma find_entry_insert_of_eqv [is_strict_weak_order α lt] (m : rbmap α β lt) {k₁ k₂ : α} (v : β) : k₁ ≈[lt] k₂ → (m.insert k₁ v).find_entry k₂ = some (k₁, v) := begin intro h, generalize h₁ : m.insert k₁ v = m', cases m' with t p, cases t, { have := mem_insert k₁ m v, rw [h₁] at this, apply absurd this, apply not_mem_mk_rbmap }, all_goals { simp [find_entry], rw [←h₁, insert], apply rbtree.find_insert_of_eqv, apply eqv_entries_of_eqv_keys _ _ h } end lemma find_entry_insert [is_strict_weak_order α lt] (m : rbmap α β lt) (k : α) (v : β) : (m.insert k v).find_entry k = some (k, v) := find_entry_insert_of_eqv m v (refl k) lemma find_insert_of_eqv [is_strict_weak_order α lt] (m : rbmap α β lt) {k₁ k₂ : α} (v : β) : k₁ ≈[lt] k₂ → (m.insert k₁ v).find k₂ = some v := begin intro h, have := find_entry_insert_of_eqv m v h, simp [find, this, to_value] end lemma find_insert [is_strict_weak_order α lt] (m : rbmap α β lt) (k : α) (v : β) : (m.insert k v).find k = some v := find_insert_of_eqv m v (refl k) lemma find_entry_insert_of_disj [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : lt k₁ k₂ ∨ lt k₂ k₁ → (m.insert k₁ v).find_entry k₂ = m.find_entry k₂ := begin intro h, have h' : ∀ {v₁ v₂ : β}, (rbmap_lt lt) (k₁, v₁) (k₂, v₂) ∨ (rbmap_lt lt) (k₂, v₂) (k₁, v₁) := λ _ _, h, generalize h₁ : m = m₁, generalize h₂ : insert m₁ k₁ v = m₂, rw [←h₁] at h₂ ⊢, rw [←h₂], cases m₁ with t₁ p₁; cases t₁; cases m₂ with t₂ p₂; cases t₂, { rw [h₂, h₁] }, iterate 2 { rw [h₂], conv { to_lhs, simp [find_entry] }, rw [←h₂, insert, rbtree.find_insert_of_disj _ h', h₁], refl }, any_goals { simp [insert] at h₂, exact absurd h₂ (rbtree.insert_ne_mk_rbtree m (k₁, v)) }, any_goals { rw [h₂, h₁], simp [find_entry], rw [←h₂, ←h₁, insert, rbtree.find_insert_of_disj _ h'], apply rbtree.find_eq_find_of_eqv, apply eqv_entries } end lemma find_entry_insert_of_not_eqv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : ¬ k₁ ≈[lt] k₂ → (m.insert k₁ v).find_entry k₂ = m.find_entry k₂ := begin intro hn, have he : lt k₁ k₂ ∨ lt k₂ k₁, { simp [strict_weak_order.equiv, decidable.not_and_iff_or_not, decidable.not_not_iff] at hn, assumption }, apply find_entry_insert_of_disj _ _ he end lemma find_entry_insert_of_ne [is_strict_total_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : k₁ ≠ k₂ → (m.insert k₁ v).find_entry k₂ = m.find_entry k₂ := begin intro h, have : ¬ k₁ ≈[lt] k₂ := λ h', h (eq_of_eqv_lt h'), apply find_entry_insert_of_not_eqv _ _ this end lemma find_insert_of_disj [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : lt k₁ k₂ ∨ lt k₂ k₁ → (m.insert k₁ v).find k₂ = m.find k₂ := begin intro h, have := find_entry_insert_of_disj m v h, simp [find, this] end lemma find_insert_of_not_eqv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : ¬ k₁ ≈[lt] k₂ → (m.insert k₁ v).find k₂ = m.find k₂ := begin intro h, have := find_entry_insert_of_not_eqv m v h, simp [find, this] end lemma find_insert_of_ne [is_strict_total_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : k₁ ≠ k₂ → (m.insert k₁ v).find k₂ = m.find k₂ := begin intro h, have := find_entry_insert_of_ne m v h, simp [find, this] end end decidable lemma mem_of_min_eq [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.min = some (k, v) → k ∈ m := λ h, to_rbmap_mem (rbtree.mem_of_min_eq h) lemma mem_of_max_eq [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.max = some (k, v) → k ∈ m := λ h, to_rbmap_mem (rbtree.mem_of_max_eq h) lemma eq_leaf_of_min_eq_none {m : rbmap α β lt} : m.min = none → m = mk_rbmap α β lt := rbtree.eq_leaf_of_min_eq_none lemma eq_leaf_of_max_eq_none {m : rbmap α β lt} : m.max = none → m = mk_rbmap α β lt := rbtree.eq_leaf_of_max_eq_none lemma min_is_minimal [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.min = some (k, v) → ∀ {k'}, k' ∈ m → k ≈[lt] k' ∨ lt k k' := λ h k' hm, or.elim (rbtree.min_is_minimal h (to_rbtree_mem' v hm)) (λ h, or.inl (eqv_keys_of_eqv_entries h)) (λ h, or.inr h) lemma max_is_maximal [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.max = some (k, v) → ∀ {k'}, k' ∈ m → k ≈[lt] k' ∨ lt k' k := λ h k' hm, or.elim (rbtree.max_is_maximal h (to_rbtree_mem' v hm)) (λ h, or.inl (eqv_keys_of_eqv_entries h)) (λ h, or.inr h) lemma min_is_minimal_of_total [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.min = some (k, v) → ∀ {k'}, k' ∈ m → k = k' ∨ lt k k' := λ h k' hm, match min_is_minimal h hm with | or.inl h := or.inl (eq_of_eqv_lt h) | or.inr h := or.inr h end lemma max_is_maximal_of_total [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.max = some (k, v) → ∀ {k'}, k' ∈ m → k = k' ∨ lt k' k := λ h k' hm, match max_is_maximal h hm with | or.inl h := or.inl (eq_of_eqv_lt h) | or.inr h := or.inr h end end rbmap
b8f22571b221599a37704e19210a19c8996fb95a
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/simplifier_synth_congr.lean
4df7322f95a90719035acf187ec52bdf5898acc7
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
1,221
lean
open tactic universe variable l constants (ss₁ : Type.{l} → Type.{l}) (ss₂ : Π {A : Type.{l}}, A → Type.{l}) [sss₁ : ∀ T, subsingleton (ss₁ T)] [sss₂ : ∀ T (t : T), subsingleton (ss₂ t)] (A B : Type.{l}) (HAB : A = B) (ss_A : ss₁ A) (ss_B : ss₁ B) (a₁ a₁' a₂ a₂' : A) (H₁ : a₁ = a₁') (H₂ : a₂ = a₂') (ss_a₁ : ss₂ a₁) (ss_a₁' : ss₂ a₁') (ss_a₂ : ss₂ a₂) (ss_a₂' : ss₂ a₂') (f : Π (X : Type.{l}) (ss_X : ss₁ X) (x₁ x₂ : X) (ss_x₁ : ss₂ x₁) (ss_x₂ : ss₂ x₂), Type.{l}) attribute sss₁ [instance] attribute sss₂ [instance] attribute HAB [simp] attribute H₁ [simp] attribute H₂ [simp] example : f A ss_A a₁ a₂ ss_a₁ ss_a₂ = f A ss_A a₁' a₂' ss_a₁' ss_a₂' := by simp attribute [reducible] noncomputable definition c₁' := a₁' attribute [reducible] noncomputable definition c₂' := a₂' example : f A ss_A a₁' a₂' ss_a₁' ss_a₂' = f A ss_A c₁' c₂' ss_a₁' ss_a₂' := by simp example : f A ss_A a₁ a₂ ss_a₁ ss_a₂ = f A ss_A c₁' c₂' ss_a₁' ss_a₂' := by simp
c3b5e43764609db2762767b6089d23c9a5cd94c1
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/matrix/kronecker.lean
9c07d87b561bf7f3c76ba7f1eefe6fb9af808e23
[ "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,288
lean
/- Copyright (c) 2021 Filippo A. E. Nuccio. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Filippo A. E. Nuccio, Eric Wieser -/ import data.matrix.basic import data.matrix.block import linear_algebra.matrix.determinant import linear_algebra.matrix.nonsingular_inverse import linear_algebra.tensor_product import ring_theory.tensor_product /-! # Kronecker product of matrices This defines the [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product). ## Main definitions * `matrix.kronecker_map`: A generalization of the Kronecker product: given a map `f : α → β → γ` and matrices `A` and `B` with coefficients in `α` and `β`, respectively, it is defined as the matrix with coefficients in `γ` such that `kronecker_map f A B (i₁, i₂) (j₁, j₂) = f (A i₁ j₁) (B i₁ j₂)`. * `matrix.kronecker_map_bilinear`: when `f` is bilinear, so is `kronecker_map f`. ## Specializations * `matrix.kronecker`: An alias of `kronecker_map (*)`. Prefer using the notation. * `matrix.kronecker_bilinear`: `matrix.kronecker` is bilinear * `matrix.kronecker_tmul`: An alias of `kronecker_map (⊗ₜ)`. Prefer using the notation. * `matrix.kronecker_tmul_bilinear`: `matrix.tmul_kronecker` is bilinear ## Notations These require `open_locale kronecker`: * `A ⊗ₖ B` for `kronecker_map (*) A B`. Lemmas about this notation use the token `kronecker`. * `A ⊗ₖₜ B` and `A ⊗ₖₜ[R] B` for `kronecker_map (⊗ₜ) A B`. Lemmas about this notation use the token `kronecker_tmul`. -/ namespace matrix open_locale matrix variables {R α α' β β' γ γ' : Type*} variables {l m n p : Type*} {q r : Type*} {l' m' n' p' : Type*} section kronecker_map /-- Produce a matrix with `f` applied to every pair of elements from `A` and `B`. -/ def kronecker_map (f : α → β → γ) (A : matrix l m α) (B : matrix n p β) : matrix (l × n) (m × p) γ := of $ λ (i : l × n) (j : m × p), f (A i.1 j.1) (B i.2 j.2) -- TODO: set as an equation lemma for `kronecker_map`, see mathlib4#3024 @[simp] lemma kronecker_map_apply (f : α → β → γ) (A : matrix l m α) (B : matrix n p β) (i j) : kronecker_map f A B i j = f (A i.1 j.1) (B i.2 j.2) := rfl lemma kronecker_map_transpose (f : α → β → γ) (A : matrix l m α) (B : matrix n p β) : kronecker_map f Aᵀ Bᵀ = (kronecker_map f A B)ᵀ := ext $ λ i j, rfl lemma kronecker_map_map_left (f : α' → β → γ) (g : α → α') (A : matrix l m α) (B : matrix n p β) : kronecker_map f (A.map g) B = kronecker_map (λ a b, f (g a) b) A B := ext $ λ i j, rfl lemma kronecker_map_map_right (f : α → β' → γ) (g : β → β') (A : matrix l m α) (B : matrix n p β) : kronecker_map f A (B.map g) = kronecker_map (λ a b, f a (g b)) A B := ext $ λ i j, rfl lemma kronecker_map_map (f : α → β → γ) (g : γ → γ') (A : matrix l m α) (B : matrix n p β) : (kronecker_map f A B).map g = kronecker_map (λ a b, g (f a b)) A B := ext $ λ i j, rfl @[simp] lemma kronecker_map_zero_left [has_zero α] [has_zero γ] (f : α → β → γ) (hf : ∀ b, f 0 b = 0) (B : matrix n p β) : kronecker_map f (0 : matrix l m α) B = 0:= ext $ λ i j,hf _ @[simp] lemma kronecker_map_zero_right [has_zero β] [has_zero γ] (f : α → β → γ) (hf : ∀ a, f a 0 = 0) (A : matrix l m α) : kronecker_map f A (0 : matrix n p β) = 0 := ext $ λ i j, hf _ lemma kronecker_map_add_left [has_add α] [has_add γ] (f : α → β → γ) (hf : ∀ a₁ a₂ b, f (a₁ + a₂) b = f a₁ b + f a₂ b) (A₁ A₂ : matrix l m α) (B : matrix n p β) : kronecker_map f (A₁ + A₂) B = kronecker_map f A₁ B + kronecker_map f A₂ B := ext $ λ i j, hf _ _ _ lemma kronecker_map_add_right [has_add β] [has_add γ] (f : α → β → γ) (hf : ∀ a b₁ b₂, f a (b₁ + b₂) = f a b₁ + f a b₂) (A : matrix l m α) (B₁ B₂ : matrix n p β) : kronecker_map f A (B₁ + B₂) = kronecker_map f A B₁ + kronecker_map f A B₂ := ext $ λ i j, hf _ _ _ lemma kronecker_map_smul_left [has_smul R α] [has_smul R γ] (f : α → β → γ) (r : R) (hf : ∀ a b, f (r • a) b = r • f a b) (A : matrix l m α) (B : matrix n p β) : kronecker_map f (r • A) B = r • kronecker_map f A B := ext $ λ i j, hf _ _ lemma kronecker_map_smul_right [has_smul R β] [has_smul R γ] (f : α → β → γ) (r : R) (hf : ∀ a b, f a (r • b) = r • f a b) (A : matrix l m α) (B : matrix n p β) : kronecker_map f A (r • B) = r • kronecker_map f A B := ext $ λ i j, hf _ _ lemma kronecker_map_diagonal_diagonal [has_zero α] [has_zero β] [has_zero γ] [decidable_eq m] [decidable_eq n] (f : α → β → γ) (hf₁ : ∀ b, f 0 b = 0) (hf₂ : ∀ a, f a 0 = 0) (a : m → α) (b : n → β): kronecker_map f (diagonal a) (diagonal b) = diagonal (λ mn, f (a mn.1) (b mn.2)) := begin ext ⟨i₁, i₂⟩ ⟨j₁, j₂⟩, simp [diagonal, apply_ite f, ite_and, ite_apply, apply_ite (f (a i₁)), hf₁, hf₂], end lemma kronecker_map_diagonal_right [has_zero β] [has_zero γ] [decidable_eq n] (f : α → β → γ) (hf : ∀ a, f a 0 = 0) (A : matrix l m α) (b : n → β): kronecker_map f A (diagonal b) = block_diagonal (λ i, A.map (λ a, f a (b i))) := begin ext ⟨i₁, i₂⟩ ⟨j₁, j₂⟩, simp [diagonal, block_diagonal, apply_ite (f (A i₁ j₁)), hf], end lemma kronecker_map_diagonal_left [has_zero α] [has_zero γ] [decidable_eq l] (f : α → β → γ) (hf : ∀ b, f 0 b = 0) (a : l → α) (B : matrix m n β) : kronecker_map f (diagonal a) B = matrix.reindex (equiv.prod_comm _ _) (equiv.prod_comm _ _) (block_diagonal (λ i, B.map (λ b, f (a i) b))) := begin ext ⟨i₁, i₂⟩ ⟨j₁, j₂⟩, simp [diagonal, block_diagonal, apply_ite f, ite_apply, hf], end @[simp] lemma kronecker_map_one_one [has_zero α] [has_zero β] [has_zero γ] [has_one α] [has_one β] [has_one γ] [decidable_eq m] [decidable_eq n] (f : α → β → γ) (hf₁ : ∀ b, f 0 b = 0) (hf₂ : ∀ a, f a 0 = 0) (hf₃ : f 1 1 = 1) : kronecker_map f (1 : matrix m m α) (1 : matrix n n β) = 1 := (kronecker_map_diagonal_diagonal _ hf₁ hf₂ _ _).trans $ by simp only [hf₃, diagonal_one] lemma kronecker_map_reindex (f : α → β → γ) (el : l ≃ l') (em : m ≃ m') (en : n ≃ n') (ep : p ≃ p') (M : matrix l m α) (N : matrix n p β) : kronecker_map f (reindex el em M) (reindex en ep N) = reindex (el.prod_congr en) (em.prod_congr ep) (kronecker_map f M N) := by { ext ⟨i, i'⟩ ⟨j, j'⟩, refl } lemma kronecker_map_reindex_left (f : α → β → γ) (el : l ≃ l') (em : m ≃ m') (M : matrix l m α) (N : matrix n n' β) : kronecker_map f (matrix.reindex el em M) N = reindex (el.prod_congr (equiv.refl _)) (em.prod_congr (equiv.refl _)) (kronecker_map f M N) := kronecker_map_reindex _ _ _ (equiv.refl _) (equiv.refl _) _ _ lemma kronecker_map_reindex_right (f : α → β → γ) (em : m ≃ m') (en : n ≃ n') (M : matrix l l' α) (N : matrix m n β) : kronecker_map f M (reindex em en N) = reindex ((equiv.refl _).prod_congr em) ((equiv.refl _).prod_congr en) (kronecker_map f M N) := kronecker_map_reindex _ (equiv.refl _) (equiv.refl _) _ _ _ _ lemma kronecker_map_assoc {δ ξ ω ω' : Type*} (f : α → β → γ) (g : γ → δ → ω) (f' : α → ξ → ω') (g' : β → δ → ξ) (A : matrix l m α) (B : matrix n p β) (D : matrix q r δ) (φ : ω ≃ ω') (hφ : ∀ a b d, φ (g (f a b) d) = f' a (g' b d)) : (reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r)).trans (equiv.map_matrix φ) (kronecker_map g (kronecker_map f A B) D) = kronecker_map f' A (kronecker_map g' B D) := ext $ λ i j, hφ _ _ _ lemma kronecker_map_assoc₁ {δ ξ ω : Type*} (f : α → β → γ) (g : γ → δ → ω) (f' : α → ξ → ω) (g' : β → δ → ξ) (A : matrix l m α) (B : matrix n p β) (D : matrix q r δ) (h : ∀ a b d, (g (f a b) d) = f' a (g' b d)) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) (kronecker_map g (kronecker_map f A B) D) = kronecker_map f' A (kronecker_map g' B D) := ext $ λ i j, h _ _ _ /-- When `f` is bilinear then `matrix.kronecker_map f` is also bilinear. -/ @[simps] def kronecker_map_bilinear [comm_semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) : matrix l m α →ₗ[R] matrix n p β →ₗ[R] matrix (l × n) (m × p) γ := linear_map.mk₂ R (kronecker_map (λ r s, f r s)) (kronecker_map_add_left _ $ f.map_add₂) (λ r, kronecker_map_smul_left _ _ $ f.map_smul₂ _) (kronecker_map_add_right _ $ λ a, (f a).map_add) (λ r, kronecker_map_smul_right _ _ $ λ a, (f a).map_smul r) /-- `matrix.kronecker_map_bilinear` commutes with `⬝` if `f` commutes with `*`. This is primarily used with `R = ℕ` to prove `matrix.mul_kronecker_mul`. -/ lemma kronecker_map_bilinear_mul_mul [comm_semiring R] [fintype m] [fintype m'] [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] [non_unital_non_assoc_semiring γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) (h_comm : ∀ a b a' b', f (a * b) (a' * b') = f a a' * f b b') (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' β) (B' : matrix m' n' β) : kronecker_map_bilinear f (A ⬝ B) (A' ⬝ B') = (kronecker_map_bilinear f A A') ⬝ (kronecker_map_bilinear f B B') := begin ext ⟨i, i'⟩ ⟨j, j'⟩, simp only [kronecker_map_bilinear_apply_apply, mul_apply, ← finset.univ_product_univ, finset.sum_product, kronecker_map_apply], simp_rw [f.map_sum, linear_map.sum_apply, linear_map.map_sum, h_comm], end /-- `trace` distributes over `matrix.kronecker_map_bilinear`. This is primarily used with `R = ℕ` to prove `matrix.trace_kronecker`. -/ lemma trace_kronecker_map_bilinear [comm_semiring R] [fintype m] [fintype n] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) (A : matrix m m α) (B : matrix n n β) : trace (kronecker_map_bilinear f A B) = f (trace A) (trace B) := by simp_rw [matrix.trace, matrix.diag, kronecker_map_bilinear_apply_apply, linear_map.map_sum₂, map_sum, ←finset.univ_product_univ, finset.sum_product, kronecker_map_apply] /-- `determinant` of `matrix.kronecker_map_bilinear`. This is primarily used with `R = ℕ` to prove `matrix.det_kronecker`. -/ lemma det_kronecker_map_bilinear [comm_semiring R] [fintype m] [fintype n] [decidable_eq m] [decidable_eq n] [comm_ring α] [comm_ring β] [comm_ring γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) (h_comm : ∀ a b a' b', f (a * b) (a' * b') = f a a' * f b b') (A : matrix m m α) (B : matrix n n β) : det (kronecker_map_bilinear f A B) = det (A.map (λ a, f a 1)) ^ fintype.card n * det (B.map (λ b, f 1 b)) ^ fintype.card m := calc det (kronecker_map_bilinear f A B) = det (kronecker_map_bilinear f A 1 ⬝ kronecker_map_bilinear f 1 B) : by rw [←kronecker_map_bilinear_mul_mul f h_comm, matrix.mul_one, matrix.one_mul] ... = det (block_diagonal (λ _, A.map (λ a, f a 1))) * det (block_diagonal (λ _, B.map (λ b, f 1 b))) : begin rw [det_mul, ←diagonal_one, ←diagonal_one, kronecker_map_bilinear_apply_apply, kronecker_map_diagonal_right _ (λ _, _), kronecker_map_bilinear_apply_apply, kronecker_map_diagonal_left _ (λ _, _), det_reindex_self], { exact linear_map.map_zero₂ _ _ }, { exact map_zero _ }, end ... = _ : by simp_rw [det_block_diagonal, finset.prod_const, finset.card_univ] end kronecker_map /-! ### Specialization to `matrix.kronecker_map (*)` -/ section kronecker open_locale matrix /-- The Kronecker product. This is just a shorthand for `kronecker_map (*)`. Prefer the notation `⊗ₖ` rather than this definition. -/ @[simp] def kronecker [has_mul α] : matrix l m α → matrix n p α → matrix (l × n) (m × p) α := kronecker_map (*) localized "infix (name := matrix.kronecker_map.mul) ` ⊗ₖ `:100 := matrix.kronecker_map (*)" in kronecker @[simp] lemma kronecker_apply [has_mul α] (A : matrix l m α) (B : matrix n p α) (i₁ i₂ j₁ j₂) : (A ⊗ₖ B) (i₁, i₂) (j₁, j₂) = A i₁ j₁ * B i₂ j₂ := rfl /-- `matrix.kronecker` as a bilinear map. -/ def kronecker_bilinear [comm_semiring R] [semiring α] [algebra R α] : matrix l m α →ₗ[R] matrix n p α →ₗ[R] matrix (l × n) (m × p) α := kronecker_map_bilinear (algebra.lmul R α) /-! What follows is a copy, in order, of every `matrix.kronecker_map` lemma above that has hypotheses which can be filled by properties of `*`. -/ @[simp] lemma zero_kronecker [mul_zero_class α] (B : matrix n p α) : (0 : matrix l m α) ⊗ₖ B = 0 := kronecker_map_zero_left _ zero_mul B @[simp] lemma kronecker_zero [mul_zero_class α] (A : matrix l m α) : A ⊗ₖ (0 : matrix n p α) = 0 := kronecker_map_zero_right _ mul_zero A lemma add_kronecker [distrib α] (A₁ A₂ : matrix l m α) (B : matrix n p α) : (A₁ + A₂) ⊗ₖ B = A₁ ⊗ₖ B + A₂ ⊗ₖ B := kronecker_map_add_left _ add_mul _ _ _ lemma kronecker_add [distrib α] (A : matrix l m α) (B₁ B₂ : matrix n p α) : A ⊗ₖ (B₁ + B₂) = A ⊗ₖ B₁ + A ⊗ₖ B₂ := kronecker_map_add_right _ mul_add _ _ _ lemma smul_kronecker [monoid R] [monoid α] [mul_action R α] [is_scalar_tower R α α] (r : R) (A : matrix l m α) (B : matrix n p α) : (r • A) ⊗ₖ B = r • (A ⊗ₖ B) := kronecker_map_smul_left _ _ (λ _ _, smul_mul_assoc _ _ _) _ _ lemma kronecker_smul [monoid R] [monoid α] [mul_action R α] [smul_comm_class R α α] (r : R) (A : matrix l m α) (B : matrix n p α) : A ⊗ₖ (r • B) = r • (A ⊗ₖ B) := kronecker_map_smul_right _ _ (λ _ _, mul_smul_comm _ _ _) _ _ lemma diagonal_kronecker_diagonal [mul_zero_class α] [decidable_eq m] [decidable_eq n] (a : m → α) (b : n → α): (diagonal a) ⊗ₖ (diagonal b) = diagonal (λ mn, (a mn.1) * (b mn.2)) := kronecker_map_diagonal_diagonal _ zero_mul mul_zero _ _ lemma kronecker_diagonal [mul_zero_class α] [decidable_eq n] (A : matrix l m α) (b : n → α): A ⊗ₖ diagonal b = block_diagonal (λ i, mul_opposite.op (b i) • A) := kronecker_map_diagonal_right _ mul_zero _ _ lemma diagonal_kronecker [mul_zero_class α] [decidable_eq l](a : l → α) (B : matrix m n α) : diagonal a ⊗ₖ B = matrix.reindex (equiv.prod_comm _ _) (equiv.prod_comm _ _) (block_diagonal (λ i, a i • B)) := kronecker_map_diagonal_left _ zero_mul _ _ @[simp] lemma one_kronecker_one [mul_zero_one_class α] [decidable_eq m] [decidable_eq n] : (1 : matrix m m α) ⊗ₖ (1 : matrix n n α) = 1 := kronecker_map_one_one _ zero_mul mul_zero (one_mul _) lemma kronecker_one [mul_zero_one_class α] [decidable_eq n] (A : matrix l m α) : A ⊗ₖ (1 : matrix n n α) = block_diagonal (λ i, A) := (kronecker_diagonal _ _).trans $ congr_arg _ $ funext $ λ _, matrix.ext $ λ _ _, mul_one _ lemma one_kronecker [mul_zero_one_class α] [decidable_eq l] (B : matrix m n α) : (1 : matrix l l α) ⊗ₖ B = matrix.reindex (equiv.prod_comm _ _) (equiv.prod_comm _ _) (block_diagonal (λ i, B)) := (diagonal_kronecker _ _).trans $ congr_arg _ $ congr_arg _ $ funext $ λ _, matrix.ext $ λ _ _, one_mul _ lemma mul_kronecker_mul [fintype m] [fintype m'] [comm_semiring α] (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' α) (B' : matrix m' n' α) : (A ⬝ B) ⊗ₖ (A' ⬝ B') = (A ⊗ₖ A') ⬝ (B ⊗ₖ B') := kronecker_map_bilinear_mul_mul (algebra.lmul ℕ α).to_linear_map mul_mul_mul_comm A B A' B' @[simp] lemma kronecker_assoc [semigroup α] (A : matrix l m α) (B : matrix n p α) (C : matrix q r α) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) ((A ⊗ₖ B) ⊗ₖ C) = A ⊗ₖ (B ⊗ₖ C) := kronecker_map_assoc₁ _ _ _ _ A B C mul_assoc lemma trace_kronecker [fintype m] [fintype n] [semiring α] (A : matrix m m α) (B : matrix n n α) : trace (A ⊗ₖ B) = trace A * trace B := trace_kronecker_map_bilinear (algebra.lmul ℕ α).to_linear_map _ _ lemma det_kronecker [fintype m] [fintype n] [decidable_eq m] [decidable_eq n] [comm_ring R] (A : matrix m m R) (B : matrix n n R) : det (A ⊗ₖ B) = det A ^ fintype.card n * det B ^ fintype.card m := begin refine (det_kronecker_map_bilinear (algebra.lmul ℕ R).to_linear_map mul_mul_mul_comm _ _).trans _, congr' 3, { ext i j, exact mul_one _}, { ext i j, exact one_mul _}, end lemma inv_kronecker [fintype m] [fintype n] [decidable_eq m] [decidable_eq n] [comm_ring R] (A : matrix m m R) (B : matrix n n R) : (A ⊗ₖ B)⁻¹ = A⁻¹ ⊗ₖ B⁻¹ := begin -- handle the special cases where either matrix is not invertible by_cases hA : is_unit A.det, swap, { casesI is_empty_or_nonempty n, { exact subsingleton.elim _ _ }, have hAB : ¬is_unit (A ⊗ₖ B).det, { refine mt (λ hAB, _) hA, rw det_kronecker at hAB, exact (is_unit_pow_iff fintype.card_ne_zero).mp (is_unit_of_mul_is_unit_left hAB) }, rw [nonsing_inv_apply_not_is_unit _ hA, zero_kronecker, nonsing_inv_apply_not_is_unit _ hAB] }, by_cases hB : is_unit B.det, swap, { casesI is_empty_or_nonempty m, { exact subsingleton.elim _ _ }, have hAB : ¬is_unit (A ⊗ₖ B).det, { refine mt (λ hAB, _) hB, rw det_kronecker at hAB, exact (is_unit_pow_iff fintype.card_ne_zero).mp (is_unit_of_mul_is_unit_right hAB) }, rw [nonsing_inv_apply_not_is_unit _ hB, kronecker_zero, nonsing_inv_apply_not_is_unit _ hAB] }, -- otherwise follows trivially from `mul_kronecker_mul` { apply inv_eq_right_inv, rw [←mul_kronecker_mul, ←one_kronecker_one, mul_nonsing_inv _ hA, mul_nonsing_inv _ hB] }, end end kronecker /-! ### Specialization to `matrix.kronecker_map (⊗ₜ)` -/ section kronecker_tmul variables (R) open tensor_product open_locale matrix tensor_product section module variables [comm_semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] variables [module R α] [module R β] [module R γ] /-- The Kronecker tensor product. This is just a shorthand for `kronecker_map (⊗ₜ)`. Prefer the notation `⊗ₖₜ` rather than this definition. -/ @[simp] def kronecker_tmul : matrix l m α → matrix n p β → matrix (l × n) (m × p) (α ⊗[R] β) := kronecker_map (⊗ₜ) localized "infix (name := matrix.kronecker_map.tmul) ` ⊗ₖₜ `:100 := matrix.kronecker_map (⊗ₜ)" in kronecker localized "notation (name := matrix.kronecker_map.tmul') x ` ⊗ₖₜ[`:100 R `] `:0 y:100 := matrix.kronecker_map (tensor_product.tmul R) x y" in kronecker @[simp] lemma kronecker_tmul_apply (A : matrix l m α) (B : matrix n p β) (i₁ i₂ j₁ j₂) : (A ⊗ₖₜ B) (i₁, i₂) (j₁, j₂) = A i₁ j₁ ⊗ₜ[R] B i₂ j₂ := rfl /-- `matrix.kronecker` as a bilinear map. -/ def kronecker_tmul_bilinear : matrix l m α →ₗ[R] matrix n p β →ₗ[R] matrix (l × n) (m × p) (α ⊗[R] β) := kronecker_map_bilinear (tensor_product.mk R α β) /-! What follows is a copy, in order, of every `matrix.kronecker_map` lemma above that has hypotheses which can be filled by properties of `⊗ₜ`. -/ @[simp] lemma zero_kronecker_tmul (B : matrix n p β) : (0 : matrix l m α) ⊗ₖₜ[R] B = 0 := kronecker_map_zero_left _ (zero_tmul α) B @[simp] lemma kronecker_tmul_zero (A : matrix l m α) : A ⊗ₖₜ[R] (0 : matrix n p β) = 0 := kronecker_map_zero_right _ (tmul_zero β) A lemma add_kronecker_tmul (A₁ A₂ : matrix l m α) (B : matrix n p α) : (A₁ + A₂) ⊗ₖₜ[R] B = A₁ ⊗ₖₜ B + A₂ ⊗ₖₜ B := kronecker_map_add_left _ add_tmul _ _ _ lemma kronecker_tmul_add (A : matrix l m α) (B₁ B₂ : matrix n p α) : A ⊗ₖₜ[R] (B₁ + B₂) = A ⊗ₖₜ B₁ + A ⊗ₖₜ B₂ := kronecker_map_add_right _ tmul_add _ _ _ lemma smul_kronecker_tmul (r : R) (A : matrix l m α) (B : matrix n p α) : (r • A) ⊗ₖₜ[R] B = r • (A ⊗ₖₜ B) := kronecker_map_smul_left _ _ (λ _ _, smul_tmul' _ _ _) _ _ lemma kronecker_tmul_smul (r : R) (A : matrix l m α) (B : matrix n p α) : A ⊗ₖₜ[R] (r • B) = r • (A ⊗ₖₜ B) := kronecker_map_smul_right _ _ (λ _ _, tmul_smul _ _ _) _ _ lemma diagonal_kronecker_tmul_diagonal [decidable_eq m] [decidable_eq n] (a : m → α) (b : n → α): (diagonal a) ⊗ₖₜ[R] (diagonal b) = diagonal (λ mn, a mn.1 ⊗ₜ b mn.2) := kronecker_map_diagonal_diagonal _ (zero_tmul _) (tmul_zero _) _ _ lemma kronecker_tmul_diagonal [decidable_eq n] (A : matrix l m α) (b : n → α): A ⊗ₖₜ[R] (diagonal b) = block_diagonal (λ i, A.map (λ a, a ⊗ₜ[R] b i)) := kronecker_map_diagonal_right _ (tmul_zero _) _ _ lemma diagonal_kronecker_tmul [decidable_eq l](a : l → α) (B : matrix m n α) : diagonal a ⊗ₖₜ[R] B = matrix.reindex (equiv.prod_comm _ _) (equiv.prod_comm _ _) (block_diagonal (λ i, B.map (λ b, a i ⊗ₜ[R] b))) := kronecker_map_diagonal_left _ (zero_tmul _) _ _ @[simp] lemma kronecker_tmul_assoc (A : matrix l m α) (B : matrix n p β) (C : matrix q r γ) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) (((A ⊗ₖₜ[R] B) ⊗ₖₜ[R] C).map (tensor_product.assoc _ _ _ _)) = A ⊗ₖₜ[R] (B ⊗ₖₜ[R] C) := ext $ λ i j, assoc_tmul _ _ _ lemma trace_kronecker_tmul [fintype m] [fintype n] (A : matrix m m α) (B : matrix n n β) : trace (A ⊗ₖₜ[R] B) = trace A ⊗ₜ[R] trace B := trace_kronecker_map_bilinear (tensor_product.mk R α β) _ _ end module section algebra open_locale kronecker open algebra.tensor_product section semiring variables [comm_semiring R] [semiring α] [semiring β] [algebra R α] [algebra R β] @[simp] lemma one_kronecker_tmul_one [decidable_eq m] [decidable_eq n] : (1 : matrix m m α) ⊗ₖₜ[R] (1 : matrix n n α) = 1 := kronecker_map_one_one _ (zero_tmul _) (tmul_zero _) rfl lemma mul_kronecker_tmul_mul [fintype m] [fintype m'] (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' β) (B' : matrix m' n' β) : (A ⬝ B) ⊗ₖₜ[R] (A' ⬝ B') = (A ⊗ₖₜ A') ⬝ (B ⊗ₖₜ B') := kronecker_map_bilinear_mul_mul (tensor_product.mk R α β) tmul_mul_tmul A B A' B' end semiring section comm_ring variables [comm_ring R] [comm_ring α] [comm_ring β] [algebra R α] [algebra R β] lemma det_kronecker_tmul [fintype m] [fintype n] [decidable_eq m] [decidable_eq n] (A : matrix m m α) (B : matrix n n β) : det (A ⊗ₖₜ[R] B) = (det A ^ fintype.card n) ⊗ₜ[R] (det B ^ fintype.card m) := begin refine (det_kronecker_map_bilinear (tensor_product.mk R α β) tmul_mul_tmul _ _).trans _, simp only [mk_apply, ←include_left_apply, ←include_right_apply] {eta := ff}, simp only [←alg_hom.map_matrix_apply, ←alg_hom.map_det], simp only [include_left_apply, include_right_apply, tmul_pow, tmul_mul_tmul, one_pow, _root_.mul_one, _root_.one_mul], end end comm_ring end algebra -- insert lemmas specific to `kronecker_tmul` below this line end kronecker_tmul end matrix
27ae5805d187a0eb728f21a98ae5f0fd53b5d640
4e959ec489fab6f8435e5a4a66b18084ad9e4651
/root_2_irrational.lean
9462ca635e58755e2823349b029da240bd0d8683
[]
no_license
iceplant/mathcamp-tutorials
af2e398b00684bd0b6805e0f65cf582cfe04a32d
481db142430e47f892e8f984aa08eecfb3167bb5
refs/heads/master
1,664,971,347,788
1,591,227,269,000
1,591,227,269,000
267,948,544
0
0
null
null
null
null
UTF-8
Lean
false
false
2,824
lean
import data.nat.basic import data.int.parity import tactic open int /-lifted from tutorial project. I think there's potential to explain and develop these lemmas and parity in detail, but it could make the tutorial pretty long-/ def odd (n : ℤ) : Prop := ∃ k, n = 2*k + 1 #check int.not_even_iff theorem not_even_iff_odd (n : ℤ) : ¬ even n ↔ odd n := begin rw int.not_even_iff, split ; intro h, use n/2, conv_rhs { rw add_comm, congr, rw ← h }, exact (int.mod_add_div n 2).symm, rcases h with ⟨k, rfl⟩, simp [add_comm], refl, end theorem square_even_iff_even (n : ℤ) : even (n^2) ↔ even n := begin -- sorry split, { contrapose, rw not_even_iff_odd, rw not_even_iff_odd, rintro ⟨k, rfl⟩, use 2*k*(k+1), ring }, { rintro ⟨k, rfl⟩, use 2*k^2, ring }, -- sorry end def int_divides (a b : ℤ) : Prop := b % a = 0 def rel_prime (a b : ℤ) : Prop := ¬ ∃ k:ℕ, (int_divides k a ∧ int_divides k b ∧ k>1) lemma even_imp_square_even (a : ℤ) : even a → even (a^2) := begin unfold even, rintro ⟨k, h⟩, use (2*k^2), rw h, ring, end def rational (n : ℤ) : Prop := ∃ a b : ℤ, (rel_prime a b ∧ a^2 = n*b^2) --I feel like this exists in mathlib. I'm trying to find it. lemma div_both_sides {a b k : ℤ} (h : k*a = k*b) (hk : k ≠ 0) : a = b := begin sorry, end --this could probably be cleaner/broken into smaller steps theorem root_two_not_rational : ¬ rational 2 := begin rintros ⟨a, b, a_b_rel_prime, h⟩, unfold rel_prime at a_b_rel_prime, have a_squared_even : even (a^2), rw h, use b^2, have a_even : even a, exact (square_even_iff_even a).mp a_squared_even, cases a_even with c a_even, rw a_even at h, have b_squared_even : even (b^2), unfold even, use c^2, rw mul_pow 2 c 2 at h, rw pow_succ at h, rw mul_assoc 2 (2^1) (c^2) at h, have h' := div_both_sides h (by linarith), simp at h', rw h', have b_even : even b, exact (square_even_iff_even b).mp b_squared_even, apply a_b_rel_prime, use 2, split, unfold int_divides, rw a_even, simp, split, rcases b_even with ⟨b_2, b_even⟩, rw b_even, unfold int_divides, simp, linarith, end --me trying to find lemmas in mathlib -- example (a b c : ℕ) (h : a*c = b*c) (h' : c ≠ 0) (h'' : a ≠ 0) (h''' : b ≠ 0) -- : a = b := -- begin -- library_search, -- sorry, -- end example (a b c : ℕ) (h : a = b) : a*c = b*c := begin exact congr_fun (congr_arg has_mul.mul h) c, end example (a b : ℕ) (h : 2*a = 2*b) : a = b := begin refine eq.symm _, sorry, end example (a : ℕ) : (2*a)^2 = 2^2 * a^2 := begin exact nat.mul_pow 2 a 2, end
963de44d38bc6094fb89c3be29e923e737c03238
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/control/basic.lean
052dd73402bc1e292fa3dad6cd3b715cde3e2bae
[ "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
6,828
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 Extends the theory on functors, applicatives and monads. -/ universes u v w variables {α β γ : Type u} notation a ` $< `:1 f:1 := f a section functor variables {f : Type u → Type v} [functor f] [is_lawful_functor f] run_cmd mk_simp_attr `functor_norm run_cmd tactic.add_doc_string `simp_attr.functor_norm "Simp set for functor_norm" @[functor_norm] theorem functor.map_map (m : α → β) (g : β → γ) (x : f α) : g <$> (m <$> x) = (g ∘ m) <$> x := (comp_map _ _ _).symm @[simp] theorem id_map' (x : f α) : (λa, a) <$> x = x := id_map _ end functor section applicative variables {F : Type u → Type v} [applicative F] def mzip_with {α₁ α₂ φ : Type u} (f : α₁ → α₂ → F φ) : Π (ma₁ : list α₁) (ma₂: list α₂), F (list φ) | (x :: xs) (y :: ys) := (::) <$> f x y <*> mzip_with xs ys | _ _ := pure [] def mzip_with' (f : α → β → F γ) : list α → list β → F punit | (x :: xs) (y :: ys) := f x y *> mzip_with' xs ys | [] _ := pure punit.star | _ [] := pure punit.star variables [is_lawful_applicative F] attribute [functor_norm] seq_assoc pure_seq_eq_map @[simp] theorem pure_id'_seq (x : F α) : pure (λx, x) <*> x = x := pure_id_seq x attribute [functor_norm] seq_assoc pure_seq_eq_map @[functor_norm] theorem seq_map_assoc (x : F (α → β)) (f : γ → α) (y : F γ) : (x <*> (f <$> y)) = (λ(m:α→β), m ∘ f) <$> x <*> y := begin simp [(pure_seq_eq_map _ _).symm], simp [seq_assoc, (comp_map _ _ _).symm, (∘)], simp [pure_seq_eq_map] end @[functor_norm] theorem map_seq (f : β → γ) (x : F (α → β)) (y : F α) : (f <$> (x <*> y)) = ((∘) f) <$> x <*> y := by simp [(pure_seq_eq_map _ _).symm]; simp [seq_assoc] end applicative -- TODO: setup `functor_norm` for `monad` laws attribute [functor_norm] pure_bind bind_assoc bind_pure section monad variables {m : Type u → Type v} [monad m] [is_lawful_monad m] open list def list.mpartition {f : Type → Type} [monad f] {α : Type} (p : α → f bool) : list α → f (list α × list α) | [] := pure ([],[]) | (x :: xs) := mcond (p x) (prod.map (cons x) id <$> list.mpartition xs) (prod.map id (cons x) <$> list.mpartition xs) lemma map_bind (x : m α) {g : α → m β} {f : β → γ} : f <$> (x >>= g) = (x >>= λa, f <$> g a) := by rw [← bind_pure_comp_eq_map,bind_assoc]; simp [bind_pure_comp_eq_map] lemma seq_bind_eq (x : m α) {g : β → m γ} {f : α → β} : (f <$> x) >>= g = (x >>= g ∘ f) := show bind (f <$> x) g = bind x (g ∘ f), by rw [← bind_pure_comp_eq_map, bind_assoc]; simp [pure_bind] lemma seq_eq_bind_map {x : m α} {f : m (α → β)} : f <*> x = (f >>= (<$> x)) := (bind_map_eq_seq f x).symm /-- This is the Kleisli composition -/ @[reducible] def fish {m} [monad m] {α β γ} (f : α → m β) (g : β → m γ) := λ x, f x >>= g -- >=> is already defined in the core library but it is unusable -- because of its precedence (it is defined with precedence 2) and -- because it is defined as a lambda instead of having a named -- function infix ` >=> `:55 := fish @[functor_norm] lemma fish_pure {α β} (f : α → m β) : f >=> pure = f := by simp only [(>=>)] with functor_norm @[functor_norm] lemma fish_pipe {α β} (f : α → m β) : pure >=> f = f := by simp only [(>=>)] with functor_norm @[functor_norm] lemma fish_assoc {α β γ φ} (f : α → m β) (g : β → m γ) (h : γ → m φ) : (f >=> g) >=> h = f >=> (g >=> h) := by simp only [(>=>)] with functor_norm variables {β' γ' : Type v} variables {m' : Type v → Type w} [monad m'] def list.mmap_accumr (f : α → β' → m' (β' × γ')) : β' → list α → m' (β' × list γ') | a [] := pure (a,[]) | a (x :: xs) := do (a',ys) ← list.mmap_accumr a xs, (a'',y) ← f x a', pure (a'',y::ys) def list.mmap_accuml (f : β' → α → m' (β' × γ')) : β' → list α → m' (β' × list γ') | a [] := pure (a,[]) | a (x :: xs) := do (a',y) ← f a x, (a'',ys) ← list.mmap_accuml a' xs, pure (a'',y :: ys) end monad section variables {m : Type u → Type u} [monad m] [is_lawful_monad m] lemma mjoin_map_map {α β : Type u} (f : α → β) (a : m (m α)) : mjoin (functor.map f <$> a) = f <$> (mjoin a) := by simp only [mjoin, (∘), id.def, (bind_pure_comp_eq_map _ _).symm, bind_assoc, map_bind, pure_bind] lemma mjoin_map_mjoin {α : Type u} (a : m (m (m α))) : mjoin (mjoin <$> a) = mjoin (mjoin a) := by simp only [mjoin, (∘), id.def, map_bind, (bind_pure_comp_eq_map _ _).symm, bind_assoc, pure_bind] @[simp] lemma mjoin_map_pure {α : Type u} (a : m α) : mjoin (pure <$> a) = a := by simp only [mjoin, (∘), id.def, map_bind, (bind_pure_comp_eq_map _ _).symm, bind_assoc, pure_bind, bind_pure] @[simp] lemma mjoin_pure {α : Type u} (a : m α) : mjoin (pure a) = a := is_lawful_monad.pure_bind a id end section alternative variables {F : Type → Type v} [alternative F] def succeeds {α} (x : F α) : F bool := (x $> tt) <|> pure ff def mtry {α} (x : F α) : F unit := (x $> ()) <|> pure () @[simp] theorem guard_true {h : decidable true} : @guard F _ true h = pure () := by simp [guard] @[simp] theorem guard_false {h : decidable false} : @guard F _ false h = failure := by simp [guard] end alternative namespace sum variables {e : Type v} protected def bind {α β} : e ⊕ α → (α → e ⊕ β) → e ⊕ β | (inl x) _ := inl x | (inr x) f := f x instance : monad (sum.{v u} e) := { pure := @sum.inr e, bind := @sum.bind e } instance : is_lawful_functor (sum.{v u} e) := by refine { .. }; intros; casesm _ ⊕ _; refl instance : is_lawful_monad (sum.{v u} e) := { bind_assoc := by { intros, casesm _ ⊕ _; refl }, pure_bind := by { intros, refl }, bind_pure_comp_eq_map := by { intros, casesm _ ⊕ _; refl }, bind_map_eq_seq := by { intros, cases f; refl } } end sum section prio set_option default_priority 100 -- see Note [default priority] class is_comm_applicative (m : Type* → Type*) [applicative m] extends is_lawful_applicative m : Prop := (commutative_prod : ∀{α β} (a : m α) (b : m β), prod.mk <$> a <*> b = (λb a, (a, b)) <$> b <*> a) end prio open functor lemma is_comm_applicative.commutative_map {m : Type* → Type*} [applicative m] [is_comm_applicative m] {α β γ} (a : m α) (b : m β) {f : α → β → γ} : f <$> a <*> b = flip f <$> b <*> a := calc f <$> a <*> b = (λp:α×β, f p.1 p.2) <$> (prod.mk <$> a <*> b) : by simp [seq_map_assoc, map_seq, seq_assoc, seq_pure, map_map] ... = (λb a, f a b) <$> b <*> a : by rw [is_comm_applicative.commutative_prod]; simp [seq_map_assoc, map_seq, seq_assoc, seq_pure, map_map]
a1036d15e761f58252ce3e4c8c0653685d30d688
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/category/Group/Z_Module_equivalence.lean
08e2dd8c84784009ea43b47387d6e48fd875a77a
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
1,444
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Module.basic /-! The forgetful functor from ℤ-modules to additive commutative groups is an equivalence of categories. TODO: either use this equivalence to transport the monoidal structure from `Module ℤ` to `Ab`, or, having constructed that monoidal structure directly, show this functor is monoidal. -/ open category_theory open category_theory.equivalence universes u namespace Module /-- The forgetful functor from `ℤ` modules to `AddCommGroup` is full. -/ instance forget₂_AddCommGroup_full : full (forget₂ (Module ℤ) AddCommGroup.{u}) := { preimage := λ A B f, -- TODO: why `add_monoid_hom.to_int_linear_map` doesn't work here? { to_fun := f, map_add' := add_monoid_hom.map_add f, map_smul' := λ n x, by simp [int_smul_eq_gsmul] } } /-- The forgetful functor from `ℤ` modules to `AddCommGroup` is essentially surjective. -/ instance forget₂_AddCommGroup_ess_surj : ess_surj (forget₂ (Module ℤ) AddCommGroup.{u}) := { mem_ess_image := λ A, ⟨Module.of ℤ A, ⟨{ hom := 𝟙 A, inv := 𝟙 A }⟩⟩} noncomputable instance forget₂_AddCommGroup_is_equivalence : is_equivalence (forget₂ (Module ℤ) AddCommGroup.{u}) := equivalence_of_fully_faithfully_ess_surj (forget₂ (Module ℤ) AddCommGroup) end Module
5de0f458f5606e915720e604be179aa147aa2398
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/category/Top/adjunctions.lean
a0ce2a4cf74308a41ca1310e433eb629c6493b15
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,315
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Mario Carneiro -/ import topology.category.Top.basic import category_theory.adjunction.basic /-! # Adjunctions regarding the category of topological spaces This file shows that the forgetful functor from topological spaces to types has a left and right adjoint, given by `Top.discrete`, resp. `Top.trivial`, the functors which equip a type with the discrete, resp. trivial, topology. -/ universe u open category_theory open Top namespace Top /-- Equipping a type with the discrete topology is left adjoint to the forgetful functor `Top ⥤ Type`. -/ @[simps unit counit] def adj₁ : discrete ⊣ forget Top.{u} := adjunction.mk_of_unit_counit { unit := { app := λ X, id }, counit := { app := λ X, ⟨id, continuous_bot⟩ } } /-- Equipping a type with the trivial topology is right adjoint to the forgetful functor `Top ⥤ Type`. -/ @[simps unit counit] def adj₂ : forget Top.{u} ⊣ trivial := adjunction.mk_of_unit_counit { unit := { app := λ X, ⟨id, continuous_top⟩ }, counit := { app := λ X, id } } instance : is_right_adjoint (forget Top.{u}) := ⟨_, adj₁⟩ instance : is_left_adjoint (forget Top.{u}) := ⟨_, adj₂⟩ end Top
ce0697f7cf01fa9bf7f96b7a92fe00e5f1f3d565
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/typeclass_easy.lean
595fc8a3134def5a73eee037bd52178960f4004f
[ "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
147
lean
#synth ToString (Nat × (Nat × Bool)) #synth Add Nat #synth Coe Bool Prop #synth Decidable (True ∧ 1 = 1) #synth DecidableEq (Nat × Nat)
a121d34cdbfa60f4285293176f89e34771163933
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/gcd.lean
8d31ece05f6046d5cc1bf32de91b48252cbed04d
[]
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
15,367
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.basic import Mathlib.PostPort namespace Mathlib /-! # Definitions and properties of `gcd`, `lcm`, and `coprime` -/ namespace nat /-! ### `gcd` -/ theorem gcd_dvd (m : ℕ) (n : ℕ) : gcd m n ∣ m ∧ gcd m n ∣ n := sorry theorem gcd_dvd_left (m : ℕ) (n : ℕ) : gcd m n ∣ m := and.left (gcd_dvd m n) theorem gcd_dvd_right (m : ℕ) (n : ℕ) : gcd m n ∣ n := and.right (gcd_dvd m n) theorem gcd_le_left {m : ℕ} (n : ℕ) (h : 0 < m) : gcd m n ≤ m := le_of_dvd h (gcd_dvd_left m n) theorem gcd_le_right (m : ℕ) {n : ℕ} (h : 0 < n) : gcd m n ≤ n := le_of_dvd h (gcd_dvd_right m n) theorem dvd_gcd {m : ℕ} {n : ℕ} {k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := sorry theorem dvd_gcd_iff {m : ℕ} {n : ℕ} {k : ℕ} : k ∣ gcd m n ↔ k ∣ m ∧ k ∣ n := sorry theorem gcd_comm (m : ℕ) (n : ℕ) : gcd m n = gcd n m := dvd_antisymm (dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n)) (dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m)) theorem gcd_eq_left_iff_dvd {m : ℕ} {n : ℕ} : m ∣ n ↔ gcd m n = m := sorry theorem gcd_eq_right_iff_dvd {m : ℕ} {n : ℕ} : m ∣ n ↔ gcd n m = m := eq.mpr (id (Eq._oldrec (Eq.refl (m ∣ n ↔ gcd n m = m)) (gcd_comm n m))) gcd_eq_left_iff_dvd theorem gcd_assoc (m : ℕ) (n : ℕ) (k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := sorry @[simp] theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 := Eq.trans (gcd_comm n 1) (gcd_one_left n) theorem gcd_mul_left (m : ℕ) (n : ℕ) (k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := sorry theorem gcd_mul_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := sorry theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : 0 < m) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_left m n) mpos theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : 0 < n) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_right m n) npos theorem eq_zero_of_gcd_eq_zero_left {m : ℕ} {n : ℕ} (H : gcd m n = 0) : m = 0 := or.elim (eq_zero_or_pos m) id fun (H1 : 0 < m) => absurd (Eq.symm H) (ne_of_lt (gcd_pos_of_pos_left n H1)) theorem eq_zero_of_gcd_eq_zero_right {m : ℕ} {n : ℕ} (H : gcd m n = 0) : n = 0 := eq_zero_of_gcd_eq_zero_left (eq.mp (Eq._oldrec (Eq.refl (gcd m n = 0)) (gcd_comm m n)) H) theorem gcd_div {m : ℕ} {n : ℕ} {k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m / k) (n / k) = gcd m n / k := sorry theorem gcd_dvd_gcd_of_dvd_left {m : ℕ} {k : ℕ} (n : ℕ) (H : m ∣ k) : gcd m n ∣ gcd k n := dvd_gcd (dvd.trans (gcd_dvd_left m n) H) (gcd_dvd_right m n) theorem gcd_dvd_gcd_of_dvd_right {m : ℕ} {k : ℕ} (n : ℕ) (H : m ∣ k) : gcd n m ∣ gcd n k := dvd_gcd (gcd_dvd_left n m) (dvd.trans (gcd_dvd_right n m) H) theorem gcd_dvd_gcd_mul_left (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd_of_dvd_left n (dvd_mul_left m k) theorem gcd_dvd_gcd_mul_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd_of_dvd_left n (dvd_mul_right m k) theorem gcd_dvd_gcd_mul_left_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd_of_dvd_right m (dvd_mul_left n k) theorem gcd_dvd_gcd_mul_right_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd_of_dvd_right m (dvd_mul_right n k) theorem gcd_eq_left {m : ℕ} {n : ℕ} (H : m ∣ n) : gcd m n = m := dvd_antisymm (gcd_dvd_left m n) (dvd_gcd (dvd_refl m) H) theorem gcd_eq_right {m : ℕ} {n : ℕ} (H : n ∣ m) : gcd m n = n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd m n = n)) (gcd_comm m n))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd n m = n)) (gcd_eq_left H))) (Eq.refl n)) @[simp] theorem gcd_mul_left_left (m : ℕ) (n : ℕ) : gcd (m * n) n = n := dvd_antisymm (gcd_dvd_right (m * n) n) (dvd_gcd (dvd_mul_left n m) (dvd_refl n)) @[simp] theorem gcd_mul_left_right (m : ℕ) (n : ℕ) : gcd n (m * n) = n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd n (m * n) = n)) (gcd_comm n (m * n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd (m * n) n = n)) (gcd_mul_left_left m n))) (Eq.refl n)) @[simp] theorem gcd_mul_right_left (m : ℕ) (n : ℕ) : gcd (n * m) n = n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd (n * m) n = n)) (mul_comm n m))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd (m * n) n = n)) (gcd_mul_left_left m n))) (Eq.refl n)) @[simp] theorem gcd_mul_right_right (m : ℕ) (n : ℕ) : gcd n (n * m) = n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd n (n * m) = n)) (gcd_comm n (n * m)))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd (n * m) n = n)) (gcd_mul_right_left m n))) (Eq.refl n)) @[simp] theorem gcd_gcd_self_right_left (m : ℕ) (n : ℕ) : gcd m (gcd m n) = gcd m n := dvd_antisymm (gcd_dvd_right m (gcd m n)) (dvd_gcd (gcd_dvd_left m n) (dvd_refl (gcd m n))) @[simp] theorem gcd_gcd_self_right_right (m : ℕ) (n : ℕ) : gcd m (gcd n m) = gcd n m := eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (gcd n m) = gcd n m)) (gcd_comm n m))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (gcd m n) = gcd m n)) (gcd_gcd_self_right_left m n))) (Eq.refl (gcd m n))) @[simp] theorem gcd_gcd_self_left_right (m : ℕ) (n : ℕ) : gcd (gcd n m) m = gcd n m := eq.mpr (id (Eq._oldrec (Eq.refl (gcd (gcd n m) m = gcd n m)) (gcd_comm (gcd n m) m))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (gcd n m) = gcd n m)) (gcd_gcd_self_right_right m n))) (Eq.refl (gcd n m))) @[simp] theorem gcd_gcd_self_left_left (m : ℕ) (n : ℕ) : gcd (gcd m n) m = gcd m n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd (gcd m n) m = gcd m n)) (gcd_comm m n))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd (gcd n m) m = gcd n m)) (gcd_gcd_self_left_right m n))) (Eq.refl (gcd n m))) theorem gcd_add_mul_self (m : ℕ) (n : ℕ) (k : ℕ) : gcd m (n + k * m) = gcd m n := sorry theorem gcd_eq_zero_iff {i : ℕ} {j : ℕ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := sorry /-! ### `lcm` -/ theorem lcm_comm (m : ℕ) (n : ℕ) : lcm m n = lcm n m := id (eq.mpr (id (Eq._oldrec (Eq.refl (m * n / gcd m n = n * m / gcd n m)) (mul_comm m n))) (eq.mpr (id (Eq._oldrec (Eq.refl (n * m / gcd m n = n * m / gcd n m)) (gcd_comm m n))) (Eq.refl (n * m / gcd n m)))) @[simp] theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 := id (eq.mpr (id (Eq._oldrec (Eq.refl (0 * m / gcd 0 m = 0)) (zero_mul m))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 / gcd 0 m = 0)) (nat.zero_div (gcd 0 m)))) (Eq.refl 0))) @[simp] theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := lcm_comm 0 m ▸ lcm_zero_left m @[simp] theorem lcm_one_left (m : ℕ) : lcm 1 m = m := sorry @[simp] theorem lcm_one_right (m : ℕ) : lcm m 1 = m := lcm_comm 1 m ▸ lcm_one_left m @[simp] theorem lcm_self (m : ℕ) : lcm m m = m := sorry theorem dvd_lcm_left (m : ℕ) (n : ℕ) : m ∣ lcm m n := dvd.intro (n / gcd m n) (Eq.symm (nat.mul_div_assoc m (gcd_dvd_right m n))) theorem dvd_lcm_right (m : ℕ) (n : ℕ) : n ∣ lcm m n := lcm_comm n m ▸ dvd_lcm_left n m theorem gcd_mul_lcm (m : ℕ) (n : ℕ) : gcd m n * lcm m n = m * n := sorry theorem lcm_dvd {m : ℕ} {n : ℕ} {k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := sorry theorem lcm_assoc (m : ℕ) (n : ℕ) (k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := sorry theorem lcm_ne_zero {m : ℕ} {n : ℕ} (hm : m ≠ 0) (hn : n ≠ 0) : lcm m n ≠ 0 := sorry /-! ### `coprime` See also `nat.coprime_of_dvd` and `nat.coprime_of_dvd'` to prove `nat.coprime m n`. -/ protected instance coprime.decidable (m : ℕ) (n : ℕ) : Decidable (coprime m n) := eq.mpr sorry (nat.decidable_eq (gcd m n) 1) theorem coprime.gcd_eq_one {m : ℕ} {n : ℕ} : coprime m n → gcd m n = 1 := id theorem coprime.symm {m : ℕ} {n : ℕ} : coprime n m → coprime m n := Eq.trans (gcd_comm m n) theorem coprime.dvd_of_dvd_mul_right {m : ℕ} {n : ℕ} {k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := sorry theorem coprime.dvd_of_dvd_mul_left {m : ℕ} {n : ℕ} {k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n := coprime.dvd_of_dvd_mul_right H1 (eq.mp (Eq._oldrec (Eq.refl (k ∣ m * n)) (mul_comm m n)) H2) theorem coprime.gcd_mul_left_cancel {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := sorry theorem coprime.gcd_mul_right_cancel (m : ℕ) {k : ℕ} {n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd (m * k) n = gcd m n)) (mul_comm m k))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd (k * m) n = gcd m n)) (coprime.gcd_mul_left_cancel m H))) (Eq.refl (gcd m n))) theorem coprime.gcd_mul_left_cancel_right {k : ℕ} {m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := sorry theorem coprime.gcd_mul_right_cancel_right {k : ℕ} {m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (n * k) = gcd m n)) (mul_comm n k))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (k * n) = gcd m n)) (coprime.gcd_mul_left_cancel_right n H))) (Eq.refl (gcd m n))) theorem coprime_div_gcd_div_gcd {m : ℕ} {n : ℕ} (H : 0 < gcd m n) : coprime (m / gcd m n) (n / gcd m n) := sorry theorem not_coprime_of_dvd_of_dvd {m : ℕ} {n : ℕ} {d : ℕ} (dgt1 : 1 < d) (Hm : d ∣ m) (Hn : d ∣ n) : ¬coprime m n := fun (co : gcd m n = 1) => not_lt_of_ge (le_of_dvd zero_lt_one (eq.mpr (id (Eq._oldrec (Eq.refl (d ∣ 1)) (Eq.symm co))) (dvd_gcd Hm Hn))) dgt1 theorem exists_coprime {m : ℕ} {n : ℕ} (H : 0 < gcd m n) : ∃ (m' : ℕ), ∃ (n' : ℕ), coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := sorry theorem exists_coprime' {m : ℕ} {n : ℕ} (H : 0 < gcd m n) : ∃ (g : ℕ), ∃ (m' : ℕ), ∃ (n' : ℕ), 0 < g ∧ coprime m' n' ∧ m = m' * g ∧ n = n' * g := sorry theorem coprime.mul {m : ℕ} {n : ℕ} {k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k := Eq.trans (coprime.gcd_mul_left_cancel n H1) H2 theorem coprime.mul_right {k : ℕ} {m : ℕ} {n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) := coprime.symm (coprime.mul (coprime.symm H1) (coprime.symm H2)) theorem coprime.coprime_dvd_left {m : ℕ} {k : ℕ} {n : ℕ} (H1 : m ∣ k) (H2 : coprime k n) : coprime m n := sorry theorem coprime.coprime_dvd_right {m : ℕ} {k : ℕ} {n : ℕ} (H1 : n ∣ m) (H2 : coprime k m) : coprime k n := coprime.symm (coprime.coprime_dvd_left H1 (coprime.symm H2)) theorem coprime.coprime_mul_left {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime (k * m) n) : coprime m n := coprime.coprime_dvd_left (dvd_mul_left m k) H theorem coprime.coprime_mul_right {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime (m * k) n) : coprime m n := coprime.coprime_dvd_left (dvd_mul_right m k) H theorem coprime.coprime_mul_left_right {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime m (k * n)) : coprime m n := coprime.coprime_dvd_right (dvd_mul_left n k) H theorem coprime.coprime_mul_right_right {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime m (n * k)) : coprime m n := coprime.coprime_dvd_right (dvd_mul_right n k) H theorem coprime.coprime_div_left {m : ℕ} {n : ℕ} {a : ℕ} (cmn : coprime m n) (dvd : a ∣ m) : coprime (m / a) n := sorry theorem coprime.coprime_div_right {m : ℕ} {n : ℕ} {a : ℕ} (cmn : coprime m n) (dvd : a ∣ n) : coprime m (n / a) := coprime.symm (coprime.coprime_div_left (coprime.symm cmn) dvd) theorem coprime_mul_iff_left {k : ℕ} {m : ℕ} {n : ℕ} : coprime (m * n) k ↔ coprime m k ∧ coprime n k := sorry theorem coprime_mul_iff_right {k : ℕ} {m : ℕ} {n : ℕ} : coprime k (m * n) ↔ coprime k m ∧ coprime k n := sorry theorem coprime.gcd_left (k : ℕ) {m : ℕ} {n : ℕ} (hmn : coprime m n) : coprime (gcd k m) n := coprime.coprime_dvd_left (gcd_dvd_right k m) hmn theorem coprime.gcd_right (k : ℕ) {m : ℕ} {n : ℕ} (hmn : coprime m n) : coprime m (gcd k n) := coprime.coprime_dvd_right (gcd_dvd_right k n) hmn theorem coprime.gcd_both (k : ℕ) (l : ℕ) {m : ℕ} {n : ℕ} (hmn : coprime m n) : coprime (gcd k m) (gcd l n) := coprime.gcd_right l (coprime.gcd_left k hmn) theorem coprime.mul_dvd_of_dvd_of_dvd {a : ℕ} {n : ℕ} {m : ℕ} (hmn : coprime m n) (hm : m ∣ a) (hn : n ∣ a) : m * n ∣ a := sorry theorem coprime_one_left (n : ℕ) : coprime 1 n := gcd_one_left theorem coprime_one_right (n : ℕ) : coprime n 1 := gcd_one_right theorem coprime.pow_left {m : ℕ} {k : ℕ} (n : ℕ) (H1 : coprime m k) : coprime (m ^ n) k := nat.rec_on n (coprime_one_left k) fun (n : ℕ) (IH : coprime (m ^ n) k) => coprime.mul H1 IH theorem coprime.pow_right {m : ℕ} {k : ℕ} (n : ℕ) (H1 : coprime k m) : coprime k (m ^ n) := coprime.symm (coprime.pow_left n (coprime.symm H1)) theorem coprime.pow {k : ℕ} {l : ℕ} (m : ℕ) (n : ℕ) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) := coprime.pow_right n (coprime.pow_left m H1) theorem coprime.eq_one_of_dvd {k : ℕ} {m : ℕ} (H : coprime k m) (d : k ∣ m) : k = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (k = 1)) (Eq.symm (coprime.gcd_eq_one H)))) (eq.mpr (id (Eq._oldrec (Eq.refl (k = gcd k m)) (gcd_eq_left d))) (Eq.refl k)) @[simp] theorem coprime_zero_left (n : ℕ) : coprime 0 n ↔ n = 1 := sorry @[simp] theorem coprime_zero_right (n : ℕ) : coprime n 0 ↔ n = 1 := sorry @[simp] theorem coprime_one_left_iff (n : ℕ) : coprime 1 n ↔ True := sorry @[simp] theorem coprime_one_right_iff (n : ℕ) : coprime n 1 ↔ True := sorry @[simp] theorem coprime_self (n : ℕ) : coprime n n ↔ n = 1 := sorry /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. -/ def prod_dvd_and_dvd_of_dvd_prod {m : ℕ} {n : ℕ} {k : ℕ} (H : k ∣ m * n) : Subtype fun (d : (Subtype fun (m' : ℕ) => m' ∣ m) × Subtype fun (n' : ℕ) => n' ∣ n) => k = ↑(prod.fst d) * ↑(prod.snd d) := (fun (_x : ℕ) (h0 : gcd k m = _x) => nat.cases_on _x (fun (h0 : gcd k m = 0) => Eq._oldrec (fun (H : 0 ∣ m * n) (h0 : gcd 0 m = 0) => Eq._oldrec (fun (H : 0 ∣ 0 * n) (h0 : gcd 0 0 = 0) => { val := ({ val := 0, property := sorry }, { val := n, property := dvd_refl n }), property := sorry }) sorry H h0) sorry H h0) (fun (n_1 : ℕ) (h0 : gcd k m = Nat.succ n_1) => (fun (h0 : gcd k m = Nat.succ n_1) => { val := ({ val := gcd k m, property := gcd_dvd_right k m }, { val := k / gcd k m, property := sorry }), property := sorry }) h0) h0) (gcd k m) sorry theorem gcd_mul_dvd_mul_gcd (k : ℕ) (m : ℕ) (n : ℕ) : gcd k (m * n) ∣ gcd k m * gcd k n := sorry theorem coprime.gcd_mul (k : ℕ) {m : ℕ} {n : ℕ} (h : coprime m n) : gcd k (m * n) = gcd k m * gcd k n := dvd_antisymm (gcd_mul_dvd_mul_gcd k m n) (coprime.mul_dvd_of_dvd_of_dvd (coprime.gcd_both k k h) (gcd_dvd_gcd_mul_right_right k m n) (gcd_dvd_gcd_mul_left_right k n m)) theorem pow_dvd_pow_iff {a : ℕ} {b : ℕ} {n : ℕ} (n0 : 0 < n) : a ^ n ∣ b ^ n ↔ a ∣ b := sorry theorem gcd_mul_gcd_of_coprime_of_mul_eq_mul {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (cop : coprime c d) (h : a * b = c * d) : gcd a c * gcd b c = c := sorry
b8aeec1bbacdcc13498b38df6e1d7fde16894081
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/nat/size.lean
56ba762a64894b1e71f93e252692e8ff177aa9a5
[ "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,757
lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import data.nat.pow import data.nat.bits /-! > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Lemmas about `size`. -/ namespace nat /-! ### `shiftl` and `shiftr` -/ lemma shiftl_eq_mul_pow (m) : ∀ n, shiftl m n = m * 2 ^ n | 0 := (nat.mul_one _).symm | (k+1) := show bit0 (shiftl m k) = m * (2 * 2 ^ k), by rw [bit0_val, shiftl_eq_mul_pow, mul_left_comm, mul_comm 2] lemma shiftl'_tt_eq_mul_pow (m) : ∀ n, shiftl' tt m n + 1 = (m + 1) * 2 ^ n | 0 := by simp [shiftl, shiftl', pow_zero, nat.one_mul] | (k+1) := begin change bit1 (shiftl' tt m k) + 1 = (m + 1) * (2 * 2 ^ k), rw bit1_val, change 2 * (shiftl' tt m k + 1) = _, rw [shiftl'_tt_eq_mul_pow, mul_left_comm, mul_comm 2], end lemma one_shiftl (n) : shiftl 1 n = 2 ^ n := (shiftl_eq_mul_pow _ _).trans (nat.one_mul _) @[simp] lemma zero_shiftl (n) : shiftl 0 n = 0 := (shiftl_eq_mul_pow _ _).trans (nat.zero_mul _) lemma shiftr_eq_div_pow (m) : ∀ n, shiftr m n = m / 2 ^ n | 0 := (nat.div_one _).symm | (k+1) := (congr_arg div2 (shiftr_eq_div_pow k)).trans $ by rw [div2_val, nat.div_div_eq_div_mul, mul_comm]; refl @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := (shiftr_eq_div_pow _ _).trans (nat.zero_div _) theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n; simp [bit_ne_zero, shiftl', *] theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ /-! ### `size` -/ @[simp] theorem size_zero : size 0 = 0 := by simp [size] @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, end @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := show size (bit1 0) = 1, by rw [size_bit1, size_zero] @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊢, rw [size_bit h, nat.add_succ], by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]], rw s0 at h ⊢, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, obtain rfl := succ.inj (eq_one_of_dvd_one ⟨_, this.symm⟩), rw one_mul at this, obtain rfl : n = 0 := nat.eq_zero_of_le_zero (le_of_not_gt $ λ hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), refl end @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : ℕ) : n < 2^size n := begin rw [← one_shiftl], have : ∀ {n}, n = 0 → n < shiftl 1 (size n), { simp }, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, simp }, { intros b m IH n h, by_cases e : bit b m = 0, { simp [e] }, rw [size_bit e], cases n with n, { exact e.elim (nat.eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n := by rw [← not_lt, decidable.iff_not_comm, not_lt, size_le] theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero] at this; exact decidable.not_iff_not.1 this theorem size_pow {n : ℕ} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_rfl) theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) lemma size_eq_bits_len (n : ℕ) : n.bits.length = n.size := begin induction n using nat.binary_rec' with b n h ih, { simp, }, rw [size_bit, bits_append_bit _ _ h], { simp [ih], }, { simpa [bit_eq_zero_iff], } end end nat
6244c4231125ffd9fa13bc442132d36b8424fa1b
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/tactic/suggest.lean
9d7664d290b89999ac8d94085024a3c7cd2d2f25
[ "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
22,032
lean
/- Copyright (c) 2019 Lucas Allen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen, Scott Morrison -/ import data.mllist import tactic.solve_by_elim /-! # `suggest` and `library_search` `suggest` and `library_search` are a pair of tactics for applying lemmas from the library to the current goal. * `suggest` prints a list of `exact ...` or `refine ...` statements, which may produce new goals * `library_search` prints a single `exact ...` which closes the goal, or fails -/ namespace tactic open native namespace suggest open solve_by_elim /-- Map a name (typically a head symbol) to a "canonical" definitional synonym. Given a name `n`, we want a name `n'` such that a sufficiently applied expression with head symbol `n` is always definitionally equal to an expression with head symbol `n'`. Thus, we can search through all lemmas with a result type of `n'` to solve a goal with head symbol `n`. For example, `>` is mapped to `<` because `a > b` is definitionally equal to `b < a`, and `not` is mapped to `false` because `¬ a` is definitionally equal to `p → false` The default is that the original argument is returned, so `<` is just mapped to `<`. `normalize_synonym` is called for every lemma in the library, so it needs to be fast. -/ -- TODO this is a hack; if you suspect more cases here would help, please report them meta def normalize_synonym : name → name | `gt := `has_lt.lt | `ge := `has_le.le | `monotone := `has_le.le | `not := `false | n := n /-- Compute the head symbol of an expression, then normalise synonyms. This is only used when analysing the goal, so it is okay to do more expensive analysis here. -/ -- We may want to tweak this further? meta def allowed_head_symbols : expr → list name -- We first have a various "customisations": -- Because in `ℕ` `a.succ ≤ b` is definitionally `a < b`, -- we add some special cases to allow looking for `<` lemmas even when the goal has a `≤`. -- Note we only do this in the `ℕ` case, for performance. | `(@has_le.le ℕ _ (nat.succ _) _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ (nat.succ _)) := [`has_le.le, `has_lt.lt] | `(@has_le.le ℕ _ 1 _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ 1) := [`has_le.le, `has_lt.lt] -- And then the generic cases: | (expr.pi _ _ _ t) := allowed_head_symbols t | (expr.app f _) := allowed_head_symbols f | (expr.const n _) := [normalize_synonym n] | _ := [`_] . /-- A declaration can match the head symbol of the current goal in four possible ways: * `ex` : an exact match * `mp` : the declaration returns an `iff`, and the right hand side matches the goal * `mpr` : the declaration returns an `iff`, and the left hand side matches the goal * `both`: the declaration returns an `iff`, and the both sides match the goal -/ @[derive decidable_eq, derive inhabited] inductive head_symbol_match | ex | mp | mpr | both open head_symbol_match /-- a textual representation of a `head_symbol_match`, for trace debugging. -/ def head_symbol_match.to_string : head_symbol_match → string | ex := "exact" | mp := "iff.mp" | mpr := "iff.mpr" | both := "iff.mp and iff.mpr" /-- Determine if, and in which way, a given expression matches the specified head symbol. -/ meta def match_head_symbol (hs : name_set) : expr → option head_symbol_match | (expr.pi _ _ _ t) := match_head_symbol t | `(%%a ↔ %%b) := if hs.contains `iff then some ex else match (match_head_symbol a, match_head_symbol b) with | (some ex, some ex) := some both | (some ex, _) := some mpr | (_, some ex) := some mp | _ := none end | (expr.app f _) := match_head_symbol f | (expr.const n _) := if hs.contains (normalize_synonym n) then some ex else none | _ := if hs.contains `_ then some ex else none /-- A package of `declaration` metadata, including the way in which its type matches the head symbol which we are searching for. -/ meta structure decl_data := (d : declaration) (n : name) (m : head_symbol_match) (l : ℕ) -- cached length of name /-- Generate a `decl_data` from the given declaration if it matches the head symbol `hs` for the current goal. -/ -- We used to check here for private declarations, or declarations with certain suffixes. -- It turns out `apply` is so fast, it's better to just try them all. meta def process_declaration (hs : name_set) (d : declaration) : option decl_data := let n := d.to_name in if !d.is_trusted || n.is_internal then none else (λ m, ⟨d, n, m, n.length⟩) <$> match_head_symbol hs d.type /-- Retrieve all library definitions with a given head symbol. -/ meta def library_defs (hs : name_set) : tactic (list decl_data) := do trace_if_enabled `suggest format!"Looking for lemmas with head symbols {hs}.", env ← get_env, let defs := env.decl_filter_map (process_declaration hs), -- Sort by length; people like short proofs let defs := defs.qsort(λ d₁ d₂, d₁.l ≤ d₂.l), trace_if_enabled `suggest format!"Found {defs.length} relevant lemmas:", trace_if_enabled `suggest $ defs.map (λ ⟨d, n, m, l⟩, (n, m.to_string)), return defs /-- We unpack any element of a list of `decl_data` corresponding to an `↔` statement that could apply in both directions into two separate elements. This ensures that both directions can be independently returned by `suggest`, and avoids a problem where the application of one direction prevents the application of the other direction. (See `exp_le_exp` in the tests.) -/ meta def unpack_iff_both : list decl_data → list decl_data | [] := [] | (⟨d, n, both, l⟩ :: L) := ⟨d, n, mp, l⟩ :: ⟨d, n, mpr, l⟩ :: unpack_iff_both L | (⟨d, n, m, l⟩ :: L) := ⟨d, n, m, l⟩ :: unpack_iff_both L /-- An extension to the option structure for `solve_by_elim`, to specify a list of local hypotheses which must appear in any solution. These are useful for constraining the results from `library_search` and `suggest`. -/ meta structure suggest_opt extends opt := (compulsory_hyps : list expr := []) /-- Convert a `suggest_opt` structure to a `opt` structure suitable for `solve_by_elim`, by setting the `accept` parameter to require that all complete solutions use everything in `compulsory_hyps`. -/ meta def suggest_opt.mk_accept (o : suggest_opt) : opt := { accept := λ gs, o.accept gs >> (guard $ o.compulsory_hyps.all (λ h, gs.any (λ g, g.contains_expr_or_mvar h))), ..o } /-- Apply the lemma `e`, then attempt to close all goals using `solve_by_elim opt`, failing if `close_goals = tt` and there are any goals remaining. Returns the number of subgoals which were closed using `solve_by_elim`. -/ -- Implementation note: as this is used by both `library_search` and `suggest`, -- we first run `solve_by_elim` separately on the independent goals, -- whether or not `close_goals` is set, -- and then run `solve_by_elim { all_goals := tt }`, -- requiring that it succeeds if `close_goals = tt`. meta def apply_and_solve (close_goals : bool) (opt : suggest_opt := { }) (e : expr) : tactic ℕ := do trace_if_enabled `suggest format!"Trying to apply lemma: {e}", apply e opt.to_apply_cfg, trace_if_enabled `suggest format!"Applied lemma: {e}", ng ← num_goals, -- Phase 1 -- Run `solve_by_elim` on each "safe" goal separately, not worrying about failures. -- (We only attempt the "safe" goals in this way in Phase 1. -- In Phase 2 we will do backtracking search across all goals, -- allowing us to guess solutions that involve data or unify metavariables, -- but only as long as we can finish all goals.) -- If `compulsory_hyps` is non-empty, we skip this phase and defer to phase 2. try (guard (opt.compulsory_hyps = []) >> any_goals (independent_goal >> solve_by_elim opt.to_opt)), -- Phase 2 (done >> return ng) <|> (do -- If there were any goals that we did not attempt solving in the first phase -- (because they weren't propositional, or contained a metavariable) -- as a second phase we attempt to solve all remaining goals at once -- (with backtracking across goals). ((guard (opt.compulsory_hyps ≠ []) <|> any_goals (success_if_fail independent_goal) >> skip) >> solve_by_elim { backtrack_all_goals := tt, ..opt.mk_accept }) <|> -- and fail unless `close_goals = ff` guard ¬ close_goals, ng' ← num_goals, return (ng - ng')) /-- Apply the declaration `d` (or the forward and backward implications separately, if it is an `iff`), and then attempt to solve the subgoal using `apply_and_solve`. Returns the number of subgoals successfully closed. -/ meta def apply_declaration (close_goals : bool) (opt : suggest_opt := { }) (d : decl_data) : tactic ℕ := let tac := apply_and_solve close_goals opt in do (e, t) ← decl_mk_const d.d, match d.m with | ex := tac e | mp := do l ← iff_mp_core e t, tac l | mpr := do l ← iff_mpr_core e t, tac l | both := undefined -- we use `unpack_iff_both` to ensure this isn't reachable end /-- An `application` records the result of a successful application of a library lemma. -/ meta structure application := (state : tactic_state) (script : string) (decl : option declaration) (num_goals : ℕ) (hyps_used : list expr) end suggest open solve_by_elim open suggest declare_trace suggest -- Trace a list of all relevant lemmas -- Call `apply_declaration`, then prepare the tactic script and -- count the number of local hypotheses used. private meta def apply_declaration_script (g : expr) (hyps : list expr) (opt : suggest_opt := { }) (d : decl_data) : tactic application := -- (This tactic block is only executed when we evaluate the mllist, -- so we need to do the `focus1` here.) retrieve $ focus1 $ do apply_declaration ff opt d, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, guard $ (opt.compulsory_hyps.all (λ h, h.occurs g)), ng ← num_goals, s ← read, m ← tactic_statement g, return { application . state := s, decl := d.d, script := m, num_goals := ng, hyps_used := hyps.filter (λ h, h.occurs g) } -- implementation note: we produce a `tactic (mllist tactic application)` first, -- because it's easier to work in the tactic monad, but in a moment we squash this -- down to an `mllist tactic application`. private meta def suggest_core' (opt : suggest_opt := { }) : tactic (mllist tactic application) := do g :: _ ← get_goals, hyps ← local_context, -- Check if `solve_by_elim` can solve the goal immediately: (retrieve (do focus1 $ solve_by_elim opt.mk_accept, s ← read, m ← tactic_statement g, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, guard (opt.compulsory_hyps.all (λ h, h.occurs g)), return $ mllist.of_list [⟨s, m, none, 0, hyps.filter (λ h, h.occurs g)⟩])) <|> -- Otherwise, let's actually try applying library lemmas. (do -- Collect all definitions with the correct head symbol t ← infer_type g, defs ← unpack_iff_both <$> library_defs (name_set.of_list $ allowed_head_symbols t), let defs : mllist tactic _ := mllist.of_list defs, -- Try applying each lemma against the goal, -- recording the tactic script as a string, -- the number of remaining goals, -- and number of local hypotheses used. let results := defs.mfilter_map (apply_declaration_script g hyps opt), -- Now call `symmetry` and try again. -- (Because we are using `mllist`, this is essentially free if we've already found a lemma.) symm_state ← retrieve $ try_core $ symmetry >> read, let results_symm := match symm_state with | (some s) := defs.mfilter_map (λ d, retrieve $ set_state s >> apply_declaration_script g hyps opt d) | none := mllist.nil end, return (results.append results_symm)) /-- The core `suggest` tactic. It attempts to apply a declaration from the library, then solve new goals using `solve_by_elim`. It returns a list of `application`s consisting of fields: * `state`, a tactic state resulting from the successful application of a declaration from the library, * `script`, a string of the form `Try this: refine ...` or `Try this: exact ...` which will reproduce that tactic state, * `decl`, an `option declaration` indicating the declaration that was applied (or none, if `solve_by_elim` succeeded), * `num_goals`, the number of remaining goals, and * `hyps_used`, the number of local hypotheses used in the solution. -/ meta def suggest_core (opt : suggest_opt := { }) : mllist tactic application := (mllist.monad_lift (suggest_core' opt)).join /-- See `suggest_core`. Returns a list of at most `limit` `application`s, sorted by number of goals, and then (reverse) number of hypotheses used. -/ meta def suggest (limit : option ℕ := none) (opt : suggest_opt := { }) : tactic (list application) := do let results := suggest_core opt, -- Get the first n elements of the successful lemmas L ← if h : limit.is_some then results.take (option.get h) else results.force, -- Sort by number of remaining goals, then by number of hypotheses used. return $ L.qsort (λ d₁ d₂, d₁.num_goals < d₂.num_goals ∨ (d₁.num_goals = d₂.num_goals ∧ d₁.hyps_used.length ≥ d₂.hyps_used.length)) /-- Returns a list of at most `limit` strings, of the form `Try this: exact ...` or `Try this: refine ...`, which make progress on the current goal using a declaration from the library. -/ meta def suggest_scripts (limit : option ℕ := none) (opt : suggest_opt := { }) : tactic (list string) := do L ← suggest limit opt, return $ L.map application.script /-- Returns a string of the form `Try this: exact ...`, which closes the current goal. -/ meta def library_search (opt : suggest_opt := { }) : tactic string := (suggest_core opt).mfirst (λ a, do guard (a.num_goals = 0), write a.state, return a.script) namespace interactive open tactic open interactive open lean.parser open interactive.types open solve_by_elim local postfix `?`:9001 := optional declare_trace silence_suggest -- Turn off `Try this: exact/refine ...` trace messages for `suggest` /-- `suggest` tries to apply suitable theorems/defs from the library, and generates a list of `exact ...` or `refine ...` scripts that could be used at this step. It leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin suggest [add_lt_add], -- Says: `Try this: exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `suggest with attr` to include all lemmas with the attribute `attr`. -/ meta def suggest (n : parse (with_desc "n" small_nat)?) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (use : parse $ (tk "using" *> many ident_) <|> return []) (opt : opt := { }) : tactic unit := do (lemma_thunks, ctx_thunk) ← mk_assumption_set ff hs attr_names, use ← use.mmap get_local, L ← tactic.suggest_scripts (n.get_or_else 50) { compulsory_hyps := use, lemma_thunks := some lemma_thunks, ctx_thunk := ctx_thunk, ..opt }, if is_trace_enabled_for `silence_suggest then skip else if L.length = 0 then fail "There are no applicable declarations" else L.mmap trace >> skip /-- `suggest` lists possible usages of the `refine` tactic and leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. `suggest using h₁ h₂` will only show solutions that make use of the local hypotheses `h₁` and `h₂`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. An example of `suggest` in action, ```lean example (n : nat) : n < n + 1 := begin suggest, sorry end ``` prints the list, ```lean Try this: exact nat.lt.base n Try this: exact nat.lt_succ_self n Try this: refine not_le.mp _ Try this: refine gt_iff_lt.mp _ Try this: refine nat.lt.step _ Try this: refine lt_of_not_ge _ ... ``` -/ add_tactic_doc { name := "suggest", category := doc_category.tactic, decl_names := [`tactic.interactive.suggest], tags := ["search", "Try this"] } -- Turn off `Try this: exact ...` trace message for `library_search` declare_trace silence_library_search /-- `library_search` is a tactic to identify existing lemmas in the library. It tries to close the current goal by applying a lemma from the library, then discharging any new goals using `solve_by_elim`. If it succeeds, it prints a trace message `exact ...` which can replace the invocation of `library_search`. Typical usage is: ```lean example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- Try this: exact nat.mul_sub_left_distrib n m k ``` `library_search using h₁ h₂` will only show solutions that make use of the local hypotheses `h₁` and `h₂`. By default `library_search` only unfolds `reducible` definitions when attempting to match lemmas against the goal. Previously, it would unfold most definitions, sometimes giving surprising answers, or slow answers. The old behaviour is still available via `library_search!`. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin library_search [add_lt_add], -- Says: `Try this: exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `library_search with attr` to include all lemmas with the attribute `attr`. -/ meta def library_search (semireducible : parse $ optional (tk "!")) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (use : parse $ (tk "using" *> many ident_) <|> return []) (opt : opt := { }) : tactic unit := do (lemma_thunks, ctx_thunk) ← mk_assumption_set ff hs attr_names, use ← use.mmap get_local, (tactic.library_search { compulsory_hyps := use, backtrack_all_goals := tt, lemma_thunks := some lemma_thunks, ctx_thunk := ctx_thunk, md := if semireducible.is_some then tactic.transparency.semireducible else tactic.transparency.reducible, ..opt } >>= if is_trace_enabled_for `silence_library_search then (λ _, skip) else trace) <|> fail "`library_search` failed. If you aren't sure what to do next, you can also try `library_search!`, `suggest`, or `hint`. Possible reasons why `library_search` failed: * `library_search` will only apply a single lemma from the library, and then try to fill in its hypotheses from local hypotheses. * If you haven't already, try stating the theorem you want in its own lemma. * Sometimes the library has one version of a lemma but not a very similar version obtained by permuting arguments. Try replacing `a + b` with `b + a`, or `a - b < c` with `a < b + c`, to see if maybe the lemma exists but isn't stated quite the way you would like. * Make sure that you have all the side conditions for your theorem to be true. For example you won't find `a - b + b = a` for natural numbers in the library because it's false! Search for `b ≤ a → a - b + b = a` instead. * If a definition you made is in the goal, you won't find any theorems about it in the library. Try unfolding the definition using `unfold my_definition`. * If all else fails, ask on https://leanprover.zulipchat.com/, and maybe we can improve the library and/or `library_search` for next time." add_tactic_doc { name := "library_search", category := doc_category.tactic, decl_names := [`tactic.interactive.library_search], tags := ["search", "Try this"] } end interactive /-- Invoking the hole command `library_search` ("Use `library_search` to complete the goal") calls the tactic `library_search` to produce a proof term with the type of the hole. Running it on ```lean example : 0 < 1 := {!!} ``` produces ```lean example : 0 < 1 := nat.one_pos ``` -/ @[hole_command] meta def library_search_hole_cmd : hole_command := { name := "library_search", descr := "Use `library_search` to complete the goal.", action := λ _, do script ← library_search, -- Is there a better API for dropping the 'Try this: exact ' prefix on this string? return [((script.get_rest "Try this: exact ").get_or_else script, "by library_search")] } add_tactic_doc { name := "library_search", category := doc_category.hole_cmd, decl_names := [`tactic.library_search_hole_cmd], tags := ["search", "Try this"] } end tactic
7c6b734b929a6beddcd5611930403a1455988326
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/library/data/sigma.lean
a28979563bfb62e806581e5ef995e9d0ba1730d6
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
3,031
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad, Floris van Doorn Sigma types, aka dependent sum. -/ import logic.cast open inhabited sigma.ops override eq.ops namespace sigma universe variables u v variables {A A' : Type.{u}} {B : A → Type.{v}} {B' : A' → Type.{v}} definition unpack {C : (Σa, B a) → Type} {u : Σa, B a} (H : C ⟨u.1 , u.2⟩) : C u := destruct u (λx y H, H) H theorem dpair_heq {a : A} {a' : A'} {b : B a} {b' : B' a'} (HB : B == B') (Ha : a == a') (Hb : b == b') : ⟨a, b⟩ == ⟨a', b'⟩ := hcongr_arg4 @mk (heq.type_eq Ha) HB Ha Hb protected theorem heq {p : Σa : A, B a} {p' : Σa' : A', B' a'} (HB : B == B') : ∀(H₁ : p.1 == p'.1) (H₂ : p.2 == p'.2), p == p' := destruct p (take a₁ b₁, destruct p' (take a₂ b₂ H₁ H₂, dpair_heq HB H₁ H₂)) protected definition is_inhabited [instance] [H₁ : inhabited A] [H₂ : inhabited (B (default A))] : inhabited (sigma B) := inhabited.destruct H₁ (λa, inhabited.destruct H₂ (λb, inhabited.mk ⟨default A, b⟩)) theorem eq_rec_dpair_commute {C : Πa, B a → Type} {a a' : A} (H : a = a') (b : B a) (c : C a b) : eq.rec_on H ⟨b, c⟩ = ⟨eq.rec_on H b, eq.rec_on (dcongr_arg2 C H rfl) c⟩ := eq.drec_on H (dpair_eq rfl (!eq.rec_on_id⁻¹)) variables {C : Πa, B a → Type} {D : Πa b, C a b → Type} definition dtrip (a : A) (b : B a) (c : C a b) := ⟨a, b, c⟩ definition dquad (a : A) (b : B a) (c : C a b) (d : D a b c) := ⟨a, b, c, d⟩ definition pr1' [reducible] (x : Σ a, B a) := x.1 definition pr2' [reducible] (x : Σ a b, C a b) := x.2.1 definition pr3 [reducible] (x : Σ a b, C a b) := x.2.2 definition pr3' [reducible] (x : Σ a b c, D a b c) := x.2.2.1 definition pr4 [reducible] (x : Σ a b c, D a b c) := x.2.2.2 theorem dtrip_eq {a₁ a₂ : A} {b₁ : B a₁} {b₂ : B a₂} {c₁ : C a₁ b₁} {c₂ : C a₂ b₂} (H₁ : a₁ = a₂) (H₂ : eq.rec_on H₁ b₁ = b₂) (H₃ : cast (dcongr_arg2 C H₁ H₂) c₁ = c₂) : ⟨a₁, b₁, c₁⟩ = ⟨a₂, b₂, c₂⟩ := dcongr_arg3 dtrip H₁ H₂ H₃ theorem ndtrip_eq {A B : Type} {C : A → B → Type} {a₁ a₂ : A} {b₁ b₂ : B} {c₁ : C a₁ b₁} {c₂ : C a₂ b₂} (H₁ : a₁ = a₂) (H₂ : b₁ = b₂) (H₃ : cast (congr_arg2 C H₁ H₂) c₁ = c₂) : ⟨a₁, b₁, c₁⟩ = ⟨a₂, b₂, c₂⟩ := hdcongr_arg3 dtrip H₁ (heq.of_eq H₂) H₃ theorem ndtrip_equal {A B : Type} {C : A → B → Type} {p₁ p₂ : Σa b, C a b} : ∀(H₁ : pr1 p₁ = pr1 p₂) (H₂ : pr2' p₁ = pr2' p₂) (H₃ : eq.rec_on (congr_arg2 C H₁ H₂) (pr3 p₁) = pr3 p₂), p₁ = p₂ := destruct p₁ (take a₁ q₁, destruct q₁ (take b₁ c₁, destruct p₂ (take a₂ q₂, destruct q₂ (take b₂ c₂ H₁ H₂ H₃, ndtrip_eq H₁ H₂ H₃)))) end sigma
45234d3293b9cf8bcc04dc969db8e75f2714b983
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/linear_algebra/quadratic_form.lean
a5b05c530d29805440a3f2648a88400db9b349cf
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,053
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Anne Baanen -/ import algebra.invertible import linear_algebra.bilinear_form import linear_algebra.determinant import linear_algebra.special_linear_group /-! # Quadratic forms This file defines quadratic forms over a `R`-module `M`. A quadratic form is a map `Q : M → R` such that (`to_fun_smul`) `Q (a • x) = a * a * Q x` (`polar_...`) The map `polar Q := λ x y, Q (x + y) - Q x - Q y` is bilinear. They come with a scalar multiplication, `(a • Q) x = Q (a • x) = a * a * Q x`, and composition with linear maps `f`, `Q.comp f x = Q (f x)`. ## Main definitions * `quadratic_form.associated`: associated bilinear form * `quadratic_form.pos_def`: positive definite quadratic forms * `quadratic_form.anisotropic`: anisotropic quadratic forms * `quadratic_form.discr`: discriminant of a quadratic form ## Main statements * `quadratic_form.associated_left_inverse`, * `quadratic_form.associated_right_inverse`: in a commutative ring where 2 has an inverse, there is a correspondence between quadratic forms and symmetric bilinear forms ## Notation In this file, the variable `R` is used when a `ring` structure is sufficient and `R₁` is used when specifically a `comm_ring` is required. This allows us to keep `[module R M]` and `[module R₁ M]` assumptions in the variables without confusion between `*` from `ring` and `*` from `comm_ring`. ## References * https://en.wikipedia.org/wiki/Quadratic_form * https://en.wikipedia.org/wiki/Discriminant#Quadratic_forms ## Tags quadratic form, homogeneous polynomial, quadratic polynomial -/ universes u v w variables {R : Type u} {M : Type v} [add_comm_group M] [ring R] variables {R₁ : Type u} [comm_ring R₁] namespace quadratic_form /-- Up to a factor 2, `Q.polar` is the associated bilinear form for a quadratic form `Q`.d Source of this name: https://en.wikipedia.org/wiki/Quadratic_form#Generalization -/ def polar (f : M → R) (x y : M) := f (x + y) - f x - f y lemma polar_add (f g : M → R) (x y : M) : polar (f + g) x y = polar f x y + polar g x y := by { simp only [polar, pi.add_apply], abel } lemma polar_neg (f : M → R) (x y : M) : polar (-f) x y = - polar f x y := by { simp only [polar, pi.neg_apply, sub_eq_add_neg, neg_add] } lemma polar_smul (f : M → R) (s : R) (x y : M) : polar (s • f) x y = s * polar f x y := by { simp only [polar, pi.smul_apply, smul_eq_mul, mul_sub] } lemma polar_comm (f : M → R₁) (x y : M) : polar f x y = polar f y x := by rw [polar, polar, add_comm, sub_sub, sub_sub, add_comm (f x) (f y)] end quadratic_form variables [module R M] [module R₁ M] open quadratic_form /-- A quadratic form over a module. -/ structure quadratic_form (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] := (to_fun : M → R) (to_fun_smul : ∀ (a : R) (x : M), to_fun (a • x) = a * a * to_fun x) (polar_add_left' : ∀ (x x' y : M), polar to_fun (x + x') y = polar to_fun x y + polar to_fun x' y) (polar_smul_left' : ∀ (a : R) (x y : M), polar to_fun (a • x) y = a • polar to_fun x y) (polar_add_right' : ∀ (x y y' : M), polar to_fun x (y + y') = polar to_fun x y + polar to_fun x y') (polar_smul_right' : ∀ (a : R) (x y : M), polar to_fun x (a • y) = a • polar to_fun x y) namespace quadratic_form variables {Q : quadratic_form R M} instance : has_coe_to_fun (quadratic_form R M) := ⟨_, λ B, B.to_fun⟩ /-- The `simp` normal form for a quadratic form is `coe_fn`, not `to_fun`. -/ @[simp] lemma to_fun_eq_apply : Q.to_fun = ⇑ Q := rfl lemma map_smul (a : R) (x : M) : Q (a • x) = a * a * Q x := Q.to_fun_smul a x lemma map_add_self (x : M) : Q (x + x) = 4 * Q x := by { rw [←one_smul R x, ←add_smul, map_smul], norm_num } @[simp] lemma map_zero : Q 0 = 0 := by rw [←@zero_smul R _ _ _ _ (0 : M), map_smul, zero_mul, zero_mul] @[simp] lemma map_neg (x : M) : Q (-x) = Q x := by rw [←@neg_one_smul R _ _ _ _ x, map_smul, neg_one_mul, neg_neg, one_mul] lemma map_sub (x y : M) : Q (x - y) = Q (y - x) := by rw [←neg_sub, map_neg] @[simp] lemma polar_zero_left (y : M) : polar Q 0 y = 0 := by simp [polar] @[simp] lemma polar_add_left (x x' y : M) : polar Q (x + x') y = polar Q x y + polar Q x' y := Q.polar_add_left' x x' y @[simp] lemma polar_smul_left (a : R) (x y : M) : polar Q (a • x) y = a * polar Q x y := Q.polar_smul_left' a x y @[simp] lemma polar_neg_left (x y : M) : polar Q (-x) y = -polar Q x y := by rw [←neg_one_smul R x, polar_smul_left, neg_one_mul] @[simp] lemma polar_sub_left (x x' y : M) : polar Q (x - x') y = polar Q x y - polar Q x' y := by rw [sub_eq_add_neg, sub_eq_add_neg, polar_add_left, polar_neg_left] @[simp] lemma polar_zero_right (y : M) : polar Q y 0 = 0 := by simp [polar] @[simp] lemma polar_add_right (x y y' : M) : polar Q x (y + y') = polar Q x y + polar Q x y' := Q.polar_add_right' x y y' @[simp] lemma polar_smul_right (a : R) (x y : M) : polar Q x (a • y) = a * polar Q x y := Q.polar_smul_right' a x y @[simp] lemma polar_neg_right (x y : M) : polar Q x (-y) = -polar Q x y := by rw [←neg_one_smul R y, polar_smul_right, neg_one_mul] @[simp] lemma polar_sub_right (x y y' : M) : polar Q x (y - y') = polar Q x y - polar Q x y' := by rw [sub_eq_add_neg, sub_eq_add_neg, polar_add_right, polar_neg_right] @[simp] lemma polar_self (x : M) : polar Q x x = 2 * Q x := begin rw [polar, map_add_self, sub_sub, sub_eq_iff_eq_add, ←two_mul, ←two_mul, ←mul_assoc], norm_num end variable {Q' : quadratic_form R M} @[ext] lemma ext (H : ∀ (x : M), Q x = Q' x) : Q = Q' := by { cases Q, cases Q', congr, funext, apply H } instance : has_zero (quadratic_form R M) := ⟨ { to_fun := λ x, 0, to_fun_smul := λ a x, by simp, polar_add_left' := λ x x' y, by simp [polar], polar_smul_left' := λ a x y, by simp [polar], polar_add_right' := λ x y y', by simp [polar], polar_smul_right' := λ a x y, by simp [polar] } ⟩ @[simp] lemma zero_apply (x : M) : (0 : quadratic_form R M) x = 0 := rfl instance : inhabited (quadratic_form R M) := ⟨0⟩ instance : has_add (quadratic_form R M) := ⟨ λ Q Q', { to_fun := Q + Q', to_fun_smul := λ a x, by simp only [pi.add_apply, map_smul, mul_add], polar_add_left' := λ x x' y, by simp only [polar_add, polar_add_left, add_assoc, add_left_comm], polar_smul_left' := λ a x y, by simp only [polar_add, smul_eq_mul, mul_add, polar_smul_left], polar_add_right' := λ x y y', by simp only [polar_add, polar_add_right, add_assoc, add_left_comm], polar_smul_right' := λ a x y, by simp only [polar_add, smul_eq_mul, mul_add, polar_smul_right] } ⟩ @[simp] lemma coe_fn_add (Q Q' : quadratic_form R M) : ⇑(Q + Q') = Q + Q' := rfl @[simp] lemma add_apply (Q Q' : quadratic_form R M) (x : M) : (Q + Q') x = Q x + Q' x := rfl instance : has_neg (quadratic_form R M) := ⟨ λ Q, { to_fun := -Q, to_fun_smul := λ a x, by simp only [pi.neg_apply, map_smul, mul_neg_eq_neg_mul_symm], polar_add_left' := λ x x' y, by simp only [polar_neg, polar_add_left, neg_add], polar_smul_left' := λ a x y, by simp only [polar_neg, polar_smul_left, mul_neg_eq_neg_mul_symm, smul_eq_mul], polar_add_right' := λ x y y', by simp only [polar_neg, polar_add_right, neg_add], polar_smul_right' := λ a x y, by simp only [polar_neg, polar_smul_right, mul_neg_eq_neg_mul_symm, smul_eq_mul] } ⟩ @[simp] lemma coe_fn_neg (Q : quadratic_form R M) : ⇑(-Q) = -Q := rfl @[simp] lemma neg_apply (Q : quadratic_form R M) (x : M) : (-Q) x = -Q x := rfl instance : add_comm_group (quadratic_form R M) := { add := (+), zero := 0, neg := has_neg.neg, add_comm := λ Q Q', by { ext, simp only [add_apply, add_comm] }, add_assoc := λ Q Q' Q'', by { ext, simp only [add_apply, add_assoc] }, add_left_neg := λ Q, by { ext, simp only [add_apply, neg_apply, zero_apply, add_left_neg] }, add_zero := λ Q, by { ext, simp only [zero_apply, add_apply, add_zero] }, zero_add := λ Q, by { ext, simp only [zero_apply, add_apply, zero_add] } } @[simp] lemma coe_fn_sub (Q Q' : quadratic_form R M) : ⇑(Q - Q') = Q - Q' := by simp [sub_eq_add_neg] @[simp] lemma sub_apply (Q Q' : quadratic_form R M) (x : M) : (Q - Q') x = Q x - Q' x := by simp [sub_eq_add_neg] instance : has_scalar R₁ (quadratic_form R₁ M) := ⟨ λ a Q, { to_fun := a • Q, to_fun_smul := λ b x, by simp only [pi.smul_apply, map_smul, smul_eq_mul, mul_left_comm], polar_add_left' := λ x x' y, by simp only [polar_smul, polar_add_left, mul_add], polar_smul_left' := λ b x y, by simp only [polar_smul, polar_smul_left, smul_eq_mul, mul_left_comm], polar_add_right' := λ x y y', by simp only [polar_smul, polar_add_right, mul_add], polar_smul_right' := λ b x y, by simp only [polar_smul, polar_smul_right, smul_eq_mul, mul_left_comm] } ⟩ @[simp] lemma coe_fn_smul (a : R₁) (Q : quadratic_form R₁ M) : ⇑(a • Q) = a • Q := rfl @[simp] lemma smul_apply (a : R₁) (Q : quadratic_form R₁ M) (x : M) : (a • Q) x = a * Q x := rfl instance : module R₁ (quadratic_form R₁ M) := { mul_smul := λ a b Q, ext (λ x, by simp only [smul_apply, mul_left_comm, mul_assoc]), one_smul := λ Q, ext (λ x, by simp), smul_add := λ a Q Q', by { ext, simp only [add_apply, smul_apply, mul_add] }, smul_zero := λ a, by { ext, simp only [zero_apply, smul_apply, mul_zero] }, zero_smul := λ Q, by { ext, simp only [zero_apply, smul_apply, zero_mul] }, add_smul := λ a b Q, by { ext, simp only [add_apply, smul_apply, add_mul] } } section comp variables {N : Type v} [add_comm_group N] [module R N] /-- Compose the quadratic form with a linear function. -/ def comp (Q : quadratic_form R N) (f : M →ₗ[R] N) : quadratic_form R M := { to_fun := λ x, Q (f x), to_fun_smul := λ a x, by simp only [map_smul, f.map_smul], polar_add_left' := λ x x' y, by convert polar_add_left (f x) (f x') (f y) using 1; simp only [polar, f.map_add], polar_smul_left' := λ a x y, by convert polar_smul_left a (f x) (f y) using 1; simp only [polar, f.map_smul, f.map_add, smul_eq_mul], polar_add_right' := λ x y y', by convert polar_add_right (f x) (f y) (f y') using 1; simp only [polar, f.map_add], polar_smul_right' := λ a x y, by convert polar_smul_right a (f x) (f y) using 1; simp only [polar, f.map_smul, f.map_add, smul_eq_mul] } @[simp] lemma comp_apply (Q : quadratic_form R N) (f : M →ₗ[R] N) (x : M) : (Q.comp f) x = Q (f x) := rfl end comp section comm_ring /-- Create a quadratic form in a commutative ring by proving only one side of the bilinearity. -/ def mk_left (f : M → R₁) (to_fun_smul : ∀ a x, f (a • x) = a * a * f x) (polar_add_left : ∀ x x' y, polar f (x + x') y = polar f x y + polar f x' y) (polar_smul_left : ∀ a x y, polar f (a • x) y = a * polar f x y) : quadratic_form R₁ M := { to_fun := f, to_fun_smul := to_fun_smul, polar_add_left' := polar_add_left, polar_smul_left' := polar_smul_left, polar_add_right' := λ x y y', by rw [polar_comm, polar_add_left, polar_comm f y x, polar_comm f y' x], polar_smul_right' := λ a x y, by rw [polar_comm, polar_smul_left, polar_comm f y x, smul_eq_mul] } /-- The product of linear forms is a quadratic form. -/ def lin_mul_lin (f g : M →ₗ[R₁] R₁) : quadratic_form R₁ M := mk_left (f * g) (λ a x, by { simp, ring }) (λ x x' y, by { simp [polar], ring }) (λ a x y, by { simp [polar], ring }) @[simp] lemma lin_mul_lin_apply (f g : M →ₗ[R₁] R₁) (x) : lin_mul_lin f g x = f x * g x := rfl @[simp] lemma add_lin_mul_lin (f g h : M →ₗ[R₁] R₁) : lin_mul_lin (f + g) h = lin_mul_lin f h + lin_mul_lin g h := ext (λ x, add_mul _ _ _) @[simp] lemma lin_mul_lin_add (f g h : M →ₗ[R₁] R₁) : lin_mul_lin f (g + h) = lin_mul_lin f g + lin_mul_lin f h := ext (λ x, mul_add _ _ _) variables {N : Type v} [add_comm_group N] [module R₁ N] @[simp] lemma lin_mul_lin_comp (f g : M →ₗ[R₁] R₁) (h : N →ₗ[R₁] M) : (lin_mul_lin f g).comp h = lin_mul_lin (f.comp h) (g.comp h) := rfl variables {n : Type*} /-- `proj i j` is the quadratic form mapping the vector `x : n → R₁` to `x i * x j` -/ def proj (i j : n) : quadratic_form R₁ (n → R₁) := lin_mul_lin (@linear_map.proj _ _ _ (λ _, R₁) _ _ i) (@linear_map.proj _ _ _ (λ _, R₁) _ _ j) @[simp] lemma proj_apply (i j : n) (x : n → R₁) : proj i j x = x i * x j := rfl end comm_ring end quadratic_form /-! ### Associated bilinear forms Over a commutative ring with an inverse of 2, the theory of quadratic forms is basically identical to that of symmetric bilinear forms. The map from quadratic forms to bilinear forms giving this identification is called the `associated` quadratic form. -/ variables {B : bilin_form R M} namespace bilin_form open quadratic_form lemma polar_to_quadratic_form (x y : M) : polar (λ x, B x x) x y = B x y + B y x := by simp [polar, add_left, add_right, sub_eq_add_neg _ (B y y), add_comm (B y x) _, add_assoc] /-- A bilinear form gives a quadratic form by applying the argument twice. -/ def to_quadratic_form (B : bilin_form R M) : quadratic_form R M := ⟨ λ x, B x x, λ a x, by simp [smul_left, smul_right, mul_assoc], λ x x' y, by simp [polar_to_quadratic_form, add_left, add_right, add_left_comm, add_assoc], λ a x y, by simp [polar_to_quadratic_form, smul_left, smul_right, mul_add], λ x y y', by simp [polar_to_quadratic_form, add_left, add_right, add_left_comm, add_assoc], λ a x y, by simp [polar_to_quadratic_form, smul_left, smul_right, mul_add] ⟩ @[simp] lemma to_quadratic_form_apply (B : bilin_form R M) (x : M) : B.to_quadratic_form x = B x x := rfl end bilin_form namespace quadratic_form open bilin_form sym_bilin_form section associated variables [invertible (2 : R₁)] {B₁ : bilin_form R₁ M} /-- `associated` is the linear map that sends a quadratic form to its associated symmetric bilinear form -/ def associated : quadratic_form R₁ M →ₗ[R₁] bilin_form R₁ M := { to_fun := λ Q, { bilin := λ x y, ⅟2 * polar Q x y, bilin_add_left := λ x y z, by rw [← mul_add, polar_add_left], bilin_smul_left := λ x y z, by rw [← mul_left_comm, polar_smul_left], bilin_add_right := λ x y z, by rw [← mul_add, polar_add_right], bilin_smul_right := λ x y z, by rw [← mul_left_comm, polar_smul_right] }, map_add' := λ Q Q', by { ext, simp [bilin_form.add_apply, polar_add, mul_add] }, map_smul' := λ a Q, by { ext, simp [bilin_form.smul_apply, polar_smul, mul_left_comm] } } variables {Q : quadratic_form R₁ M} @[simp] lemma associated_apply (x y : M) : associated Q x y = ⅟2 * (Q (x + y) - Q x - Q y) := rfl lemma associated_is_sym : is_sym Q.associated := λ x y, by simp only [associated_apply, add_comm, add_left_comm, sub_eq_add_neg] @[simp] lemma associated_comp {N : Type v} [add_comm_group N] [module R₁ N] (f : N →ₗ[R₁] M) : (Q.comp f).associated = Q.associated.comp f f := by { ext, simp } @[simp] lemma associated_lin_mul_lin (f g : M →ₗ[R₁] R₁) : (lin_mul_lin f g).associated = ⅟(2 : R₁) • (bilin_form.lin_mul_lin f g + bilin_form.lin_mul_lin g f) := by { ext, simp [bilin_form.add_apply, bilin_form.smul_apply], ring } lemma associated_to_quadratic_form (B : bilin_form R₁ M) (x y : M) : associated B.to_quadratic_form x y = ⅟2 * (B x y + B y x) := by simp [associated_apply, ←polar_to_quadratic_form, polar] lemma associated_left_inverse (h : is_sym B₁) : B₁.to_quadratic_form.associated = B₁ := bilin_form.ext $ λ x y, by rw [associated_to_quadratic_form, sym h x y, ←two_mul, ←mul_assoc, inv_of_mul_self, one_mul] lemma associated_right_inverse : Q.associated.to_quadratic_form = Q := quadratic_form.ext $ λ x, calc Q.associated.to_quadratic_form x = ⅟2 * (Q x + Q x) : by simp [map_add_self, bit0, add_mul, add_assoc] ... = Q x : by rw [← two_mul (Q x), ←mul_assoc, inv_of_mul_self, one_mul] end associated section anisotropic /-- An anisotropic quadratic form is zero only on zero vectors. -/ def anisotropic (Q : quadratic_form R M) : Prop := ∀ x, Q x = 0 → x = 0 lemma not_anisotropic_iff_exists (Q : quadratic_form R M) : ¬anisotropic Q ↔ ∃ x ≠ 0, Q x = 0 := by simp only [anisotropic, not_forall, exists_prop, and_comm] end anisotropic section pos_def variables {R₂ : Type u} [ordered_ring R₂] [module R₂ M] {Q₂ : quadratic_form R₂ M} /-- A positive definite quadratic form is positive on nonzero vectors. -/ def pos_def (Q₂ : quadratic_form R₂ M) : Prop := ∀ x ≠ 0, 0 < Q₂ x lemma pos_def.smul {R} [linear_ordered_comm_ring R] [module R M] {Q : quadratic_form R M} (h : pos_def Q) {a : R} (a_pos : 0 < a) : pos_def (a • Q) := λ x hx, mul_pos a_pos (h x hx) variables {n : Type*} lemma pos_def.add (Q Q' : quadratic_form R₂ M) (hQ : pos_def Q) (hQ' : pos_def Q') : pos_def (Q + Q') := λ x hx, add_pos (hQ x hx) (hQ' x hx) lemma lin_mul_lin_self_pos_def {R} [linear_ordered_comm_ring R] [module R M] (f : M →ₗ[R] R) (hf : linear_map.ker f = ⊥) : pos_def (lin_mul_lin f f) := λ x hx, mul_self_pos (λ h, hx (linear_map.ker_eq_bot.mp hf (by rw [h, linear_map.map_zero]))) end pos_def end quadratic_form section /-! ### Quadratic forms and matrices Connect quadratic forms and matrices, in order to explicitly compute with them. The convention is twos out, so there might be a factor 2⁻¹ in the entries of the matrix. The determinant of the matrix is the discriminant of the quadratic form. -/ variables {n : Type w} [fintype n] [decidable_eq n] /-- `M.to_quadratic_form` is the map `λ x, col x ⬝ M ⬝ row x` as a quadratic form. -/ def matrix.to_quadratic_form' (M : matrix n n R₁) : quadratic_form R₁ (n → R₁) := M.to_bilin'.to_quadratic_form variables [invertible (2 : R₁)] /-- A matrix representation of the quadratic form. -/ def quadratic_form.to_matrix' (Q : quadratic_form R₁ (n → R₁)) : matrix n n R₁ := Q.associated.to_matrix' open quadratic_form lemma quadratic_form.to_matrix'_smul (a : R₁) (Q : quadratic_form R₁ (n → R₁)) : (a • Q).to_matrix' = a • Q.to_matrix' := by simp only [to_matrix', linear_equiv.map_smul, linear_map.map_smul] end namespace quadratic_form variables {n : Type w} [fintype n] variables [decidable_eq n] [invertible (2 : R₁)] variables {m : Type w} [decidable_eq m] [fintype m] open_locale matrix @[simp] lemma to_matrix'_comp (Q : quadratic_form R₁ (m → R₁)) (f : (n → R₁) →ₗ[R₁] (m → R₁)) : (Q.comp f).to_matrix' = f.to_matrix'ᵀ ⬝ Q.to_matrix' ⬝ f.to_matrix' := by { ext, simp [to_matrix', bilin_form.to_matrix'_comp] } section discriminant variables {Q : quadratic_form R₁ (n → R₁)} /-- The discriminant of a quadratic form generalizes the discriminant of a quadratic polynomial. -/ def discr (Q : quadratic_form R₁ (n → R₁)) : R₁ := Q.to_matrix'.det lemma discr_smul (a : R₁) : (a • Q).discr = a ^ fintype.card n * Q.discr := by simp only [discr, to_matrix'_smul, matrix.det_smul] lemma discr_comp (f : (n → R₁) →ₗ[R₁] (n → R₁)) : (Q.comp f).discr = f.to_matrix'.det * f.to_matrix'.det * Q.discr := by simp [discr, mul_left_comm, mul_comm] end discriminant end quadratic_form namespace quadratic_form variables {M₁ : Type*} {M₂ : Type*} {M₃ : Type*} variables [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₃] variables [module R M₁] [module R M₂] [module R M₃] /-- An isometry between two quadratic spaces `M₁, Q₁` and `M₂, Q₂` over a ring `R`, is a linear equivalence between `M₁` and `M₂` that commutes with the quadratic forms. -/ @[nolint has_inhabited_instance] structure isometry (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) extends M₁ ≃ₗ[R] M₂ := (map_app' : ∀ m, Q₂ (to_fun m) = Q₁ m) /-- Two quadratic forms over a ring `R` are equivalent if there exists an isometry between them: a linear equivalence that transforms one quadratic form into the other. -/ def equivalent (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) := nonempty (Q₁.isometry Q₂) namespace isometry variables {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} instance : has_coe (Q₁.isometry Q₂) (M₁ ≃ₗ[R] M₂) := ⟨isometry.to_linear_equiv⟩ instance : has_coe_to_fun (Q₁.isometry Q₂) := { F := λ _, M₁ → M₂, coe := λ f, ⇑(f : M₁ ≃ₗ[R] M₂) } @[simp] lemma map_app (f : Q₁.isometry Q₂) (m : M₁) : Q₂ (f m) = Q₁ m := f.map_app' m /-- The identity isometry from a quadratic form to itself. -/ @[refl] def refl (Q : quadratic_form R M) : Q.isometry Q := { map_app' := λ m, rfl, .. linear_equiv.refl R M } /-- The inverse isometry of an isometry between two quadratic forms. -/ @[symm] def symm (f : Q₁.isometry Q₂) : Q₂.isometry Q₁ := { map_app' := by { intro m, rw ← f.map_app, congr, exact f.to_linear_equiv.apply_symm_apply m }, .. (f : M₁ ≃ₗ[R] M₂).symm } /-- The composition of two isometries between quadratic forms. -/ @[trans] def trans (f : Q₁.isometry Q₂) (g : Q₂.isometry Q₃) : Q₁.isometry Q₃ := { map_app' := by { intro m, rw [← f.map_app, ← g.map_app], refl }, .. (f : M₁ ≃ₗ[R] M₂).trans (g : M₂ ≃ₗ[R] M₃) } end isometry namespace equivalent variables {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} @[refl] lemma refl (Q : quadratic_form R M) : Q.equivalent Q := ⟨isometry.refl Q⟩ @[symm] lemma symm (h : Q₁.equivalent Q₂) : Q₂.equivalent Q₁ := h.elim $ λ f, ⟨f.symm⟩ @[trans] lemma trans (h : Q₁.equivalent Q₂) (h' : Q₂.equivalent Q₃) : Q₁.equivalent Q₃ := h'.elim $ h.elim $ λ f g, ⟨f.trans g⟩ end equivalent end quadratic_form
7ffc30bb111ef72b37b744499a3cd17392317532
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/limits/shapes/regular_mono.lean
5d943cf2b7d8f03d4c44e00bde2ff94555ca3898
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
5,964
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.kernels import category_theory.limits.shapes.strong_epi /-! # Definitions and basic properties of regular and normal monomorphisms and epimorphisms. A regular monomorphism is a morphism that is the equalizer of some parallel pair. A normal monomorphism is a morphism that is the kernel of some other morphism. We give the constructions * `split_mono → regular_mono` * `normal_mono → regular_mono`, and * `regular_mono → mono` as well as the dual constructions for regular and normal epimorphisms. Additionally, we give the construction * `regular_epi ⟶ strong_epi`. -/ namespace category_theory open category_theory.limits universes v₁ u₁ variables {C : Type u₁} [category.{v₁} C] variables {X Y : C} /-- A regular monomorphism is a morphism which is the equalizer of some parallel pair. -/ class regular_mono (f : X ⟶ Y) := (Z : C) (left right : Y ⟶ Z) (w : f ≫ left = f ≫ right) (is_limit : is_limit (fork.of_ι f w)) attribute [reassoc] regular_mono.w /-- Every regular monomorphism is a monomorphism. -/ @[priority 100] instance regular_mono.mono (f : X ⟶ Y) [regular_mono f] : mono f := mono_of_is_limit_parallel_pair regular_mono.is_limit /-- Every split monomorphism is a regular monomorphism. -/ @[priority 100] instance regular_mono.of_split_mono (f : X ⟶ Y) [split_mono f] : regular_mono f := { Z := Y, left := 𝟙 Y, right := retraction f ≫ f, w := by tidy, is_limit := split_mono_equalizes f } /-- If `f` is a regular mono, then any map `k : W ⟶ Y` equalizing `regular_mono.left` and `regular_mono.right` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/ def regular_mono.lift' {W : C} (f : X ⟶ Y) [regular_mono f] (k : W ⟶ Y) (h : k ≫ (regular_mono.left : Y ⟶ @regular_mono.Z _ _ _ _ f _) = k ≫ regular_mono.right) : {l : W ⟶ X // l ≫ f = k} := fork.is_limit.lift' regular_mono.is_limit _ h /-- A regular monomorphism is an isomorphism if it is an epimorphism. -/ def is_iso_of_regular_mono_of_epi (f : X ⟶ Y) [regular_mono f] [e : epi f] : is_iso f := @is_iso_limit_cone_parallel_pair_of_epi _ _ _ _ _ _ _ regular_mono.is_limit e section variables [has_zero_morphisms.{v₁} C] /-- A normal monomorphism is a morphism which is the kernel of some morphism. -/ class normal_mono (f : X ⟶ Y) := (Z : C) (g : Y ⟶ Z) (w : f ≫ g = 0) (is_limit : is_limit (kernel_fork.of_ι f w)) /-- Every normal monomorphism is a regular monomorphism. -/ @[priority 100] instance normal_mono.regular_mono (f : X ⟶ Y) [I : normal_mono f] : regular_mono f := { left := I.g, right := 0, w := (by simpa using I.w), ..I } /-- If `f` is a normal mono, then any map `k : W ⟶ Y` such that `k ≫ normal_mono.g = 0` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/ def normal_mono.lift' {W : C} (f : X ⟶ Y) [normal_mono f] (k : W ⟶ Y) (h : k ≫ normal_mono.g = 0) : {l : W ⟶ X // l ≫ f = k} := kernel_fork.is_limit.lift' normal_mono.is_limit _ h end /-- A regular epimorphism is a morphism which is the coequalizer of some parallel pair. -/ class regular_epi (f : X ⟶ Y) := (W : C) (left right : W ⟶ X) (w : left ≫ f = right ≫ f) (is_colimit : is_colimit (cofork.of_π f w)) attribute [reassoc] regular_epi.w /-- Every regular epimorphism is an epimorphism. -/ @[priority 100] instance regular_epi.epi (f : X ⟶ Y) [regular_epi f] : epi f := epi_of_is_colimit_parallel_pair regular_epi.is_colimit /-- Every split epimorphism is a regular epimorphism. -/ @[priority 100] instance regular_epi.of_split_epi (f : X ⟶ Y) [split_epi f] : regular_epi f := { W := X, left := 𝟙 X, right := f ≫ section_ f, w := by tidy, is_colimit := split_epi_coequalizes f } /-- If `f` is a regular epi, then every morphism `k : X ⟶ W` coequalizing `regular_epi.left` and `regular_epi.right` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/ def regular_epi.desc' {W : C} (f : X ⟶ Y) [regular_epi f] (k : X ⟶ W) (h : (regular_epi.left : regular_epi.W f ⟶ X) ≫ k = regular_epi.right ≫ k) : {l : Y ⟶ W // f ≫ l = k} := cofork.is_colimit.desc' (regular_epi.is_colimit) _ h /-- A regular epimorphism is an isomorphism if it is a monomorphism. -/ def is_iso_of_regular_epi_of_mono (f : X ⟶ Y) [regular_epi f] [m : mono f] : is_iso f := @is_iso_limit_cocone_parallel_pair_of_epi _ _ _ _ _ _ _ regular_epi.is_colimit m @[priority 100] instance strong_epi_of_regular_epi (f : X ⟶ Y) [regular_epi f] : strong_epi f := { epi := by apply_instance, has_lift := begin introsI, have : (regular_epi.left : regular_epi.W f ⟶ X) ≫ u = regular_epi.right ≫ u, { apply (cancel_mono z).1, simp only [category.assoc, h, regular_epi.w_assoc] }, obtain ⟨t, ht⟩ := regular_epi.desc' f u this, exact ⟨t, ht, (cancel_epi f).1 (by simp only [←category.assoc, ht, ←h, arrow.mk_hom, arrow.hom_mk'_right])⟩, end } section variables [has_zero_morphisms.{v₁} C] /-- A normal epimorphism is a morphism which is the cokernel of some morphism. -/ class normal_epi (f : X ⟶ Y) := (W : C) (g : W ⟶ X) (w : g ≫ f = 0) (is_colimit : is_colimit (cokernel_cofork.of_π f w)) /-- Every normal epimorphism is a regular epimorphism. -/ @[priority 100] instance normal_epi.regular_epi (f : X ⟶ Y) [I : normal_epi f] : regular_epi f := { left := I.g, right := 0, w := (by simpa using I.w), ..I } /-- If `f` is a normal epi, then every morphism `k : X ⟶ W` satisfying `normal_epi.g ≫ k = 0` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/ def normal_epi.desc' {W : C} (f : X ⟶ Y) [normal_epi f] (k : X ⟶ W) (h : normal_epi.g ≫ k = 0) : {l : Y ⟶ W // f ≫ l = k} := cokernel_cofork.is_colimit.desc' (normal_epi.is_colimit) _ h end end category_theory
4d528bd08f54ea76b643a859c0a6af134a778da4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/geometry/manifold/vector_bundle/hom.lean
ef6b4079edcfb17172e18cd85304c39190d2f721
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,038
lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import geometry.manifold.vector_bundle.basic import topology.vector_bundle.hom /-! # Homs of smooth vector bundles over the same base space > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Here we show that `bundle.continuous_linear_map` is a smooth vector bundle. Note that we only do this for bundles of linear maps, not for bundles of arbitrary semilinear maps. To do it for semilinear maps, we would need to generalize `continuous_linear_map.cont_mdiff` (and `continuous_linear_map.cont_diff`) to semilinear maps. -/ noncomputable theory open bundle set local_homeomorph continuous_linear_map pretrivialization open_locale manifold bundle variables {𝕜 B F F₁ F₂ M M₁ M₂ : Type*} {E : B → Type*} {E₁ : B → Type*} {E₂ : B → Type*} [nontrivially_normed_field 𝕜] [∀ x, add_comm_group (E x)] [∀ x, module 𝕜 (E x)] [normed_add_comm_group F] [normed_space 𝕜 F] [topological_space (total_space F E)] [∀ x, topological_space (E x)] [∀ x, add_comm_group (E₁ x)] [∀ x, module 𝕜 (E₁ x)] [normed_add_comm_group F₁] [normed_space 𝕜 F₁] [topological_space (total_space F₁ E₁)] [∀ x, topological_space (E₁ x)] [∀ x, add_comm_group (E₂ x)] [∀ x, module 𝕜 (E₂ x)] [normed_add_comm_group F₂] [normed_space 𝕜 F₂] [topological_space (total_space F₂ E₂)] [∀ x, topological_space (E₂ x)] [_i₁ : ∀ x, topological_add_group (E₂ x)] [_i₂ : ∀ x, has_continuous_smul 𝕜 (E₂ x)] {EB : Type*} [normed_add_comm_group EB] [normed_space 𝕜 EB] {HB : Type*} [topological_space HB] (IB : model_with_corners 𝕜 EB HB) [topological_space B] [charted_space HB B] {EM : Type*} [normed_add_comm_group EM] [normed_space 𝕜 EM] {HM : Type*} [topological_space HM] {IM : model_with_corners 𝕜 EM HM} [topological_space M] [charted_space HM M] [Is : smooth_manifold_with_corners IM M] {n : ℕ∞} [fiber_bundle F₁ E₁] [vector_bundle 𝕜 F₁ E₁] [fiber_bundle F₂ E₂] [vector_bundle 𝕜 F₂ E₂] {e₁ e₁' : trivialization F₁ (π F₁ E₁)} {e₂ e₂' : trivialization F₂ (π F₂ E₂)} local notation `LE₁E₂` := total_space (F₁ →L[𝕜] F₂) (bundle.continuous_linear_map (ring_hom.id 𝕜) E₁ E₂) /- This proof is slow, especially the `simp only` and the elaboration of `h₂`. -/ lemma smooth_on_continuous_linear_map_coord_change [smooth_manifold_with_corners IB B] [smooth_vector_bundle F₁ E₁ IB] [smooth_vector_bundle F₂ E₂ IB] [mem_trivialization_atlas e₁] [mem_trivialization_atlas e₁'] [mem_trivialization_atlas e₂] [mem_trivialization_atlas e₂'] : smooth_on IB 𝓘(𝕜, ((F₁ →L[𝕜] F₂) →L[𝕜] (F₁ →L[𝕜] F₂))) (continuous_linear_map_coord_change (ring_hom.id 𝕜) e₁ e₁' e₂ e₂') ((e₁.base_set ∩ e₂.base_set) ∩ (e₁'.base_set ∩ e₂'.base_set)) := begin let L₁ := compL 𝕜 F₁ F₂ F₂, have h₁ : smooth _ _ _ := L₁.cont_mdiff, have h₂ : smooth _ _ _ := (continuous_linear_map.flip (compL 𝕜 F₁ F₁ F₂)).cont_mdiff, have h₃ : smooth_on IB _ _ _ := smooth_on_coord_change e₁' e₁, have h₄ : smooth_on IB _ _ _ := smooth_on_coord_change e₂ e₂', refine ((h₁.comp_smooth_on (h₄.mono _)).clm_comp (h₂.comp_smooth_on (h₃.mono _))).congr _, { mfld_set_tac }, { mfld_set_tac }, { intros b hb, ext L v, simp only [continuous_linear_map_coord_change, continuous_linear_equiv.coe_coe, continuous_linear_equiv.arrow_congrSL_apply, comp_apply, function.comp, compL_apply, flip_apply, continuous_linear_equiv.symm_symm, linear_equiv.to_fun_eq_coe, continuous_linear_map.coe_comp'] }, end include _i₁ _i₂ lemma hom_chart (y₀ y : LE₁E₂) : chart_at (model_prod HB (F₁ →L[𝕜] F₂)) y₀ y = (chart_at HB y₀.1 y.1, in_coordinates F₁ E₁ F₂ E₂ y₀.1 y.1 y₀.1 y.1 y.2) := by simp_rw [fiber_bundle.charted_space_chart_at, trans_apply, local_homeomorph.prod_apply, trivialization.coe_coe, local_homeomorph.refl_apply, function.id_def, hom_trivialization_at_apply] variables {IB} lemma cont_mdiff_at_hom_bundle (f : M → LE₁E₂) {x₀ : M} {n : ℕ∞} : cont_mdiff_at IM (IB.prod 𝓘(𝕜, F₁ →L[𝕜] F₂)) n f x₀ ↔ cont_mdiff_at IM IB n (λ x, (f x).1) x₀ ∧ cont_mdiff_at IM 𝓘(𝕜, F₁ →L[𝕜] F₂) n (λ x, in_coordinates F₁ E₁ F₂ E₂ (f x₀).1 (f x).1 (f x₀).1 (f x).1 (f x).2) x₀ := by apply cont_mdiff_at_total_space lemma smooth_at_hom_bundle (f : M → LE₁E₂) {x₀ : M} : smooth_at IM (IB.prod 𝓘(𝕜, F₁ →L[𝕜] F₂)) f x₀ ↔ smooth_at IM IB (λ x, (f x).1) x₀ ∧ smooth_at IM 𝓘(𝕜, F₁ →L[𝕜] F₂) (λ x, in_coordinates F₁ E₁ F₂ E₂ (f x₀).1 (f x).1 (f x₀).1 (f x).1 (f x).2) x₀ := cont_mdiff_at_hom_bundle f variables [smooth_manifold_with_corners IB B] [smooth_vector_bundle F₁ E₁ IB] [smooth_vector_bundle F₂ E₂ IB] instance bundle.continuous_linear_map.vector_prebundle.is_smooth : (bundle.continuous_linear_map.vector_prebundle (ring_hom.id 𝕜) F₁ E₁ F₂ E₂).is_smooth IB := { exists_smooth_coord_change := begin rintro _ ⟨e₁, e₂, he₁, he₂, rfl⟩ _ ⟨e₁', e₂', he₁', he₂', rfl⟩, resetI, refine ⟨continuous_linear_map_coord_change (ring_hom.id 𝕜) e₁ e₁' e₂ e₂', smooth_on_continuous_linear_map_coord_change IB, continuous_linear_map_coord_change_apply (ring_hom.id 𝕜) e₁ e₁' e₂ e₂'⟩ end } instance smooth_vector_bundle.continuous_linear_map : smooth_vector_bundle (F₁ →L[𝕜] F₂) (bundle.continuous_linear_map (ring_hom.id 𝕜) E₁ E₂) IB := (bundle.continuous_linear_map.vector_prebundle (ring_hom.id 𝕜) F₁ E₁ F₂ E₂).smooth_vector_bundle IB
ea3dfef5efd1aceea71433f0d415c0640b2f844e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/zify.lean
8fe6c2a516c4dfc0cc0a993dd275cda15e0b4334
[]
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
3,049
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.norm_cast import Mathlib.data.int.cast import Mathlib.PostPort namespace Mathlib /-! # A tactic to shift `ℕ` goals to `ℤ` It is often easier to work in `ℤ`, where subtraction is well behaved, than in `ℕ` where it isn't. `zify` is a tactic that casts goals and hypotheses about natural numbers to ones about integers. It makes use of `push_cast`, part of the `norm_cast` family, to simplify these goals. ## Implementation notes `zify` is extensible, using the attribute `@[zify]` to label lemmas used for moving propositions from `ℕ` to `ℤ`. `zify` lemmas should have the form `∀ a₁ ... aₙ : ℕ, Pz (a₁ : ℤ) ... (aₙ : ℤ) ↔ Pn a₁ ... aₙ`. For example, `int.coe_nat_le_coe_nat_iff : ∀ (m n : ℕ), ↑m ≤ ↑n ↔ m ≤ n` is a `zify` lemma. `zify` is very nearly just `simp only with zify push_cast`. There are a few minor differences: * `zify` lemmas are used in the opposite order of the standard simp form. E.g. we will rewrite with `int.coe_nat_le_coe_nat_iff` from right to left. * `zify` should fail if no `zify` lemma applies (i.e. it was unable to shift any proposition to ℤ). However, once this succeeds, it does not necessarily need to rewrite with any `push_cast` rules. -/ namespace zify /-- The `zify` attribute is used by the `zify` tactic. It applies to lemmas that shift propositions between `nat` and `int`. `zify` lemmas should have the form `∀ a₁ ... aₙ : ℕ, Pz (a₁ : ℤ) ... (aₙ : ℤ) ↔ Pn a₁ ... aₙ`. For example, `int.coe_nat_le_coe_nat_iff : ∀ (m n : ℕ), ↑m ≤ ↑n ↔ m ≤ n` is a `zify` lemma. -/ /-- Given an expression `e`, `lift_to_z e` looks for subterms of `e` that are propositions "about" natural numbers and change them to propositions about integers. Returns an expression `e'` and a proof that `e = e'`. Includes `ge_iff_le` and `gt_iff_lt` in the simp set. These can't be tagged with `zify` as we want to use them in the "forward", not "backward", direction. -/ end zify theorem int.coe_nat_ne_coe_nat_iff (a : ℕ) (b : ℕ) : ↑a ≠ ↑b ↔ a ≠ b := sorry /-- `zify extra_lems e` is used to shift propositions in `e` from `ℕ` to `ℤ`. This is often useful since `ℤ` has well-behaved subtraction. The list of extra lemmas is used in the `push_cast` step. Returns an expression `e'` and a proof that `e = e'`.-/ /-- A variant of `tactic.zify` that takes `h`, a proof of a proposition about natural numbers, and returns a proof of the zified version of that propositon. -/ /-- The `zify` tactic is used to shift propositions from `ℕ` to `ℤ`. This is often useful since `ℤ` has well-behaved subtraction. ```lean example (a b c x y z : ℕ) (h : ¬ x*y*z < 0) : c < a + 3*b := begin zify, zify at h, /- h : ¬↑x * ↑y * ↑z < 0 ⊢ ↑c < ↑a + 3 * ↑b -/
1e619c92c3a9c453d025aad0d6df142127353d84
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/local_context.lean
146efdc6da41c7be0f612d1771f15c48f43092ba
[]
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
170
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.name import Mathlib.Lean3Lib.init.meta.expr import Mathlib.Lean3Lib.init.data.option.basic namespace Mathlib
a0378129bcbddcb71071303867003a2c24a190d0
9bb72db9297f7837f673785604fb89b3184e13f8
/library/init/data/nat/lemmas.lean
2ad62873d48e42444d333eb56513309ce67cf9f9
[ "Apache-2.0" ]
permissive
dselsam/lean
ec83d7592199faa85687d884bbaaa570b62c1652
6b0bd5bc2e07e13880d332c89093fe3032bb2469
refs/heads/master
1,621,807,064,966
1,611,454,685,000
1,611,975,642,000
42,734,348
3
3
null
1,498,748,560,000
1,442,594,289,000
C++
UTF-8
Lean
false
false
47,304
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad -/ prelude import init.data.nat.basic init.data.nat.div init.meta init.algebra.functions universes u namespace nat attribute [pre_smt] nat_zero_eq_zero protected lemma add_comm : ∀ n m : ℕ, n + m = m + n | n 0 := eq.symm (nat.zero_add n) | n (m+1) := suffices succ (n + m) = succ (m + n), from eq.symm (succ_add m n) ▸ this, congr_arg succ (add_comm n m) protected lemma add_assoc : ∀ n m k : ℕ, (n + m) + k = n + (m + k) | n m 0 := rfl | n m (succ k) := by rw [add_succ, add_succ, add_assoc] protected lemma add_left_comm : ∀ (n m k : ℕ), n + (m + k) = m + (n + k) := left_comm nat.add nat.add_comm nat.add_assoc protected lemma add_left_cancel : ∀ {n m k : ℕ}, n + m = n + k → m = k | 0 m k := by simp [nat.zero_add] {contextual := tt} | (succ n) m k := λ h, have n+m = n+k, by { simp [succ_add] at h, assumption }, add_left_cancel this protected lemma add_right_cancel {n m k : ℕ} (h : n + m = k + m) : n = k := have m + n = m + k, by rwa [nat.add_comm n m, nat.add_comm k m] at h, nat.add_left_cancel this lemma succ_ne_zero (n : ℕ) : succ n ≠ 0 := assume h, nat.no_confusion h lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n | 0 h := absurd h (nat.succ_ne_zero 0) | (n+1) h := succ_ne_self n (nat.no_confusion h (λ h, h)) protected lemma one_ne_zero : 1 ≠ (0 : ℕ) := assume h, nat.no_confusion h protected lemma zero_ne_one : 0 ≠ (1 : ℕ) := assume h, nat.no_confusion h lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0 | 0 m := by simp [nat.zero_add] | (n+1) m := λ h, begin exfalso, rw [add_one, succ_add] at h, apply succ_ne_zero _ h end lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 := @eq_zero_of_add_eq_zero_right m n (nat.add_comm n m ▸ h) @[simp] lemma pred_zero : pred 0 = 0 := rfl @[simp] lemma pred_succ (n : ℕ) : pred (succ n) = n := rfl protected lemma mul_zero (n : ℕ) : n * 0 = 0 := rfl lemma mul_succ (n m : ℕ) : n * succ m = n * m + n := rfl protected theorem zero_mul : ∀ (n : ℕ), 0 * n = 0 | 0 := rfl | (succ n) := by rw [mul_succ, zero_mul] private meta def sort_add := `[simp [nat.add_assoc, nat.add_comm, nat.add_left_comm]] lemma succ_mul : ∀ (n m : ℕ), (succ n) * m = (n * m) + m | n 0 := rfl | n (succ m) := begin simp [mul_succ, add_succ, succ_mul n m], sort_add end protected lemma right_distrib : ∀ (n m k : ℕ), (n + m) * k = n * k + m * k | n m 0 := rfl | n m (succ k) := begin simp [mul_succ, right_distrib n m k], sort_add end protected lemma left_distrib : ∀ (n m k : ℕ), n * (m + k) = n * m + n * k | 0 m k := by simp [nat.zero_mul] | (succ n) m k := begin simp [succ_mul, left_distrib n m k], sort_add end protected lemma mul_comm : ∀ (n m : ℕ), n * m = m * n | n 0 := by rw [nat.zero_mul, nat.mul_zero] | n (succ m) := by simp [mul_succ, succ_mul, mul_comm n m] protected lemma mul_assoc : ∀ (n m k : ℕ), (n * m) * k = n * (m * k) | n m 0 := rfl | n m (succ k) := by simp [mul_succ, nat.left_distrib, mul_assoc n m k] protected lemma mul_one : ∀ (n : ℕ), n * 1 = n := nat.zero_add protected lemma one_mul (n : ℕ) : 1 * n = n := by rw [nat.mul_comm, nat.mul_one] /- properties of inequality -/ protected lemma le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := p ▸ less_than_or_equal.refl lemma le_succ_of_le {n m : ℕ} (h : n ≤ m) : n ≤ succ m := nat.le_trans h (le_succ m) lemma le_of_succ_le {n m : ℕ} (h : succ n ≤ m) : n ≤ m := nat.le_trans (le_succ n) h protected lemma le_of_lt {n m : ℕ} (h : n < m) : n ≤ m := le_of_succ_le h def lt.step {n m : ℕ} : n < m → n < succ m := less_than_or_equal.step lemma eq_zero_or_pos (n : ℕ) : n = 0 ∨ n > 0 := by {cases n, exact or.inl rfl, exact or.inr (succ_pos _)} protected lemma pos_of_ne_zero {n : nat} : n ≠ 0 → n > 0 := or.resolve_left (eq_zero_or_pos n) protected lemma lt_trans {n m k : ℕ} (h₁ : n < m) : m < k → n < k := nat.le_trans (less_than_or_equal.step h₁) protected lemma lt_of_le_of_lt {n m k : ℕ} (h₁ : n ≤ m) : m < k → n < k := nat.le_trans (succ_le_succ h₁) def lt.base (n : ℕ) : n < succ n := nat.le_refl (succ n) lemma lt_succ_self (n : ℕ) : n < succ n := lt.base n protected lemma le_antisymm {n m : ℕ} (h₁ : n ≤ m) : m ≤ n → n = m := less_than_or_equal.cases_on h₁ (λ a, rfl) (λ a b c, absurd (nat.lt_of_le_of_lt b c) (nat.lt_irrefl n)) protected lemma lt_or_ge : ∀ (a b : ℕ), a < b ∨ a ≥ b | a 0 := or.inr (zero_le a) | a (b+1) := match lt_or_ge a b with | or.inl h := or.inl (le_succ_of_le h) | or.inr h := match nat.eq_or_lt_of_le h with | or.inl h1 := or.inl (h1 ▸ lt_succ_self b) | or.inr h1 := or.inr h1 end end protected lemma le_total {m n : ℕ} : m ≤ n ∨ n ≤ m := or.imp_left nat.le_of_lt (nat.lt_or_ge m n) protected lemma lt_of_le_and_ne {m n : ℕ} (h1 : m ≤ n) : m ≠ n → m < n := or.resolve_right (or.swap (nat.eq_or_lt_of_le h1)) protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ (m ≤ n ∧ ¬ n ≤ m) := ⟨λ hmn, ⟨nat.le_of_lt hmn, λ hnm, nat.lt_irrefl _ (nat.lt_of_le_of_lt hnm hmn)⟩, λ ⟨hmn, hnm⟩, nat.lt_of_le_and_ne hmn (λ heq, hnm (heq ▸ nat.le_refl _))⟩ instance : linear_order ℕ := { le := nat.less_than_or_equal, le_refl := @nat.le_refl, le_trans := @nat.le_trans, le_antisymm := @nat.le_antisymm, le_total := @nat.le_total, lt := nat.lt, lt_iff_le_not_le := @nat.lt_iff_le_not_le, decidable_lt := nat.decidable_lt, decidable_le := nat.decidable_le, decidable_eq := nat.decidable_eq } lemma eq_zero_of_le_zero {n : nat} (h : n ≤ 0) : n = 0 := le_antisymm h (zero_le _) lemma succ_lt_succ {a b : ℕ} : a < b → succ a < succ b := succ_le_succ lemma lt_of_succ_lt {a b : ℕ} : succ a < b → a < b := le_of_succ_le lemma lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b := le_of_succ_le_succ lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → n < m → pred n < pred m | 0 _ h₁ h := absurd rfl h₁ | _ 0 h₁ h := absurd h (not_lt_zero _) | (succ n) (succ m) _ h := lt_of_succ_lt_succ h lemma lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h lemma succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h lemma le_add_right : ∀ (n k : ℕ), n ≤ n + k | n 0 := nat.le_refl n | n (k+1) := le_succ_of_le (le_add_right n k) lemma le_add_left (n m : ℕ): n ≤ m + n := nat.add_comm n m ▸ le_add_right n m lemma le.dest : ∀ {n m : ℕ}, n ≤ m → ∃ k, n + k = m | n _ less_than_or_equal.refl := ⟨0, rfl⟩ | n _ (less_than_or_equal.step h) := match le.dest h with | ⟨w, hw⟩ := ⟨succ w, hw ▸ add_succ n w⟩ end lemma le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m := h ▸ le_add_right n k protected lemma add_le_add_left {n m : ℕ} (h : n ≤ m) (k : ℕ) : k + n ≤ k + m := match le.dest h with | ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc, hw] end end protected lemma add_le_add_right {n m : ℕ} (h : n ≤ m) (k : ℕ) : n + k ≤ m + k := begin rw [nat.add_comm n k, nat.add_comm m k], apply nat.add_le_add_left h end protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m := match le.dest h with | ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc] at hw, apply nat.add_left_cancel hw end end protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m := begin rw [nat.add_comm _ k, nat.add_comm _ k], apply nat.le_of_add_le_add_left end protected lemma add_le_add_iff_le_right (k n m : ℕ) : n + k ≤ m + k ↔ n ≤ m := ⟨ nat.le_of_add_le_add_right , assume h, nat.add_le_add_right h _ ⟩ protected theorem lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m := let h' := nat.le_of_lt h in nat.lt_of_le_and_ne (nat.le_of_add_le_add_left h') (λ heq, nat.lt_irrefl (k + m) begin rw heq at h, assumption end) protected lemma lt_of_add_lt_add_right {a b c : ℕ} (h : a + b < c + b) : a < c := nat.lt_of_add_lt_add_left $ show b + a < b + c, by rwa [nat.add_comm b a, nat.add_comm b c] protected lemma add_lt_add_left {n m : ℕ} (h : n < m) (k : ℕ) : k + n < k + m := lt_of_succ_le (add_succ k n ▸ nat.add_le_add_left (succ_le_of_lt h) k) protected lemma add_lt_add_right {n m : ℕ} (h : n < m) (k : ℕ) : n + k < m + k := nat.add_comm k m ▸ nat.add_comm k n ▸ nat.add_lt_add_left h k protected lemma lt_add_of_pos_right {n k : ℕ} (h : k > 0) : n < n + k := nat.add_lt_add_left h n protected lemma lt_add_of_pos_left {n k : ℕ} (h : k > 0) : n < k + n := by rw nat.add_comm; exact nat.lt_add_of_pos_right h protected lemma add_lt_add {a b c d : ℕ} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := lt_trans (nat.add_lt_add_right h₁ c) (nat.add_lt_add_left h₂ b) protected lemma add_le_add {a b c d : ℕ} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := le_trans (nat.add_le_add_right h₁ c) (nat.add_le_add_left h₂ b) protected lemma zero_lt_one : 0 < (1:nat) := zero_lt_succ 0 lemma mul_le_mul_left {n m : ℕ} (k : ℕ) (h : n ≤ m) : k * n ≤ k * m := match le.dest h with | ⟨l, hl⟩ := have k * n + k * l = k * m, by rw [← nat.left_distrib, hl], le.intro this end lemma mul_le_mul_right {n m : ℕ} (k : ℕ) (h : n ≤ m) : n * k ≤ m * k := nat.mul_comm k m ▸ nat.mul_comm k n ▸ mul_le_mul_left k h protected lemma mul_lt_mul_of_pos_left {n m k : ℕ} (h : n < m) (hk : k > 0) : k * n < k * m := nat.lt_of_lt_of_le (nat.lt_add_of_pos_right hk) (mul_succ k n ▸ nat.mul_le_mul_left k (succ_le_of_lt h)) protected lemma mul_lt_mul_of_pos_right {n m k : ℕ} (h : n < m) (hk : k > 0) : n * k < m * k := nat.mul_comm k m ▸ nat.mul_comm k n ▸ nat.mul_lt_mul_of_pos_left h hk protected lemma le_of_mul_le_mul_left {a b c : ℕ} (h : c * a ≤ c * b) (hc : c > 0) : a ≤ b := decidable.not_lt.1 (assume h1 : b < a, have h2 : c * b < c * a, from nat.mul_lt_mul_of_pos_left h1 hc, not_le_of_gt h2 h) lemma le_of_lt_succ {m n : nat} : m < succ n → m ≤ n := le_of_succ_le_succ theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k := le_antisymm (nat.le_of_mul_le_mul_left (le_of_eq H) Hn) (nat.le_of_mul_le_mul_left (le_of_eq H.symm) Hn) /- sub properties -/ @[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0 | 0 := rfl | (a+1) := congr_arg pred (zero_sub a) lemma sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le (sub_le a b) protected theorem sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k | 0 := h | (succ z) := pred_le_pred (sub_le_sub_right z) /- bit0/bit1 properties -/ protected lemma bit1_eq_succ_bit0 (n : ℕ) : bit1 n = succ (bit0 n) := rfl protected lemma bit1_succ_eq (n : ℕ) : bit1 (succ n) = succ (succ (bit1 n)) := eq.trans (nat.bit1_eq_succ_bit0 (succ n)) (congr_arg succ (nat.bit0_succ_eq n)) protected lemma bit1_ne_one : ∀ {n : ℕ}, n ≠ 0 → bit1 n ≠ 1 | 0 h h1 := absurd rfl h | (n+1) h h1 := nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero _)) protected lemma bit0_ne_one : ∀ n : ℕ, bit0 n ≠ 1 | 0 h := absurd h (ne.symm nat.one_ne_zero) | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h, nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero (n + n))) protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1 | 0 h := nat.no_confusion h | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h, nat.no_confusion h1 (λ h2, absurd h2 (nat.succ_ne_zero (n + n))) protected lemma bit1_ne_bit0 : ∀ (n m : ℕ), bit1 n ≠ bit0 m | 0 m h := absurd h (ne.symm (nat.add_self_ne_one m)) | (n+1) 0 h := have h1 : succ (bit0 (succ n)) = 0, from h, absurd h1 (nat.succ_ne_zero _) | (n+1) (m+1) h := have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)), from nat.bit0_succ_eq m ▸ nat.bit1_succ_eq n ▸ h, have h2 : bit1 n = bit0 m, from nat.no_confusion h1 (λ h2', nat.no_confusion h2' (λ h2'', h2'')), absurd h2 (bit1_ne_bit0 n m) protected lemma bit0_ne_bit1 : ∀ (n m : ℕ), bit0 n ≠ bit1 m := λ n m : nat, ne.symm (nat.bit1_ne_bit0 m n) protected lemma bit0_inj : ∀ {n m : ℕ}, bit0 n = bit0 m → n = m | 0 0 h := rfl | 0 (m+1) h := by contradiction | (n+1) 0 h := by contradiction | (n+1) (m+1) h := have succ (succ (n + n)) = succ (succ (m + m)), by { unfold bit0 at h, simp [add_one, add_succ, succ_add] at h, have aux : n + n = m + m := h, rw aux }, have n + n = m + m, by iterate { injection this with this }, have n = m, from bit0_inj this, by rw this protected lemma bit1_inj : ∀ {n m : ℕ}, bit1 n = bit1 m → n = m := λ n m h, have succ (bit0 n) = succ (bit0 m), begin simp [nat.bit1_eq_succ_bit0] at h, rw h end, have bit0 n = bit0 m, by injection this, nat.bit0_inj this protected lemma bit0_ne {n m : ℕ} : n ≠ m → bit0 n ≠ bit0 m := λ h₁ h₂, absurd (nat.bit0_inj h₂) h₁ protected lemma bit1_ne {n m : ℕ} : n ≠ m → bit1 n ≠ bit1 m := λ h₁ h₂, absurd (nat.bit1_inj h₂) h₁ protected lemma zero_ne_bit0 {n : ℕ} : n ≠ 0 → 0 ≠ bit0 n := λ h, ne.symm (nat.bit0_ne_zero h) protected lemma zero_ne_bit1 (n : ℕ) : 0 ≠ bit1 n := ne.symm (nat.bit1_ne_zero n) protected lemma one_ne_bit0 (n : ℕ) : 1 ≠ bit0 n := ne.symm (nat.bit0_ne_one n) protected lemma one_ne_bit1 {n : ℕ} : n ≠ 0 → 1 ≠ bit1 n := λ h, ne.symm (nat.bit1_ne_one h) protected lemma one_lt_bit1 : ∀ {n : nat}, n ≠ 0 → 1 < bit1 n | 0 h := by contradiction | (succ n) h := begin rw nat.bit1_succ_eq, apply succ_lt_succ, apply zero_lt_succ end protected lemma one_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 1 < bit0 n | 0 h := by contradiction | (succ n) h := begin rw nat.bit0_succ_eq, apply succ_lt_succ, apply zero_lt_succ end protected lemma bit0_lt {n m : nat} (h : n < m) : bit0 n < bit0 m := nat.add_lt_add h h protected lemma bit1_lt {n m : nat} (h : n < m) : bit1 n < bit1 m := succ_lt_succ (nat.add_lt_add h h) protected lemma bit0_lt_bit1 {n m : nat} (h : n ≤ m) : bit0 n < bit1 m := lt_succ_of_le (nat.add_le_add h h) protected lemma bit1_lt_bit0 : ∀ {n m : nat}, n < m → bit1 n < bit0 m | n 0 h := absurd h (not_lt_zero _) | n (succ m) h := have n ≤ m, from le_of_lt_succ h, have succ (n + n) ≤ succ (m + m), from succ_le_succ (nat.add_le_add this this), have succ (n + n) ≤ succ m + m, {rw succ_add, assumption}, show succ (n + n) < succ (succ m + m), from lt_succ_of_le this protected lemma one_le_bit1 (n : ℕ) : 1 ≤ bit1 n := show 1 ≤ succ (bit0 n), from succ_le_succ (zero_le (bit0 n)) protected lemma one_le_bit0 : ∀ (n : ℕ), n ≠ 0 → 1 ≤ bit0 n | 0 h := absurd rfl h | (n+1) h := suffices 1 ≤ succ (succ (bit0 n)), from eq.symm (nat.bit0_succ_eq n) ▸ this, succ_le_succ (zero_le (succ (bit0 n))) /- subtraction -/ @[simp] protected theorem sub_zero (n : ℕ) : n - 0 = n := rfl theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) := rfl theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m := succ_sub_succ_eq_sub n m protected theorem sub_self : ∀ (n : ℕ), n - n = 0 | 0 := by rw nat.sub_zero | (succ n) := by rw [succ_sub_succ, sub_self n] /- TODO(Leo): remove the following ematch annotations as soon as we have arithmetic theory in the smt_stactic -/ @[ematch_lhs] protected theorem add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m | n 0 m := by rw [nat.add_zero, nat.add_zero] | n (succ k) m := by rw [add_succ, add_succ, succ_sub_succ, add_sub_add_right n k m] @[ematch_lhs] protected theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m := by rw [nat.add_comm k n, nat.add_comm k m, nat.add_sub_add_right] @[ematch_lhs] protected theorem add_sub_cancel (n m : ℕ) : n + m - m = n := suffices n + m - (0 + m) = n, from by rwa [nat.zero_add] at this, by rw [nat.add_sub_add_right, nat.sub_zero] @[ematch_lhs] protected theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m := show n + m - (n + 0) = m, from by rw [nat.add_sub_add_left, nat.sub_zero] protected theorem sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k) | n m 0 := by rw [nat.add_zero, nat.sub_zero] | n m (succ k) := by rw [add_succ, nat.sub_succ, nat.sub_succ, sub_sub n m k] theorem le_of_le_of_sub_le_sub_right {n m k : ℕ} (h₀ : k ≤ m) (h₁ : n - k ≤ m - k) : n ≤ m := begin revert k m, induction n with n ; intros k m h₀ h₁, { apply zero_le }, { cases k with k, { apply h₁ }, cases m with m, { cases not_succ_le_zero _ h₀ }, { simp [succ_sub_succ] at h₁, apply succ_le_succ, apply n_ih _ h₁, apply le_of_succ_le_succ h₀ }, } end protected theorem sub_le_sub_right_iff (n m k : ℕ) (h : k ≤ m) : n - k ≤ m - k ↔ n ≤ m := ⟨ le_of_le_of_sub_le_sub_right h , assume h, nat.sub_le_sub_right h k ⟩ theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 := show (n + 0) - (n + m) = 0, from by rw [nat.add_sub_add_left, nat.zero_sub] theorem add_le_to_le_sub (x : ℕ) {y k : ℕ} (h : k ≤ y) : x + k ≤ y ↔ x ≤ y - k := by rw [← nat.add_sub_cancel x k, nat.sub_le_sub_right_iff _ _ _ h, nat.add_sub_cancel] lemma sub_lt_of_pos_le (a b : ℕ) (h₀ : 0 < a) (h₁ : a ≤ b) : b - a < b := begin apply sub_lt _ h₀, apply lt_of_lt_of_le h₀ h₁ end theorem sub_one (n : ℕ) : n - 1 = pred n := rfl theorem succ_sub_one (n : ℕ) : succ n - 1 = n := rfl theorem succ_pred_eq_of_pos : ∀ {n : ℕ}, n > 0 → succ (pred n) = n | 0 h := absurd h (lt_irrefl 0) | (succ k) h := rfl theorem sub_eq_zero_of_le {n m : ℕ} (h : n ≤ m) : n - m = 0 := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, sub_self_add]) protected theorem le_of_sub_eq_zero : ∀{n m : ℕ}, n - m = 0 → n ≤ m | n 0 H := begin rw [nat.sub_zero] at H, simp [H] end | 0 (m+1) H := zero_le _ | (n+1) (m+1) H := nat.add_le_add_right (le_of_sub_eq_zero begin simp [nat.add_sub_add_right] at H, exact H end) _ protected theorem sub_eq_zero_iff_le {n m : ℕ} : n - m = 0 ↔ n ≤ m := ⟨nat.le_of_sub_eq_zero, nat.sub_eq_zero_of_le⟩ theorem add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, nat.add_sub_cancel_left]) protected theorem sub_add_cancel {n m : ℕ} (h : n ≥ m) : n - m + m = n := by rw [nat.add_comm, add_sub_of_le h] protected theorem add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) := exists.elim (nat.le.dest h) (assume l, assume hl : k + l = m, by rw [← hl, nat.add_sub_cancel_left, nat.add_comm k, ← nat.add_assoc, nat.add_sub_cancel]) protected lemma sub_eq_iff_eq_add {a b c : ℕ} (ab : b ≤ a) : a - b = c ↔ a = c + b := ⟨assume c_eq, begin rw [c_eq.symm, nat.sub_add_cancel ab] end, assume a_eq, begin rw [a_eq, nat.add_sub_cancel] end⟩ protected lemma lt_of_sub_eq_succ {m n l : ℕ} (H : m - n = nat.succ l) : n < m := not_le.1 (assume (H' : n ≥ m), begin simp [nat.sub_eq_zero_of_le H'] at H, contradiction end) @[simp] lemma zero_min (a : ℕ) : min 0 a = 0 := min_eq_left (zero_le a) @[simp] lemma min_zero (a : ℕ) : min a 0 = 0 := min_eq_right (zero_le a) -- Distribute succ over min theorem min_succ_succ (x y : ℕ) : min (succ x) (succ y) = succ (min x y) := have f : x ≤ y → min (succ x) (succ y) = succ (min x y), from λp, calc min (succ x) (succ y) = succ x : if_pos (succ_le_succ p) ... = succ (min x y) : congr_arg succ (eq.symm (if_pos p)), have g : ¬ (x ≤ y) → min (succ x) (succ y) = succ (min x y), from λp, calc min (succ x) (succ y) = succ y : if_neg (λeq, p (pred_le_pred eq)) ... = succ (min x y) : congr_arg succ (eq.symm (if_neg p)), decidable.by_cases f g theorem sub_eq_sub_min (n m : ℕ) : n - m = n - min n m := if h : n ≥ m then by rewrite [min_eq_right h] else by rewrite [sub_eq_zero_of_le (le_of_not_ge h), min_eq_left (le_of_not_ge h), nat.sub_self] @[simp] theorem sub_add_min_cancel (n m : ℕ) : n - m + min n m = n := by rw [sub_eq_sub_min, nat.sub_add_cancel (min_le_left n m)] /- TODO(Leo): sub + inequalities -/ protected def strong_rec_on {p : nat → Sort u} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n := suffices ∀ n m, m < n → p m, from this (succ n) n (lt_succ_self _), begin intros n, induction n with n ih, {intros m h₁, exact absurd h₁ (not_lt_zero _)}, {intros m h₁, apply or.by_cases (decidable.lt_or_eq_of_le (le_of_lt_succ h₁)), {intros, apply ih, assumption}, {intros, subst m, apply h _ ih}} end protected lemma strong_induction_on {p : nat → Prop} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n := nat.strong_rec_on n h protected lemma case_strong_induction_on {p : nat → Prop} (a : nat) (hz : p 0) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a := nat.strong_induction_on a $ λ n, match n with | 0 := λ _, hz | (n+1) := λ h₁, hi n (λ m h₂, h₁ _ (lt_succ_of_le h₂)) end /- mod -/ lemma mod_def (x y : nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x := by have h := mod_def_aux x y; rwa [dif_eq_if] at h @[simp] lemma mod_zero (a : nat) : a % 0 = a := begin rw mod_def, have h : ¬ (0 < 0 ∧ 0 ≤ a), simp [lt_irrefl], simp [if_neg, h] end lemma mod_eq_of_lt {a b : nat} (h : a < b) : a % b = a := begin rw mod_def, have h' : ¬(0 < b ∧ b ≤ a), simp [not_le_of_gt h], simp [if_neg, h'] end @[simp] lemma zero_mod (b : nat) : 0 % b = 0 := begin rw mod_def, have h : ¬(0 < b ∧ b ≤ 0), {intro hn, cases hn with l r, exact absurd (lt_of_lt_of_le l r) (lt_irrefl 0)}, simp [if_neg, h] end lemma mod_eq_sub_mod {a b : nat} (h : a ≥ b) : a % b = (a - b) % b := or.elim (eq_zero_or_pos b) (λb0, by rw [b0, nat.sub_zero]) (λh₂, by rw [mod_def, if_pos (and.intro h₂ h)]) lemma mod_lt (x : nat) {y : nat} (h : y > 0) : x % y < y := begin induction x using nat.case_strong_induction_on with x ih, { rw zero_mod, assumption }, { by_cases h₁ : succ x < y, { rwa [mod_eq_of_lt h₁] }, { have h₁ : succ x % y = (succ x - y) % y := mod_eq_sub_mod (decidable.not_lt.1 h₁), have : succ x - y ≤ x := le_of_lt_succ (sub_lt (succ_pos x) h), have h₂ : (succ x - y) % y < y := ih _ this, rwa [← h₁] at h₂ } } end @[simp] theorem mod_self (n : nat) : n % n = 0 := by rw [mod_eq_sub_mod (le_refl _), nat.sub_self, zero_mod] @[simp] lemma mod_one (n : ℕ) : n % 1 = 0 := have n % 1 < 1, from (mod_lt n) (succ_pos 0), eq_zero_of_le_zero (le_of_lt_succ this) lemma mod_two_eq_zero_or_one (n : ℕ) : n % 2 = 0 ∨ n % 2 = 1 := match n % 2, @nat.mod_lt n 2 dec_trivial with | 0, _ := or.inl rfl | 1, _ := or.inr rfl | k+2, h := absurd h dec_trivial end /- div & mod -/ lemma div_def (x y : nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := by have h := div_def_aux x y; rwa dif_eq_if at h lemma mod_add_div (m k : ℕ) : m % k + k * (m / k) = m := begin apply nat.strong_induction_on m, clear m, intros m IH, cases decidable.em (0 < k ∧ k ≤ m) with h h', -- 0 < k ∧ k ≤ m { have h' : m - k < m, { apply nat.sub_lt _ h.left, apply lt_of_lt_of_le h.left h.right }, rw [div_def, mod_def, if_pos h, if_pos h], simp [nat.left_distrib, IH _ h', nat.add_comm, nat.add_left_comm], rw [nat.add_comm, ← nat.add_sub_assoc h.right, nat.mul_one, nat.add_sub_cancel_left] }, -- ¬ (0 < k ∧ k ≤ m) { rw [div_def, mod_def, if_neg h', if_neg h', nat.mul_zero, nat.add_zero] }, end /- div -/ @[simp] protected lemma div_one (n : ℕ) : n / 1 = n := have n % 1 + 1 * (n / 1) = n, from mod_add_div _ _, by { rwa [mod_one, nat.zero_add, nat.one_mul] at this } @[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 := begin rw [div_def], simp [lt_irrefl] end @[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 := eq.trans (div_def 0 b) $ if_neg (and.rec not_le_of_gt) protected lemma div_le_of_le_mul {m n : ℕ} : ∀ {k}, m ≤ k * n → m / k ≤ n | 0 h := by simp [nat.div_zero]; apply zero_le | (succ k) h := suffices succ k * (m / succ k) ≤ succ k * n, from nat.le_of_mul_le_mul_left this (zero_lt_succ _), calc succ k * (m / succ k) ≤ m % succ k + succ k * (m / succ k) : le_add_left _ _ ... = m : by rw mod_add_div ... ≤ succ k * n : h protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m | m 0 := by simp [nat.div_zero]; apply zero_le | m (succ n) := have m ≤ succ n * m, from calc m = 1 * m : by rw nat.one_mul ... ≤ succ n * m : mul_le_mul_right _ (succ_le_succ (zero_le _)), nat.div_le_of_le_mul this lemma div_eq_sub_div {a b : nat} (h₁ : b > 0) (h₂ : a ≥ b) : a / b = (a - b) / b + 1 := begin rw [div_def a, if_pos], split ; assumption end lemma div_eq_of_lt {a b : ℕ} (h₀ : a < b) : a / b = 0 := begin rw [div_def a, if_neg], intro h₁, apply not_le_of_gt h₀ h₁.right end -- this is a Galois connection -- f x ≤ y ↔ x ≤ g y -- with -- f x = x * k -- g y = y / k theorem le_div_iff_mul_le (x y : ℕ) {k : ℕ} (Hk : k > 0) : x ≤ y / k ↔ x * k ≤ y := begin -- Hk is needed because, despite div being made total, y / 0 := 0 -- x * 0 ≤ y ↔ x ≤ y / 0 -- ↔ 0 ≤ y ↔ x ≤ 0 -- ↔ true ↔ x = 0 -- ↔ x = 0 revert x, apply nat.strong_induction_on y _, clear y, intros y IH x, cases decidable.lt_or_le y k with h h, -- base case: y < k { rw [div_eq_of_lt h], cases x with x, { simp [nat.zero_mul, zero_le] }, { simp [succ_mul, not_succ_le_zero, nat.add_comm], apply lt_of_lt_of_le h, apply le_add_right } }, -- step: k ≤ y { rw [div_eq_sub_div Hk h], cases x with x, { simp [nat.zero_mul, zero_le] }, { have Hlt : y - k < y, { apply sub_lt_of_pos_le ; assumption }, rw [ ← add_one , nat.add_le_add_iff_le_right , IH (y - k) Hlt x , add_one , succ_mul, add_le_to_le_sub _ h ] } } end theorem div_lt_iff_lt_mul (x y : ℕ) {k : ℕ} (Hk : k > 0) : x / k < y ↔ x < y * k := begin simp [← not_le], apply not_iff_not_of_iff, apply le_div_iff_mul_le _ _ Hk end def iterate {α : Sort u} (op : α → α) : ℕ → α → α | 0 a := a | (succ k) a := iterate k (op a) notation f`^[`n`]` := iterate f n /- successor and predecessor -/ theorem add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _ theorem eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) := by cases n; simp theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : ∃k : ℕ, n = succ k := ⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩ theorem discriminate {B : Sort u} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B := by induction h : n; [exact H1 h, exact H2 _ h] theorem one_succ_zero : 1 = succ 0 := rfl theorem two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1) (H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : Π (a : ℕ), P a | 0 := H1 | 1 := H2 | (succ (succ n)) := H3 _ (two_step_induction _) (two_step_induction _) theorem sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m) (H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : Π (n m : ℕ), P n m | 0 m := H1 _ | (succ n) 0 := H2 _ | (succ n) (succ m) := H3 _ _ (sub_induction n m) /- addition -/ theorem succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m := by simp [succ_add, add_succ] -- theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] protected theorem add_right_comm : ∀ (n m k : ℕ), n + m + k = n + k + m := right_comm nat.add nat.add_comm nat.add_assoc theorem eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 := ⟨nat.eq_zero_of_add_eq_zero_right H, nat.eq_zero_of_add_eq_zero_left H⟩ theorem eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0 | 0 m := λ h, or.inl rfl | (succ n) m := begin rw succ_mul, intro h, exact or.inr (eq_zero_of_add_eq_zero_left h) end /- properties of inequality -/ theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m := nat.cases_on n less_than_or_equal.step (λ a, succ_le_succ) theorem le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : false := nat.lt_irrefl n (nat.lt_of_le_of_lt h₁ h₂) theorem lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : false := le_lt_antisymm h₂ h₁ protected theorem lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n := le_lt_antisymm (nat.le_of_lt h₁) protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a ≥ b → C) : C := decidable.by_cases h₁ (λ h, h₂ (or.elim (nat.lt_or_ge a b) (λ a, absurd a h) (λ a, a))) protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C) (h₃ : b < a → C) : C := nat.lt_ge_by_cases h₁ (λ h₁, nat.lt_ge_by_cases h₃ (λ h, h₂ (nat.le_antisymm h h₁))) protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a := nat.lt_by_cases (λ h, or.inl h) (λ h, or.inr (or.inl h)) (λ h, or.inr (or.inr h)) protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a := (nat.lt_trichotomy a b).resolve_left hnlt theorem lt_succ_of_lt {a b : nat} (h : a < b) : a < succ b := le_succ_of_le h def one_pos := nat.zero_lt_one /- subtraction -/ protected theorem sub_le_sub_left {n m : ℕ} (k) (h : n ≤ m) : k - m ≤ k - n := by induction h; [refl, exact le_trans (pred_le _) h_ih] theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k := by rw [nat.sub_sub, nat.sub_sub, add_succ, succ_sub_succ] protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n := by rw [nat.sub_sub, nat.sub_sub, nat.add_comm] theorem mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m | 0 m := by simp [nat.zero_sub, pred_zero, nat.zero_mul] | (succ n) m := by rw [pred_succ, succ_mul, nat.add_sub_cancel] theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n := by rw [nat.mul_comm, mul_pred_left, nat.mul_comm] protected theorem mul_sub_right_distrib : ∀ (n m k : ℕ), (n - m) * k = n * k - m * k | n 0 k := by simp [nat.sub_zero, nat.zero_mul] | n (succ m) k := by rw [nat.sub_succ, mul_pred_left, mul_sub_right_distrib, succ_mul, nat.sub_sub] protected theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k := by rw [nat.mul_comm, nat.mul_sub_right_distrib, nat.mul_comm m n, nat.mul_comm n k] protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) := by rw [nat.mul_sub_left_distrib, nat.right_distrib, nat.right_distrib, nat.mul_comm b a, nat.add_comm (a*a) (a*b), nat.add_sub_add_left] theorem succ_mul_succ_eq (a b : nat) : succ a * succ b = a*b + a + b + 1 := begin rw [← add_one, ← add_one], simp [nat.right_distrib, nat.left_distrib, nat.add_left_comm, nat.mul_one, nat.one_mul, nat.add_assoc], end theorem succ_sub {m n : ℕ} (h : m ≥ n) : succ m - n = succ (m - n) := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, nat.add_sub_cancel_left, ← add_succ, nat.add_sub_cancel_left]) protected theorem sub_pos_of_lt {m n : ℕ} (h : m < n) : n - m > 0 := have 0 + m < n - m + m, begin rw [nat.zero_add, nat.sub_add_cancel (le_of_lt h)], exact h end, nat.lt_of_add_lt_add_right this protected theorem sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m := (nat.sub_eq_iff_eq_add (nat.sub_le _ _)).2 (eq.symm (add_sub_of_le h)) protected theorem sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m := (nat.sub_eq_iff_eq_add (nat.le_trans h (nat.le_add_right _ _))).2 (by rwa [nat.add_right_comm, nat.sub_add_cancel]) theorem sub_one_sub_lt {n i} (h : i < n) : n - 1 - i < n := begin rw nat.sub_sub, apply nat.sub_lt, apply lt_of_lt_of_le (nat.zero_lt_succ _) h, rw nat.add_comm, apply nat.zero_lt_succ end theorem pred_inj : ∀ {a b : nat}, a > 0 → b > 0 → nat.pred a = nat.pred b → a = b | (succ a) (succ b) ha hb h := have a = b, from h, by rw this | (succ a) 0 ha hb h := absurd hb (lt_irrefl _) | 0 (succ b) ha hb h := absurd ha (lt_irrefl _) | 0 0 ha hb h := rfl /- find -/ section find parameter {p : ℕ → Prop} private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ¬p k parameters [decidable_pred p] (H : ∃n, p n) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in suffices ∀m k, n ≤ k + m → acc lbp k, from λa, this _ _ (nat.le_add_left _ _), λm, nat.rec_on m (λk kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := absurd pn (a _ kn) end⟩) (λm IH k kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := IH _ (by rw nat.add_right_comm; exact kn) end⟩)⟩ protected def find_x : {n // p n ∧ ∀m < n, ¬p m} := @well_founded.fix _ (λk, (∀n < k, ¬p n) → {n // p n ∧ ∀m < n, ¬p m}) lbp wf_lbp (λm IH al, if pm : p m then ⟨m, pm, al⟩ else have ∀ n ≤ m, ¬p n, from λn h, or.elim (decidable.lt_or_eq_of_le h) (al n) (λe, by rw e; exact pm), IH _ ⟨rfl, this⟩ (λn h, this n $ nat.le_of_succ_le_succ h)) 0 (λn h, absurd h (nat.not_lt_zero _)) protected def find : ℕ := nat.find_x.1 protected theorem find_spec : p nat.find := nat.find_x.2.left protected theorem find_min : ∀ {m : ℕ}, m < nat.find → ¬p m := nat.find_x.2.right protected theorem find_min' {m : ℕ} (h : p m) : nat.find ≤ m := decidable.le_of_not_lt (λ l, find_min l h) end find /- mod -/ theorem mod_le (x y : ℕ) : x % y ≤ x := or.elim (decidable.lt_or_le x y) (λxlty, by rw mod_eq_of_lt xlty; refl) (λylex, or.elim (eq_zero_or_pos y) (λy0, by rw [y0, mod_zero]; refl) (λypos, le_trans (le_of_lt (mod_lt _ ypos)) ylex)) @[simp] theorem add_mod_right (x z : ℕ) : (x + z) % z = x % z := by rw [mod_eq_sub_mod (nat.le_add_left _ _), nat.add_sub_cancel] @[simp] theorem add_mod_left (x z : ℕ) : (x + z) % x = z % x := by rw [nat.add_comm, add_mod_right] @[simp] theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y := by {induction z with z ih, rw [nat.mul_zero, nat.add_zero], rw [mul_succ, ← nat.add_assoc, add_mod_right, ih]} @[simp] theorem add_mul_mod_self_right (x y z : ℕ) : (x + y * z) % z = x % z := by rw [nat.mul_comm, add_mul_mod_self_left] @[simp] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 := by rw [← nat.zero_add (m*n), add_mul_mod_self_left, zero_mod] @[simp] theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 := by rw [nat.mul_comm, mul_mod_right] theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) := if y0 : y = 0 then by rw [y0, nat.mul_zero, mod_zero, mod_zero] else if z0 : z = 0 then by rw [z0, nat.zero_mul, nat.zero_mul, nat.zero_mul, mod_zero] else x.strong_induction_on $ λn IH, have y0 : y > 0, from nat.pos_of_ne_zero y0, have z0 : z > 0, from nat.pos_of_ne_zero z0, or.elim (decidable.le_or_lt y n) (λyn, by rw [ mod_eq_sub_mod yn, mod_eq_sub_mod (mul_le_mul_left z yn), ← nat.mul_sub_left_distrib]; exact IH _ (sub_lt (lt_of_lt_of_le y0 yn) y0)) (λyn, by rw [mod_eq_of_lt yn, mod_eq_of_lt (nat.mul_lt_mul_of_pos_left yn z0)]) theorem mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z := by rw [nat.mul_comm x z, nat.mul_comm y z, nat.mul_comm (x % y) z]; apply mul_mod_mul_left theorem cond_to_bool_mod_two (x : ℕ) [d : decidable (x % 2 = 1)] : cond (@to_bool (x % 2 = 1) d) 1 0 = x % 2 := begin by_cases h : x % 2 = 1, { simp! [*] }, { cases mod_two_eq_zero_or_one x; simp! [*, nat.zero_ne_one] } end theorem sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n := begin induction k with k, { rw [nat.mul_zero, nat.sub_zero] }, { have h₂ : n * k ≤ x, { rw [mul_succ] at h₁, apply nat.le_trans _ h₁, apply le_add_right _ n }, have h₄ : x - n * k ≥ n, { apply @nat.le_of_add_le_add_right (n*k), rw [nat.sub_add_cancel h₂], simp [mul_succ, nat.add_comm] at h₁, simp [h₁] }, rw [mul_succ, ← nat.sub_sub, ← mod_eq_sub_mod h₄, k_ih h₂] } end /- div -/ theorem sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p := begin cases eq_zero_or_pos n with h₀ h₀, { rw [h₀, nat.div_zero, nat.div_zero, nat.zero_sub] }, { induction p with p, { rw [nat.mul_zero, nat.sub_zero, nat.sub_zero] }, { have h₂ : n*p ≤ x, { transitivity, { apply nat.mul_le_mul_left, apply le_succ }, { apply h₁ } }, have h₃ : x - n * p ≥ n, { apply nat.le_of_add_le_add_right, rw [nat.sub_add_cancel h₂, nat.add_comm], rw [mul_succ] at h₁, apply h₁ }, rw [sub_succ, ← p_ih h₂], rw [@div_eq_sub_div (x - n*p) _ h₀ h₃], simp [add_one, pred_succ, mul_succ, nat.sub_sub] } } end theorem div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m | m 0 := by simp; apply zero_le | m (succ n) := (le_div_iff_mul_le _ _ (nat.succ_pos _)).1 (le_refl _) @[simp] theorem add_div_right (x : ℕ) {z : ℕ} (H : z > 0) : (x + z) / z = succ (x / z) := by rw [div_eq_sub_div H (nat.le_add_left _ _), nat.add_sub_cancel] @[simp] theorem add_div_left (x : ℕ) {z : ℕ} (H : z > 0) : (z + x) / z = succ (x / z) := by rw [nat.add_comm, add_div_right x H] @[simp] theorem mul_div_right (n : ℕ) {m : ℕ} (H : m > 0) : m * n / m = n := by {induction n; simp [*, mul_succ, nat.mul_zero] } @[simp] theorem mul_div_left (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m := by rw [nat.mul_comm, mul_div_right _ H] protected theorem div_self {n : ℕ} (H : n > 0) : n / n = 1 := let t := add_div_right 0 H in by rwa [nat.zero_add, nat.zero_div] at t theorem add_mul_div_left (x z : ℕ) {y : ℕ} (H : y > 0) : (x + y * z) / y = x / y + z := begin induction z with z ih, { rw [nat.mul_zero, nat.add_zero, nat.add_zero] }, { rw [mul_succ, ← nat.add_assoc, add_div_right _ H, ih] } end theorem add_mul_div_right (x y : ℕ) {z : ℕ} (H : z > 0) : (x + y * z) / z = x / z + y := by rw [nat.mul_comm, add_mul_div_left _ _ H] protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m := let t := add_mul_div_right 0 m H in by rwa [nat.zero_add, nat.zero_div, nat.zero_add] at t protected theorem mul_div_cancel_left (m : ℕ) {n : ℕ} (H : n > 0) : n * m / n = m := by rw [nat.mul_comm, nat.mul_div_cancel _ H] protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : n > 0) (H2 : m = k * n) : m / n = k := by rw [H2, nat.mul_div_cancel _ H1] protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : n > 0) (H2 : m = n * k) : m / n = k := by rw [H2, nat.mul_div_cancel_left _ H1] protected theorem div_eq_of_lt_le {m n k : ℕ} (lo : k * n ≤ m) (hi : m < succ k * n) : m / n = k := have npos : n > 0, from (eq_zero_or_pos _).resolve_left $ λ hn, by rw [hn, nat.mul_zero] at hi lo; exact absurd lo (not_le_of_gt hi), le_antisymm (le_of_lt_succ ((nat.div_lt_iff_lt_mul _ _ npos).2 hi)) ((nat.le_div_iff_mul_le _ _ npos).2 lo) theorem mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) := begin have npos : n > 0 := (eq_zero_or_pos _).resolve_left (λ n0, by rw [n0, nat.zero_mul] at h₁; exact not_lt_zero _ h₁), apply nat.div_eq_of_lt_le, { rw [nat.mul_sub_right_distrib, nat.mul_comm], apply nat.sub_le_sub_left, exact (div_lt_iff_lt_mul _ _ npos).1 (lt_succ_self _) }, { change succ (pred (n * p - x)) ≤ (succ (pred (p - x / n))) * n, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁), succ_pred_eq_of_pos (nat.sub_pos_of_lt _)], { rw [nat.mul_sub_right_distrib, nat.mul_comm], apply nat.sub_le_sub_left, apply div_mul_le_self }, { apply (div_lt_iff_lt_mul _ _ npos).2, rwa nat.mul_comm } } end protected lemma mul_pos {a b : ℕ} (ha : a > 0) (hb : b > 0) : a * b > 0 := have h : 0 * b < a * b, from nat.mul_lt_mul_of_pos_right ha hb, by rwa nat.zero_mul at h protected theorem div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) := begin cases eq_zero_or_pos k with k0 kpos, {rw [k0, nat.mul_zero, nat.div_zero, nat.div_zero]}, cases eq_zero_or_pos n with n0 npos, {rw [n0, nat.zero_mul, nat.div_zero, nat.zero_div]}, apply le_antisymm, { apply (le_div_iff_mul_le _ _ (nat.mul_pos npos kpos)).2, rw [nat.mul_comm n k, ← nat.mul_assoc], apply (le_div_iff_mul_le _ _ npos).1, apply (le_div_iff_mul_le _ _ kpos).1, refl }, { apply (le_div_iff_mul_le _ _ kpos).2, apply (le_div_iff_mul_le _ _ npos).2, rw [nat.mul_assoc, nat.mul_comm n k], apply (le_div_iff_mul_le _ _ (nat.mul_pos kpos npos)).1, refl } end protected theorem mul_div_mul {m : ℕ} (n k : ℕ) (H : m > 0) : m * n / (m * k) = n / k := by rw [← nat.div_div_eq_div_mul, nat.mul_div_cancel_left _ H] /- dvd -/ @[simp] protected theorem dvd_mul_right (a b : ℕ) : a ∣ a * b := ⟨b, rfl⟩ protected theorem dvd_trans {a b c : ℕ} (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c := match h₁, h₂ with | ⟨d, (h₃ : b = a * d)⟩, ⟨e, (h₄ : c = b * e)⟩ := ⟨d * e, show c = a * (d * e), by simp [h₃, h₄, nat.mul_assoc]⟩ end protected theorem eq_zero_of_zero_dvd {a : ℕ} (h : 0 ∣ a) : a = 0 := exists.elim h (assume c, assume H' : a = 0 * c, eq.trans H' (nat.zero_mul c)) protected theorem dvd_add {a b c : ℕ} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := exists.elim h₁ (λ d hd, exists.elim h₂ (λ e he, ⟨d + e, by simp [nat.left_distrib, hd, he]⟩)) protected theorem dvd_add_iff_right {k m n : ℕ} (h : k ∣ m) : k ∣ n ↔ k ∣ m + n := ⟨nat.dvd_add h, exists.elim h $ λd hd, match m, hd with | ._, rfl := λh₂, exists.elim h₂ $ λe he, ⟨e - d, by rw [nat.mul_sub_left_distrib, ← he, nat.add_sub_cancel_left]⟩ end⟩ protected theorem dvd_add_iff_left {k m n : ℕ} (h : k ∣ n) : k ∣ m ↔ k ∣ m + n := by rw nat.add_comm; exact nat.dvd_add_iff_right h theorem dvd_sub {k m n : ℕ} (H : n ≤ m) (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n := (nat.dvd_add_iff_left h₂).2 $ by rw nat.sub_add_cancel H; exact h₁ theorem dvd_mod_iff {k m n : ℕ} (h : k ∣ n) : k ∣ m % n ↔ k ∣ m := let t := @nat.dvd_add_iff_left _ (m % n) _ (nat.dvd_trans h (nat.dvd_mul_right n (m / n))) in by rwa mod_add_div at t theorem le_of_dvd {m n : ℕ} (h : n > 0) : m ∣ n → m ≤ n := λ⟨k, e⟩, by { revert h, rw e, refine k.cases_on _ _, exact λhn, absurd hn (lt_irrefl _), exact λk _, let t := mul_le_mul_left m (succ_pos k) in by rwa nat.mul_one at t } theorem dvd_antisymm : Π {m n : ℕ}, m ∣ n → n ∣ m → m = n | m 0 h₁ h₂ := nat.eq_zero_of_zero_dvd h₂ | 0 n h₁ h₂ := (nat.eq_zero_of_zero_dvd h₁).symm | (succ m) (succ n) h₁ h₂ := le_antisymm (le_of_dvd (succ_pos _) h₁) (le_of_dvd (succ_pos _) h₂) theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : n > 0) : m > 0 := nat.pos_of_ne_zero $ λm0, by rw m0 at H1; rw nat.eq_zero_of_zero_dvd H1 at H2; exact lt_irrefl _ H2 theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 := le_antisymm (le_of_dvd dec_trivial H) (pos_of_dvd_of_pos H dec_trivial) theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n := ⟨n / m, by { have t := (mod_add_div n m).symm, rwa [H, nat.zero_add] at t }⟩ theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 := exists.elim H (λ z H1, by rw [H1, mul_mod_right]) theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n % m = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ instance decidable_dvd : @decidable_rel ℕ (∣) := λm n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m := let t := mod_add_div m n in by rwa [mod_eq_zero_of_dvd H, nat.zero_add] at t protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m := by rw [nat.mul_comm, nat.mul_div_cancel' H] protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) := or.elim (eq_zero_or_pos k) (λh, by rw [h, nat.div_zero, nat.div_zero, nat.mul_zero]) (λh, have m * n / k = m * (n / k * k) / k, by rw nat.div_mul_cancel H, by rw[this, ← nat.mul_assoc, nat.mul_div_cancel _ h]) theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : k > 0) (H : k * m ∣ k * n) : m ∣ n := exists.elim H (λl H1, by rw nat.mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left kpos H1⟩) theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : k > 0) (H : m * k ∣ n * k) : m ∣ n := by rw [nat.mul_comm m k, nat.mul_comm n k] at H; exact dvd_of_mul_dvd_mul_left kpos H /- --- -/ protected lemma mul_le_mul_of_nonneg_left {a b c : ℕ} (h₁ : a ≤ b) : c * a ≤ c * b := begin by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] }, by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 (zero_le c), nat.zero_mul] }, exact (le_not_le_of_lt (nat.mul_lt_mul_of_pos_left (lt_of_le_not_le h₁ hba) (lt_of_le_not_le (zero_le c) hc0))).left, end protected lemma mul_le_mul_of_nonneg_right {a b c : ℕ} (h₁ : a ≤ b) : a * c ≤ b * c := begin by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] }, by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 (zero_le c), nat.mul_zero] }, exact (le_not_le_of_lt (nat.mul_lt_mul_of_pos_right (lt_of_le_not_le h₁ hba) (lt_of_le_not_le (zero_le c) hc0))).left, end protected lemma mul_lt_mul {a b c d : ℕ} (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) : a * b < c * d := calc a * b < c * b : nat.mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd protected lemma mul_lt_mul' {a b c d : ℕ} (h1 : a ≤ c) (h2 : b < d) (h3 : 0 < c) : a * b < c * d := calc a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right h1 ... < c * d : nat.mul_lt_mul_of_pos_left h2 h3 -- TODO: there are four variations, depending on which variables we assume to be nonneg protected lemma mul_le_mul {a b c d : ℕ} (hac : a ≤ c) (hbd : b ≤ d) : a * b ≤ c * d := calc a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right hac ... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd lemma div_lt_self {n m : nat} : n > 0 → m > 1 → n / m < n := begin intros h₁ h₂, have m_pos : m > 0, { apply lt_trans _ h₂, comp_val }, suffices : 1 * n < m * n, { rw [nat.one_mul, nat.mul_comm] at this, exact iff.mpr (nat.div_lt_iff_lt_mul n n m_pos) this }, exact nat.mul_lt_mul h₂ (le_refl _) h₁ end end nat
3256bb1ea432a7e7ffbb86de5a9e8e0818c21758
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/hit/set_quotient.hlean
9f1cdf570ae20e7cd8f87c2284276689bf906f4b
[ "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
5,763
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of set-quotients, i.e. quotient of a mere relation which is then set-truncated. -/ import function algebra.relation types.trunc types.eq hit.quotient open eq is_trunc trunc quotient equiv namespace set_quotient section parameters {A : Type} (R : A → A → Prop) -- set-quotients are just set-truncations of (type) quotients definition set_quotient : Type := trunc 0 (quotient R) parameter {R} definition class_of (a : A) : set_quotient := tr (class_of _ a) definition eq_of_rel {a a' : A} (H : R a a') : class_of a = class_of a' := ap tr (eq_of_rel _ H) theorem is_set_set_quotient [instance] : is_set set_quotient := begin unfold set_quotient, exact _ end protected definition rec {P : set_quotient → Type} [Pt : Πaa, is_set (P aa)] (Pc : Π(a : A), P (class_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel H] Pc a') (x : set_quotient) : P x := begin apply (@trunc.rec_on _ _ P x), { intro x', apply Pt}, { intro y, induction y, { apply Pc}, { exact pathover_of_pathover_ap P tr (Pp H)}} end protected definition rec_on [reducible] {P : set_quotient → Type} (x : set_quotient) [Pt : Πaa, is_set (P aa)] (Pc : Π(a : A), P (class_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel H] Pc a') : P x := rec Pc Pp x theorem rec_eq_of_rel {P : set_quotient → Type} [Pt : Πaa, is_set (P aa)] (Pc : Π(a : A), P (class_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel H] Pc a') {a a' : A} (H : R a a') : apd (rec Pc Pp) (eq_of_rel H) = Pp H := !is_set.elimo protected definition elim {P : Type} [Pt : is_set P] (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') (x : set_quotient) : P := rec Pc (λa a' H, pathover_of_eq _ (Pp H)) x protected definition elim_on [reducible] {P : Type} (x : set_quotient) [Pt : is_set P] (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') : P := elim Pc Pp x theorem elim_eq_of_rel {P : Type} [Pt : is_set P] (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') {a a' : A} (H : R a a') : ap (elim Pc Pp) (eq_of_rel H) = Pp H := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (eq_of_rel H)), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim,rec_eq_of_rel], end protected definition rec_prop {P : set_quotient → Type} [Pt : Πaa, is_prop (P aa)] (Pc : Π(a : A), P (class_of a)) (x : set_quotient) : P x := rec Pc (λa a' H, !is_prop.elimo) x protected definition elim_prop {P : Type} [Pt : is_prop P] (Pc : A → P) (x : set_quotient) : P := elim Pc (λa a' H, !is_prop.elim) x end end set_quotient attribute set_quotient.class_of [constructor] attribute set_quotient.rec set_quotient.elim [unfold 7] [recursor 7] attribute set_quotient.rec_on set_quotient.elim_on [unfold 4] open sigma relation function namespace set_quotient variables {A B C : Type} (R : A → A → Prop) (S : B → B → Prop) (T : C → C → Prop) definition is_surjective_class_of : is_surjective (class_of : A → set_quotient R) := λx, set_quotient.rec_on x (λa, tr (fiber.mk a idp)) (λa a' r, !is_prop.elimo) /- non-dependent universal property -/ definition set_quotient_arrow_equiv (B : Type) [H : is_set B] : (set_quotient R → B) ≃ (Σ(f : A → B), Π(a a' : A), R a a' → f a = f a') := begin fapply equiv.MK, { intro f, exact ⟨λa, f (class_of a), λa a' r, ap f (eq_of_rel r)⟩}, { intro v x, induction v with f p, exact set_quotient.elim_on x f p}, { intro v, induction v with f p, esimp, apply ap (sigma.mk f), apply eq_of_homotopy3, intro a a' r, apply elim_eq_of_rel}, { intro f, apply eq_of_homotopy, intro x, refine set_quotient.rec_on x _ _: esimp, intro a, reflexivity, intro a a' r, apply eq_pathover, apply hdeg_square, apply elim_eq_of_rel} end protected definition code [unfold 4] (a : A) (x : set_quotient R) [H : is_equivalence R] : Prop := set_quotient.elim_on x (R a) begin intros a' a'' H1, refine to_inv !trunctype_eq_equiv _, esimp, apply ua, apply equiv_of_is_prop, { intro H2, exact is_transitive.trans R H2 H1}, { intro H2, apply is_transitive.trans R H2, exact is_symmetric.symm R H1} end protected definition encode {a : A} {x : set_quotient R} (p : class_of a = x) [H : is_equivalence R] : set_quotient.code R a x := begin induction p, esimp, apply is_reflexive.refl R end definition rel_of_eq {a a' : A} (p : class_of a = class_of a' :> set_quotient R) [H : is_equivalence R] : R a a' := set_quotient.encode R p variables {R S T} definition quotient_unary_map [unfold 7] (f : A → B) (H : Π{a a'} (r : R a a'), S (f a) (f a')) : set_quotient R → set_quotient S := set_quotient.elim (class_of ∘ f) (λa a' r, eq_of_rel (H r)) definition quotient_binary_map [unfold 11 12] (f : A → B → C) (H : Π{a a'} (r : R a a') {b b'} (s : S b b'), T (f a b) (f a' b')) [HR : is_reflexive R] [HS : is_reflexive S] : set_quotient R → set_quotient S → set_quotient T := begin refine set_quotient.elim _ _, { intro a, refine set_quotient.elim _ _, { intro b, exact class_of (f a b)}, { intro b b' s, apply eq_of_rel, apply H, apply is_reflexive.refl R, exact s}}, { intro a a' r, apply eq_of_homotopy, refine set_quotient.rec _ _, { intro b, esimp, apply eq_of_rel, apply H, exact r, apply is_reflexive.refl S}, { intro b b' s, apply eq_pathover, esimp, apply is_set.elims}} end end set_quotient
ae9aadb6389bde51db3ac0c162b16b508fae71d0
c777c32c8e484e195053731103c5e52af26a25d1
/counterexamples/pseudoelement.lean
5a28cf838eabb86307b074127dd0a18b35e6782f
[ "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
5,366
lean
/- Copyright (c) 2022 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import category_theory.abelian.pseudoelements import algebra.category.Module.biproducts /-! # Pseudoelements and pullbacks Borceux claims in Proposition 1.9.5 that the pseudoelement constructed in `category_theory.abelian.pseudoelement.pseudo_pullback` is unique. We show here that this claim is false. This means in particular that we cannot have an extensionality principle for pullbacks in terms of pseudoelements. ## Implementation details The construction, suggested in https://mathoverflow.net/a/419951/7845, is the following. We work in the category of `Module ℤ` and we consider the special case of `ℚ ⊞ ℚ` (that is the pullback over the terminal object). We consider the pseudoelements associated to `x : ℚ ⟶ ℚ ⊞ ℚ` given by `t ↦ (t, 2 * t)` and `y : ℚ ⟶ ℚ ⊞ ℚ` given by `t ↦ (t, t)`. ## Main results * `category_theory.abelian.pseudoelement.exist_ne_and_fst_eq_fst_and_snd_eq_snd` : there are two pseudoelements `x y : ℚ ⊞ ℚ` such that `x ≠ y`, `biprod.fst x = biprod.fst y` and `biprod.snd x = biprod.snd y`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ open category_theory.abelian category_theory category_theory.limits Module linear_map noncomputable theory namespace category_theory.abelian.pseudoelement /-- `x` is given by `t ↦ (t, 2 * t)`. -/ def x : over ((of ℤ ℚ) ⊞ (of ℤ ℚ)) := over.mk (biprod.lift (of_hom id) (of_hom (2 * id))) /-- `y` is given by `t ↦ (t, t)`. -/ def y : over ((of ℤ ℚ) ⊞ (of ℤ ℚ)) := over.mk (biprod.lift (of_hom id) (of_hom id)) /-- `biprod.fst ≫ x` is pseudoequal to `biprod.fst y`. -/ lemma fst_x_pseudo_eq_fst_y : pseudo_equal _ (app biprod.fst x) (app biprod.fst y) := begin refine ⟨of ℤ ℚ, (of_hom id), (of_hom id), category_struct.id.epi (of ℤ ℚ), _, _⟩, { exact (Module.epi_iff_surjective _).2 (λ a, ⟨(a : ℚ), by simp⟩) }, { dsimp [x, y], simp } end /-- `biprod.snd ≫ x` is pseudoequal to `biprod.snd y`. -/ lemma snd_x_pseudo_eq_snd_y : pseudo_equal _ (app biprod.snd x) (app biprod.snd y) := begin refine ⟨of ℤ ℚ, (of_hom id), 2 • (of_hom id), category_struct.id.epi (of ℤ ℚ), _, _⟩, { refine (Module.epi_iff_surjective _).2 (λ a, ⟨(a/2 : ℚ), _⟩), simp only [two_smul, add_apply, of_hom_apply, id_coe, id.def], exact add_halves' (show ℚ, from a) }, { dsimp [x, y], exact concrete_category.hom_ext _ _ (λ a, by simpa) } end /-- `x` is not pseudoequal to `y`. -/ lemma x_not_pseudo_eq : ¬(pseudo_equal _ x y) := begin intro h, replace h := Module.eq_range_of_pseudoequal h, dsimp [x, y] at h, let φ := (biprod.lift (of_hom (id : ℚ →ₗ[ℤ] ℚ)) (of_hom (2 * id))), have mem_range := mem_range_self φ (1 : ℚ), rw h at mem_range, obtain ⟨a, ha⟩ := mem_range, rw [← Module.id_apply (φ (1 : ℚ)), ← biprod.total, ← linear_map.comp_apply, ← comp_def, preadditive.comp_add] at ha, let π₁ := (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _), have ha₁ := congr_arg π₁ ha, simp only [← linear_map.comp_apply, ← comp_def] at ha₁, simp only [biprod.lift_fst, of_hom_apply, id_coe, id.def, preadditive.add_comp, category.assoc, biprod.inl_fst, category.comp_id, biprod.inr_fst, limits.comp_zero, add_zero] at ha₁, let π₂ := (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _), have ha₂ := congr_arg π₂ ha, simp only [← linear_map.comp_apply, ← comp_def] at ha₂, have : (2 : ℚ →ₗ[ℤ] ℚ) 1 = 1 + 1 := rfl, simp only [ha₁, this, biprod.lift_snd, of_hom_apply, id_coe, id.def, preadditive.add_comp, category.assoc, biprod.inl_snd, limits.comp_zero, biprod.inr_snd, category.comp_id, zero_add, mul_apply, self_eq_add_left] at ha₂, exact one_ne_zero' ℚ ha₂, end local attribute [instance] pseudoelement.setoid open_locale pseudoelement /-- `biprod.fst ⟦x⟧ = biprod.fst ⟦y⟧`. -/ lemma fst_mk_x_eq_fst_mk_y : (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦x⟧ = (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦y⟧ := by simpa only [abelian.pseudoelement.pseudo_apply_mk, quotient.eq] using fst_x_pseudo_eq_fst_y /-- `biprod.snd ⟦x⟧ = biprod.snd ⟦y⟧`. -/ lemma snd_mk_x_eq_snd_mk_y : (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦x⟧ = (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦y⟧ := by simpa only [abelian.pseudoelement.pseudo_apply_mk, quotient.eq] using snd_x_pseudo_eq_snd_y /-- `⟦x⟧ ≠ ⟦y⟧`. -/ lemma mk_x_ne_mk_y : ⟦x⟧ ≠ ⟦y⟧ := λ h, x_not_pseudo_eq $ quotient.eq.1 h /-- There are two pseudoelements `x y : ℚ ⊞ ℚ` such that `x ≠ y`, `biprod.fst x = biprod.fst y` and `biprod.snd x = biprod.snd y`. -/ lemma exist_ne_and_fst_eq_fst_and_snd_eq_snd : ∃ x y : (of ℤ ℚ) ⊞ (of ℤ ℚ), x ≠ y ∧ (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) x = (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) y ∧ (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) x = (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) y:= ⟨⟦x⟧, ⟦y⟧, mk_x_ne_mk_y, fst_mk_x_eq_fst_mk_y, snd_mk_x_eq_snd_mk_y⟩ end category_theory.abelian.pseudoelement
8af7bc38e87ed2dba03c8b50c18cf51ceb3f822a
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/meta/interaction_monad.lean
ed578f380a8c112a027467d89a6984dd189be6d7
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
4,435
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.data.to_string universes u v meta inductive interaction_monad.result (state : Type) (α : Type u) | success : α → state → interaction_monad.result | exception {} : option (unit → format) → option pos → state → interaction_monad.result open interaction_monad.result section variables {state : Type} {α : Type u} variables [has_to_string α] meta def interaction_monad.result_to_string : result state α → string | (success a s) := to_string a | (exception (some t) ref s) := "Exception: " ++ to_string (t ()) | (exception none ref s) := "[silent exception]" meta instance interaction_monad.result_has_string : has_to_string (result state α) := ⟨interaction_monad.result_to_string⟩ end meta def interaction_monad.result.clamp_pos {state : Type} {α : Type u} (line0 line col : ℕ) : result state α → result state α | (success a s) := success a s | (exception msg (some p) s) := exception msg (some $ if p.line < line0 then ⟨line, col⟩ else p) s | (exception msg none s) := exception msg (some ⟨line, col⟩) s @[reducible] meta def interaction_monad (state : Type) (α : Type u) := state → result state α section parameter {state : Type} variables {α : Type u} {β : Type v} local notation `m` := interaction_monad state @[inline] meta def interaction_monad_fmap (f : α → β) (t : m α) : m β := λ s, interaction_monad.result.cases_on (t s) (λ a s', success (f a) s') (λ e s', exception e s') @[inline] meta def interaction_monad_bind (t₁ : m α) (t₂ : α → m β) : m β := λ s, interaction_monad.result.cases_on (t₁ s) (λ a s', t₂ a s') (λ e s', exception e s') @[inline] meta def interaction_monad_return (a : α) : m α := λ s, success a s meta def interaction_monad_orelse {α : Type u} (t₁ t₂ : m α) : m α := λ s, interaction_monad.result.cases_on (t₁ s) success (λ e₁ ref₁ s', interaction_monad.result.cases_on (t₂ s) success exception) @[inline] meta def interaction_monad_seq (t₁ : m α) (t₂ : m β) : m β := interaction_monad_bind t₁ (λ a, t₂) meta instance interaction_monad.monad : monad m := {map := @interaction_monad_fmap, pure := @interaction_monad_return, bind := @interaction_monad_bind, map_const_eq := undefined, seq_left_eq := undefined, seq_right_eq := undefined, id_map := undefined, pure_bind := undefined, bind_assoc := undefined, bind_pure_comp_eq_map := undefined, bind_map_eq_seq := undefined} meta def interaction_monad.mk_exception {α : Type u} {β : Type v} [has_to_format β] (msg : β) (ref : option expr) (s : state) : result state α := exception (some (λ _, to_fmt msg)) none s meta def interaction_monad.fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : m α := λ s, interaction_monad.mk_exception msg none s meta def interaction_monad.silent_fail {α : Type u} : m α := λ s, exception none none s meta def interaction_monad.failed {α : Type u} : m α := interaction_monad.fail "failed" /- Alternative orelse operator that allows to select which exception should be used. The default is to use the first exception since the standard `orelse` uses the second. -/ meta def interaction_monad.orelse' {α : Type u} (t₁ t₂ : m α) (use_first_ex := tt) : m α := λ s, interaction_monad.result.cases_on (t₁ s) success (λ e₁ ref₁ s₁', interaction_monad.result.cases_on (t₂ s) success (λ e₂ ref₂ s₂', if use_first_ex then (exception e₁ ref₁ s₁') else (exception e₂ ref₂ s₂'))) meta instance interaction_monad.monad_fail : monad_fail m := { interaction_monad.monad with fail := λ α s, interaction_monad.fail (to_fmt s) } -- TODO: unify `parser` and `tactic` behavior? -- meta instance interaction_monad.alternative : alternative m := -- ⟨@interaction_monad_fmap, (λ α a s, success a s), (@fapp _ _), @interaction_monad.failed, @interaction_monad_orelse⟩ end
0a549df7117c794629f215833ba621f049b4a85e
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/topology/metric_space/gromov_hausdorff_realized.lean
8b1df978a2722228d16ded753079d6b0fd2d4525
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,160
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 Construction of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces -/ import topology.metric_space.gluing import topology.metric_space.hausdorff_distance noncomputable theory open_locale classical open_locale topological_space universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union α ⊕ β of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] @[reducible] private def prod_space_fun : Type* := ((α ⊕ β) × (α ⊕ β)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((α ⊕ β) × (α ⊕ β)) ℝ private def max_var : nnreal := 2 * ⟨diam (univ : set α), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set β), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var α β := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num /-- The set of functions on α ⊕ β that are candidates distances to realize the minimum of the Hausdorff distances between α and β in a coupling -/ def candidates : set (prod_space_fun α β) := {f | (((((∀x y : α, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀x y : β, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀x y, f (x, y) = f (y, x))) ∧ (∀x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀x, f (x, x) = 0)) ∧ (∀x y, f (x, y) ≤ max_var α β) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb α β) := {f : Cb α β | f.val ∈ candidates α β} end definitions --section section constructions variables {α : Type u} {β : Type v} [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] {f : prod_space_fun α β} {x y z t : α ⊕ β} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var α β := calc dist x y ≤ diam (univ : set (α ⊕ β)) : dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set α) ∪ inr '' (univ : set β)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≤ diam (inl '' (univ : set α)) + dist (inl (default α)) (inr (default β)) + diam (inr '' (univ : set β)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set α) + (dist (default α) (default α) + 1 + dist (default β) (default β)) + diam (univ : set β) : by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl } ... = 1 * diam (univ : set α) + 1 + 1 * diam (univ : set β) : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates α β) : f (x, y) = f (y ,x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates α β) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates α β) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates α β) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates α β) (x y: α) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates α β) (x y : β) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates α β) : f (x, y) ≤ max_var α β := fA.2 x y /-- candidates are bounded by max_var α β -/ private lemma candidates_dist_bound (fA : f ∈ candidates α β) : ∀ {x y : α ⊕ β}, f (x, y) ≤ max_var α β * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var α β * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var α β * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates α β) : f (x, y) - f (z, t) ≤ 2 * max_var α β * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : sub_le_sub_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : sub_le_sub_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc] ... ≤ max_var α β * dist x z + max_var α β * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var α β * max (dist x z) (dist t y) + max_var α β * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)), end ... = 2 * max_var α β * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var α β * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates α β) : lipschitz_with (2 * max_var α β) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw [real.dist_eq, abs_sub_le_iff], use candidates_lipschitz_aux fA, rw [dist_comm], exact candidates_lipschitz_aux fA end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun α β) (fA : f ∈ candidates α β) : Cb α β := bounded_continuous_function.mk_of_compact f (candidates_lipschitz fA).continuous lemma candidates_b_of_candidates_mem (f : prod_space_fun α β) (fA : f ∈ candidates α β) : candidates_b_of_candidates f fA ∈ candidates_b α β := fA /-- The distance on α ⊕ β is a candidate -/ private lemma dist_mem_candidates : (λp : (α ⊕ β) × (α ⊕ β), dist p.1 p.2) ∈ candidates α β := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end def candidates_b_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α] [inhabited α] [metric_space β] [compact_space β] [inhabited β] : Cb α β := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist α β ∈ candidates_b α β := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b α β).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness -/ private lemma closed_candidates_b : is_closed (candidates_b α β) := begin have I1 : ∀x y, is_closed {f : Cb α β | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_evalx continuous_const, have I2 : ∀x y, is_closed {f : Cb α β | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_evalx continuous_const, have I3 : ∀x y, is_closed {f : Cb α β | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_evalx continuous_evalx, have I4 : ∀x y z, is_closed {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx), have I5 : ∀x, is_closed {f : Cb α β | f (x, x) = 0} := λx, is_closed_eq continuous_evalx continuous_const, have I6 : ∀x y, is_closed {f : Cb α β | f (x, y) ≤ max_var α β} := λx y, is_closed_le continuous_evalx continuous_const, have : candidates_b α β = (⋂x y, {f : Cb α β | f ((@inl α β x), (@inl α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f ((@inr α β x), (@inr α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb α β | f (x, x) = 0}) ∩ (⋂x y, {f : Cb α β | f (x, y) ≤ max_var α β}) := begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end, rw this, repeat { apply is_closed_inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows -/ private lemma compact_candidates_b : is_compact (candidates_b α β) := begin refine arzela_ascoli₂ (Icc 0 (max_var α β)) compact_Icc (candidates_b α β) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var α β * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var α β : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var α β * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb α β) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y)) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb α β} (C : ℝ) {x : α} : bdd_below (range (λ (y : β), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (x : α), ⨅ y, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr (default β)) + C : cinfi_le (HD_below_aux1 C) (default β) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end lemma HD_below_aux2 {f : Cb α β} (C : ℝ) {y : β} : bdd_below (range (λ (x : α), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (y : β), ⨅ x, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl (default α), inr y) + C : cinfi_le (HD_below_aux2 C) (default α) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end /-- Explicit bound on HD (dist). This means that when looking for minimizers it will be sufficient to look for functions with HD(f) bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist α β) ≤ diam (univ : set α) + 1 + diam (univ : set β) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : (⨅ y, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl x, inr (default β)) := cinfi_le (by simpa using HD_below_aux1 0) (default β), have B : dist (inl x) (inr (default β)) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl x) (inr (default β)) = dist x (default α) + 1 + dist (default β) (default β) : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, { have A : (⨅ x, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl (default α), inr y) := cinfi_le (by simpa using HD_below_aux2 0) (default α), have B : dist (inl (default α)) (inr y) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl (default α)) (inr y) = dist (default α) (default α) + 1 + dist (default β) y : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb α β) : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux1 _ (dist f g)) (λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g, { assume x, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λ (y : β), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb α β) : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux2 _ (dist f g)) (λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g, { assume y, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λx:α, g (inl x, inr y))), from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } }, have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1] end private lemma HD_lipschitz_aux3 (f g : Cb α β) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb α β → ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃f ∈ candidates_b α β, ∀g ∈ candidates_b α β, HD f ≤ HD g := compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb α β := classical.some (exists_minimizer α β) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist α β ∈ candidates_b α β := by cases (classical.some_spec (exists_minimizer α β)); assumption private lemma HD_optimal_GH_dist_le (g : Cb α β) (hg : g ∈ candidates_b α β) : HD (optimal_GH_dist α β) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer α β) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on α ⊕ β, on which the predistance is given by the candidate. Then, we will identify points at 0 predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : premetric_space (α ⊕ β) := { dist := λp q, optimal_GH_dist α β (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b α β), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b α β), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b α β) } local attribute [instance] premetric_optimal_GH_dist premetric.dist_setoid /-- A metric space which realizes the optimal coupling between α and β -/ @[derive [metric_space]] definition optimal_GH_coupling : Type* := premetric.metric_quot (α ⊕ β) /-- Injection of α in the optimal coupling between α and β -/ def optimal_GH_injl (x : α) : optimal_GH_coupling α β := ⟦inl x⟧ /-- The injection of α in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- Injection of β in the optimal coupling between α and β -/ def optimal_GH_injr (y : β) : optimal_GH_coupling α β := ⟦inr y⟧ /-- The injection of β in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- The optimal coupling between two compact spaces α and β is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling α β) := ⟨begin have : (univ : set (optimal_GH_coupling α β)) = (optimal_GH_injl α β '' univ) ∪ (optimal_GH_injr α β '' univ), { refine subset.antisymm (λxc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl α β x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr α β x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (compact_univ.image (isometry_optimal_GH_injl α β).continuous).union (compact_univ.image (isometry_optimal_GH_injr α β).continuous) end⟩ /-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b α β) : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le α β f h), have A : ∀ x ∈ range (optimal_GH_injl α β), ∃ y ∈ range (optimal_GH_injr α β), dist x y ≤ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : (⨅ y, optimal_GH_dist α β (inl z, inr y)) ≤ ⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : (⨅ y, optimal_GH_dist α β (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z, inr z') ≤ r := begin rw hz', exact le_of_lt hr' end, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : optimal_GH_injl α β xα ∈ range (optimal_GH_injl α β) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : (⨅ x, optimal_GH_dist α β (inl x, inr z)) ≤ ⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : (⨅ x, optimal_GH_dist α β (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z', inr z) ≤ r := begin rw hz', exact le_of_lt hr' end, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
1b13075f9ec0f9029b3f12b0d1594e1c9ef54691
1a61aba1b67cddccce19532a9596efe44be4285f
/hott/init/path.hlean
bf08efe492dcda79bfa91379ec6d521d7795d2bf
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
25,587
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .function .tactic open function eq /- Path equality -/ namespace eq variables {A B C : Type} {P : A → Type} {x y z t : A} --notation a = b := eq a b notation x = y `:>`:50 A:49 := @eq A x y definition idp [reducible] [constructor] {a : A} := refl a definition idpath [reducible] [constructor] (a : A) := refl a -- unbased path induction definition rec' [reducible] [unfold 6] {P : Π (a b : A), (a = b) → Type} (H : Π (a : A), P a a idp) {a b : A} (p : a = b) : P a b p := eq.rec (H a) p definition rec_on' [reducible] [unfold 5] {P : Π (a b : A), (a = b) → Type} {a b : A} (p : a = b) (H : Π (a : A), P a a idp) : P a b p := eq.rec (H a) p /- Concatenation and inverse -/ definition concat [trans] [unfold 6] (p : x = y) (q : y = z) : x = z := eq.rec (λp', p') q p definition inverse [symm] [unfold 4] (p : x = y) : y = x := eq.rec (refl x) p infix ⬝ := concat postfix ⁻¹ := inverse --a second notation for the inverse, which is not overloaded postfix [parsing-only] `⁻¹ᵖ`:std.prec.max_plus := inverse /- The 1-dimensional groupoid structure -/ -- The identity path is a right unit. definition con_idp [unfold-full] (p : x = y) : p ⬝ idp = p := idp -- The identity path is a right unit. definition idp_con [unfold 4] (p : x = y) : idp ⬝ p = p := eq.rec_on p idp -- Concatenation is associative. definition con.assoc' (p : x = y) (q : y = z) (r : z = t) : p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r := eq.rec_on r (eq.rec_on q idp) definition con.assoc (p : x = y) (q : y = z) (r : z = t) : (p ⬝ q) ⬝ r = p ⬝ (q ⬝ r) := eq.rec_on r (eq.rec_on q idp) -- The left inverse law. definition con.right_inv [unfold 4] (p : x = y) : p ⬝ p⁻¹ = idp := eq.rec_on p idp -- The right inverse law. definition con.left_inv [unfold 4] (p : x = y) : p⁻¹ ⬝ p = idp := eq.rec_on p idp /- Several auxiliary theorems about canceling inverses across associativity. These are somewhat redundant, following from earlier theorems. -/ definition inv_con_cancel_left (p : x = y) (q : y = z) : p⁻¹ ⬝ (p ⬝ q) = q := eq.rec_on q (eq.rec_on p idp) definition con_inv_cancel_left (p : x = y) (q : x = z) : p ⬝ (p⁻¹ ⬝ q) = q := eq.rec_on q (eq.rec_on p idp) definition con_inv_cancel_right (p : x = y) (q : y = z) : (p ⬝ q) ⬝ q⁻¹ = p := eq.rec_on q (eq.rec_on p idp) definition inv_con_cancel_right (p : x = z) (q : y = z) : (p ⬝ q⁻¹) ⬝ q = p := eq.rec_on q (take p, eq.rec_on p idp) p -- Inverse distributes over concatenation definition con_inv (p : x = y) (q : y = z) : (p ⬝ q)⁻¹ = q⁻¹ ⬝ p⁻¹ := eq.rec_on q (eq.rec_on p idp) definition inv_con_inv_left (p : y = x) (q : y = z) : (p⁻¹ ⬝ q)⁻¹ = q⁻¹ ⬝ p := eq.rec_on q (eq.rec_on p idp) -- universe metavariables definition inv_con_inv_right (p : x = y) (q : z = y) : (p ⬝ q⁻¹)⁻¹ = q ⬝ p⁻¹ := eq.rec_on p (take q, eq.rec_on q idp) q definition inv_con_inv_inv (p : y = x) (q : z = y) : (p⁻¹ ⬝ q⁻¹)⁻¹ = q ⬝ p := eq.rec_on p (eq.rec_on q idp) -- Inverse is an involution. definition inv_inv (p : x = y) : p⁻¹⁻¹ = p := eq.rec_on p idp -- auxiliary definition used by 'cases' tactic definition elim_inv_inv {A : Type} {a b : A} {C : a = b → Type} (H₁ : a = b) (H₂ : C (H₁⁻¹⁻¹)) : C H₁ := eq.rec_on (inv_inv H₁) H₂ /- Theorems for moving things around in equations -/ definition con_eq_of_eq_inv_con {p : x = z} {q : y = z} {r : y = x} : p = r⁻¹ ⬝ q → r ⬝ p = q := eq.rec_on r (take p h, !idp_con ⬝ h ⬝ !idp_con) p definition con_eq_of_eq_con_inv [unfold 5] {p : x = z} {q : y = z} {r : y = x} : r = q ⬝ p⁻¹ → r ⬝ p = q := eq.rec_on p (take q h, h) q definition inv_con_eq_of_eq_con {p : x = z} {q : y = z} {r : x = y} : p = r ⬝ q → r⁻¹ ⬝ p = q := eq.rec_on r (take q h, !idp_con ⬝ h ⬝ !idp_con) q definition con_inv_eq_of_eq_con [unfold 5] {p : z = x} {q : y = z} {r : y = x} : r = q ⬝ p → r ⬝ p⁻¹ = q := eq.rec_on p (take r h, h) r definition eq_con_of_inv_con_eq {p : x = z} {q : y = z} {r : y = x} : r⁻¹ ⬝ q = p → q = r ⬝ p := eq.rec_on r (take p h, !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹) p definition eq_con_of_con_inv_eq [unfold 5] {p : x = z} {q : y = z} {r : y = x} : q ⬝ p⁻¹ = r → q = r ⬝ p := eq.rec_on p (take q h, h) q definition eq_inv_con_of_con_eq {p : x = z} {q : y = z} {r : x = y} : r ⬝ q = p → q = r⁻¹ ⬝ p := eq.rec_on r (take q h, !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹) q definition eq_con_inv_of_con_eq [unfold 5] {p : z = x} {q : y = z} {r : y = x} : q ⬝ p = r → q = r ⬝ p⁻¹ := eq.rec_on p (take r h, h) r definition eq_of_con_inv_eq_idp [unfold 5] {p q : x = y} : p ⬝ q⁻¹ = idp → p = q := eq.rec_on q (take p h, h) p definition eq_of_inv_con_eq_idp {p q : x = y} : q⁻¹ ⬝ p = idp → p = q := eq.rec_on q (take p h, !idp_con⁻¹ ⬝ h) p definition eq_inv_of_con_eq_idp' [unfold 5] {p : x = y} {q : y = x} : p ⬝ q = idp → p = q⁻¹ := eq.rec_on q (take p h, h) p definition eq_inv_of_con_eq_idp {p : x = y} {q : y = x} : q ⬝ p = idp → p = q⁻¹ := eq.rec_on q (take p h, !idp_con⁻¹ ⬝ h) p definition eq_of_idp_eq_inv_con {p q : x = y} : idp = p⁻¹ ⬝ q → p = q := eq.rec_on p (take q h, h ⬝ !idp_con) q definition eq_of_idp_eq_con_inv [unfold 4] {p q : x = y} : idp = q ⬝ p⁻¹ → p = q := eq.rec_on p (take q h, h) q definition inv_eq_of_idp_eq_con [unfold 4] {p : x = y} {q : y = x} : idp = q ⬝ p → p⁻¹ = q := eq.rec_on p (take q h, h) q definition inv_eq_of_idp_eq_con' {p : x = y} {q : y = x} : idp = p ⬝ q → p⁻¹ = q := eq.rec_on p (take q h, h ⬝ !idp_con) q definition con_inv_eq_idp [unfold 6] {p q : x = y} (r : p = q) : p ⬝ q⁻¹ = idp := by cases r;apply con.right_inv definition inv_con_eq_idp [unfold 6] {p q : x = y} (r : p = q) : q⁻¹ ⬝ p = idp := by cases r;apply con.left_inv definition con_eq_idp {p : x = y} {q : y = x} (r : p = q⁻¹) : p ⬝ q = idp := by cases q;exact r definition idp_eq_inv_con {p q : x = y} (r : p = q) : idp = p⁻¹ ⬝ q := by cases r;exact !con.left_inv⁻¹ definition idp_eq_con_inv {p q : x = y} (r : p = q) : idp = q ⬝ p⁻¹ := by cases r;exact !con.right_inv⁻¹ definition idp_eq_con {p : x = y} {q : y = x} (r : p⁻¹ = q) : idp = q ⬝ p := by cases p;exact r /- Transport -/ definition transport [subst] [reducible] [unfold 5] (P : A → Type) {x y : A} (p : x = y) (u : P x) : P y := eq.rec_on p u -- This idiom makes the operation right associative. infixr `▸` := transport _ definition cast [reducible] [unfold 3] {A B : Type} (p : A = B) (a : A) : B := p ▸ a definition tr_rev [reducible] [unfold 6] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x := p⁻¹ ▸ u definition ap [unfold 6] ⦃A B : Type⦄ (f : A → B) {x y:A} (p : x = y) : f x = f y := eq.rec_on p idp abbreviation ap01 [parsing-only] := ap definition homotopy [reducible] (f g : Πx, P x) : Type := Πx : A, f x = g x infix ~ := homotopy protected definition homotopy.refl [refl] [reducible] [unfold-full] (f : Πx, P x) : f ~ f := λ x, idp protected definition homotopy.symm [symm] [reducible] [unfold-full] {f g : Πx, P x} (H : f ~ g) : g ~ f := λ x, (H x)⁻¹ protected definition homotopy.trans [trans] [reducible] [unfold-full] {f g h : Πx, P x} (H1 : f ~ g) (H2 : g ~ h) : f ~ h := λ x, H1 x ⬝ H2 x definition homotopy_of_eq {f g : Πx, P x} (H1 : f = g) : f ~ g := H1 ▸ homotopy.refl f definition apd10 [unfold 5] {f g : Πx, P x} (H : f = g) : f ~ g := λx, eq.rec_on H idp --the next theorem is useful if you want to write "apply (apd10' a)" definition apd10' [unfold 6] {f g : Πx, P x} (a : A) (H : f = g) : f a = g a := eq.rec_on H idp definition ap10 [reducible] [unfold 5] {f g : A → B} (H : f = g) : f ~ g := apd10 H definition ap11 {f g : A → B} (H : f = g) {x y : A} (p : x = y) : f x = g y := eq.rec_on H (eq.rec_on p idp) definition apd [unfold 6] (f : Πa, P a) {x y : A} (p : x = y) : p ▸ f x = f y := eq.rec_on p idp /- More theorems for moving things around in equations -/ definition tr_eq_of_eq_inv_tr {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : u = p⁻¹ ▸ v → p ▸ u = v := eq.rec_on p (take v, id) v definition inv_tr_eq_of_eq_tr {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : u = p ▸ v → p⁻¹ ▸ u = v := eq.rec_on p (take u, id) u definition eq_inv_tr_of_tr_eq {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : p ▸ u = v → u = p⁻¹ ▸ v := eq.rec_on p (take v, id) v definition eq_tr_of_inv_tr_eq {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : p⁻¹ ▸ u = v → u = p ▸ v := eq.rec_on p (take u, id) u /- Functoriality of functions -/ -- Here we prove that functions behave like functors between groupoids, and that [ap] itself is -- functorial. -- Functions take identity paths to identity paths definition ap_idp (x : A) (f : A → B) : ap f idp = idp :> (f x = f x) := idp -- Functions commute with concatenation. definition ap_con (f : A → B) {x y z : A} (p : x = y) (q : y = z) : ap f (p ⬝ q) = ap f p ⬝ ap f q := eq.rec_on q (eq.rec_on p idp) definition con_ap_con_eq_con_ap_con_ap (f : A → B) {w x y z : A} (r : f w = f x) (p : x = y) (q : y = z) : r ⬝ ap f (p ⬝ q) = (r ⬝ ap f p) ⬝ ap f q := eq.rec_on q (take p, eq.rec_on p idp) p definition ap_con_con_eq_ap_con_ap_con (f : A → B) {w x y z : A} (p : x = y) (q : y = z) (r : f z = f w) : ap f (p ⬝ q) ⬝ r = ap f p ⬝ (ap f q ⬝ r) := eq.rec_on q (eq.rec_on p (take r, con.assoc _ _ _)) r -- Functions commute with path inverses. definition ap_inv' (f : A → B) {x y : A} (p : x = y) : (ap f p)⁻¹ = ap f p⁻¹ := eq.rec_on p idp definition ap_inv {A B : Type} (f : A → B) {x y : A} (p : x = y) : ap f p⁻¹ = (ap f p)⁻¹ := eq.rec_on p idp -- [ap] itself is functorial in the first argument. definition ap_id (p : x = y) : ap id p = p := eq.rec_on p idp definition ap_compose [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (g ∘ f) p = ap g (ap f p) := eq.rec_on p idp -- Sometimes we don't have the actual function [compose]. definition ap_compose' [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (λa, g (f a)) p = ap g (ap f p) := eq.rec_on p idp -- The action of constant maps. definition ap_constant [unfold 5] (p : x = y) (z : B) : ap (λu, z) p = idp := eq.rec_on p idp -- Naturality of [ap]. -- see also natural_square in cubical.square definition ap_con_eq_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ ap g q := eq.rec_on q !idp_con -- Naturality of [ap] at identity. definition ap_con_eq_con {f : A → A} (p : Πx, f x = x) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ q := eq.rec_on q !idp_con definition con_ap_eq_con {f : A → A} (p : Πx, x = f x) {x y : A} (q : x = y) : p x ⬝ ap f q = q ⬝ p y := eq.rec_on q !idp_con⁻¹ -- Naturality of [ap] with constant function definition ap_con_eq {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : ap f q ⬝ p y = p x := eq.rec_on q !idp_con -- Naturality with other paths hanging around. definition con_ap_con_con_eq_con_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w z : B} (r : w = f x) (s : g y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (ap g q ⬝ s) := eq.rec_on s (eq.rec_on q idp) definition con_ap_con_eq_con_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w : B} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ ap g q := eq.rec_on q idp -- TODO: try this using the simplifier, and compare proofs definition ap_con_con_eq_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {z : B} (s : g y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (ap g q ⬝ s) := eq.rec_on s (eq.rec_on q (calc (ap f idp) ⬝ (p x ⬝ idp) = idp ⬝ p x : idp ... = p x : !idp_con ... = (p x) ⬝ (ap g idp ⬝ idp) : idp)) -- This also works: -- eq.rec_on s (eq.rec_on q (!idp_con ▸ idp)) definition con_ap_con_con_eq_con_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w z : A} (r : w = f x) (s : y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (q ⬝ s) := eq.rec_on s (eq.rec_on q idp) definition con_con_ap_con_eq_con_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w z : A} (r : w = x) (s : g y = z) : (r ⬝ p x) ⬝ (ap g q ⬝ s) = (r ⬝ q) ⬝ (p y ⬝ s) := eq.rec_on s (eq.rec_on q idp) definition con_ap_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w : A} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ q := eq.rec_on q idp definition ap_con_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {z : A} (s : y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (q ⬝ s) := eq.rec_on s (eq.rec_on q (!idp_con ▸ idp)) definition con_con_ap_eq_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w : A} (r : w = x) : (r ⬝ p x) ⬝ ap g q = (r ⬝ q) ⬝ p y := begin cases q, exact idp end definition con_ap_con_eq_con_con' {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {z : A} (s : g y = z) : p x ⬝ (ap g q ⬝ s) = q ⬝ (p y ⬝ s) := begin apply (eq.rec_on s), apply (eq.rec_on q), apply (idp_con (p x) ▸ idp) end /- Action of [apd10] and [ap10] on paths -/ -- Application of paths between functions preserves the groupoid structure definition apd10_idp (f : Πx, P x) (x : A) : apd10 (refl f) x = idp := idp definition apd10_con {f f' f'' : Πx, P x} (h : f = f') (h' : f' = f'') (x : A) : apd10 (h ⬝ h') x = apd10 h x ⬝ apd10 h' x := eq.rec_on h (take h', eq.rec_on h' idp) h' definition apd10_inv {f g : Πx : A, P x} (h : f = g) (x : A) : apd10 h⁻¹ x = (apd10 h x)⁻¹ := eq.rec_on h idp definition ap10_idp {f : A → B} (x : A) : ap10 (refl f) x = idp := idp definition ap10_con {f f' f'' : A → B} (h : f = f') (h' : f' = f'') (x : A) : ap10 (h ⬝ h') x = ap10 h x ⬝ ap10 h' x := apd10_con h h' x definition ap10_inv {f g : A → B} (h : f = g) (x : A) : ap10 h⁻¹ x = (ap10 h x)⁻¹ := apd10_inv h x -- [ap10] also behaves nicely on paths produced by [ap] definition ap_ap10 (f g : A → B) (h : B → C) (p : f = g) (a : A) : ap h (ap10 p a) = ap10 (ap (λ f', h ∘ f') p) a:= eq.rec_on p idp /- Transport and the groupoid structure of paths -/ definition idp_tr {P : A → Type} {x : A} (u : P x) : idp ▸ u = u := idp definition con_tr [unfold 7] {P : A → Type} {x y z : A} (p : x = y) (q : y = z) (u : P x) : p ⬝ q ▸ u = q ▸ p ▸ u := eq.rec_on q idp definition tr_inv_tr {P : A → Type} {x y : A} (p : x = y) (z : P y) : p ▸ p⁻¹ ▸ z = z := (con_tr p⁻¹ p z)⁻¹ ⬝ ap (λr, transport P r z) (con.left_inv p) definition inv_tr_tr {P : A → Type} {x y : A} (p : x = y) (z : P x) : p⁻¹ ▸ p ▸ z = z := (con_tr p p⁻¹ z)⁻¹ ⬝ ap (λr, transport P r z) (con.right_inv p) definition con_tr_lemma {P : A → Type} {x y z w : A} (p : x = y) (q : y = z) (r : z = w) (u : P x) : ap (λe, e ▸ u) (con.assoc' p q r) ⬝ (con_tr (p ⬝ q) r u) ⬝ ap (transport P r) (con_tr p q u) = (con_tr p (q ⬝ r) u) ⬝ (con_tr q r (p ▸ u)) :> ((p ⬝ (q ⬝ r)) ▸ u = r ▸ q ▸ p ▸ u) := eq.rec_on r (eq.rec_on q (eq.rec_on p idp)) -- Here is another coherence lemma for transport. definition tr_inv_tr_lemma {P : A → Type} {x y : A} (p : x = y) (z : P x) : tr_inv_tr p (transport P p z) = ap (transport P p) (inv_tr_tr p z) := eq.rec_on p idp /- some properties for apd -/ definition apd_idp (x : A) (f : Πx, P x) : apd f idp = idp :> (f x = f x) := idp definition apd_con (f : Πx, P x) {x y z : A} (p : x = y) (q : y = z) : apd f (p ⬝ q) = con_tr p q (f x) ⬝ ap (transport P q) (apd f p) ⬝ apd f q := by cases p;cases q;apply idp definition apd_inv (f : Πx, P x) {x y : A} (p : x = y) : apd f p⁻¹ = (eq_inv_tr_of_tr_eq (apd f p))⁻¹ := by cases p;apply idp -- Dependent transport in a doubly dependent type. definition transportD [unfold 6] {P : A → Type} (Q : Πa, P a → Type) {a a' : A} (p : a = a') (b : P a) (z : Q a b) : Q a' (p ▸ b) := eq.rec_on p z -- In Coq the variables P, Q and b are explicit, but in Lean we can probably have them implicit -- using the following notation notation p `▸D`:65 x:64 := transportD _ p _ x -- Transporting along higher-dimensional paths definition transport2 [unfold 7] (P : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : P x) : p ▸ z = q ▸ z := ap (λp', p' ▸ z) r notation p `▸2`:65 x:64 := transport2 _ p _ x -- An alternative definition. definition tr2_eq_ap10 (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r z = ap10 (ap (transport Q) r) z := eq.rec_on r idp definition tr2_con {P : A → Type} {x y : A} {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3) (z : P x) : transport2 P (r1 ⬝ r2) z = transport2 P r1 z ⬝ transport2 P r2 z := eq.rec_on r1 (eq.rec_on r2 idp) definition tr2_inv (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r⁻¹ z = (transport2 Q r z)⁻¹ := eq.rec_on r idp definition transportD2 [unfold 7] (B C : A → Type) (D : Π(a:A), B a → C a → Type) {x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C x1) (w : D x1 y z) : D x2 (p ▸ y) (p ▸ z) := eq.rec_on p w notation p `▸D2`:65 x:64 := transportD2 _ _ _ p _ _ x definition ap_tr_con_tr2 (P : A → Type) {x y : A} {p q : x = y} {z w : P x} (r : p = q) (s : z = w) : ap (transport P p) s ⬝ transport2 P r w = transport2 P r z ⬝ ap (transport P q) s := eq.rec_on r !idp_con⁻¹ definition fn_tr_eq_tr_fn {P Q : A → Type} {x y : A} (p : x = y) (f : Πx, P x → Q x) (z : P x) : f y (p ▸ z) = (p ▸ (f x z)) := eq.rec_on p idp /- Transporting in particular fibrations -/ /- From the Coq HoTT library: One frequently needs lemmas showing that transport in a certain dependent type is equal to some more explicitly defined operation, defined according to the structure of that dependent type. For most dependent types, we prove these lemmas in the appropriate file in the types/ subdirectory. Here we consider only the most basic cases. -/ -- Transporting in a constant fibration. definition tr_constant (p : x = y) (z : B) : transport (λx, B) p z = z := eq.rec_on p idp definition tr2_constant {p q : x = y} (r : p = q) (z : B) : tr_constant p z = transport2 (λu, B) r z ⬝ tr_constant q z := eq.rec_on r !idp_con⁻¹ -- Transporting in a pulled back fibration. definition tr_compose (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) : transport (P ∘ f) p z = transport P (ap f p) z := eq.rec_on p idp definition ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : ap (λh, h ∘ f) p = transport (λh : B → C, g ∘ f = h ∘ f) p idp := eq.rec_on p idp definition apd10_ap_precompose (f : A → B) (g g' : B → C) (p : g = g') (a : A) : apd10 (ap (λh : B → C, h ∘ f) p) a = apd10 p (f a) := eq.rec_on p idp definition apd10_ap_postcompose (f : B → C) (g g' : A → B) (p : g = g') (a : A) : apd10 (ap (λh : A → B, f ∘ h) p) a = ap f (apd10 p a) := eq.rec_on p idp -- A special case of [tr_compose] which seems to come up a lot. definition tr_eq_cast_ap {P : A → Type} {x y} (p : x = y) (u : P x) : p ▸ u = cast (ap P p) u := eq.rec_on p idp definition tr_eq_cast_ap_fn {P : A → Type} {x y} (p : x = y) : transport P p = cast (ap P p) := eq.rec_on p idp /- The behavior of [ap] and [apd] -/ -- In a constant fibration, [apd] reduces to [ap], modulo [transport_const]. definition apd_eq_tr_constant_con_ap (f : A → B) (p : x = y) : apd f p = tr_constant p (f x) ⬝ ap f p := eq.rec_on p idp /- The 2-dimensional groupoid structure -/ -- Horizontal composition of 2-dimensional paths. definition concat2 [unfold 9 10] {p p' : x = y} {q q' : y = z} (h : p = p') (h' : q = q') : p ⬝ q = p' ⬝ q' := eq.rec_on h (eq.rec_on h' idp) -- 2-dimensional path inversion definition inverse2 [unfold 6] {p q : x = y} (h : p = q) : p⁻¹ = q⁻¹ := eq.rec_on h idp infixl `◾`:75 := concat2 postfix [parsing-only] `⁻²`:(max+10) := inverse2 --this notation is abusive, should we use it? /- Whiskering -/ definition whisker_left [unfold 8] (p : x = y) {q r : y = z} (h : q = r) : p ⬝ q = p ⬝ r := idp ◾ h definition whisker_right [unfold 7] {p q : x = y} (h : p = q) (r : y = z) : p ⬝ r = q ⬝ r := h ◾ idp -- Unwhiskering, a.k.a. cancelling definition cancel_left {x y z : A} {p : x = y} {q r : y = z} : (p ⬝ q = p ⬝ r) → (q = r) := λs, !inv_con_cancel_left⁻¹ ⬝ whisker_left p⁻¹ s ⬝ !inv_con_cancel_left definition cancel_right {x y z : A} {p q : x = y} {r : y = z} : (p ⬝ r = q ⬝ r) → (p = q) := λs, !con_inv_cancel_right⁻¹ ⬝ whisker_right s r⁻¹ ⬝ !con_inv_cancel_right -- Whiskering and identity paths. definition whisker_right_idp {p q : x = y} (h : p = q) : whisker_right h idp = h := eq.rec_on h (eq.rec_on p idp) definition whisker_right_idp_left (p : x = y) (q : y = z) : whisker_right idp q = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp_right (p : x = y) (q : y = z) : whisker_left p idp = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp {p q : x = y} (h : p = q) : (idp_con p) ⁻¹ ⬝ whisker_left idp h ⬝ idp_con q = h := eq.rec_on h (eq.rec_on p idp) definition con2_idp {p q : x = y} (h : p = q) : h ◾ idp = whisker_right h idp :> (p ⬝ idp = q ⬝ idp) := idp definition idp_con2 {p q : x = y} (h : p = q) : idp ◾ h = whisker_left idp h :> (idp ⬝ p = idp ⬝ q) := idp -- The interchange law for concatenation. definition con2_con_con2 {p p' p'' : x = y} {q q' q'' : y = z} (a : p = p') (b : p' = p'') (c : q = q') (d : q' = q'') : (a ◾ c) ⬝ (b ◾ d) = (a ⬝ b) ◾ (c ⬝ d) := eq.rec_on d (eq.rec_on c (eq.rec_on b (eq.rec_on a idp))) definition whisker_right_con_whisker_left {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : (whisker_right a q) ⬝ (whisker_left p' b) = (whisker_left p b) ⬝ (whisker_right a q') := eq.rec_on b (eq.rec_on a !idp_con⁻¹) -- Structure corresponding to the coherence equations of a bicategory. -- The "pentagonator": the 3-cell witnessing the associativity pentagon. definition pentagon {v w x y z : A} (p : v = w) (q : w = x) (r : x = y) (s : y = z) : whisker_left p (con.assoc' q r s) ⬝ con.assoc' p (q ⬝ r) s ⬝ whisker_right (con.assoc' p q r) s = con.assoc' p q (r ⬝ s) ⬝ con.assoc' (p ⬝ q) r s := by induction s;induction r;induction q;induction p;reflexivity -- The 3-cell witnessing the left unit triangle. definition triangulator (p : x = y) (q : y = z) : con.assoc' p idp q ⬝ whisker_right (con_idp p) q = whisker_left p (idp_con q) := eq.rec_on q (eq.rec_on p idp) definition eckmann_hilton {x:A} (p q : idp = idp :> x = x) : p ⬝ q = q ⬝ p := (!whisker_right_idp ◾ !whisker_left_idp)⁻¹ ⬝ whisker_left _ !idp_con ⬝ !whisker_right_con_whisker_left ⬝ whisker_right !idp_con⁻¹ _ ⬝ (!whisker_left_idp ◾ !whisker_right_idp) -- The action of functions on 2-dimensional paths definition ap02 [unfold 8] [reducible] (f : A → B) {x y : A} {p q : x = y} (r : p = q) : ap f p = ap f q := ap (ap f) r definition ap02_con (f : A → B) {x y : A} {p p' p'' : x = y} (r : p = p') (r' : p' = p'') : ap02 f (r ⬝ r') = ap02 f r ⬝ ap02 f r' := eq.rec_on r (eq.rec_on r' idp) definition ap02_con2 (f : A → B) {x y z : A} {p p' : x = y} {q q' :y = z} (r : p = p') (s : q = q') : ap02 f (r ◾ s) = ap_con f p q ⬝ (ap02 f r ◾ ap02 f s) ⬝ (ap_con f p' q')⁻¹ := eq.rec_on r (eq.rec_on s (eq.rec_on q (eq.rec_on p idp))) definition apd02 [unfold 8] {p q : x = y} (f : Π x, P x) (r : p = q) : apd f p = transport2 P r (f x) ⬝ apd f q := eq.rec_on r !idp_con⁻¹ -- And now for a lemma whose statement is much longer than its proof. definition apd02_con {P : A → Type} (f : Π x:A, P x) {x y : A} {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3) : apd02 f (r1 ⬝ r2) = apd02 f r1 ⬝ whisker_left (transport2 P r1 (f x)) (apd02 f r2) ⬝ con.assoc' _ _ _ ⬝ (whisker_right (tr2_con r1 r2 (f x))⁻¹ (apd f p3)) := eq.rec_on r2 (eq.rec_on r1 (eq.rec_on p1 idp)) end eq
b14119027eb5d1fa50c6566c53aa4d53fedeb6d3
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/category/Groupoid.lean
ab0b1b7cbfd269d2e1140eff764705260e447d8c
[ "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
1,969
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import category_theory.single_obj /-! # Category of groupoids This file contains the definition of the category `Groupoid` of all groupoids. In this category objects are groupoids and morphisms are functors between these groupoids. We also provide two “forgetting” functors: `objects : Groupoid ⥤ Type` and `forget_to_Cat : Groupoid ⥤ Cat`. ## Implementation notes Though `Groupoid` is not a concrete category, we use `bundled` to define its carrier type. -/ universes v u namespace category_theory /-- Category of groupoids -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def Groupoid := bundled groupoid.{v u} namespace Groupoid instance : inhabited Groupoid := ⟨bundled.of (single_obj punit)⟩ instance str (C : Groupoid.{v u}) : groupoid.{v u} C.α := C.str /-- Construct a bundled `Groupoid` from the underlying type and the typeclass. -/ def of (C : Type u) [groupoid.{v} C] : Groupoid.{v u} := bundled.of C /-- Category structure on `Groupoid` -/ instance category : large_category.{max v u} Groupoid.{v u} := { hom := λ C D, C.α ⥤ D.α, id := λ C, 𝟭 C.α, comp := λ C D E F G, F ⋙ G, id_comp' := λ C D F, by cases F; refl, comp_id' := λ C D F, by cases F; refl, assoc' := by intros; refl } /-- Functor that gets the set of objects of a groupoid. It is not called `forget`, because it is not a faithful functor. -/ def objects : Groupoid.{v u} ⥤ Type u := { obj := bundled.α, map := λ C D F, F.obj } /-- Forgetting functor to `Cat` -/ def forget_to_Cat : Groupoid.{v u} ⥤ Cat.{v u} := { obj := λ C, Cat.of C.α, map := λ C D, id } instance forget_to_Cat_full : full forget_to_Cat := { preimage := λ C D, id } instance forget_to_Cat_faithful : faithful forget_to_Cat := { } end Groupoid end category_theory
e52047fd55dd608a7e7e7220077227cfb82b402c
b328e8ebb2ba923140e5137c83f09fa59516b793
/stage0/src/Lean/Server/Utils.lean
b8092c4a1521abb3412e04ed189a1c21cb891d70
[ "Apache-2.0" ]
permissive
DrMaxis/lean4
a781bcc095511687c56ab060e816fd948553e162
5a02c4facc0658aad627cfdcc3db203eac0cb544
refs/heads/master
1,677,051,517,055
1,611,876,226,000
1,611,876,226,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,883
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.Data.Position import Lean.Data.Lsp namespace IO def throwServerError (err : String) : IO α := throw (userError err) namespace FS.Stream /-- Chains two streams by creating a new stream s.t. writing to it just writes to `a` but reading from it also duplicates the read output into `b`, c.f. `a | tee b` on Unix. NB: if `a` is written to but this stream is never read from, the output will *not* be duplicated. Use this if you only care about the data that was actually read. -/ def chainRight (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { a with flush := a.flush *> b.flush read := fun sz => do let bs ← a.read sz b.write bs when flushEagerly b.flush pure bs getLine := do let ln ← a.getLine b.putStr ln when flushEagerly b.flush pure ln } /-- Like `tee a | b` on Unix. See `chainOut`. -/ def chainLeft (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { b with flush := a.flush *> b.flush write := fun bs => do a.write bs when flushEagerly a.flush b.write bs putStr := fun s => do a.putStr s when flushEagerly a.flush b.putStr s } /-- Prefixes all written outputs with `pre`. -/ def withPrefix (a : Stream) (pre : String) : Stream := { a with write := fun bs => do a.putStr pre a.write bs putStr := fun s => a.putStr (pre ++ s) } end FS.Stream end IO namespace Lean.Server structure DocumentMeta where uri : Lsp.DocumentUri version : Nat text : FileMap deriving Inhabited def replaceLspRange (text : FileMap) (r : Lsp.Range) (newText : String) : FileMap := let start := text.lspPosToUtf8Pos r.start let «end» := text.lspPosToUtf8Pos r.«end» let pre := text.source.extract 0 start let post := text.source.extract «end» text.source.bsize (pre ++ newText ++ post).toFileMap open IO /-- Duplicates an I/O stream to a log file `fName` in LEAN_SERVER_LOG_DIR if that envvar is set. -/ def maybeTee (fName : String) (isOut : Bool) (h : FS.Stream) : IO FS.Stream := do match (← IO.getEnv "LEAN_SERVER_LOG_DIR") with | none => pure h | some logDir => let hTee ← FS.Handle.mk (System.mkFilePath [logDir, fName]) FS.Mode.write true let hTee := FS.Stream.ofHandle hTee pure $ if isOut then hTee.chainLeft h true else h.chainRight hTee true open Lsp /-- Returns the document contents with all changes applied, together with the position of the change which lands earliest in the file. Panics if there are no changes. -/ def foldDocumentChanges (changes : @& Array Lsp.TextDocumentContentChangeEvent) (oldText : FileMap) : FileMap × String.Pos := if changes.isEmpty then panic! "Lean.Server.foldDocumentChanges: empty change array" else let accumulateChanges : FileMap × String.Pos → TextDocumentContentChangeEvent → FileMap × String.Pos := fun ⟨newDocText, minStartOff⟩ change => match change with | TextDocumentContentChangeEvent.rangeChange (range : Range) (newText : String) => let startOff := oldText.lspPosToUtf8Pos range.start let newDocText := replaceLspRange newDocText range newText let minStartOff := minStartOff.min startOff ⟨newDocText, minStartOff⟩ | TextDocumentContentChangeEvent.fullChange (newText : String) => ⟨newText.toFileMap, 0⟩ -- NOTE: We assume Lean files are below 16 EiB. changes.foldl accumulateChanges (oldText, 0xffffffff) end Lean.Server namespace List universe u def takeWhile (p : α → Bool) : List α → List α | [] => [] | hd :: tl => if p hd then hd :: takeWhile p tl else [] end List
01aedf5ba60fe70ebf76779b41541678e9c45b82
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/run/1468.lean
a824a40cb1ffed15dc75d8313742381bbf7fd441
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
293
lean
local infix * := _root_.mul namespace Y def mul : bool → bool := λ b, b example (m n : ℕ) : true := begin definev k : ℕ := m * n, definev a : bool := mul tt, trivial end end Y meta def is_mul : expr → option (expr × expr) | ```(%%a * %%b) := some (a, b) | _ := none
a1f7f9d763d94667e82e64a80caf3d6560b6c1d7
2fbe653e4bc441efde5e5d250566e65538709888
/src/data/list/basic.lean
6789cf3fdc3db920a47716afccc029b9502f2848
[ "Apache-2.0" ]
permissive
aceg00/mathlib
5e15e79a8af87ff7eb8c17e2629c442ef24e746b
8786ea6d6d46d6969ac9a869eb818bf100802882
refs/heads/master
1,649,202,698,930
1,580,924,783,000
1,580,924,783,000
149,197,272
0
0
Apache-2.0
1,537,224,208,000
1,537,224,207,000
null
UTF-8
Lean
false
false
220,514
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 logic.basic logic.function logic.relator algebra.group order.basic data.list.defs data.nat.basic data.option.basic data.bool data.prod 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 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 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] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[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] /- length -/ 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 ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] := λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l := λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ lemma exists_of_length_succ {n} : ∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t | [] H := absurd H.symm $ succ_ne_zero n | (h :: t) H := ⟨h, t, rfl⟩ lemma injective_length_iff : injective (list.length : list α → ℕ) ↔ subsingleton α := begin split, { intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, { refl }, { cases hl }, { cases hl }, congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } end lemma injective_length [subsingleton α] : injective (length : list α → ℕ) := injective_length_iff.mpr $ by apply_instance /- set-theoretic notation of lists -/ lemma empty_eq : (∅ : list α) = [] := by refl lemma singleton_eq [decidable_eq α] (x : α) : ({x} : list α) = [x] := by refl lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) : has_insert.insert x l = x :: l := if_neg h lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) : has_insert.insert x l = l := if_pos h lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [y, x] := by { rw [insert_neg, singleton_eq], show y ∉ [x], rw [mem_singleton], exact h.symm } /- 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_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_append_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 append_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 _) @[simp] theorem append_subset_iff {l₁ l₂ l : list α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := begin split, { intro h, simp only [subset_def] at *, split; intros; simp* }, { rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 } end 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⟩ theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := begin refine ⟨_, map_subset f⟩, intros h2 x hx, rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, cases h hxx', exact hx' end /- 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]] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } /- 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} /- 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_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_append_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_append_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 append_sublist_append {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (append_sublist_append_of_sublist_right hl _).trans ((append_sublist_append_left _).2 hr) 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_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_len_le (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_len_le 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 /-- A version of `nth_le_map` that can be used for rewriting. -/ theorem nth_le_map_rev (f : α → β) {l n} (H) : f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) := (nth_le_map f _ _).symm @[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 _ _ lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length := begin rw list.length_append at h₂, convert (nat.sub_lt_sub_right_iff h₁).mpr h₂, simp, end lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂), (l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂) | [] _ n h₁ h₂ := rfl | (a :: l) _ (n+1) h₁ h₂ := begin dsimp, conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], }, rw nth_le_append_right (nat.lt_succ_iff.mp h₁), end @[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] lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos) | [] h := rfl | [a] h := by rw [last_singleton, nth_le_singleton] | (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)], refl, exact cons_ne_nil b l } @[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] @[ext] 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_len_le h₁, nth_len_le], 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) lemma index_of_inj [decidable_eq α] {l : list α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := ⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) = nth_le l (index_of y l) (index_of_lt_length.2 hy), by simp only [h], by simpa only [index_of_nth_le], λ h, by subst h⟩ 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] @[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α) (h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a := by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at * @[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α) (hj : j < (l.update_nth i a).length) : (l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) := by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth] lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α} (h : a ∈ l.update_nth n b), a ∈ l ∨ a = b | [] n a b h := false.elim h | (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim or.inr (or.inl ∘ mem_cons_of_mem _) | (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim (λ h, h ▸ or.inl (mem_cons_self _ _)) (λ h, (mem_or_eq_of_mem_update_nth h).elim (or.inl ∘ mem_cons_of_mem _) or.inr) 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₁) lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length), a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l | 0 as h := iff.rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := begin dsimp [list.insert_nth], erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff, ← or.assoc, or_comm (a = a'), or.assoc] end end insert_nth /- 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₂] lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) := begin refine ⟨_, map_congr⟩, intros h x hx, rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩, rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h end 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 (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α) (h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) := eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] } theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α) (h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op 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 @[simp] theorem injective_map_iff {f : α → β} : injective (map f) ↔ injective f := begin split; intros h x y hxy, { suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] }, { induction y generalizing x, simpa using hxy, cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] } end /- 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 /- 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_le : ∀ {n} {l : list α}, length l ≤ n → 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_le (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 /- scanl -/ lemma length_scanl {β : Type*} {f : α → β → α} : ∀ a l, length (scanl f a l) = l.length + 1 | a [] := rfl | a (x :: l) := by erw [length_cons, length_cons, length_scanl] /- 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 foldl_eq_foldlr' variables {f : α → β → α} variables hf : ∀ a b c, f (f a b) c = f (f a c) b include hf theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b | a b [] := rfl | a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf] theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l | a [] := rfl | a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl end foldl_eq_foldlr' section foldl_eq_foldlr' variables {f : α → β → β} variables hf : ∀ a b c, f a (f b c) = f b (f a c) include hf theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l | a b [] := rfl | a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl end foldl_eq_foldlr' 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 /- prod and sum -/ -- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet. attribute [to_additive] list.prod section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive] theorem prod_nil : ([] : list α).prod = 1 := rfl @[simp, to_additive] 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] 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] 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]] @[to_additive] theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (l.map f).prod (l.map g).prod := list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl]) @[to_additive] theorem prod_hom [monoid β] (l : list α) (f : α → β) [is_monoid_hom f] : (l.map f).prod = f l.prod := by { simp only [prod, foldl_map, (is_monoid_hom.map_one f).symm], exact l.foldl_hom _ _ _ 1 (is_monoid_hom.map_mul f) } end monoid @[simp, to_additive] 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]] theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum := begin induction l with x l ih, { exact dvd_zero _ }, { rw [list.sum_cons], exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) } end @[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] lemma exists_lt_of_sum_lt [decidable_linear_ordered_cancel_comm_monoid β] {l : list α} (f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x := begin induction l with x l, { exfalso, exact lt_irrefl _ h }, { by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) } end lemma exists_le_of_sum_le [decidable_linear_ordered_cancel_comm_monoid β] {l : list α} (hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x := begin cases l with x l, { contradiction }, { by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩, exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) } end /- 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⟩ @[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l []. 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] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) : @filter α (λ _, true) h l = l := by convert filter_eq_self.2 (λ _ _, trivial) @[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) : @filter α (λ _, false) h l = [] := by convert filter_eq_nil.2 (λ _ _, id) @[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_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } 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) /- sublists_len -/ def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β | 0 l f r := f [] :: r | (n+1) [] f r := r | (n+1) (a::l) f r := sublists_len_aux (n + 1) l f (sublists_len_aux n l (f ∘ list.cons a) r) def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) := sublists_len_aux n l id [] lemma sublists_len_aux_append {α β γ : Type*} : ∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ), sublists_len_aux n l (g ∘ f) (r.map g ++ s) = (sublists_len_aux n l f r).map g ++ s | 0 l f g r s := rfl | (n+1) [] f g r s := rfl | (n+1) (a::l) f g r s := begin unfold sublists_len_aux, rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl, sublists_len_aux_append, sublists_len_aux_append] end lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) : sublists_len_aux n l f r = (sublists_len n l).map f ++ r := by rw [sublists_len, ← sublists_len_aux_append]; refl lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) : sublists_len_aux 0 l f r = f [] :: r := by cases l; refl @[simp] lemma sublists_len_zero {α : Type*} (l : list α) : sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _ @[simp] lemma sublists_len_succ_nil {α : Type*} (n) : sublists_len (n+1) (@nil α) = [] := rfl @[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) : sublists_len (n + 1) (a::l) = sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) := by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq, sublists_len_aux_eq, map_id, append_nil]; refl @[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α), length (sublists_len n l) = nat.choose (length l) n | 0 l := by simp | (n+1) [] := by simp | (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α), sublists_len n l <+ sublists' l | 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _)) | (n+1) [] := nil_sublist _ | (n+1) (a::l) := begin rw [sublists_len_succ_cons, sublists'_cons], exact append_sublist_append (sublists_len_sublist_sublists' _ _) (map_sublist_map _ (sublists_len_sublist_sublists' _ _)) end lemma sublists_len_sublist_of_sublist {α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl}, { refine IH.trans _, rw sublists_len_succ_cons, apply sublist_append_left }, { simp [sublists_len_succ_cons], exact append_sublist_append IH (map_sublist_map _ (IHn s)) } end lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α}, l' ∈ sublists_len n l → length l' = n | 0 l l' (or.inl rfl) := rfl | (n+1) (a::l) l' h := begin rw [sublists_len_succ_cons, mem_append, mem_map] at h, rcases h with h | ⟨l', h, rfl⟩, { exact length_of_sublists_len h }, { exact congr_arg (+1) (length_of_sublists_len h) }, end lemma mem_sublists_len_self {α : Type*} {l l' : list α} (h : l' <+ l) : l' ∈ sublists_len (length l') l := begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH, { exact or.inl rfl }, { cases l₁ with b l₁, { exact or.inl rfl }, { rw [length, sublists_len_succ_cons], exact mem_append_left _ IH } }, { rw [length, sublists_len_succ_cons], exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) } end @[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} : l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n := ⟨λ h, ⟨mem_sublists'.1 (subset_of_sublist (sublists_len_sublist_sublists' _ _) h), length_of_sublists_len h⟩, λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩ /- forall₂ -/ section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} open relator 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 : ((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] lemma rel_prod [monoid α] [monoid β] (h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod := rel_foldl 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 : α} {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 : α} {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 (p : α → Prop) [decidable_pred p] (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 p 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 p 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, *]] @[simp] theorem count_erase_self (a : α) : ∀ (s : list α), count a (list.erase s a) = pred (count a s) | [] := by simp | (h :: t) := begin rw erase_cons, by_cases p : h = a, { rw [if_pos p, count_cons', if_pos p.symm], simp }, { rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self], simp, } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) : ∀ (s : list α), count a (list.erase s b) = count a s | [] := by simp | (x :: xs) := begin rw erase_cons, split_ifs with h, { rw [count_cons', h, if_neg ab], simp }, { rw [count_cons', count_cons', count_erase_of_ne] } end 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) using_well_founded wf_tacs 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 _ theorem mem_enum_from {x : α} {i : ℕ} : Π {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs | j [] := by simp [enum_from] | j (y :: ys) := by { simp [enum_from,mem_enum_from ys], rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply lt_of_lt_of_le (nat.lt_add_of_pos_right zero_lt_one), apply nat.add_le_add_left, apply nat.le_add_right }, { replace h := mem_enum_from _ h, simp at h, revert h, apply and_implies _ (and_implies id or.inr), intro h, transitivity j+1, apply nat.le_add_right, exact h } } /- 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 @[simp] 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 @[simp] theorem count_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, count a (l₁.bag_inter l₂) = min (count a l₁) (count a l₂) | [] l₂ := by simp | l₁ [] := by simp | (h₁ :: l₁) (h₂ :: l₂) := begin simp only [list.bag_inter, list.mem_cons_iff], by_cases p₁ : h₂ = h₁; by_cases p₂ : h₁ = a, { simp only [p₁, p₂, count_bag_inter, min_succ_succ, erase_cons_head, if_true, mem_cons_iff, count_cons_self, true_or, eq_self_iff_true] }, { simp only [p₁, ne.symm p₂, count_bag_inter, count_cons, erase_cons_head, if_true, mem_cons_iff, true_or, eq_self_iff_true, if_false] }, { rw p₂ at p₁, by_cases p₃ : a ∈ l₂, { simp only [p₁, ne.symm p₁, p₂, p₃, erase_cons, count_bag_inter, eq.symm (min_succ_succ _ _), succ_pred_eq_of_pos (count_pos.2 p₃), if_true, mem_cons_iff, false_or, count_cons_self, eq_self_iff_true, if_false, ne.def, not_false_iff, count_erase_self, list.count_cons_of_ne] }, { simp [ne.symm p₁, p₂, p₃] } }, { by_cases p₄ : h₁ ∈ l₂; simp only [ne.symm p₁, ne.symm p₂, p₄, count_bag_inter, if_true, if_false, mem_cons_iff, false_or, eq_self_iff_true, ne.def, not_false_iff,count_erase_of_ne, count_cons_of_ne] } 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 theorem bag_inter_nil_iff_inter_nil : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ = [] ↔ l₁ ∩ l₂ = [] | [] l₂ := by simp | (b::l₁) l₂ := begin by_cases h : b ∈ l₂; simp [h], exact bag_inter_nil_iff_inter_nil l₁ l₂ 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_append_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_append_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_map (f : β → α) : Π (l : list β), pw_filter R (map f l) = map f (pw_filter (λ x y, R (f x) (f y)) l) | [] := rfl | (x :: xs) := if h : ∀ b ∈ pw_filter R (map f xs), R (f x) b then have h' : ∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ b hb, h _ (by rw [pw_filter_map]; apply mem_map_of_mem _ hb), by rw [map,pw_filter_cons_of_pos h,pw_filter_cons_of_pos h',pw_filter_map,map] else have h' : ¬∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ hh, h $ λ a ha, by { rw [pw_filter_map,mem_map] at ha, rcases ha with ⟨b,hb₀,hb₁⟩, subst a, exact hh _ hb₀, }, by rw [map,pw_filter_cons_of_neg h,pw_filter_cons_of_neg h',pw_filter_map] 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 : ∀ {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_append_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 nodup_diff [decidable_eq α] : ∀ {l₁ l₂ : list α} (h : l₁.nodup), (l₁.diff l₂).nodup | l₁ [] h := h | l₁ (a::l₂) h := by rw diff_cons; exact nodup_diff (nodup_erase_of_nodup _ h) 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] lemma nodup_sublists_len {α : Type*} (n) {l : list α} (nd : nodup l) : (sublists_len n l).nodup := nodup_of_sublist (sublists_len_sublist_sublists' _ _) (nodup_sublists'.2 nd) lemma diff_eq_filter_of_nodup [decidable_eq α] : ∀ {l₁ l₂ : list α} (hl₁ : l₁.nodup), l₁.diff l₂ = l₁.filter (∉ l₂) | l₁ [] hl₁ := by simp | l₁ (a::l₂) hl₁ := begin rw [diff_cons, diff_eq_filter_of_nodup (nodup_erase_of_nodup _ hl₁), nodup_erase_eq_filter _ hl₁, filter_filter], simp only [mem_cons_iff, not_or_distrib, and.comm], congr end lemma mem_diff_iff_of_nodup [decidable_eq α] {l₁ l₂ : list α} (hl₁ : l₁.nodup) {a : α} : a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ := by rw [diff_eq_filter_of_nodup hl₁, mem_filter] lemma nodup_update_nth : ∀ {l : list α} {n : ℕ} {a : α} (hl : l.nodup) (ha : a ∉ l), (l.update_nth n a).nodup | [] n a hl ha := nodup_nil | (b::l) 0 a hl ha := nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩ | (b::l) (n+1) a hl ha := nodup_cons.2 ⟨λ h, (mem_or_eq_of_mem_update_nth h).elim (nodup_cons.1 hl).1 (λ hba, ha (hba ▸ mem_cons_self _ _)), nodup_update_nth (nodup_cons.1 hl).2 (mt (mem_cons_of_mem _) ha)⟩ 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 map_sub_range' (a) : ∀ (s n : ℕ) (h : a ≤ s), map (λ x, x - a) (range' s n) = range' (s - a) n | s 0 _ := rfl | s (n+1) h := begin convert congr_arg (cons (s-a)) (map_sub_range' (s+1) n (nat.le_succ_of_le h)), rw nat.succ_sub h, refl, end 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) @[simp] 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 (succ n) = 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 /-- All elements of `fin n`, from `0` to `n-1`. -/ def fin_range (n : ℕ) : list (fin n) := (range n).pmap fin.mk (λ _, list.mem_range.1) @[simp] lemma mem_fin_range {n : ℕ} (a : fin n) : a ∈ fin_range n := mem_pmap.2 ⟨a.1, mem_range.2 a.2, fin.eta _ _⟩ lemma nodup_fin_range (n : ℕ) : (fin_range n).nodup := nodup_pmap (λ _ _ _ _, fin.veq_of_eq) (nodup_range _) @[simp] lemma length_fin_range (n : ℕ) : (fin_range n).length = n := by rw [fin_range, length_pmap, length_range] @[to_additive] theorem prod_range_succ {α : Type u} [monoid α] (f : ℕ → α) (n : ℕ) : ((range n.succ).map f).prod = ((range n).map f).prod * f n := by rw [range_concat, map_append, map_singleton, prod_append, prod_cons, prod_nil, mul_one] /-- `Ico n m` is the list of natural numbers `n ≤ x < m`. (Ico stands for "interval, closed-open".) See also `data/set/intervals.lean` for `set.Ico`, modelling intervals in general preorders, and `multiset.Ico` and `finset.Ico` for `n ≤ x < m` as a multiset or as a finset. @TODO (anyone): Define `Ioo` and `Icc`, state basic lemmas about them. @TODO (anyone): Prove that `finset.Ico` and `set.Ico` agree. @TODO (anyone): Also do the versions for integers? @TODO (anyone): One could generalise even further, defining 'locally finite partial orders', for which `set.Ico a b` is `[finite]`, and 'locally finite total orders', for which there is a list model. -/ def Ico (n m : ℕ) : list ℕ := range' n (m - n) namespace Ico theorem zero_bot (n : ℕ) : Ico 0 n = range n := by rw [Ico, nat.sub_zero, range_eq_range'] @[simp] theorem length (n m : ℕ) : length (Ico n m) = m - n := by dsimp [Ico]; simp only [length_range'] theorem pairwise_lt (n m : ℕ) : pairwise (<) (Ico n m) := by dsimp [Ico]; simp only [pairwise_lt_range'] theorem nodup (n m : ℕ) : nodup (Ico n m) := by dsimp [Ico]; simp only [nodup_range'] @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := suffices n ≤ l ∧ l < n + (m - n) ↔ n ≤ l ∧ l < m, by simp [Ico, this], begin cases le_total n m with hnm hmn, { rw [nat.add_sub_of_le hnm] }, { rw [nat.sub_eq_zero_of_le hmn, add_zero], exact and_congr_right (assume hnl, iff.intro (assume hln, (not_le_of_gt hln hnl).elim) (assume hlm, lt_of_lt_of_le hlm hmn)) } end theorem eq_nil_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = [] := by simp [Ico, nat.sub_eq_zero_of_le h] theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := by rw [Ico, Ico, map_add_range', nat.add_sub_add_right, add_comm n k] theorem map_sub (n m k : ℕ) (h₁ : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := begin by_cases h₂ : n < m, { rw [Ico, Ico], rw nat.sub_sub_sub_cancel_right h₁, rw [map_sub_range' _ _ _ h₁] }, { simp at h₂, rw [eq_nil_of_le h₂], rw [eq_nil_of_le (nat.sub_le_sub_right h₂ _)], refl } end @[simp] theorem self_empty {n : ℕ} : Ico n n = [] := eq_nil_of_le (le_refl n) @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = [] ↔ m ≤ n := iff.intro (assume h, nat.le_of_sub_eq_zero $ by rw [← length, h]; refl) eq_nil_of_le lemma append_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ++ Ico m l = Ico n l := begin dunfold Ico, convert range'_append _ _ _, { exact (nat.add_sub_of_le hnm).symm }, { rwa [← nat.add_sub_assoc hnm, nat.sub_add_cancel] } end @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = [] := begin apply eq_nil_iff_forall_not_mem.2, intro a, simp only [and_imp, not_and, not_lt, list.mem_inter, list.Ico.mem], intros h₁ h₂ h₃, exfalso, exact not_lt_of_ge h₃ h₂ end @[simp] lemma bag_inter_consecutive (n m l : ℕ) : list.bag_inter (Ico n m) (Ico m l) = [] := (bag_inter_nil_iff_inter_nil _ _).2 (inter_consecutive n m l) @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = [n] := by dsimp [Ico]; simp [nat.add_sub_cancel_left] theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = Ico n m ++ [m] := by rwa [← succ_singleton, append_consecutive]; exact nat.le_succ _ theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := by rw [← append_consecutive (nat.le_succ n) h, succ_singleton]; refl @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = [m - 1] := by dsimp [Ico]; rw nat.sub_sub_self h; simp theorem chain'_succ (n m : ℕ) : chain' (λa b, b = succ a) (Ico n m) := begin by_cases n < m, { rw [eq_cons h], exact chain_succ_range' _ _ }, { rw [eq_nil_of_le (le_of_not_gt h)], trivial } end @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := by simp; intros; refl lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := filter_eq_self.2 $ assume k hk, lt_of_lt_of_le (mem.1 hk).2 hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = [] := filter_eq_nil.2 $ assume k hk, not_lt_of_le $ le_trans hln $ (mem.1 hk).1 lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := begin cases le_total n l with hnl hln, { rw [← append_consecutive hnl hlm, filter_append, filter_lt_of_top_le (le_refl l), filter_lt_of_le_bot (le_refl l), append_nil] }, { rw [eq_nil_of_le hln, filter_lt_of_le_bot hln] } end @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := begin cases le_total m l with hml hlm, { rw [min_eq_left hml, filter_lt_of_top_le hml] }, { rw [min_eq_right hlm, filter_lt_of_ge hlm] } end lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := filter_eq_self.2 $ assume k hk, le_trans hln (mem.1 hk).1 lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = [] := filter_eq_nil.2 $ assume k hk, not_le_of_gt (lt_of_lt_of_le (mem.1 hk).2 hml) lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := begin cases le_total l m with hlm hml, { rw [← append_consecutive hnl hlm, filter_append, filter_le_of_top_le (le_refl l), filter_le_of_le_bot (le_refl l), nil_append] }, { rw [eq_nil_of_le hml, filter_le_of_top_le hml] } end @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (_root_.max n l) m := begin cases le_total n l with hnl hln, { rw [max_eq_right hnl, filter_le_of_le hnl] }, { rw [max_eq_left hln, filter_le_of_le_bot hln] } end end Ico @[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 ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (ilast'_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, -eq_iff_iff] 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) → (ilast' b l → a) → tfae (a::b::l) := begin induction l with c l IH generalizing a b; simp only [tfae_cons_cons, tfae_singleton, and_true, chain_cons, chain.nil] at *, { intros a b, exact iff.intro a b }, rintros ⟨ab,⟨bc,ch⟩⟩ la, have := IH ⟨bc,ch⟩ (ab ∘ la), exact ⟨⟨ab, la ∘ (this.2 c (or.inl rfl) _ (ilast'_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 mem_rotate : ∀ {l : list α} {a : α} {n : ℕ}, a ∈ l.rotate n ↔ a ∈ l | [] _ n := by simp | (a::l) _ 0 := by simp | (a::l) _ (n+1) := by simp [rotate_cons_succ, mem_rotate, or.comm] @[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 namespace func variables {a : α} variables {as as1 as2 as3 : list α} localized "notation as ` {` m ` ↦ ` a `}` := list.func.set a as m" in list.func /- set -/ lemma length_set [inhabited α] : ∀ {m : ℕ} {as : list α}, (as {m ↦ a}).length = _root_.max as.length (m+1) | 0 [] := rfl | 0 (a::as) := by {rw max_eq_left, refl, simp [nat.le_add_right]} | (m+1) [] := by simp only [set, nat.zero_max, length, @length_set m] | (m+1) (a::as) := by simp only [set, nat.max_succ_succ, length, @length_set m] @[simp] lemma get_nil [inhabited α] {k : ℕ} : get k [] = default α := by {cases k; refl} lemma get_eq_default_of_le [inhabited α] : ∀ (k : ℕ) {as : list α}, as.length ≤ k → get k as = default α | 0 [] h1 := rfl | 0 (a::as) h1 := by cases h1 | (k+1) [] h1 := rfl | (k+1) (a::as) h1 := begin apply get_eq_default_of_le k, rw ← nat.succ_le_succ_iff, apply h1, end @[simp] lemma get_set [inhabited α] {a : α} : ∀ {k : ℕ} {as : list α}, get k (as {k ↦ a}) = a | 0 as := by {cases as; refl, } | (k+1) as := by {cases as; simp [get_set]} lemma eq_get_of_mem [inhabited α] {a : α} : ∀ {as : list α}, a ∈ as → ∃ n : nat, ∀ d : α, a = (get n as) | [] h := by cases h | (b::as) h := begin rw mem_cons_iff at h, cases h, { existsi 0, intro d, apply h }, { cases eq_get_of_mem h with n h2, existsi (n+1), apply h2 } end lemma mem_get_of_le [inhabited α] : ∀ {n : ℕ} {as : list α}, n < as.length → get n as ∈ as | _ [] h1 := by cases h1 | 0 (a::as) _ := or.inl rfl | (n+1) (a::as) h1 := begin apply or.inr, unfold get, apply mem_get_of_le, apply nat.lt_of_succ_lt_succ h1, end lemma mem_get_of_ne_zero [inhabited α] : ∀ {n : ℕ} {as : list α}, get n as ≠ default α → get n as ∈ as | _ [] h1 := begin exfalso, apply h1, rw get_nil end | 0 (a::as) h1 := or.inl rfl | (n+1) (a::as) h1 := begin unfold get, apply (or.inr (mem_get_of_ne_zero _)), apply h1 end lemma get_set_eq_of_ne [inhabited α] {a : α} : ∀ {as : list α} (k : ℕ) (m : ℕ), m ≠ k → get m (as {k ↦ a}) = get m as | as 0 m h1 := by { cases m, contradiction, cases as; simp only [set, get, get_nil] } | as (k+1) m h1 := begin cases as; cases m, simp only [set, get], { have h3 : get m (nil {k ↦ a}) = default α, { rw [get_set_eq_of_ne k m, get_nil], intro hc, apply h1, simp [hc] }, apply h3 }, simp only [set, get], { apply get_set_eq_of_ne k m, intro hc, apply h1, simp [hc], } end lemma get_map [inhabited α] [inhabited β] {f : α → β} : ∀ {n : ℕ} {as : list α}, n < as.length → get n (as.map f) = f (get n as) | _ [] h := by cases h | 0 (a::as) h := rfl | (n+1) (a::as) h1 := begin have h2 : n < length as, { rw [← nat.succ_le_iff, ← nat.lt_succ_iff], apply h1 }, apply get_map h2, end lemma get_map' [inhabited α] [inhabited β] {f : α → β} {n : ℕ} {as : list α} : f (default α) = (default β) → get n (as.map f) = f (get n as) := begin intro h1, by_cases h2 : n < as.length, { apply get_map h2, }, { rw not_lt at h2, rw [get_eq_default_of_le _ h2, get_eq_default_of_le, h1], rw [length_map], apply h2 } end lemma forall_val_of_forall_mem [inhabited α] {as : list α} {p : α → Prop} : p (default α) → (∀ x ∈ as, p x) → (∀ n, p (get n as)) := begin intros h1 h2 n, by_cases h3 : n < as.length, { apply h2 _ (mem_get_of_le h3) }, { rw not_lt at h3, rw get_eq_default_of_le _ h3, apply h1 } end /- equiv -/ lemma equiv_refl [inhabited α] : equiv as as := λ k, rfl lemma equiv_symm [inhabited α] : equiv as1 as2 → equiv as2 as1 := λ h1 k, (h1 k).symm lemma equiv_trans [inhabited α] : equiv as1 as2 → equiv as2 as3 → equiv as1 as3 := λ h1 h2 k, eq.trans (h1 k) (h2 k) lemma equiv_of_eq [inhabited α] : as1 = as2 → equiv as1 as2 := begin intro h1, rw h1, apply equiv_refl end lemma eq_of_equiv [inhabited α] : ∀ {as1 as2 : list α}, as1.length = as2.length → equiv as1 as2 → as1 = as2 | [] [] h1 h2 := rfl | (_::_) [] h1 h2 := by cases h1 | [] (_::_) h1 h2 := by cases h1 | (a1::as1) (a2::as2) h1 h2 := begin congr, { apply h2 0 }, have h3 : as1.length = as2.length, { simpa [add_left_inj, add_comm, length] using h1 }, apply eq_of_equiv h3, intro m, apply h2 (m+1) end /- neg -/ @[simp] lemma get_neg [inhabited α] [add_group α] {k : ℕ} {as : list α} : @get α ⟨0⟩ k (neg as) = -(@get α ⟨0⟩ k as) := by {unfold neg, rw (@get_map' α α ⟨0⟩), apply neg_zero} @[simp] lemma length_neg [inhabited α] [has_neg α] (as : list α) : (neg as).length = as.length := by simp only [neg, length_map] /- pointwise -/ lemma nil_pointwise [inhabited α] [inhabited β] {f : α → β → γ} : ∀ bs : list β, pointwise f [] bs = bs.map (f $ default α) | [] := rfl | (b::bs) := by simp only [nil_pointwise bs, pointwise, eq_self_iff_true, and_self, map] lemma pointwise_nil [inhabited α] [inhabited β] {f : α → β → γ} : ∀ as : list α, pointwise f as [] = as.map (λ a, f a $ default β) | [] := rfl | (a::as) := by simp only [pointwise_nil as, pointwise, eq_self_iff_true, and_self, list.map] lemma get_pointwise [inhabited α] [inhabited β] [inhabited γ] {f : α → β → γ} (h1 : f (default α) (default β) = default γ) : ∀ (k : nat) (as : list α) (bs : list β), get k (pointwise f as bs) = f (get k as) (get k bs) | k [] [] := by simp only [h1, get_nil, pointwise, get] | 0 [] (b::bs) := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) [] (b::bs) := by { have : get k (map (f $ default α) bs) = f (default α) (get k bs), { simpa [nil_pointwise, get_nil] using (get_pointwise k [] bs) }, simpa [get, get_nil, pointwise, map] } | 0 (a::as) [] := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) (a::as) [] := by simpa [get, get_nil, pointwise, map, pointwise_nil, get_nil] using get_pointwise k as [] | 0 (a::as) (b::bs) := by simp only [pointwise, get] | (k+1) (a::as) (b::bs) := by simp only [pointwise, get, get_pointwise k] lemma length_pointwise [inhabited α] [inhabited β] {f : α → β → γ} : ∀ {as : list α} {bs : list β}, (pointwise f as bs).length = _root_.max as.length bs.length | [] [] := rfl | [] (b::bs) := by simp only [pointwise, length, length_map, max_eq_right (nat.zero_le (length bs + 1))] | (a::as) [] := by simp only [pointwise, length, length_map, max_eq_left (nat.zero_le (length as + 1))] | (a::as) (b::bs) := by simp only [pointwise, length, nat.max_succ_succ, @length_pointwise as bs] /- add -/ @[simp] lemma get_add {α : Type u} [add_monoid α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (add xs ys) = ( @get α ⟨0⟩ k xs + @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply zero_add} @[simp] lemma length_add {α : Type u} [has_zero α] [has_add α] {xs ys : list α} : (add xs ys).length = _root_.max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_add {α : Type u} [add_monoid α] (as : list α) : add [] as = as := begin rw [add, @nil_pointwise α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, zero_add], refl end @[simp] lemma add_nil {α : Type u} [add_monoid α] (as : list α) : add as [] = as := begin rw [add, @pointwise_nil α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, add_zero], refl end lemma map_add_map {α : Type u} [add_monoid α] (f g : α → α) {as : list α} : add (as.map f) (as.map g) = as.map (λ x, f x + g x) := begin apply @eq_of_equiv _ (⟨0⟩ : inhabited α), { rw [length_map, length_add, max_eq_left, length_map], apply le_of_eq, rw [length_map, length_map] }, intros m, rw [get_add], by_cases h : m < length as, { repeat {rw [@get_map α α ⟨0⟩ ⟨0⟩ _ _ _ h]} }, rw not_lt at h, repeat {rw [get_eq_default_of_le m]}; try {rw length_map, apply h}, apply zero_add end /- sub -/ @[simp] lemma get_sub {α : Type u} [add_group α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (sub xs ys) = (@get α ⟨0⟩ k xs - @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply sub_zero} @[simp] lemma length_sub [has_zero α] [has_sub α] {xs ys : list α} : (sub xs ys).length = _root_.max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_sub {α : Type} [add_group α] (as : list α) : sub [] as = neg as := begin rw [sub, nil_pointwise], congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, zero_sub] end @[simp] lemma sub_nil {α : Type} [add_group α] (as : list α) : sub as [] = as := begin rw [sub, pointwise_nil], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, sub_zero], refl end end func namespace nat /-- The antidiagonal of a natural number `n` is the list of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : list (ℕ × ℕ) := (range (n+1)).map (λ i, (i, n - i)) /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := begin rw [antidiagonal, mem_map], split, { rintros ⟨i, hi, rfl⟩, rw [mem_range, lt_succ_iff] at hi, exact add_sub_of_le hi }, { rintro rfl, refine ⟨x.fst, _, _⟩, { rw [mem_range, add_assoc, lt_add_iff_pos_right], exact zero_lt_succ _ }, { exact prod.ext rfl (nat.add_sub_cancel_left _ _) } } end /-- The length of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma length_antidiagonal (n : ℕ) : (antidiagonal n).length = n+1 := by rw [antidiagonal, length_map, length_range] /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = [(0, 0)] := ext_le (length_antidiagonal 0) $ λ n h₁ h₂, begin rw [length_antidiagonal, lt_succ_iff, le_zero_iff] at h₁, subst n, simp [antidiagonal] end /-- The antidiagonal of `n` does not contain duplicate entries. -/ lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := nodup_map (@injective_of_left_inverse ℕ (ℕ × ℕ) prod.fst (λ i, (i, n-i)) $ λ i, rfl) (nodup_range _) end nat end list theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup | none := list.nodup_nil | (some x) := list.nodup_singleton x @[to_additive] theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) : f l.prod = (l.map f).prod := (l.prod_hom f).symm
2800710c65b9683470f1452fab28e5c91e0ea42b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/set/pairwise.lean
c384054eb6531ee6759f88b02a37192a788a529b
[ "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
13,774
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 data.set.lattice /-! # Relations holding pairwise This file defines pairwise relations and pairwise disjoint indexed sets. ## Main declarations * `pairwise`: `pairwise r` states that `r i j` for all `i ≠ j`. * `set.pairwise`: `s.pairwise r` states that `r i j` for all `i ≠ j` with `i, j ∈ s`. * `set.pairwise_disjoint`: `s.pairwise_disjoint f` states that images under `f` of distinct elements of `s` are either equal or `disjoint`. -/ open set variables {α ι ι' : Type*} {r p q : α → α → Prop} section pairwise variables {f : ι → α} {s t u : set α} {a b : α} /-- A relation `r` holds pairwise if `r i j` for all `i ≠ j`. -/ def pairwise (r : α → α → Prop) := ∀ i j, i ≠ j → r i j lemma pairwise.mono (hr : pairwise r) (h : ∀ ⦃i j⦄, r i j → p i j) : pairwise p := λ i j hij, h $ hr i j hij lemma pairwise_on_bool (hr : symmetric r) {a b : α} : pairwise (r on (λ c, cond c a b)) ↔ r a b := by simpa [pairwise, function.on_fun] using @hr a b lemma pairwise_disjoint_on_bool [semilattice_inf_bot α] {a b : α} : pairwise (disjoint on (λ c, cond c a b)) ↔ disjoint a b := pairwise_on_bool disjoint.symm lemma symmetric.pairwise_on [linear_order ι] (hr : symmetric r) (f : ι → α) : pairwise (r on f) ↔ ∀ m n, m < n → r (f m) (f n) := ⟨λ h m n hmn, h m n hmn.ne, λ h m n hmn, begin obtain hmn' | hmn' := hmn.lt_or_lt, { exact h _ _ hmn' }, { exact hr (h _ _ hmn') } end⟩ lemma pairwise_disjoint_on [semilattice_inf_bot α] [linear_order ι] (f : ι → α) : pairwise (disjoint on f) ↔ ∀ m n, m < n → disjoint (f m) (f n) := symmetric.pairwise_on disjoint.symm f namespace set /-- The relation `r` holds pairwise on the set `s` if `r x y` for all *distinct* `x y ∈ s`. -/ protected def pairwise (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y lemma pairwise_of_forall (s : set α) (r : α → α → Prop) (h : ∀ a b, r a b) : s.pairwise r := λ a _ b _ _, h a b lemma pairwise.imp_on (h : s.pairwise r) (hrp : s.pairwise (λ ⦃a b : α⦄, r a b → p a b)) : s.pairwise p := λ a ha b hb hab, hrp a ha b hb hab (h a ha b hb hab) lemma pairwise.imp (h : s.pairwise r) (hpq : ∀ ⦃a b : α⦄, r a b → p a b) : s.pairwise p := h.imp_on $ pairwise_of_forall s _ hpq lemma pairwise.mono (h : t ⊆ s) (hs : s.pairwise r) : t.pairwise r := λ x xt y yt, hs x (h xt) y (h yt) lemma pairwise.mono' (H : r ≤ p) (hr : s.pairwise r) : s.pairwise p := hr.imp H lemma pairwise_top (s : set α) : s.pairwise ⊤ := pairwise_of_forall s _ (λ a b, trivial) protected lemma subsingleton.pairwise (h : s.subsingleton) (r : α → α → Prop) : s.pairwise r := λ x hx y hy hne, (hne (h hx hy)).elim @[simp] lemma pairwise_empty (r : α → α → Prop) : (∅ : set α).pairwise r := subsingleton_empty.pairwise r @[simp] lemma pairwise_singleton (a : α) (r : α → α → Prop) : set.pairwise {a} r := subsingleton_singleton.pairwise r lemma nonempty.pairwise_iff_exists_forall [is_equiv α r] {s : set ι} (hs : s.nonempty) : (s.pairwise (r on f)) ↔ ∃ z, ∀ x ∈ s, r (f x) z := begin fsplit, { rcases hs with ⟨y, hy⟩, refine λ H, ⟨f y, λ x hx, _⟩, rcases eq_or_ne x y with rfl|hne, { apply is_refl.refl }, { exact H _ hx _ hy hne } }, { rintro ⟨z, hz⟩ x hx y hy hne, exact @is_trans.trans α r _ (f x) z (f y) (hz _ hx) (is_symm.symm _ _ $ hz _ hy) } end /-- For a nonempty set `s`, a function `f` takes pairwise equal values on `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `set.pairwise_eq_iff_exists_eq` for a version that assumes `[nonempty ι]` instead of `set.nonempty s`. -/ lemma nonempty.pairwise_eq_iff_exists_eq {s : set α} (hs : s.nonempty) {f : α → ι} : (s.pairwise (λ x y, f x = f y)) ↔ ∃ z, ∀ x ∈ s, f x = z := hs.pairwise_iff_exists_forall lemma pairwise_iff_exists_forall [nonempty ι] (s : set α) (f : α → ι) {r : ι → ι → Prop} [is_equiv ι r] : (s.pairwise (r on f)) ↔ ∃ z, ∀ x ∈ s, r (f x) z := begin rcases s.eq_empty_or_nonempty with rfl|hne, { simp }, { exact hne.pairwise_iff_exists_forall } end /-- A function `f : α → ι` with nonempty codomain takes pairwise equal values on a set `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `set.nonempty.pairwise_eq_iff_exists_eq` for a version that assumes `set.nonempty s` instead of `[nonempty ι]`. -/ lemma pairwise_eq_iff_exists_eq [nonempty ι] (s : set α) (f : α → ι) : (s.pairwise (λ x y, f x = f y)) ↔ ∃ z, ∀ x ∈ s, f x = z := pairwise_iff_exists_forall s f lemma pairwise_union : (s ∪ t).pairwise r ↔ s.pairwise r ∧ t.pairwise r ∧ ∀ (a ∈ s) (b ∈ t), a ≠ b → r a b ∧ r b a := begin simp only [set.pairwise, mem_union_eq, or_imp_distrib, forall_and_distrib], exact ⟨λ H, ⟨H.1.1, H.2.2, H.2.1, λ x hx y hy hne, H.1.2 y hy x hx hne.symm⟩, λ H, ⟨⟨H.1, λ x hx y hy hne, H.2.2.2 y hy x hx hne.symm⟩, H.2.2.1, H.2.1⟩⟩ end lemma pairwise_union_of_symmetric (hr : symmetric r) : (s ∪ t).pairwise r ↔ s.pairwise r ∧ t.pairwise r ∧ ∀ (a ∈ s) (b ∈ t), a ≠ b → r a b := pairwise_union.trans $ by simp only [hr.iff, and_self] lemma pairwise_insert : (insert a s).pairwise r ↔ s.pairwise r ∧ ∀ b ∈ s, a ≠ b → r a b ∧ r b a := by simp only [insert_eq, pairwise_union, pairwise_singleton, true_and, mem_singleton_iff, forall_eq] lemma pairwise_insert_of_symmetric (hr : symmetric r) : (insert a s).pairwise r ↔ s.pairwise r ∧ ∀ b ∈ s, a ≠ b → r a b := by simp only [pairwise_insert, hr.iff a, and_self] lemma pairwise_pair : set.pairwise {a, b} r ↔ (a ≠ b → r a b ∧ r b a) := by simp [pairwise_insert] lemma pairwise_pair_of_symmetric (hr : symmetric r) : set.pairwise {a, b} r ↔ (a ≠ b → r a b) := by simp [pairwise_insert_of_symmetric hr] lemma pairwise_univ : (univ : set α).pairwise r ↔ pairwise r := by simp only [set.pairwise, pairwise, mem_univ, forall_const] lemma pairwise.on_injective (hs : s.pairwise r) (hf : function.injective f) (hfs : ∀ x, f x ∈ s) : pairwise (r on f) := λ i j hij, hs _ (hfs i) _ (hfs j) (hf.ne hij) lemma inj_on.pairwise_image {s : set ι} (h : s.inj_on f) : (f '' s).pairwise r ↔ s.pairwise (r on f) := by simp [h.eq_iff, set.pairwise] {contextual := tt} lemma pairwise_Union {f : ι → set α} (h : directed (⊆) f) : (⋃ n, f n).pairwise r ↔ ∀ n, (f n).pairwise r := begin split, { assume H n, exact pairwise.mono (subset_Union _ _) H }, { assume H i hi j hj hij, rcases mem_Union.1 hi with ⟨m, hm⟩, rcases mem_Union.1 hj with ⟨n, hn⟩, rcases h m n with ⟨p, mp, np⟩, exact H p i (mp hm) j (np hn) hij } end lemma pairwise_sUnion {r : α → α → Prop} {s : set (set α)} (h : directed_on (⊆) s) : (⋃₀ s).pairwise r ↔ (∀ a ∈ s, set.pairwise a r) := by { rw [sUnion_eq_Union, pairwise_Union (h.directed_coe), set_coe.forall], refl } end set lemma pairwise.set_pairwise (h : pairwise r) (s : set α) : s.pairwise r := λ x hx y hy, h x y end pairwise lemma pairwise_subtype_iff_pairwise_set {α : Type*} (s : set α) (r : α → α → Prop) : pairwise (λ (x : s) (y : s), r x y) ↔ s.pairwise r := begin split, { assume h x hx y hy hxy, exact h ⟨x, hx⟩ ⟨y, hy⟩ (by simpa only [subtype.mk_eq_mk, ne.def]) }, { rintros h ⟨x, hx⟩ ⟨y, hy⟩ hxy, simp only [subtype.mk_eq_mk, ne.def] at hxy, exact h x hx y hy hxy } end alias pairwise_subtype_iff_pairwise_set ↔ pairwise.set_of_subtype set.pairwise.subtype namespace set section semilattice_inf_bot variables [semilattice_inf_bot α] {s t : set ι} {f g : ι → α} /-- A set is `pairwise_disjoint` under `f`, if the images of any distinct two elements under `f` are disjoint. -/ def pairwise_disjoint (s : set ι) (f : ι → α) : Prop := s.pairwise (disjoint on f) lemma pairwise_disjoint.subset (ht : t.pairwise_disjoint f) (h : s ⊆ t) : s.pairwise_disjoint f := pairwise.mono h ht lemma pairwise_disjoint.mono_on (hs : s.pairwise_disjoint f) (h : ∀ ⦃i⦄, i ∈ s → g i ≤ f i) : s.pairwise_disjoint g := λ a ha b hb hab, (hs a ha b hb hab).mono (h ha) (h hb) lemma pairwise_disjoint.mono (hs : s.pairwise_disjoint f) (h : g ≤ f) : s.pairwise_disjoint g := hs.mono_on (λ i _, h i) @[simp] lemma pairwise_disjoint_empty : (∅ : set ι).pairwise_disjoint f := pairwise_empty _ @[simp] lemma pairwise_disjoint_singleton (i : ι) (f : ι → α) : pairwise_disjoint {i} f := pairwise_singleton i _ lemma pairwise_disjoint_insert {i : ι} : (insert i s).pairwise_disjoint f ↔ s.pairwise_disjoint f ∧ ∀ j ∈ s, i ≠ j → disjoint (f i) (f j) := set.pairwise_insert_of_symmetric $ symmetric_disjoint.comap f lemma pairwise_disjoint.insert (hs : s.pairwise_disjoint f) {i : ι} (h : ∀ j ∈ s, i ≠ j → disjoint (f i) (f j)) : (insert i s).pairwise_disjoint f := set.pairwise_disjoint_insert.2 ⟨hs, h⟩ lemma pairwise_disjoint.image_of_le (hs : s.pairwise_disjoint f) {g : ι → ι} (hg : f ∘ g ≤ f) : (g '' s).pairwise_disjoint f := begin rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ h, exact (hs a ha b hb $ ne_of_apply_ne _ h).mono (hg a) (hg b), end lemma inj_on.pairwise_disjoint_image {g : ι' → ι} {s : set ι'} (h : s.inj_on g) : (g '' s).pairwise_disjoint f ↔ s.pairwise_disjoint (f ∘ g) := h.pairwise_image lemma pairwise_disjoint.range (g : s → ι) (hg : ∀ (i : s), f (g i) ≤ f i) (ht : s.pairwise_disjoint f) : (range g).pairwise_disjoint f := begin rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, exact (ht _ x.2 _ y.2 $ λ h, hxy $ congr_arg g $ subtype.ext h).mono (hg x) (hg y), end lemma pairwise_disjoint_union : (s ∪ t).pairwise_disjoint f ↔ s.pairwise_disjoint f ∧ t.pairwise_disjoint f ∧ ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ t → i ≠ j → disjoint (f i) (f j) := pairwise_union_of_symmetric $ symmetric_disjoint.comap f lemma pairwise_disjoint.union (hs : s.pairwise_disjoint f) (ht : t.pairwise_disjoint f) (h : ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ t → i ≠ j → disjoint (f i) (f j)) : (s ∪ t).pairwise_disjoint f := pairwise_disjoint_union.2 ⟨hs, ht, h⟩ lemma pairwise_disjoint_Union {g : ι' → set ι} (h : directed (⊆) g) : (⋃ n, g n).pairwise_disjoint f ↔ ∀ ⦃n⦄, (g n).pairwise_disjoint f := pairwise_Union h lemma pairwise_disjoint_sUnion {s : set (set ι)} (h : directed_on (⊆) s) : (⋃₀ s).pairwise_disjoint f ↔ ∀ ⦃a⦄, a ∈ s → set.pairwise_disjoint a f := pairwise_sUnion h -- classical lemma pairwise_disjoint.elim (hs : s.pairwise_disjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (h : ¬ disjoint (f i) (f j)) : i = j := of_not_not $ λ hij, h $ hs _ hi _ hj hij -- classical lemma pairwise_disjoint.elim' (hs : s.pairwise_disjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (h : f i ⊓ f j ≠ ⊥) : i = j := hs.elim hi hj $ λ hij, h hij.eq_bot end semilattice_inf_bot section complete_lattice variables [complete_lattice α] /-- Bind operation for `set.pairwise_disjoint`. If you want to only consider finsets of indices, you can use `set.pairwise_disjoint.bUnion_finset`. -/ lemma pairwise_disjoint.bUnion {s : set ι'} {g : ι' → set ι} {f : ι → α} (hs : s.pairwise_disjoint (λ i' : ι', ⨆ i ∈ g i', f i)) (hg : ∀ i ∈ s, (g i).pairwise_disjoint f) : (⋃ i ∈ s, g i).pairwise_disjoint f := begin rintro a ha b hb hab, simp_rw set.mem_Union at ha hb, obtain ⟨c, hc, ha⟩ := ha, obtain ⟨d, hd, hb⟩ := hb, obtain hcd | hcd := eq_or_ne (g c) (g d), { exact hg d hd a (hcd ▸ ha) b hb hab }, { exact (hs _ hc _ hd (ne_of_apply_ne _ hcd)).mono (le_bsupr a ha) (le_bsupr b hb) } end end complete_lattice /-! ### Pairwise disjoint set of sets -/ lemma pairwise_disjoint_range_singleton : (set.range (singleton : ι → set ι)).pairwise_disjoint id := begin rintro _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ h, exact disjoint_singleton.2 (ne_of_apply_ne _ h), end lemma pairwise_disjoint_fiber (f : ι → α) (s : set α) : s.pairwise_disjoint (λ a, f ⁻¹' {a}) := λ a _ b _ h i ⟨hia, hib⟩, h $ (eq.symm hia).trans hib -- classical lemma pairwise_disjoint.elim_set {s : set ι} {f : ι → set α} (hs : s.pairwise_disjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (a : α) (hai : a ∈ f i) (haj : a ∈ f j) : i = j := hs.elim hi hj $ not_disjoint_iff.2 ⟨a, hai, haj⟩ lemma bUnion_diff_bUnion_eq {s t : set ι} {f : ι → set α} (h : (s ∪ t).pairwise_disjoint f) : (⋃ i ∈ s, f i) \ (⋃ i ∈ t, f i) = (⋃ i ∈ s \ t, f i) := begin refine (bUnion_diff_bUnion_subset f s t).antisymm (bUnion_subset $ λ i hi a ha, (mem_diff _).2 ⟨mem_bUnion hi.1 ha, _⟩), rw mem_bUnion_iff, rintro ⟨j, hj, haj⟩, exact h i (or.inl hi.1) j (or.inr hj) (ne_of_mem_of_not_mem hj hi.2).symm ⟨ha, haj⟩, end /-- Equivalence between a disjoint bounded union and a dependent sum. -/ noncomputable def bUnion_eq_sigma_of_disjoint {s : set ι} {f : ι → set α} (h : s.pairwise (disjoint on f)) : (⋃ i ∈ s, f i) ≃ (Σ i : s, f i) := (equiv.set_congr (bUnion_eq_Union _ _)).trans $ Union_eq_sigma_of_disjoint $ λ ⟨i, hi⟩ ⟨j, hj⟩ ne, h _ hi _ hj $ λ eq, ne $ subtype.eq eq end set lemma pairwise_disjoint_fiber (f : ι → α) : pairwise (disjoint on (λ a : α, f ⁻¹' {a})) := set.pairwise_univ.1 $ set.pairwise_disjoint_fiber f univ
88a3232fb1eb1a1866b35ad393dc41502e714f25
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/group_theory/perm/fin.lean
b17760f644d4520d537ec51335d994316f8df7da
[ "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
8,662
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import data.equiv.fin import data.equiv.fintype import group_theory.perm.option /-! # Permutations of `fin n` -/ open equiv /-- Permutations of `fin (n + 1)` are equivalent to fixing a single `fin (n + 1)` and permuting the remaining with a `perm (fin n)`. The fixed `fin (n + 1)` is swapped with `0`. -/ def equiv.perm.decompose_fin {n : ℕ} : perm (fin n.succ) ≃ fin n.succ × perm (fin n) := ((equiv.perm_congr $ fin_succ_equiv n).trans equiv.perm.decompose_option).trans (equiv.prod_congr (fin_succ_equiv n).symm (equiv.refl _)) @[simp] lemma equiv.perm.decompose_fin_symm_of_refl {n : ℕ} (p : fin (n + 1)) : equiv.perm.decompose_fin.symm (p, equiv.refl _) = swap 0 p := by simp [equiv.perm.decompose_fin, equiv.perm_congr_def] @[simp] lemma equiv.perm.decompose_fin_symm_of_one {n : ℕ} (p : fin (n + 1)) : equiv.perm.decompose_fin.symm (p, 1) = swap 0 p := equiv.perm.decompose_fin_symm_of_refl p @[simp] lemma equiv.perm.decompose_fin_symm_apply_zero {n : ℕ} (p : fin (n + 1)) (e : perm (fin n)) : equiv.perm.decompose_fin.symm (p, e) 0 = p := by simp [equiv.perm.decompose_fin] @[simp] lemma equiv.perm.decompose_fin_symm_apply_succ {n : ℕ} (e : perm (fin n)) (p : fin (n + 1)) (x : fin n) : equiv.perm.decompose_fin.symm (p, e) x.succ = swap 0 p (e x).succ := begin refine fin.cases _ _ p, { simp [equiv.perm.decompose_fin, equiv_functor.map] }, { intros i, by_cases h : i = e x, { simp [h, equiv.perm.decompose_fin, equiv_functor.map] }, { have h' : some (e x) ≠ some i := λ H, h (option.some_injective _ H).symm, have h'' : (e x).succ ≠ i.succ := λ H, h (fin.succ_injective _ H).symm, simp [h, h'', fin.succ_ne_zero, equiv.perm.decompose_fin, equiv_functor.map, swap_apply_of_ne_of_ne, swap_apply_of_ne_of_ne (option.some_ne_none (e x)) h'] } } end @[simp] lemma equiv.perm.decompose_fin_symm_apply_one {n : ℕ} (e : perm (fin (n + 1))) (p : fin (n + 2)) : equiv.perm.decompose_fin.symm (p, e) 1 = swap 0 p (e 0).succ := by rw [← fin.succ_zero_eq_one, equiv.perm.decompose_fin_symm_apply_succ e p 0] @[simp] lemma equiv.perm.decompose_fin.symm_sign {n : ℕ} (p : fin (n + 1)) (e : perm (fin n)) : perm.sign (equiv.perm.decompose_fin.symm (p, e)) = ite (p = 0) 1 (-1) * perm.sign e := by { refine fin.cases _ _ p; simp [equiv.perm.decompose_fin, fin.succ_ne_zero] } /-- The set of all permutations of `fin (n + 1)` can be constructed by augmenting the set of permutations of `fin n` by each element of `fin (n + 1)` in turn. -/ lemma finset.univ_perm_fin_succ {n : ℕ} : @finset.univ (perm $ fin n.succ) _ = (finset.univ : finset $ fin n.succ × perm (fin n)).map equiv.perm.decompose_fin.symm.to_embedding := (finset.univ_map_equiv_to_embedding _).symm section cycle_range /-! ### `cycle_range` section Define the permutations `fin.cycle_range i`, the cycle `(0 1 2 ... i)`. -/ open equiv.perm lemma fin_rotate_succ {n : ℕ} : fin_rotate n.succ = decompose_fin.symm (1, fin_rotate n) := begin ext i, cases n, { simp }, refine fin.cases _ (λ i, _) i, { simp }, rw [coe_fin_rotate, decompose_fin_symm_apply_succ, if_congr (i.succ_eq_last_succ) rfl rfl], split_ifs with h, { simp [h] }, { rw [fin.coe_succ, function.injective.map_swap fin.coe_injective, fin.coe_succ, coe_fin_rotate, if_neg h, fin.coe_zero, fin.coe_one, swap_apply_of_ne_of_ne (nat.succ_ne_zero _) (nat.succ_succ_ne_one _)] } end @[simp] lemma sign_fin_rotate (n : ℕ) : perm.sign (fin_rotate (n + 1)) = (-1) ^ n := begin induction n with n ih, { simp }, { rw fin_rotate_succ, simp [ih, pow_succ] }, end namespace fin /-- `fin.cycle_range i` is the cycle `(0 1 2 ... i)` leaving `(i+1 ... (n-1))` unchanged. -/ def cycle_range {n : ℕ} (i : fin n) : perm (fin n) := (fin_rotate (i + 1)) .extend_domain (equiv.of_left_inverse' (fin.cast_le (nat.succ_le_of_lt i.is_lt)).to_embedding coe (by { intros x, ext, simp })) lemma cycle_range_of_gt {n : ℕ} {i j : fin n.succ} (h : i < j) : cycle_range i j = j := begin rw [cycle_range, of_left_inverse'_eq_of_injective, ←function.embedding.to_equiv_range_eq_of_injective, ←via_embedding, via_embedding_apply_not_mem_range], simpa end lemma cycle_range_of_le {n : ℕ} {i j : fin n.succ} (h : j ≤ i) : cycle_range i j = if j = i then 0 else j + 1 := begin cases n, { simp }, have : j = (fin.cast_le (nat.succ_le_of_lt i.is_lt)).to_embedding ⟨j, lt_of_le_of_lt h (nat.lt_succ_self i)⟩, { simp }, ext, rw [this, cycle_range, of_left_inverse'_eq_of_injective, ←function.embedding.to_equiv_range_eq_of_injective, ←via_embedding, via_embedding_apply_image, rel_embedding.coe_fn_to_embedding, coe_cast_le, coe_fin_rotate], simp only [fin.ext_iff, coe_last, coe_mk, coe_zero, fin.eta, apply_ite coe, cast_le_mk], split_ifs with heq, { refl }, { rw fin.coe_add_one_of_lt, exact lt_of_lt_of_le (lt_of_le_of_ne h (mt (congr_arg coe) heq)) (le_last i) } end lemma coe_cycle_range_of_le {n : ℕ} {i j : fin n.succ} (h : j ≤ i) : (cycle_range i j : ℕ) = if j = i then 0 else j + 1 := by { rw [cycle_range_of_le h], split_ifs with h', { refl }, exact coe_add_one_of_lt (calc (j : ℕ) < i : fin.lt_iff_coe_lt_coe.mp (lt_of_le_of_ne h h') ... ≤ n : nat.lt_succ_iff.mp i.2) } lemma cycle_range_of_lt {n : ℕ} {i j : fin n.succ} (h : j < i) : cycle_range i j = j + 1 := by rw [cycle_range_of_le h.le, if_neg h.ne] lemma coe_cycle_range_of_lt {n : ℕ} {i j : fin n.succ} (h : j < i) : (cycle_range i j : ℕ) = j + 1 := by rw [coe_cycle_range_of_le h.le, if_neg h.ne] lemma cycle_range_of_eq {n : ℕ} {i j : fin n.succ} (h : j = i) : cycle_range i j = 0 := by rw [cycle_range_of_le h.le, if_pos h] @[simp] lemma cycle_range_self {n : ℕ} (i : fin n.succ) : cycle_range i i = 0 := cycle_range_of_eq rfl lemma cycle_range_apply {n : ℕ} (i j : fin n.succ) : cycle_range i j = if j < i then j + 1 else if j = i then 0 else j := begin split_ifs with h₁ h₂, { exact cycle_range_of_lt h₁ }, { exact cycle_range_of_eq h₂ }, { exact cycle_range_of_gt (lt_of_le_of_ne (le_of_not_gt h₁) (ne.symm h₂)) }, end @[simp] lemma cycle_range_zero (n : ℕ) : cycle_range (0 : fin n.succ) = 1 := begin ext j, refine fin.cases _ (λ j, _) j, { simp }, { rw [cycle_range_of_gt (fin.succ_pos j), one_apply] }, end @[simp] lemma cycle_range_last (n : ℕ) : cycle_range (last n) = fin_rotate (n + 1) := by { ext i, rw [coe_cycle_range_of_le (le_last _), coe_fin_rotate] } @[simp] lemma cycle_range_zero' {n : ℕ} (h : 0 < n) : cycle_range ⟨0, h⟩ = 1 := begin cases n with n, { cases h }, exact cycle_range_zero n end @[simp] lemma sign_cycle_range {n : ℕ} (i : fin n) : perm.sign (cycle_range i) = (-1) ^ (i : ℕ) := by simp [cycle_range] @[simp] lemma succ_above_cycle_range {n : ℕ} (i j : fin n) : i.succ.succ_above (i.cycle_range j) = swap 0 i.succ j.succ := begin cases n, { rcases j with ⟨_, ⟨⟩⟩ }, rcases lt_trichotomy j i with hlt | heq | hgt, { have : (j + 1).cast_succ = j.succ, { ext, rw [coe_cast_succ, coe_succ, fin.coe_add_one_of_lt (lt_of_lt_of_le hlt i.le_last)] }, rw [fin.cycle_range_of_lt hlt, fin.succ_above_below, this, swap_apply_of_ne_of_ne], { apply fin.succ_ne_zero }, { exact (fin.succ_injective _).ne hlt.ne }, { rw fin.lt_iff_coe_lt_coe, simpa [this] using hlt } }, { rw [heq, fin.cycle_range_self, fin.succ_above_below, swap_apply_right, fin.cast_succ_zero], { rw fin.cast_succ_zero, apply fin.succ_pos } }, { rw [fin.cycle_range_of_gt hgt, fin.succ_above_above, swap_apply_of_ne_of_ne], { apply fin.succ_ne_zero }, { apply (fin.succ_injective _).ne hgt.ne.symm }, { simpa [fin.le_iff_coe_le_coe] using hgt } }, end @[simp] lemma cycle_range_succ_above {n : ℕ} (i : fin (n + 1)) (j : fin n) : i.cycle_range (i.succ_above j) = j.succ := begin cases lt_or_ge j.cast_succ i with h h, { rw [fin.succ_above_below _ _ h, fin.cycle_range_of_lt h, fin.coe_succ_eq_succ] }, { rw [fin.succ_above_above _ _ h, fin.cycle_range_of_gt (fin.le_cast_succ_iff.mp h)] } end @[simp] lemma cycle_range_symm_zero {n : ℕ} (i : fin (n + 1)) : i.cycle_range.symm 0 = i := i.cycle_range.injective (by simp) @[simp] lemma cycle_range_symm_succ {n : ℕ} (i : fin (n + 1)) (j : fin n) : i.cycle_range.symm j.succ = i.succ_above j := i.cycle_range.injective (by simp) end fin end cycle_range
f3dd140dd57da6aaf24b8b5d9a81a443e9e7a974
5ec8f5218a7c8e87dd0d70dc6b715b36d61a8d61
/cminor.lean
dc53e2c9a08f40a369eec0262042c23cebd2910a
[]
no_license
mbrodersen/kremlin
f9f2f9dd77b9744fe0ffd5f70d9fa0f1f8bd8cec
d4665929ce9012e93a0b05fc7063b96256bab86f
refs/heads/master
1,624,057,268,130
1,496,957,084,000
1,496,957,084,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,103
lean
import .events .switch namespace cminor open integers ast floats maps values memory events globalenvs switch ast.fundef /- Abstract syntax and semantics for the Cminor language. -/ /- * Abstract syntax -/ /- Cminor is a low-level imperative language structured in expressions, statements, functions and programs. We first define the consts and operators that occur within expressions. -/ inductive const : Type | Ointconst : int32 → const /- integer const -/ | Ofloatconst : float → const /- double-precision floating-point const -/ | Osingleconst : float32 → const /- single-precision floating-point const -/ | Olongconst : int64 → const /- long integer const -/ | Oaddrsymbol : ident → ptrofs → const /- address of the symbol plus the offset -/ | Oaddrstack : ptrofs → const /- stack pointer plus the given offset -/ open const inductive unary_operation : Type | Ocast8unsigned : unary_operation /- 8-bit zero extension -/ | Ocast8signed : unary_operation /- 8-bit sign extension -/ | Ocast16unsigned : unary_operation /- 16-bit zero extension -/ | Ocast16signed : unary_operation /- 16-bit sign extension -/ | Onegint : unary_operation /- integer opposite -/ | Onotint : unary_operation /- bitwise complement -/ | Onegf : unary_operation /- float64 opposite -/ | Oabsf : unary_operation /- float64 absolute value -/ | Onegfs : unary_operation /- float32 opposite -/ | Oabsfs : unary_operation /- float32 absolute value -/ | Osingleoffloat : unary_operation /- float truncation to float32 -/ | Ofloatofsingle : unary_operation /- float extension to float64 -/ | Ointoffloat : unary_operation /- signed integer to float64 -/ | Ointuoffloat : unary_operation /- unsigned integer to float64 -/ | Ofloatofint : unary_operation /- float64 to signed integer -/ | Ofloatofintu : unary_operation /- float64 to unsigned integer -/ | Ointofsingle : unary_operation /- signed integer to float32 -/ | Ointuofsingle : unary_operation /- unsigned integer to float32 -/ | Osingleofint : unary_operation /- float32 to signed integer -/ | Osingleofintu : unary_operation /- float32 to unsigned integer -/ | Onegl : unary_operation /- long integer opposite -/ | Onotl : unary_operation /- long bitwise complement -/ | Ointoflong : unary_operation /- long to int -/ | Olongofint : unary_operation /- signed int to long -/ | Olongofintu : unary_operation /- unsigned int to long -/ | Olongoffloat : unary_operation /- float64 to signed long -/ | Olonguoffloat : unary_operation /- float64 to unsigned long -/ | Ofloatoflong : unary_operation /- signed long to float64 -/ | Ofloatoflongu : unary_operation /- unsigned long to float64 -/ | Olongofsingle : unary_operation /- float32 to signed long -/ | Olonguofsingle : unary_operation /- float32 to unsigned long -/ | Osingleoflong : unary_operation /- signed long to float32 -/ | Osingleoflongu : unary_operation /- unsigned long to float32 -/ export unary_operation inductive binary_operation : Type | Oadd : binary_operation /- integer addition -/ | Osub : binary_operation /- integer subtraction -/ | Omul : binary_operation /- integer multiplication -/ | Odiv : binary_operation /- integer signed division -/ | Odivu : binary_operation /- integer unsigned division -/ | Omod : binary_operation /- integer signed modulus -/ | Omodu : binary_operation /- integer unsigned modulus -/ | Oand : binary_operation /- integer bitwise ``and'' -/ | Oor : binary_operation /- integer bitwise ``or'' -/ | Oxor : binary_operation /- integer bitwise ``xor'' -/ | Oshl : binary_operation /- integer left shift -/ | Oshr : binary_operation /- integer right signed shift -/ | Oshru : binary_operation /- integer right unsigned shift -/ | Oaddf : binary_operation /- float64 addition -/ | Osubf : binary_operation /- float64 subtraction -/ | Omulf : binary_operation /- float64 multiplication -/ | Odivf : binary_operation /- float64 division -/ | Oaddfs : binary_operation /- float32 addition -/ | Osubfs : binary_operation /- float32 subtraction -/ | Omulfs : binary_operation /- float32 multiplication -/ | Odivfs : binary_operation /- float32 division -/ | Oaddl : binary_operation /- long addition -/ | Osubl : binary_operation /- long subtraction -/ | Omull : binary_operation /- long multiplication -/ | Odivl : binary_operation /- long signed division -/ | Odivlu : binary_operation /- long unsigned division -/ | Omodl : binary_operation /- long signed modulus -/ | Omodlu : binary_operation /- long unsigned modulus -/ | Oandl : binary_operation /- long bitwise ``and'' -/ | Oorl : binary_operation /- long bitwise ``or'' -/ | Oxorl : binary_operation /- long bitwise ``xor'' -/ | Oshll : binary_operation /- long left shift -/ | Oshrl : binary_operation /- long right signed shift -/ | Oshrlu : binary_operation /- long right unsigned shift -/ | Ocmp : comparison → binary_operation /- integer signed comparison -/ | Ocmpu : comparison → binary_operation /- integer unsigned comparison -/ | Ocmpf : comparison → binary_operation /- float64 comparison -/ | Ocmpfs : comparison → binary_operation /- float32 comparison -/ | Ocmpl : comparison → binary_operation /- long signed comparison -/ | Ocmplu : comparison → binary_operation /- long unsigned comparison -/ open binary_operation /- Expressions include reading local variables, constants, arithmetic operations, and memory loads. -/ inductive expr : Type | Evar : ident → expr | Econst : const → expr | Eunop : unary_operation → expr → expr | Ebinop : binary_operation → expr → expr → expr | Eload : memory_chunk → expr → expr open cminor.expr /- Statements include expression evaluation, assignment to local variables, memory stores, function calls, an if/then/else conditional, infinite loops, blocks and early block exits, and early function returns. [Sexit n] terminates prematurely the execution of the [n+1] enclosing [Sblock] statements. -/ def label := ident inductive stmt : Type | Sskip : stmt | Sassign : ident → expr → stmt | Sstore : memory_chunk → expr → expr → stmt | Scall : option ident → signature → expr → list expr → stmt | Stailcall : signature → expr → list expr → stmt | Sbuiltin : option ident → external_function → list expr → stmt | Sseq : stmt → stmt → stmt | Sifthenelse : expr → stmt → stmt → stmt | Sloop : stmt → stmt | Sblock : stmt → stmt | Sexit : ℕ → stmt | Sswitch : bool → expr → list (ℤ × ℕ) → ℕ → stmt | Sreturn : option expr → stmt | Slabel : label → stmt → stmt | Sgoto : label → stmt open stmt /- Functions are composed of a signature, a list of parameter names, a list of local variables, and a statement representing the function body. Each function can allocate a memory block of size [fn_stackspace] on entrance. This block will be deallocated automatically before the function returns. Pointers into this block can be taken with the [Oaddrstack] operator. -/ structure function : Type := (sig : signature) (params : list ident) (vars : list ident) (stackspace : ℕ) (body : stmt) def fundef := ast.fundef function. def program := ast.program fundef unit. def funsig : fundef → signature | (fundef.Internal f) := f.sig | (fundef.External ef) := ef_sig ef /- * Operational semantics (small-step) -/ /- Two kinds of evaluation environments are involved: - [genv]: global environments, define symbols and functions; - [env]: local environments, map local variables to values. -/ def genv := Genv fundef unit def env := PTree val instance : has_coe genv Senv := ⟨Genv.to_senv⟩ /- The following functions build the initial local environment at function entry, binding parameters to the provided arguments and initializing local variables to [Vundef]. -/ def set_params : list ident → list val → env | [] _ := (∅ : PTree _) | (i1 :: is) vs := (set_params is vs.tail).set i1 vs.head def set_locals (e : env) : list ident → env | [] := e | (i1 :: is) := (set_locals is).set i1 Vundef def set_optvar (e : env) : option ident → val → env | none v := e | (some id) v := e.set id v /- Continuations -/ inductive cont : Type | Kstop : cont /- stop program execution -/ | Kseq : stmt → cont → cont /- execute stmt, then cont -/ | Kblock : cont → cont /- exit a block, then do cont -/ | Kcall : option ident → function → val → env → cont → cont /- return to caller -/ open cont /- States -/ inductive state : Type | State /- Execution within a function -/ (f : function) /- currently executing function -/ (s : stmt) /- statement under consideration -/ (k : cont) /- its continuation -- what to do next -/ (sp : val) /- current stack pointer -/ (e : env) /- current local environment -/ (m : mem) /- current memory state -/ : state | Callstate /- Invocation of a function -/ (f : fundef) /- function to invoke -/ (args : list val) /- arguments provided by caller -/ (k : cont) /- what to do next -/ (m : mem) /- memory state -/ : state | Returnstate /- Return from a function -/ (v : val) /- Return value -/ (k : cont) /- what to do next -/ (m : mem) /- memory state -/ : state open cminor.state section relsem parameter (ge : genv) /- Evaluation of constants and operator applications. [None] is returned when the computation is undefined, e.g. if arguments are of the wrong types, or in case of an integer division by zero. -/ def eval_const (sp : val) : const → val | (Ointconst n) := Vint n | (Ofloatconst n) := Vfloat n | (Osingleconst n) := Vsingle n | (Olongconst n) := Vlong n | (Oaddrsymbol s ofs) := ge.symbol_address s ofs | (Oaddrstack ofs) := offset_ptr sp ofs def eval_unop (arg : val) : unary_operation → option val | Ocast8unsigned := some (zero_ext 8 arg) | Ocast8signed := some (sign_ext 8 arg) | Ocast16unsigned := some (zero_ext 16 arg) | Ocast16signed := some (sign_ext 16 arg) | Onegint := some (negint arg) | Onotint := some (notint arg) | Onegf := some (negf arg) | Oabsf := some (absf arg) | Onegfs := some (negfs arg) | Oabsfs := some (absfs arg) | Osingleoffloat := some (single_of_float arg) | Ofloatofsingle := some (float_of_single arg) | Ointoffloat := int_of_float arg | Ointuoffloat := intu_of_float arg | Ofloatofint := float_of_int arg | Ofloatofintu := float_of_intu arg | Ointofsingle := int_of_single arg | Ointuofsingle := intu_of_single arg | Osingleofint := single_of_int arg | Osingleofintu := single_of_intu arg | Onegl := some (negl arg) | Onotl := some (notl arg) | Ointoflong := some (loword arg) | Olongofint := some (long_of_int arg) | Olongofintu := some (long_of_intu arg) | Olongoffloat := long_of_float arg | Olonguoffloat := longu_of_float arg | Ofloatoflong := float_of_long arg | Ofloatoflongu := float_of_longu arg | Olongofsingle := long_of_single arg | Olonguofsingle := longu_of_single arg | Osingleoflong := single_of_long arg | Osingleoflongu := single_of_longu arg def eval_binop (arg1 arg2 : val) (m : mem) : binary_operation → option val | Oadd := some (arg1 + arg2) | Osub := some (arg1 - arg2) | Omul := some (arg1 * arg2) | Odiv := divs arg1 arg2 | Odivu := divu arg1 arg2 | Omod := mods arg1 arg2 | Omodu := modu arg1 arg2 | Oand := some (val.and arg1 arg2) | Oor := some (val.or arg1 arg2) | Oxor := some (val.xor arg1 arg2) | Oshl := some (shl arg1 arg2) | Oshr := some (shr arg1 arg2) | Oshru := some (shru arg1 arg2) | Oaddf := some (addf arg1 arg2) | Osubf := some (subf arg1 arg2) | Omulf := some (mulf arg1 arg2) | Odivf := some (divf arg1 arg2) | Oaddfs := some (addfs arg1 arg2) | Osubfs := some (subfs arg1 arg2) | Omulfs := some (mulfs arg1 arg2) | Odivfs := some (divfs arg1 arg2) | Oaddl := some (addl arg1 arg2) | Osubl := some (subl arg1 arg2) | Omull := some (mull arg1 arg2) | Odivl := divls arg1 arg2 | Odivlu := divlu arg1 arg2 | Omodl := modls arg1 arg2 | Omodlu := modlu arg1 arg2 | Oandl := some (andl arg1 arg2) | Oorl := some (orl arg1 arg2) | Oxorl := some (xorl arg1 arg2) | Oshll := some (shll arg1 arg2) | Oshrl := some (shrl arg1 arg2) | Oshrlu := some (shrlu arg1 arg2) | (Ocmp c) := some (cmp c arg1 arg2) | (Ocmpu c) := some (cmpu (valid_pointer m) c arg1 arg2) | (Ocmpf c) := some (cmpf c arg1 arg2) | (Ocmpfs c) := some (cmpfs c arg1 arg2) | (Ocmpl c) := cmpl c arg1 arg2 | (Ocmplu c) := cmplu (valid_pointer m) c arg1 arg2 /- Evaluation of an expression: [eval_expr ge sp e m a = some v] states that expression [a] evaluates to value [v]. [ge] is the global environment, [e] the local environment, and [m] the current memory state. They are unchanged during evaluation. [sp] is the pointer to the memory block allocated for this function (stack frame). -/ section eval_expr parameters (sp : val) (e : env) (m : mem) def eval_expr : expr → option val | (Evar id) := PTree.get id e | (Econst cst) := eval_const sp cst | (Eunop op a1) := do v1 ← eval_expr a1, eval_unop v1 op | (Ebinop op a1 a2) := do v1 ← eval_expr a1, v2 ← eval_expr a2, eval_binop v1 v2 m op | (Eload chunk addr) := do vaddr ← eval_expr addr, loadv chunk m vaddr end eval_expr /- Pop continuation until a call or stop -/ def call_cont : cont → cont | (Kseq s k) := call_cont k | (Kblock k) := call_cont k | k := k def is_call_cont : cont → bool | Kstop := tt | (Kcall _ _ _ _ _) := tt | _ := ff /- Find the statement and manufacture the continuation corresponding to a label -/ def find_label (lbl : label) : stmt → cont → option (stmt × cont) | (Sseq s1 s2) k := find_label s1 (Kseq s2 k) <|> find_label s2 k | (Sifthenelse a s1 s2) k := find_label s1 k <|> find_label s2 k | (Sloop s1) k := find_label s1 (Kseq (Sloop s1) k) | (Sblock s1) k := find_label s1 (Kblock k) | (Slabel lbl' s') k := if lbl = lbl' then some (s', k) else find_label s' k | _ k := none /- One step of execution -/ inductive step : state → list event → state → Prop | step_skip_seq (f s k sp e m) : step (State f Sskip (Kseq s k) sp e m) [] (State f s k sp e m) | step_skip_block (f k sp e m) : step (State f Sskip (Kblock k) sp e m) [] (State f Sskip k sp e m) | step_skip_call (f : function) (k sp e m m') : is_call_cont k → free m sp 0 f.stackspace = some m' → step (State f Sskip k (Vptr sp 0) e m) [] (Returnstate Vundef k m') | step_assign (f id a k sp e m v) : eval_expr sp e m a = some v → step (State f (Sassign id a) k sp e m) [] (State f Sskip k sp (PTree.set id v e) m) | step_store (f chunk addr a k sp e m vaddr v m') : eval_expr sp e m addr = some vaddr → eval_expr sp e m a = some v → storev chunk m vaddr v = some m' → step (State f (Sstore chunk addr a) k sp e m) [] (State f Sskip k sp e m') | step_call (f optid a bl k sp e m vf vargs fd) : eval_expr sp e m a = some vf → mmap (eval_expr sp e m) bl = some vargs → ge.find_funct vf = some fd → step (State f (Scall optid (funsig fd) a bl) k sp e m) [] (Callstate fd vargs (Kcall optid f sp e k) m) | step_tailcall (f : function) (a bl k sp e m vf vargs fd m') : eval_expr (Vptr sp 0) e m a = some vf → mmap (eval_expr (Vptr sp 0) e m) bl = some vargs → ge.find_funct vf = some fd → free m sp 0 f.stackspace = some m' → step (State f (Stailcall (funsig fd) a bl) k (Vptr sp 0) e m) [] (Callstate fd vargs (call_cont k) m') | step_builtin (f optid ef bl k sp e m vargs t vres m') : mmap (eval_expr sp e m) bl = some vargs → external_call ef ge vargs m t vres m' → step (State f (Sbuiltin optid ef bl) k sp e m) t (State f Sskip k sp (set_optvar e optid vres) m') | step_seq (f s1 s2 k sp e m) : step (State f (Sseq s1 s2) k sp e m) [] (State f s1 (Kseq s2 k) sp e m) | step_ifthenelse (f a s1 s2 k sp e m b) : eval_expr sp e m a >>= to_bool = some b → step (State f (Sifthenelse a s1 s2) k sp e m) [] (State f (if b then s1 else s2) k sp e m) | step_loop (f s k sp e m) : step (State f (Sloop s) k sp e m) [] (State f s (Kseq (Sloop s) k) sp e m) | step_block (f s k sp e m) : step (State f (Sblock s) k sp e m) [] (State f s (Kblock k) sp e m) | step_exit_seq (f n s k sp e m) : step (State f (Sexit n) (Kseq s k) sp e m) [] (State f (Sexit n) k sp e m) | step_exit_block_0 (f k sp e m) : step (State f (Sexit 0) (Kblock k) sp e m) [] (State f Sskip k sp e m) | step_exit_block_S (f n k sp e m) : step (State f (Sexit (n + 1)) (Kblock k) sp e m) [] (State f (Sexit n) k sp e m) | step_switch (f islong a cases default k sp e m v w n) : eval_expr sp e m a = some v → switch_argument islong v w n → step (State f (Sswitch islong a cases default) k sp e m) [] (State f (Sexit (switch_target' w n default cases)) k sp e m) | step_return_0 (f : function) (k sp e m m') : free m sp 0 f.stackspace = some m' → step (State f (Sreturn none) k (Vptr sp 0) e m) [] (Returnstate Vundef (call_cont k) m') | step_return_1 (f : function) (a k sp e m v m') : eval_expr (Vptr sp 0) e m a = some v → free m sp 0 f.stackspace = some m' → step (State f (Sreturn (some a)) k (Vptr sp 0) e m) [] (Returnstate v (call_cont k) m') | step_label (f lbl s k sp e m) : step (State f (Slabel lbl s) k sp e m) [] (State f s k sp e m) | step_goto (f : function) (lbl k sp e m s' k') : find_label lbl f.body (call_cont k) = some (s', k') → step (State f (Sgoto lbl) k sp e m) [] (State f s' k' sp e m) | step_internal_function (f : function) (vargs k) (m : mem) : step (Callstate (Internal f) vargs k m) [] (State f f.body k (Vptr m.nextblock 0) (set_locals (set_params f.params vargs) f.vars) (m.alloc 0 f.stackspace)) | step_external_function (ef vargs k m t vres m') : external_call ef ge vargs m t vres m' → step (Callstate (External ef) vargs k m) t (Returnstate vres k m') | step_return (v optid f sp e k m) : step (Returnstate v (Kcall optid f sp e k) m) [] (State f Sskip k sp (set_optvar e optid v) m) end relsem /- Execution of whole programs are described as sequences of transitions from an initial state to a final state. An initial state is a [Callstate] corresponding to the invocation of the ``main'' function of the program without arguments and with an empty continuation. -/ inductive initial_state (p : program) : state → Prop | mk (b f m0) : Genv.init_mem p = some m0 → Genv.find_symbol (Genv.globalenv p) p.main = some b → Genv.find_funct_ptr (Genv.globalenv p) b = some f → funsig f = signature_main → initial_state (Callstate f [] Kstop m0) /- A final state is a [Returnstate] with an empty continuation. -/ inductive final_state : state → int32 → Prop | mk (r m) : final_state (Returnstate (Vint r) Kstop m) r /- * Alternate operational semantics (big-step) -/ /- We now define another semantics for Cminor without [goto] that follows the ``big-step'' style of semantics, also known as natural semantics. In this style, just like expressions evaluate to values, statements evaluate to``outcomes'' indicating how execution should proceed afterwards. -/ inductive outcome : Type | normal : outcome /- continue in sequence -/ | exit : ℕ → outcome /- terminate [n+1] enclosing blocks -/ | return : option val → outcome /- return immediately to caller -/ | tailcall_return : val → outcome /- already returned to caller via a tailcall -/ def outcome_block : outcome → outcome | (outcome.exit 0) := outcome.normal | (outcome.exit (n+1)) := outcome.exit n | out := out def outcome_result_value (retsig : option typ) (vres : val) : outcome → Prop | outcome.normal := vres = Vundef | (outcome.return none) := vres = Vundef | (outcome.return (some v)) := retsig ≠ none ∧ vres = v | (outcome.tailcall_return v) := vres = v | _ := false def outcome_free_mem (m : mem) (sp : block) (sz : ℕ) (m' : mem) : outcome → Prop | (outcome.tailcall_return _) := m' = m | _ := free m sp 0 sz = some m' section naturalsem parameter (ge : genv) /- Evaluation of a function invocation: [eval_funcall ge m f args t m' res] means that the function [f], applied to the arguments [args] in memory state [m], returns the value [res] in modified memory state [m']. [t] is the trace of observable events generated during the invocation. -/ mutual inductive eval_funcall, exec_stmt with eval_funcall : mem → fundef → list val → list event → mem → val → Prop | eval_funcall_internal (m : mem) (f : function) (vargs m1 sp e t e2 m2 out vres m3) : m.alloc 0 f.stackspace = m1 → m.nextblock = sp → set_locals (set_params f.params vargs) f.vars = e → exec_stmt f (Vptr sp 0) e m1 f.body t e2 m2 out → outcome_result_value f.sig.sig_res vres out → outcome_free_mem m2 sp f.stackspace m3 out → eval_funcall m (Internal f) vargs t m3 vres | eval_funcall_external : ∀ ef m args t res m', external_call ef ge args m t res m' → eval_funcall m (External ef) args t m' res /- Execution of a statement: [exec_stmt ge f sp e m s t e' m' out] means that statement [s] executes with outcome [out]. [e] is the initial environment and [m] is the initial memory state. [e'] is the final environment, reflecting variable assignments performed by [s]. [m'] is the final memory state, reflecting memory stores performed by [s]. [t] is the trace of I/O events performed during the execution. The other parameters are as in [eval_expr]. -/ with exec_stmt : function → val → env → mem → stmt → list event → env → mem → outcome → Prop | exec_Sskip (f sp e m) : exec_stmt f sp e m Sskip [] e m outcome.normal | exec_Sassign (f sp e m id a v) : eval_expr ge sp e m a = some v → exec_stmt f sp e m (Sassign id a) [] (PTree.set id v e) m outcome.normal | exec_Sstore (f sp e m chunk addr a vaddr v m') : eval_expr ge sp e m addr = some vaddr → eval_expr ge sp e m a = some v → storev chunk m vaddr v = some m' → exec_stmt f sp e m (Sstore chunk addr a) [] e m' outcome.normal | exec_Scall (f sp e m optid sig a bl vf vargs fd t m' vres e') : eval_expr ge sp e m a = some vf → mmap (eval_expr ge sp e m) bl = some vargs → Genv.find_funct ge vf = some fd → funsig fd = sig → eval_funcall m fd vargs t m' vres → e' = set_optvar e optid vres → exec_stmt f sp e m (Scall optid sig a bl) t e' m' outcome.normal | exec_Sbuiltin (f sp e m optid ef bl t m' vargs vres e') : mmap (eval_expr ge sp e m) bl = some vargs → external_call ef ge vargs m t vres m' → e' = set_optvar e optid vres → exec_stmt f sp e m (Sbuiltin optid ef bl) t e' m' outcome.normal | exec_Sifthenelse (f sp e m a s1 s2 v b t e' m' out) : eval_expr ge sp e m a = some v → v.to_bool = some b → exec_stmt f sp e m (if b then s1 else s2) t e' m' out → exec_stmt f sp e m (Sifthenelse a s1 s2) t e' m' out | exec_Sseq_continue (f sp e m s1 t1 e1 m1 s2 t2 e2 m2 out) : exec_stmt f sp e m s1 t1 e1 m1 outcome.normal → exec_stmt f sp e1 m1 s2 t2 e2 m2 out → exec_stmt f sp e m (Sseq s1 s2) (t1 ++ t2) e2 m2 out | exec_Sseq_stop (f sp e m t s1 s2 e1 m1 out) : exec_stmt f sp e m s1 t e1 m1 out → out ≠ outcome.normal → exec_stmt f sp e m (Sseq s1 s2) t e1 m1 out | exec_Sloop_loop (f sp e m s t1 e1 m1 t2 e2 m2 out) : exec_stmt f sp e m s t1 e1 m1 outcome.normal → exec_stmt f sp e1 m1 (Sloop s) t2 e2 m2 out → exec_stmt f sp e m (Sloop s) (t1 ++ t2) e2 m2 out | exec_Sloop_stop (f sp e m t s e1 m1 out) : exec_stmt f sp e m s t e1 m1 out → out ≠ outcome.normal → exec_stmt f sp e m (Sloop s) t e1 m1 out | exec_Sblock (f sp e m s t e1 m1 out) : exec_stmt f sp e m s t e1 m1 out → exec_stmt f sp e m (Sblock s) t e1 m1 (outcome_block out) | exec_Sexit (f sp e m n) : exec_stmt f sp e m (Sexit n) [] e m (outcome.exit n) | exec_Sswitch (f sp e m islong a cases default v w n) : eval_expr ge sp e m a = some v → switch_argument islong v w n → exec_stmt f sp e m (Sswitch islong a cases default) [] e m (outcome.exit (switch_target' w n default cases)) | exec_Sreturn_none (f sp e m) : exec_stmt f sp e m (Sreturn none) [] e m (outcome.return none) | exec_Sreturn_some (f sp e m a v) : eval_expr ge sp e m a = some v → exec_stmt f sp e m (Sreturn (some a)) [] e m (outcome.return (some v)) | exec_Stailcall (f : function) (sp e m sig a bl vf vargs fd t m' m'' vres) : eval_expr ge (Vptr sp 0) e m a = some vf → mmap (eval_expr ge (Vptr sp 0) e m) bl = some vargs → Genv.find_funct ge vf = some fd → funsig fd = sig → free m sp 0 f.stackspace = some m' → eval_funcall m' fd vargs t m'' vres → exec_stmt f (Vptr sp 0) e m (Stailcall sig a bl) t e m'' (outcome.tailcall_return vres) end naturalsem /- Big-step execution of a whole program -/ inductive bigstep_program_terminates (p : program) : list event → int32 → Prop | mk (b f m0 t m r) : Genv.init_mem p = some m0 → Genv.find_symbol (Genv.globalenv p) p.main = some b → Genv.find_funct_ptr (Genv.globalenv p) b = some f → funsig f = signature_main → eval_funcall (Genv.globalenv p) m0 f [] t m (Vint r) → bigstep_program_terminates t r end cminor
ea32e29aade14b5e32ec08df120e9903a3bc6679
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/category/Module/abelian.lean
f2e94e5b62e503153aee91180042bbd6fc81e002
[ "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,240
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 linear_algebra.isomorphisms import algebra.category.Module.kernels import algebra.category.Module.limits import category_theory.abelian.exact /-! # The category of left R-modules is abelian. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Additionally, two linear maps are exact in the categorical sense iff `range f = ker g`. -/ open category_theory open category_theory.limits noncomputable theory universes w v u namespace Module variables {R : Type u} [ring R] {M N : Module.{v} R} (f : M ⟶ N) /-- In the category of modules, every monomorphism is normal. -/ def normal_mono (hf : mono f) : normal_mono f := { Z := of R (N ⧸ f.range), g := f.range.mkq, w := linear_map.range_mkq_comp _, is_limit := is_kernel.iso_kernel _ _ (kernel_is_limit _) /- The following [invalid Lean code](https://github.com/leanprover-community/lean/issues/341) might help you understand what's going on here: ``` calc M ≃ₗ[R] f.ker.quotient : (submodule.quot_equiv_of_eq_bot _ (ker_eq_bot_of_mono _)).symm ... ≃ₗ[R] f.range : linear_map.quot_ker_equiv_range f ... ≃ₗ[R] r.range.mkq.ker : linear_equiv.of_eq _ _ (submodule.ker_mkq _).symm ``` -/ (linear_equiv.to_Module_iso' ((submodule.quot_equiv_of_eq_bot _ (ker_eq_bot_of_mono _)).symm ≪≫ₗ ((linear_map.quot_ker_equiv_range f) ≪≫ₗ (linear_equiv.of_eq _ _ (submodule.ker_mkq _).symm)))) $ by { ext, refl } } /-- In the category of modules, every epimorphism is normal. -/ def normal_epi (hf : epi f) : normal_epi f := { W := of R f.ker, g := f.ker.subtype, w := linear_map.comp_ker_subtype _, is_colimit := is_cokernel.cokernel_iso _ _ (cokernel_is_colimit _) (linear_equiv.to_Module_iso' /- The following invalid Lean code might help you understand what's going on here: ``` calc f.ker.subtype.range.quotient ≃ₗ[R] f.ker.quotient : submodule.quot_equiv_of_eq _ _ (submodule.range_subtype _) ... ≃ₗ[R] f.range : linear_map.quot_ker_equiv_range f ... ≃ₗ[R] N : linear_equiv.of_top _ (range_eq_top_of_epi _) ``` -/ (((submodule.quot_equiv_of_eq _ _ (submodule.range_subtype _)) ≪≫ₗ (linear_map.quot_ker_equiv_range f)) ≪≫ₗ (linear_equiv.of_top _ (range_eq_top_of_epi _)))) $ by { ext, refl } } /-- The category of R-modules is abelian. -/ instance abelian : abelian (Module R) := { has_finite_products := ⟨λ n, limits.has_limits_of_shape_of_has_limits⟩, has_kernels := limits.has_kernels_of_has_equalizers (Module R), has_cokernels := has_cokernels_Module, normal_mono_of_mono := λ X Y, normal_mono, normal_epi_of_epi := λ X Y, normal_epi } section reflects_limits /- We need to put this in this weird spot because we need to know that the category of modules is balanced. -/ instance forget_reflects_limits_of_size : reflects_limits_of_size.{v v} (forget (Module.{max v w} R)) := reflects_limits_of_reflects_isomorphisms instance forget₂_reflects_limits_of_size : reflects_limits_of_size.{v v} (forget₂ (Module.{max v w} R) AddCommGroup.{max v w}) := reflects_limits_of_reflects_isomorphisms instance forget_reflects_limits : reflects_limits (forget (Module.{v} R)) := Module.forget_reflects_limits_of_size.{v v} instance forget₂_reflects_limits : reflects_limits (forget₂ (Module.{v} R) AddCommGroup.{v}) := Module.forget₂_reflects_limits_of_size.{v v} end reflects_limits variables {O : Module.{v} R} (g : N ⟶ O) open linear_map local attribute [instance] preadditive.has_equalizers_of_has_kernels theorem exact_iff : exact f g ↔ f.range = g.ker := begin rw abelian.exact_iff' f g (kernel_is_limit _) (cokernel_is_colimit _), exact ⟨λ h, le_antisymm (range_le_ker_iff.2 h.1) (ker_le_range_iff.2 h.2), λ h, ⟨range_le_ker_iff.1 $ le_of_eq h, ker_le_range_iff.1 $ le_of_eq h.symm⟩⟩ end end Module
754bb288e218a7b26e99c61aa083406c4d7be824
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/297.lean
6568419571357c4e3b9826367de0fe1bce72c2da
[ "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
30
lean
theorem r:0:=do 0if 0then 0 .
385e758dd179c9a7af0ad11c0d54a2a1dcd2af25
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/logic_auto.lean
ff0b7e2c9322b011cb1b6e1085d0774d58188343
[]
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
41,491
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.core universes u v w l u_1 r s namespace Mathlib @[simp] theorem opt_param_eq (α : Sort u) (default : α) : optParam α default = α := rfl def id {α : Sort u} (a : α) : α := a def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := fun (b : β) (a : α) => f a b /- implication -/ def implies (a : Prop) (b : Prop) := a → b /-- Implication `→` is transitive. If `P → Q` and `Q → R` then `P → R`. -/ theorem implies.trans {p : Prop} {q : Prop} {r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := fun (hp : p) => h₂ (h₁ hp) def trivial : True := True.intro /-- We can't have `a` and `¬a`, that would be absurd!-/ def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b := False._oldrec (h₂ h₁) theorem not.intro {a : Prop} (h : a → False) : ¬a := h /-- Modus tollens. If an implication is true, then so is its contrapositive. -/ theorem mt {a : Prop} {b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := fun (ha : a) => h₂ (h₁ ha) /- not -/ theorem not_false : ¬False := id def non_contradictory (a : Prop) := ¬¬a theorem non_contradictory_intro {a : Prop} (ha : a) : ¬¬a := fun (hna : ¬a) => absurd ha hna /- false -/ def false.elim {C : Sort u} (h : False) : C := False._oldrec h /- eq -/ -- proof irrelevance is built in theorem proof_irrel {a : Prop} (h₁ : a) (h₂ : a) : h₁ = h₂ := rfl @[simp] theorem id.def {α : Sort u} (a : α) : id a = a := rfl def eq.mp {α : Sort u} {β : Sort u} : α = β → α → β := eq.rec_on def eq.mpr {α : Sort u} {β : Sort u} : α = β → β → α := fun (h₁ : α = β) (h₂ : β) => eq.rec_on sorry h₂ theorem eq.substr {α : Sort u} {p : α → Prop} {a : α} {b : α} (h₁ : b = a) : p a → p b := Eq.subst (Eq.symm h₁) theorem congr {α : Sort u} {β : Sort v} {f₁ : α → β} {f₂ : α → β} {a₁ : α} {a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := h₁ ▸ h₂ ▸ rfl theorem congr_fun {α : Sort u} {β : α → Sort v} {f : (x : α) → β x} {g : (x : α) → β x} (h : f = g) (a : α) : f a = g a := h ▸ Eq.refl (f a) theorem congr_arg {α : Sort u} {β : Sort v} {a₁ : α} {a₂ : α} (f : α → β) : a₁ = a₂ → f a₁ = f a₂ := congr rfl theorem trans_rel_left {α : Sort u} {a : α} {b : α} {c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ theorem trans_rel_right {α : Sort u} {a : α} {b : α} {c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := Eq.symm h₁ ▸ h₂ theorem of_eq_true {p : Prop} (h : p = True) : p := Eq.symm h ▸ trivial theorem not_of_eq_false {p : Prop} (h : p = False) : ¬p := fun (hp : p) => h ▸ hp def cast {α : Sort u} {β : Sort u} (h : α = β) (a : α) : β := Eq._oldrec a h theorem cast_proof_irrel {α : Sort u} {β : Sort u} (h₁ : α = β) (h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl theorem cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl /- ne -/ def ne {α : Sort u} (a : α) (b : α) := ¬a = b infixl:50 " ≠ " => Mathlib.ne @[simp] theorem ne.def {α : Sort u} (a : α) (b : α) : a ≠ b = (¬a = b) := rfl namespace ne theorem intro {α : Sort u} {a : α} {b : α} (h : a = b → False) : a ≠ b := h theorem elim {α : Sort u} {a : α} {b : α} (h : a ≠ b) : a = b → False := h theorem irrefl {α : Sort u} {a : α} (h : a ≠ a) : False := h rfl theorem symm {α : Sort u} {a : α} {b : α} (h : a ≠ b) : b ≠ a := fun (h₁ : b = a) => h (Eq.symm h₁) end ne theorem false_of_ne {α : Sort u} {a : α} : a ≠ a → False := ne.irrefl theorem ne_false_of_self {p : Prop} : p → p ≠ False := fun (hp : p) (heq : p = False) => heq ▸ hp theorem ne_true_of_not {p : Prop} : ¬p → p ≠ True := fun (hnp : ¬p) (heq : p = True) => Eq.subst heq hnp trivial theorem true_ne_false : ¬True = False := ne_false_of_self trivial theorem heq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a == b) : p a → p b := eq.rec_on (eq_of_heq h₁) theorem heq.subst {α : Sort u} {β : Sort u} {a : α} {b : β} {p : (T : Sort u) → T → Prop} : a == b → p α a → p β b := heq.rec_on theorem heq.symm {α : Sort u} {β : Sort u} {a : α} {b : β} (h : a == b) : b == a := heq.rec_on h (HEq.refl a) theorem heq_of_eq {α : Sort u} {a : α} {a' : α} (h : a = a') : a == a' := h ▸ HEq.refl a theorem heq.trans {α : Sort u} {β : Sort u} {φ : Sort u} {a : α} {b : β} {c : φ} (h₁ : a == b) (h₂ : b == c) : a == c := HEq.subst h₂ h₁ theorem heq_of_heq_of_eq {α : Sort u} {β : Sort u} {a : α} {b : β} {b' : β} (h₁ : a == b) (h₂ : b = b') : a == b' := HEq.trans h₁ (heq_of_eq h₂) theorem heq_of_eq_of_heq {α : Sort u} {β : Sort u} {a : α} {a' : α} {b : β} (h₁ : a = a') (h₂ : a' == b) : a == b := HEq.trans (heq_of_eq h₁) h₂ def type_eq_of_heq {α : Sort u} {β : Sort u} {a : α} {b : β} (h : a == b) : α = β := heq.rec_on h (Eq.refl α) theorem eq_rec_heq {α : Sort u} {φ : α → Sort v} {a : α} {a' : α} (h : a = a') (p : φ a) : eq.rec_on h p == p := sorry theorem heq_of_eq_rec_left {α : Sort u} {φ : α → Sort v} {a : α} {a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a = a') (h₂ : eq.rec_on e p₁ = p₂) : p₁ == p₂ := sorry theorem heq_of_eq_rec_right {α : Sort u} {φ : α → Sort v} {a : α} {a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a' = a) (h₂ : p₁ = eq.rec_on e p₂) : p₁ == p₂ := sorry theorem of_heq_true {a : Prop} (h : a == True) : a := of_eq_true (eq_of_heq h) theorem eq_rec_compose {α : Sort u} {β : Sort u} {φ : Sort u} (p₁ : β = φ) (p₂ : α = β) (a : α) : eq.rec_on p₁ (eq.rec_on p₂ a) = eq.rec_on (Eq.trans p₂ p₁) a := sorry theorem cast_heq {α : Sort u} {β : Sort u} (h : α = β) (a : α) : cast h a == a := sorry infixr:35 " /\ " => Mathlib.and infixr:35 " ∧ " => Mathlib.and /- and -/ theorem and.elim {a : Prop} {b : Prop} {c : Prop} (h₁ : a ∧ b) (h₂ : a → b → c) : c := And._oldrec h₂ h₁ theorem and.swap {a : Prop} {b : Prop} : a ∧ b → b ∧ a := fun (_x : a ∧ b) => (fun (_a : a ∧ b) => and.dcases_on _a fun (left : a) (right : b) => idRhs (b ∧ a) { left := right, right := left }) _x def and.symm {a : Prop} {b : Prop} : a ∧ b → b ∧ a := and.swap infixr:30 " \/ " => Mathlib.or infixr:30 " ∨ " => Mathlib.or /- or -/ namespace or theorem elim {a : Prop} {b : Prop} {c : Prop} (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := Or._oldrec h₂ h₃ h₁ end or theorem non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := fun (not_em : ¬(a ∨ ¬a)) => (fun (neg_a : ¬a) => absurd (Or.inr neg_a) not_em) fun (pos_a : a) => absurd (Or.inl pos_a) not_em def not_not_em (a : Prop) : ¬¬(a ∨ ¬a) := non_contradictory_em theorem or.swap {a : Prop} {b : Prop} : a ∨ b → b ∨ a := Or._oldrec Or.inr Or.inl def or.symm {a : Prop} {b : Prop} : a ∨ b → b ∨ a := or.swap /- xor -/ def xor (a : Prop) (b : Prop) := a ∧ ¬b ∨ b ∧ ¬a /- iff -/ /-- `iff P Q`, with notation `P ↔ Q`, is the proposition asserting that `P` and `Q` are equivalent, that is, have the same truth value. -/ not found infixl:20 " <-> " => Mathlib.iff infixl:20 " ↔ " => Mathlib.iff theorem iff.elim {a : Prop} {b : Prop} {c : Prop} : ((a → b) → (b → a) → c) → (a ↔ b) → c := Iff._oldrec theorem iff.elim_left {a : Prop} {b : Prop} : (a ↔ b) → a → b := iff.mp theorem iff.elim_right {a : Prop} {b : Prop} : (a ↔ b) → b → a := iff.mpr theorem iff_iff_implies_and_implies (a : Prop) (b : Prop) : a ↔ b ↔ (a → b) ∧ (b → a) := { mp := fun (h : a ↔ b) => { left := iff.mp h, right := iff.mpr h }, mpr := fun (h : (a → b) ∧ (b → a)) => { mp := and.left h, mpr := and.right h } } theorem iff.refl (a : Prop) : a ↔ a := { mp := fun (h : a) => h, mpr := fun (h : a) => h } theorem iff.rfl {a : Prop} : a ↔ a := iff.refl a theorem iff.trans {a : Prop} {b : Prop} {c : Prop} (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := { mp := fun (ha : a) => iff.mp h₂ (iff.mp h₁ ha), mpr := fun (hc : c) => iff.mpr h₁ (iff.mpr h₂ hc) } theorem iff.symm {a : Prop} {b : Prop} (h : a ↔ b) : b ↔ a := { mp := iff.elim_right h, mpr := iff.elim_left h } theorem iff.comm {a : Prop} {b : Prop} : a ↔ b ↔ (b ↔ a) := { mp := iff.symm, mpr := iff.symm } theorem eq.to_iff {a : Prop} {b : Prop} (h : a = b) : a ↔ b := eq.rec_on h iff.rfl theorem neq_of_not_iff {a : Prop} {b : Prop} : ¬(a ↔ b) → a ≠ b := fun (h₁ : ¬(a ↔ b)) (h₂ : a = b) => (fun (this : a ↔ b) => absurd this h₁) (h₂ ▸ iff.refl a) theorem not_iff_not_of_iff {a : Prop} {b : Prop} (h₁ : a ↔ b) : ¬a ↔ ¬b := { mp := fun (hna : ¬a) (hb : b) => hna (iff.elim_right h₁ hb), mpr := fun (hnb : ¬b) (ha : a) => hnb (iff.elim_left h₁ ha) } theorem of_iff_true {a : Prop} (h : a ↔ True) : a := iff.mp (iff.symm h) trivial theorem not_of_iff_false {a : Prop} : (a ↔ False) → ¬a := iff.mp theorem iff_true_intro {a : Prop} (h : a) : a ↔ True := { mp := fun (hl : a) => trivial, mpr := fun (hr : True) => h } theorem iff_false_intro {a : Prop} (h : ¬a) : a ↔ False := { mp := h, mpr := False._oldrec } theorem not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := { mp := fun (hl : ¬¬¬a) (ha : a) => hl (non_contradictory_intro ha), mpr := absurd } def not_not_not_iff (a : Prop) : ¬¬¬a ↔ ¬a := not_non_contradictory_iff_absurd theorem imp_congr {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ↔ c) (h₂ : b ↔ d) : a → b ↔ c → d := { mp := fun (hab : a → b) (hc : c) => iff.mp h₂ (hab (iff.mpr h₁ hc)), mpr := fun (hcd : c → d) (ha : a) => iff.mpr h₂ (hcd (iff.mp h₁ ha)) } theorem imp_congr_ctx {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : a → b ↔ c → d := { mp := fun (hab : a → b) (hc : c) => (fun (ha : a) => (fun (hb : b) => iff.mp (h₂ hc) hb) (hab ha)) (iff.mpr h₁ hc), mpr := fun (hcd : c → d) (ha : a) => (fun (hc : c) => (fun (hd : d) => iff.mpr (h₂ hc) hd) (hcd hc)) (iff.mp h₁ ha) } theorem imp_congr_right {a : Prop} {b : Prop} {c : Prop} (h : a → (b ↔ c)) : a → b ↔ a → c := { mp := fun (hab : a → b) (ha : a) => iff.elim_left (h ha) (hab ha), mpr := fun (hab : a → c) (ha : a) => iff.elim_right (h ha) (hab ha) } theorem not_not_intro {a : Prop} (ha : a) : ¬¬a := fun (hna : ¬a) => hna ha theorem not_of_not_not_not {a : Prop} (h : ¬¬¬a) : ¬a := fun (ha : a) => absurd (not_not_intro ha) h @[simp] theorem not_true : ¬True ↔ False := iff_false_intro (not_not_intro trivial) def not_true_iff : ¬True ↔ False := not_true @[simp] theorem not_false_iff : ¬False ↔ True := iff_true_intro not_false theorem not_congr {a : Prop} {b : Prop} (h : a ↔ b) : ¬a ↔ ¬b := { mp := fun (h₁ : ¬a) (h₂ : b) => h₁ (iff.mpr h h₂), mpr := fun (h₁ : ¬b) (h₂ : a) => h₁ (iff.mp h h₂) } @[simp] theorem ne_self_iff_false {α : Sort u} (a : α) : ¬a = a ↔ False := { mp := false_of_ne, mpr := false.elim } @[simp] theorem eq_self_iff_true {α : Sort u} (a : α) : a = a ↔ True := iff_true_intro rfl @[simp] theorem heq_self_iff_true {α : Sort u} (a : α) : a == a ↔ True := iff_true_intro (HEq.refl a) @[simp] theorem iff_not_self (a : Prop) : a ↔ ¬a ↔ False := iff_false_intro fun (h : a ↔ ¬a) => (fun (h' : ¬a) => h' (iff.mpr h h')) fun (ha : a) => iff.mp h ha ha @[simp] theorem not_iff_self (a : Prop) : ¬a ↔ a ↔ False := iff_false_intro fun (h : ¬a ↔ a) => (fun (h' : ¬a) => h' (iff.mp h h')) fun (ha : a) => iff.mpr h ha ha @[simp] theorem true_iff_false : True ↔ False ↔ False := iff_false_intro fun (h : True ↔ False) => iff.mp h trivial @[simp] theorem false_iff_true : False ↔ True ↔ False := iff_false_intro fun (h : False ↔ True) => iff.mpr h trivial theorem false_of_true_iff_false : (True ↔ False) → False := fun (h : True ↔ False) => iff.mp h trivial theorem false_of_true_eq_false : True = False → False := fun (h : True = False) => h ▸ trivial theorem true_eq_false_of_false : False → True = False := false.elim theorem eq_comm {α : Sort u} {a : α} {b : α} : a = b ↔ b = a := { mp := Eq.symm, mpr := Eq.symm } /- and simp rules -/ theorem and.imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := sorry def and_implies {a : Prop} {b : Prop} {c : Prop} {d : Prop} (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := and.imp theorem and_congr {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ↔ c) (h₂ : b ↔ d) : a ∧ b ↔ c ∧ d := { mp := and.imp (iff.mp h₁) (iff.mp h₂), mpr := and.imp (iff.mpr h₁) (iff.mpr h₂) } theorem and_congr_right {a : Prop} {b : Prop} {c : Prop} (h : a → (b ↔ c)) : a ∧ b ↔ a ∧ c := sorry theorem and.comm {a : Prop} {b : Prop} : a ∧ b ↔ b ∧ a := { mp := and.swap, mpr := and.swap } theorem and_comm (a : Prop) (b : Prop) : a ∧ b ↔ b ∧ a := and.comm theorem and.assoc {a : Prop} {b : Prop} {c : Prop} : (a ∧ b) ∧ c ↔ a ∧ b ∧ c := sorry theorem and_assoc {c : Prop} (a : Prop) (b : Prop) : (a ∧ b) ∧ c ↔ a ∧ b ∧ c := and.assoc theorem and.left_comm {a : Prop} {b : Prop} {c : Prop} : a ∧ b ∧ c ↔ b ∧ a ∧ c := iff.trans (iff.symm and.assoc) (iff.trans (and_congr and.comm (iff.refl c)) and.assoc) theorem and_iff_left {a : Prop} {b : Prop} (hb : b) : a ∧ b ↔ a := { mp := and.left, mpr := fun (ha : a) => { left := ha, right := hb } } theorem and_iff_right {a : Prop} {b : Prop} (ha : a) : a ∧ b ↔ b := { mp := and.right, mpr := And.intro ha } @[simp] theorem and_true (a : Prop) : a ∧ True ↔ a := and_iff_left trivial @[simp] theorem true_and (a : Prop) : True ∧ a ↔ a := and_iff_right trivial @[simp] theorem and_false (a : Prop) : a ∧ False ↔ False := iff_false_intro and.right @[simp] theorem false_and (a : Prop) : False ∧ a ↔ False := iff_false_intro and.left @[simp] theorem not_and_self (a : Prop) : ¬a ∧ a ↔ False := iff_false_intro fun (h : ¬a ∧ a) => and.elim h fun (h₁ : ¬a) (h₂ : a) => absurd h₂ h₁ @[simp] theorem and_not_self (a : Prop) : a ∧ ¬a ↔ False := iff_false_intro fun (_x : a ∧ ¬a) => (fun (_a : a ∧ ¬a) => and.dcases_on _a fun (left : a) (right : ¬a) => idRhs False (absurd left right)) _x @[simp] theorem and_self (a : Prop) : a ∧ a ↔ a := { mp := and.left, mpr := fun (h : a) => { left := h, right := h } } /- or simp rules -/ theorem or.imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₂ : a → c) (h₃ : b → d) : a ∨ b → c ∨ d := Or._oldrec (fun (h : a) => Or.inl (h₂ h)) fun (h : b) => Or.inr (h₃ h) theorem or.imp_left {a : Prop} {b : Prop} {c : Prop} (h : a → b) : a ∨ c → b ∨ c := or.imp h id theorem or.imp_right {a : Prop} {b : Prop} {c : Prop} (h : a → b) : c ∨ a → c ∨ b := or.imp id h theorem or_congr {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ↔ c) (h₂ : b ↔ d) : a ∨ b ↔ c ∨ d := { mp := or.imp (iff.mp h₁) (iff.mp h₂), mpr := or.imp (iff.mpr h₁) (iff.mpr h₂) } theorem or.comm {a : Prop} {b : Prop} : a ∨ b ↔ b ∨ a := { mp := or.swap, mpr := or.swap } theorem or_comm (a : Prop) (b : Prop) : a ∨ b ↔ b ∨ a := or.comm theorem or.assoc {a : Prop} {b : Prop} {c : Prop} : (a ∨ b) ∨ c ↔ a ∨ b ∨ c := { mp := Or._oldrec (or.imp_right Or.inl) fun (h : c) => Or.inr (Or.inr h), mpr := Or._oldrec (fun (h : a) => Or.inl (Or.inl h)) (or.imp_left Or.inr) } theorem or_assoc {c : Prop} (a : Prop) (b : Prop) : (a ∨ b) ∨ c ↔ a ∨ b ∨ c := or.assoc theorem or.left_comm {a : Prop} {b : Prop} {c : Prop} : a ∨ b ∨ c ↔ b ∨ a ∨ c := iff.trans (iff.symm or.assoc) (iff.trans (or_congr or.comm (iff.refl c)) or.assoc) theorem or_iff_right_of_imp {a : Prop} {b : Prop} (ha : a → b) : a ∨ b ↔ b := { mp := Or._oldrec ha id, mpr := Or.inr } theorem or_iff_left_of_imp {a : Prop} {b : Prop} (hb : b → a) : a ∨ b ↔ a := { mp := Or._oldrec id hb, mpr := Or.inl } @[simp] theorem or_true (a : Prop) : a ∨ True ↔ True := iff_true_intro (Or.inr trivial) @[simp] theorem true_or (a : Prop) : True ∨ a ↔ True := iff_true_intro (Or.inl trivial) @[simp] theorem or_false (a : Prop) : a ∨ False ↔ a := { mp := Or._oldrec id false.elim, mpr := Or.inl } @[simp] theorem false_or (a : Prop) : False ∨ a ↔ a := iff.trans or.comm (or_false a) @[simp] theorem or_self (a : Prop) : a ∨ a ↔ a := { mp := Or._oldrec id id, mpr := Or.inl } theorem not_or {a : Prop} {b : Prop} : ¬a → ¬b → ¬(a ∨ b) := fun (ᾰ : ¬a) (ᾰ_1 : ¬b) (ᾰ_2 : a ∨ b) => or.dcases_on ᾰ_2 (fun (ᾰ_1 : a) => idRhs False (absurd ᾰ_1 ᾰ)) fun (ᾰ_1_1 : b) => idRhs False (absurd ᾰ_1_1 ᾰ_1) /- or resolution rulse -/ def or.resolve_left {a : Prop} {b : Prop} (h : a ∨ b) (na : ¬a) : b := or.elim h (fun (ha : a) => absurd ha na) id def or.neg_resolve_left {a : Prop} {b : Prop} (h : ¬a ∨ b) (ha : a) : b := or.elim h (fun (na : ¬a) => absurd ha na) id def or.resolve_right {a : Prop} {b : Prop} (h : a ∨ b) (nb : ¬b) : a := or.elim h id fun (hb : b) => absurd hb nb def or.neg_resolve_right {a : Prop} {b : Prop} (h : a ∨ ¬b) (hb : b) : a := or.elim h id fun (nb : ¬b) => absurd hb nb /- iff simp rules -/ @[simp] theorem iff_true (a : Prop) : a ↔ True ↔ a := { mp := fun (h : a ↔ True) => iff.mpr h trivial, mpr := iff_true_intro } @[simp] theorem true_iff (a : Prop) : True ↔ a ↔ a := iff.trans iff.comm (iff_true a) @[simp] theorem iff_false (a : Prop) : a ↔ False ↔ ¬a := { mp := iff.mp, mpr := iff_false_intro } @[simp] theorem false_iff (a : Prop) : False ↔ a ↔ ¬a := iff.trans iff.comm (iff_false a) @[simp] theorem iff_self (a : Prop) : a ↔ a ↔ True := iff_true_intro iff.rfl theorem iff_congr {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ↔ c) (h₂ : b ↔ d) : a ↔ b ↔ (c ↔ d) := iff.trans (iff_iff_implies_and_implies a b) (iff.trans (and_congr (imp_congr h₁ h₂) (imp_congr h₂ h₁)) (iff.symm (iff_iff_implies_and_implies c d))) /- implies simp rule -/ @[simp] theorem implies_true_iff (α : Sort u) : α → True ↔ True := { mp := fun (h : α → True) => trivial, mpr := fun (ha : True) (h : α) => trivial } @[simp] theorem false_implies_iff (a : Prop) : False → a ↔ True := { mp := fun (h : False → a) => trivial, mpr := fun (ha : True) (h : False) => false.elim h } @[simp] theorem true_implies_iff (α : Prop) : True → α ↔ α := { mp := fun (h : True → α) => h trivial, mpr := fun (h : α) (h' : True) => h } /-- The existential quantifier. To prove a goal of the form `⊢ ∃ x, p x`, you can provide a witness `y` with the tactic `existsi y`. If you are working in a project that depends on mathlib, then we recommend the `use` tactic instead. You'll then be left with the goal `⊢ p y`. To extract a witness `x` and proof `hx : p x` from a hypothesis `h : ∃ x, p x`, use the tactic `cases h with x hx`. See also the mathlib tactics `obtain` and `rcases`. -/ not found def exists.intro {α : Sort u_1} {p : α → Prop} (w : α) (h : p w) : Exists p := Exists.intro theorem exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : ∃ (x : α), p x) (h₂ : ∀ (a : α), p a → b) : b := Exists._oldrec h₂ h₁ /- exists unique -/ def exists_unique {α : Sort u} (p : α → Prop) := ∃ (x : α), p x ∧ ∀ (y : α), p y → y = x theorem exists_unique.intro {α : Sort u} {p : α → Prop} (w : α) (h₁ : p w) (h₂ : ∀ (y : α), p y → y = w) : exists_unique fun (x : α) => p x := exists.intro w { left := h₁, right := h₂ } theorem exists_unique.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₂ : exists_unique fun (x : α) => p x) (h₁ : ∀ (x : α), p x → (∀ (y : α), p y → y = x) → b) : b := exists.elim h₂ fun (w : α) (hw : (fun (x : α) => p x) w ∧ ∀ (y : α), p y → y = w) => h₁ w (and.left hw) (and.right hw) theorem exists_unique_of_exists_of_unique {α : Type u} {p : α → Prop} (hex : ∃ (x : α), p x) (hunique : ∀ (y₁ y₂ : α), p y₁ → p y₂ → y₁ = y₂) : exists_unique fun (x : α) => p x := exists.elim hex fun (x : α) (px : p x) => exists_unique.intro x px fun (y : α) (this : p y) => hunique y x this px theorem exists_of_exists_unique {α : Sort u} {p : α → Prop} (h : exists_unique fun (x : α) => p x) : ∃ (x : α), p x := exists.elim h fun (x : α) (hx : (fun (x : α) => p x) x ∧ ∀ (y : α), p y → y = x) => Exists.intro x (and.left hx) theorem unique_of_exists_unique {α : Sort u} {p : α → Prop} (h : exists_unique fun (x : α) => p x) {y₁ : α} {y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := exists_unique.elim h fun (x : α) (this : p x) (unique : ∀ (y : α), p y → y = x) => (fun (this : y₁ = y₂) => this) (Eq.trans (unique y₁ py₁) (Eq.symm (unique y₂ py₂))) /- exists, forall, exists unique congruences -/ theorem forall_congr {α : Sort u} {p : α → Prop} {q : α → Prop} (h : ∀ (a : α), p a ↔ q a) : (∀ (a : α), p a) ↔ ∀ (a : α), q a := { mp := fun (p_1 : ∀ (a : α), p a) (a : α) => iff.mp (h a) (p_1 a), mpr := fun (q_1 : ∀ (a : α), q a) (a : α) => iff.mpr (h a) (q_1 a) } theorem exists_imp_exists {α : Sort u} {p : α → Prop} {q : α → Prop} (h : ∀ (a : α), p a → q a) : (∃ (a : α), p a) → ∃ (a : α), q a := fun (p_1 : ∃ (a : α), p a) => exists.elim p_1 fun (a : α) (hp : p a) => Exists.intro a (h a hp) theorem exists_congr {α : Sort u} {p : α → Prop} {q : α → Prop} (h : ∀ (a : α), p a ↔ q a) : Exists p ↔ ∃ (a : α), q a := { mp := exists_imp_exists fun (a : α) => iff.mp (h a), mpr := exists_imp_exists fun (a : α) => iff.mpr (h a) } theorem exists_unique_congr {α : Sort u} {p₁ : α → Prop} {p₂ : α → Prop} (h : ∀ (x : α), p₁ x ↔ p₂ x) : exists_unique p₁ ↔ exists_unique fun (x : α) => p₂ x := exists_congr fun (x : α) => and_congr (h x) (forall_congr fun (y : α) => imp_congr (h y) iff.rfl) theorem forall_not_of_not_exists {α : Sort u} {p : α → Prop} : (¬∃ (x : α), p x) → ∀ (x : α), ¬p x := fun (hne : ¬∃ (x : α), p x) (x : α) (hp : p x) => hne (Exists.intro x hp) /- decidable -/ def decidable.to_bool (p : Prop) [h : Decidable p] : Bool := decidable.cases_on h (fun (h₁ : ¬p) => false) fun (h₂ : p) => tt @[simp] theorem to_bool_true_eq_tt (h : Decidable True) : to_bool True = tt := decidable.cases_on h (fun (h : ¬True) => false.elim (iff.mp not_true h)) fun (_x : True) => rfl @[simp] theorem to_bool_false_eq_ff (h : Decidable False) : to_bool False = false := decidable.cases_on h (fun (h : ¬False) => rfl) fun (h : False) => false.elim h protected instance decidable.true : Decidable True := is_true trivial protected instance decidable.false : Decidable False := is_false not_false -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches def dite (c : Prop) [h : Decidable c] {α : Sort u} : (c → α) → (¬c → α) → α := fun (t : c → α) (e : ¬c → α) => decidable.rec_on h e t /- if-then-else -/ def ite (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : α := decidable.rec_on h (fun (hnc : ¬c) => e) fun (hc : c) => t namespace decidable def rec_on_true {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (fun (h : ¬p) => False._oldrec (h h₃)) fun (h : p) => h₄ def rec_on_false {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (fun (h : ¬p) => h₄) fun (h : p) => False._oldrec (h₃ h) def by_cases {p : Prop} {q : Sort u} [φ : Decidable p] : (p → q) → (¬p → q) → q := dite p theorem em (p : Prop) [Decidable p] : p ∨ ¬p := by_cases Or.inl Or.inr theorem by_contradiction {p : Prop} [Decidable p] (h : ¬p → False) : p := dite p (fun (h₁ : p) => h₁) fun (h₁ : ¬p) => False._oldrec (h h₁) theorem of_not_not {p : Prop} [Decidable p] : ¬¬p → p := fun (hnn : ¬¬p) => by_contradiction fun (hn : ¬p) => absurd hn hnn theorem not_not_iff (p : Prop) [Decidable p] : ¬¬p ↔ p := { mp := of_not_not, mpr := not_not_intro } theorem not_and_iff_or_not (p : Prop) (q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬(p ∧ q) ↔ ¬p ∨ ¬q := sorry theorem not_or_iff_and_not (p : Prop) (q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬(p ∨ q) ↔ ¬p ∧ ¬q := sorry end decidable def decidable_of_decidable_of_iff {p : Prop} {q : Prop} (hp : Decidable p) (h : p ↔ q) : Decidable q := dite p (fun (hp : p) => is_true (iff.mp h hp)) fun (hp : ¬p) => is_false sorry def decidable_of_decidable_of_eq {p : Prop} {q : Prop} (hp : Decidable p) (h : p = q) : Decidable q := decidable_of_decidable_of_iff hp (eq.to_iff h) protected def or.by_cases {p : Prop} {q : Prop} [Decidable p] [Decidable q] {α : Sort u} (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := dite p (fun (hp : p) => h₁ hp) fun (hp : ¬p) => dite q (fun (hq : q) => h₂ hq) fun (hq : ¬q) => False._oldrec (or.elim h hp hq) protected instance and.decidable {p : Prop} {q : Prop} [Decidable p] [Decidable q] : Decidable (p ∧ q) := dite p (fun (hp : p) => dite q (fun (hq : q) => is_true { left := hp, right := hq }) fun (hq : ¬q) => is_false sorry) fun (hp : ¬p) => is_false sorry protected instance or.decidable {p : Prop} {q : Prop} [Decidable p] [Decidable q] : Decidable (p ∨ q) := dite p (fun (hp : p) => is_true (Or.inl hp)) fun (hp : ¬p) => dite q (fun (hq : q) => is_true (Or.inr hq)) fun (hq : ¬q) => is_false (Or._oldrec hp hq) protected instance not.decidable {p : Prop} [Decidable p] : Decidable (¬p) := dite p (fun (hp : p) => is_false (absurd hp)) fun (hp : ¬p) => is_true hp protected instance implies.decidable {p : Prop} {q : Prop} [Decidable p] [Decidable q] : Decidable (p → q) := dite p (fun (hp : p) => dite q (fun (hq : q) => is_true sorry) fun (hq : ¬q) => is_false sorry) fun (hp : ¬p) => is_true sorry protected instance iff.decidable {p : Prop} {q : Prop} [Decidable p] [Decidable q] : Decidable (p ↔ q) := dite p (fun (hp : p) => dite q (fun (hq : q) => is_true sorry) fun (hq : ¬q) => is_false sorry) fun (hp : ¬p) => dite q (fun (hq : q) => is_false sorry) fun (hq : ¬q) => is_true sorry protected instance xor.decidable {p : Prop} {q : Prop} [Decidable p] [Decidable q] : Decidable (xor p q) := dite p (fun (hp : p) => dite q (fun (hq : q) => is_false sorry) fun (hq : ¬q) => is_true sorry) fun (hp : ¬p) => dite q (fun (hq : q) => is_true sorry) fun (hq : ¬q) => is_false sorry protected instance exists_prop_decidable {p : Prop} (P : p → Prop) [Dp : Decidable p] [DP : (h : p) → Decidable (P h)] : Decidable (∃ (h : p), P h) := dite p (fun (h : p) => decidable_of_decidable_of_iff (DP h) sorry) fun (h : ¬p) => is_false sorry protected instance forall_prop_decidable {p : Prop} (P : p → Prop) [Dp : Decidable p] [DP : (h : p) → Decidable (P h)] : Decidable (∀ (h : p), P h) := dite p (fun (h : p) => decidable_of_decidable_of_iff (DP h) sorry) fun (h : ¬p) => is_true sorry protected instance ne.decidable {α : Sort u} [DecidableEq α] (a : α) (b : α) : Decidable (a ≠ b) := implies.decidable theorem bool.ff_ne_tt : false = tt → False := fun (ᾰ : false = tt) => eq.dcases_on ᾰ (fun (H_1 : tt = false) => bool.no_confusion H_1) (Eq.refl tt) (HEq.refl ᾰ) def is_dec_eq {α : Sort u} (p : α → α → Bool) := ∀ {x y : α}, p x y = tt → x = y def is_dec_refl {α : Sort u} (p : α → α → Bool) := ∀ (x : α), p x x = tt protected instance bool.decidable_eq : DecidableEq Bool := sorry def decidable_eq_of_bool_pred {α : Sort u} {p : α → α → Bool} (h₁ : is_dec_eq p) (h₂ : is_dec_refl p) : DecidableEq α := fun (x y : α) => dite (p x y = tt) (fun (hp : p x y = tt) => is_true (h₁ hp)) fun (hp : ¬p x y = tt) => is_false sorry theorem decidable_eq_inl_refl {α : Sort u} [h : DecidableEq α] (a : α) : h a a = is_true (Eq.refl a) := sorry theorem decidable_eq_inr_neg {α : Sort u} [h : DecidableEq α] {a : α} {b : α} (n : a ≠ b) : h a b = is_false n := sorry /- inhabited -/ not found def arbitrary (α : Sort u) [Inhabited α] : α := Inhabited.default protected instance prop.inhabited : Inhabited Prop := { default := True } protected instance pi.inhabited (α : Sort u) {β : α → Sort v} [(x : α) → Inhabited (β x)] : Inhabited ((x : α) → β x) := { default := fun (a : α) => Inhabited.default } protected instance bool.inhabited : Inhabited Bool := { default := false } protected instance true.inhabited : Inhabited True := { default := trivial } not found protected def nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := Nonempty._oldrec h₂ h₁ protected instance nonempty_of_inhabited {α : Sort u} [Inhabited α] : Nonempty α := Nonempty.intro Inhabited.default theorem nonempty_of_exists {α : Sort u} {p : α → Prop} : (∃ (x : α), p x) → Nonempty α := fun (ᾰ : ∃ (x : α), p x) => Exists.dcases_on ᾰ fun (ᾰ_w : α) (ᾰ_h : p ᾰ_w) => idRhs (Nonempty α) (Nonempty.intro ᾰ_w) /- subsingleton -/ class inductive subsingleton (α : Sort u) where | intro : (∀ (a b : α), a = b) → subsingleton α protected def subsingleton.elim {α : Sort u} [h : subsingleton α] (a : α) (b : α) : a = b := subsingleton._oldrec (fun (p : ∀ (a b : α), a = b) => p) h protected def subsingleton.helim {α : Sort u} {β : Sort u} [h : subsingleton α] : α = β → ∀ (a : α) (b : β), a == b := fun (h_1 : α = β) => eq.rec_on h_1 fun (a b : α) => heq_of_eq (subsingleton.elim a b) protected instance subsingleton_prop (p : Prop) : subsingleton p := subsingleton.intro fun (a b : p) => proof_irrel a b protected instance decidable.subsingleton (p : Prop) : subsingleton (Decidable p) := subsingleton.intro fun (d₁ : Decidable p) => sorry protected theorem rec_subsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : ∀ (h : p), subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), subsingleton (h₂ h)] : subsingleton (decidable.rec_on h h₂ h₁) := sorry theorem if_pos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : α} {e : α} : ite c t e = t := sorry theorem if_neg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : α} {e : α} : ite c t e = e := sorry @[simp] theorem if_t_t (c : Prop) [h : Decidable c] {α : Sort u} (t : α) : ite c t t = t := sorry theorem implies_of_if_pos {c : Prop} {t : Prop} {e : Prop} [Decidable c] (h : ite c t e) : c → t := fun (hc : c) => eq.rec_on (if_pos hc) h theorem implies_of_if_neg {c : Prop} {t : Prop} {e : Prop} [Decidable c] (h : ite c t e) : ¬c → e := fun (hnc : ¬c) => eq.rec_on (if_neg hnc) h theorem if_ctx_congr {α : Sort u} {b : Prop} {c : Prop} [dec_b : Decidable b] [dec_c : Decidable c] {x : α} {y : α} {u : α} {v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := sorry theorem if_congr {α : Sort u} {b : Prop} {c : Prop} [dec_b : Decidable b] [dec_c : Decidable c] {x : α} {y : α} {u : α} {v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := if_ctx_congr h_c (fun (h : c) => h_t) fun (h : ¬c) => h_e @[simp] theorem if_true {α : Sort u} {h : Decidable True} (t : α) (e : α) : ite True t e = t := if_pos trivial @[simp] theorem if_false {α : Sort u} {h : Decidable False} (t : α) (e : α) : ite False t e = e := if_neg not_false theorem if_ctx_congr_prop {b : Prop} {c : Prop} {x : Prop} {y : Prop} {u : Prop} {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 := sorry theorem if_congr_prop {b : Prop} {c : Prop} {x : Prop} {y : Prop} {u : Prop} {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 (fun (h : c) => h_t) fun (h : ¬c) => h_e theorem if_ctx_simp_congr_prop {b : Prop} {c : Prop} {x : Prop} {y : Prop} {u : Prop} {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 u v := if_ctx_congr_prop h_c h_t h_e theorem if_simp_congr_prop {b : Prop} {c : Prop} {x : Prop} {y : Prop} {u : Prop} {v : Prop} [dec_b : Decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_simp_congr_prop h_c (fun (h : c) => h_t) fun (h : ¬c) => h_e @[simp] theorem dif_pos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬c → α} : dite c t e = t hc := sorry @[simp] theorem dif_neg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬c → α} : dite c t e = e hnc := sorry theorem dif_ctx_congr {α : Sort u} {b : Prop} {c : Prop} [dec_b : Decidable b] [dec_c : Decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (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 x y = dite c u v := sorry theorem dif_ctx_simp_congr {α : Sort u} {b : Prop} {c : Prop} [dec_b : Decidable b] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (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 x y = dite c u v := dif_ctx_congr h_c h_t h_e -- Remark: dite and ite are "defally equal" when we ignore the proofs. theorem dif_eq_if (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : (dite c (fun (h : c) => t) fun (h : ¬c) => e) = ite c t e := sorry protected instance ite.decidable {c : Prop} {t : Prop} {e : Prop} [d_c : Decidable c] [d_t : Decidable t] [d_e : Decidable e] : Decidable (ite c t e) := sorry protected instance dite.decidable {c : Prop} {t : c → Prop} {e : ¬c → Prop} [d_c : Decidable c] [d_t : (h : c) → Decidable (t h)] [d_e : (h : ¬c) → Decidable (e h)] : Decidable (dite c (fun (h : c) => t h) fun (h : ¬c) => e h) := sorry def as_true (c : Prop) [Decidable c] := ite c True False def as_false (c : Prop) [Decidable c] := ite c False True def of_as_true {c : Prop} [h₁ : Decidable c] (h₂ : as_true c) : c := sorry /-- Universe lifting operation -/ structure ulift (α : Type s) where up :: (down : α) namespace ulift /- Bijection between α and ulift.{v} α -/ theorem up_down {α : Type u} (b : ulift α) : up (down b) = b := cases_on b fun (b : α) => idRhs (up (down (up b)) = up (down (up b))) rfl end ulift theorem ulift.down_up {α : Type u} (a : α) : ulift.down (ulift.up a) = a := rfl /-- Universe lifting operation from Sort to Type -/ structure plift (α : Sort u) where up :: (down : α) namespace plift /- Bijection between α and plift α -/ theorem up_down {α : Sort u} (b : plift α) : up (down b) = b := cases_on b fun (b : α) => idRhs (up (down (up b)) = up (down (up b))) rfl end plift theorem plift.down_up {α : Sort u} (a : α) : plift.down (plift.up a) = a := rfl /- Equalities for rewriting let-expressions -/ theorem let_value_eq {α : Sort u} {β : Sort v} {a₁ : α} {a₂ : α} (b : α → β) : a₁ = a₂ → (let x : α := a₁; b x) = let x : α := a₂; b x := fun (h : a₁ = a₂) => eq.rec_on h rfl theorem let_value_heq {α : Sort v} {β : α → Sort u} {a₁ : α} {a₂ : α} (b : (x : α) → β x) : a₁ = a₂ → (let x : α := a₁; b x) == let x : α := a₂; b x := fun (h : a₁ = a₂) => eq.rec_on h (HEq.refl (b a₁)) theorem let_body_eq {α : Sort v} {β : α → Sort u} (a : α) {b₁ : (x : α) → β x} {b₂ : (x : α) → β x} : (∀ (x : α), b₁ x = b₂ x) → (let x : α := a; b₁ x) = let x : α := a; b₂ x := fun (h : ∀ (x : α), b₁ x = b₂ x) => h a theorem let_eq {α : Sort v} {β : Sort u} {a₁ : α} {a₂ : α} {b₁ : α → β} {b₂ : α → β} : a₁ = a₂ → (∀ (x : α), b₁ x = b₂ x) → (let x : α := a₁; b₁ x) = let x : α := a₂; b₂ x := fun (h₁ : a₁ = a₂) (h₂ : ∀ (x : α), b₁ x = b₂ x) => eq.rec_on h₁ (h₂ a₁) def reflexive {β : Sort v} (r : β → β → Prop) := ∀ (x : β), r x x def symmetric {β : Sort v} (r : β → β → Prop) := ∀ {x y : β}, r x y → r y x def transitive {β : Sort v} (r : β → β → Prop) := ∀ {x y z : β}, r x y → r y z → r x z def equivalence {β : Sort v} (r : β → β → Prop) := reflexive r ∧ symmetric r ∧ transitive r def total {β : Sort v} (r : β → β → Prop) := ∀ (x y : β), r x y ∨ r y x def mk_equivalence {β : Sort v} (r : β → β → Prop) (rfl : reflexive r) (symm : symmetric r) (trans : transitive r) : equivalence r := { left := rfl, right := { left := symm, right := trans } } def irreflexive {β : Sort v} (r : β → β → Prop) := ∀ (x : β), ¬r x x def anti_symmetric {β : Sort v} (r : β → β → Prop) := ∀ {x y : β}, r x y → r y x → x = y def empty_relation {α : Sort u} (a₁ : α) (a₂ : α) := False def subrelation {β : Sort v} (q : β → β → Prop) (r : β → β → Prop) := ∀ {x y : β}, q x y → r x y def inv_image {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop := fun (a₁ a₂ : α) => r (f a₁) (f a₂) theorem inv_image.trans {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) (h : transitive r) : transitive (inv_image r f) := fun (a₁ a₂ a₃ : α) (h₁ : inv_image r f a₁ a₂) (h₂ : inv_image r f a₂ a₃) => h h₁ h₂ theorem inv_image.irreflexive {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) (h : irreflexive r) : irreflexive (inv_image r f) := fun (a : α) (h₁ : inv_image r f a a) => h (f a) h₁ inductive tc {α : Sort u} (r : α → α → Prop) : α → α → Prop where | base : ∀ (a b : α), r a b → tc r a b | trans : ∀ (a b c : α), tc r a b → tc r b c → tc r a c def commutative {α : Type u} (f : α → α → α) := ∀ (a b : α), f a b = f b a def associative {α : Type u} (f : α → α → α) := ∀ (a b c : α), f (f a b) c = f a (f b c) def left_identity {α : Type u} (f : α → α → α) (one : α) := ∀ (a : α), f one a = a def right_identity {α : Type u} (f : α → α → α) (one : α) := ∀ (a : α), f a one = a def right_inverse {α : Type u} (f : α → α → α) (inv : α → α) (one : α) := ∀ (a : α), f a (inv a) = one def left_cancelative {α : Type u} (f : α → α → α) := ∀ (a b c : α), f a b = f a c → b = c def right_cancelative {α : Type u} (f : α → α → α) := ∀ (a b c : α), f a b = f c b → a = c def left_distributive {α : Type u} (f : α → α → α) (g : α → α → α) := ∀ (a b c : α), f a (g b c) = g (f a b) (f a c) def right_distributive {α : Type u} (f : α → α → α) (g : α → α → α) := ∀ (a b c : α), f (g a b) c = g (f a c) (f b c) def right_commutative {α : Type u} {β : Type v} (h : β → α → β) := ∀ (b : β) (a₁ a₂ : α), h (h b a₁) a₂ = h (h b a₂) a₁ def left_commutative {α : Type u} {β : Type v} (h : α → β → β) := ∀ (a₁ a₂ : α) (b : β), h a₁ (h a₂ b) = h a₂ (h a₁ b) theorem left_comm {α : Type u} (f : α → α → α) : commutative f → associative f → left_commutative f := fun (hcomm : commutative f) (hassoc : associative f) (a b c : α) => Eq.trans (Eq.trans (Eq.symm (hassoc a b c)) (hcomm a b ▸ rfl)) (hassoc b a c) theorem right_comm {α : Type u} (f : α → α → α) : commutative f → associative f → right_commutative f := fun (hcomm : commutative f) (hassoc : associative f) (a b c : α) => Eq.trans (Eq.trans (hassoc a b c) (hcomm b c ▸ rfl)) (Eq.symm (hassoc a c b)) end Mathlib
b4de26a019861238210ec3b67045854cb8614d6c
d257837ee5f268fcb6e9b719129ff77f25de30a0
/xenalib/commutative_ring_theory.lean
2b758155316a71e638d4cc6ce5d32dd031aba405
[]
no_license
pirocks/xena
a05a8a7da5d15b1cc28830eb84d370f3d60edbbf
458a43f36964e5bb7d2d8ea74060d105519e331a
refs/heads/master
1,620,756,281,811
1,516,097,784,000
1,516,097,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,459
lean
import order.zorn noncomputable theory local attribute [instance] classical.prop_decidable class is_ideal {R : Type*} [comm_ring R] (J : set R) : Prop := (zero : (0:R) ∈ J) (add : ∀ {x y}, x ∈ J → y ∈ J → x + y ∈ J) (mul : ∀ r x : R, x ∈ J → r * x ∈ J) class is_proper_ideal {R : Type*} [comm_ring R] (J : set R) extends is_ideal J : Prop := (one_not_in : ¬ ((1:R) ∈ J) ) class is_prime_ideal {R : Type*} [comm_ring R] (P : set R) extends is_proper_ideal P : Prop := (is_prime : ∀ x y : R, x * y ∈ P → x ∈ P ∨ y ∈ P) class is_maximal_ideal {R : Type*} [comm_ring R] (m : set R) extends is_proper_ideal m : Prop := (is_maximal : ∀ J : set R, (is_proper_ideal J) → m ⊆ J → J = m) /-- increasing union of ideals is an ideal --/ lemma union_of_ideals {R : Type*} [comm_ring R] {γ : Type*} [inhabited γ] [decidable_linear_order γ] (Ix : γ → set R) (IxI : ∀ x : γ, is_ideal (Ix x)) (I_inc : ∀ {x y : γ}, x ≤ y → Ix x ⊆ Ix y) : is_ideal {r : R | ∃ x : γ, r ∈ Ix x} := begin constructor, { show (0:R) ∈ {r : R | ∃ x : γ, r ∈ Ix x}, let x := inhabited.default γ, existsi x, exact (IxI x).zero }, { -- additivity intros r s Hr Hs, cases Hr with x Hx, cases Hs with y Hy, let z := max x y, have rIz : r ∈ Ix z := I_inc (le_max_left x y) Hx, have sIz : s ∈ Ix z := I_inc (le_max_right x y) Hy, existsi z, exact is_ideal.add rIz sIz, }, { -- external mult intros r j Hj, cases Hj with x Hx, existsi x, exact is_ideal.mul r j Hx, } end --set_option pp.all true lemma union_of_proper_ideals {R : Type*} [comm_ring R] {γ : Type*} [decidable_linear_order γ] (Iγ : inhabited γ) (Ix : γ → set R) (IxI : ∀ x : γ, is_proper_ideal (Ix x)) (I_inc : ∀ {x y : γ}, x ≤ y → Ix x ⊆ Ix y) : is_proper_ideal {r : R | ∃ x : γ, r ∈ Ix x} := begin constructor, { show is_ideal {r : R | ∃ x : γ, r ∈ Ix x}, exact union_of_ideals Ix (λ x, (IxI x).to_is_ideal) @I_inc }, { show (1:R) ∉ {r : R | ∃ x : γ, r ∈ Ix x}, intro H,cases H with x Hx, revert Hx, exact (IxI x).one_not_in } end --#print zorn.chain --set_option pp.all true #check dite #check or.inl #check @rfl --set_option pp.all true lemma proper_ideal_of_non_zero_ring {R : Type*} [comm_ring R] (H : ∃ r : R, r ≠ 0) : is_proper_ideal ({0}:set R) := { zero := set.mem_singleton _, add := λ x y, match x, y with .(0), .(0), or.inl (@rfl _ 0), or.inl (@rfl _ 0) := or.inl (add_zero 0) end, mul := _, one_not_in := _, } /- begin constructor, { show (is_ideal {r : R | r = 0}), constructor, { simp}, { simp, end -/ /-- a non-zero ring has a maximal ideal-/ lemma stacks_tag_00E0_2 {R : Type*} [comm_ring R] : (∃ r : R, r ≠ 0) → (∃ m : set R, is_maximal_ideal m) := begin let P := {I : set R // is_proper_ideal I}, let PP : partial_order P := { le := (λ P Q, P.val ⊆ Q.val), le_refl := λ a, set.subset.refl a.val, le_trans := λ a b c Hab Hbc, set.subset.trans Hab Hbc, le_antisymm := λ a b Hab Hba, subtype.eq (set.subset.antisymm Hab Hba) }, intro HR_nonzero, suffices : ∃ (m : P), ∀ (a : P), m ≤ a → a = m, { cases this with m Hm, existsi m.val, constructor, { exact m.property}, intros J HJ H3, rw ←(Hm ⟨J,HJ⟩ H3) }, apply @zorn.zorn_partial_order P PP, intros c Hc, let c_subtype := {I : P // c I}, let H_par_c : partial_order c_subtype := { le := λ P Q, P.val.val ⊆ Q.val.val, le_refl := λ a, set.subset.refl a.val.val, le_trans := λ a b c Hab Hbc, set.subset.trans Hab Hbc, le_antisymm := λ a b Hab Hba, subtype.eq (subtype.eq (set.subset.antisymm Hab Hba)) }, let H_lin_c : decidable_linear_order c_subtype, refine { ..H_par_c,.. }, { intros a b, cases classical.em (a=b), { left, exact le_of_eq h}, have H1 := Hc a.val a.property b.val b.property, have H2 : a.val ≠ b.val := λ H, h (subtype.eq H), have H3 := H1 H2, exact H3, }, { apply_instance}, let ub_val := set.Union (λ (I : { I : P // c I}), (I.val).val), let ub_prop := union_of_proper_ideals (λ I : { I : P // c I},I.val.val) --lemma union_of_proper_ideals {R : Type*} [comm_ring R] {γ : Type*} [inhabited γ] [decidable_linear_order γ] -- (Ix : γ → set R) (IxI : ∀ x : γ, is_proper_ideal (Ix x)) -- (I_inc : ∀ {x y : γ}, x ≤ y → Ix x ⊆ Ix y) -- : is_proper_ideal {r : R | ∃ x : γ, r ∈ Ix x} := }, intro H_nonzero, suffices : ∃ m, ∀ a : P, m ≤ a → a = m, { cases this with m Hm, existsi m.val, constructor, { show is_proper_ideal m.val, exact m.property, }, intros J HJ Hsub, let JJ:P := ⟨J,HJ⟩, have := Hm ⟨J,HJ⟩, have Htemp : (⟨J,HJ⟩ : P).val = J := by simp, rw ←Htemp, suffices : (⟨J,HJ⟩:P) = m, { rw [this] }, apply this, -- unfold has_le.le preorder.le partial_order.le partial_order.le partial_order.le, show m ≤ JJ, suffices : m.val ⊆ JJ.val, { admit }, simp [Hsub], }, apply zorn.zorn_partial_order, end --#check set.ssubset_def #check nat.succ_pos #check @zorn.zorn_partial_order --#check zorn.zorn_partial_order /- zorn.zorn_partial_order : (∀ (c : set ?M_1), zorn.chain c → (∃ (ub : ?M_1), ∀ (a : ?M_1), a ∈ c → a ≤ ub)) → (∃ (m : ?M_1), ∀ (a : ?M_1), m ≤ a → a = m) -/ #check @zorn.chain
5d78c2c5e98eae915ea7c3dff5a73d69f01e00fd
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/data/set.lean
ad968cdd77284fc0be8f0a1b6729706f11c3fba1
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,639
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.logic init.category.functor universes u v def set (α : Type u) := α → Prop def set_of {α : Type u} (p : α → Prop) : set α := p namespace set variables {α : Type u} {β : Type v} protected def mem (a : α) (s : set α) := s a instance : has_mem α (set α) := ⟨set.mem⟩ protected def subset (s₁ s₂ : set α) := ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂ instance : has_subset (set α) := ⟨set.subset⟩ protected def sep (p : α → Prop) (s : set α) : set α := {a | a ∈ s ∧ p a} instance : has_sep α (set α) := ⟨set.sep⟩ instance : has_emptyc (set α) := ⟨λ a, false⟩ protected def insert (a : α) (s : set α) : set α := {b | b = a ∨ b ∈ s} instance : has_insert α (set α) := ⟨set.insert⟩ protected def union (s₁ s₂ : set α) : set α := {a | a ∈ s₁ ∨ a ∈ s₂} instance : has_union (set α) := ⟨set.union⟩ protected def inter (s₁ s₂ : set α) : set α := {a | a ∈ s₁ ∧ a ∈ s₂} instance : has_inter (set α) := ⟨set.inter⟩ def compl (s : set α) : set α := {a | a ∉ s} instance : has_neg (set α) := ⟨compl⟩ protected def diff (s t : set α) : set α := {a ∈ s | a ∉ t} instance : has_sdiff (set α) := ⟨set.diff⟩ def powerset (s : set α) : set (set α) := {t | t ⊆ s} prefix `𝒫`:100 := powerset def image (f : α → β) (s : set α) : set β := {b | ∃ a, a ∈ s ∧ f a = b} instance : functor set := ⟨@set.image⟩ end set
0303278dd00b22c0cf0aaa63226e14db2660553b
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast_cc9.lean
ee10671dc8df9833a885da81fa56f6a52c869002
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
433
lean
import data.list open perm set_option blast.subst false set_option blast.simp false example (a b : nat) : a = b → (b = a ↔ true) := by blast example (a b c : nat) : a = b → b = c → (true ↔ a = c) := by blast example (l₁ l₂ l₃ : list nat) : l₁ ~ l₂ → l₂ ~ l₃ → (true ↔ l₁ ~ l₃) := by blast example (l₁ l₂ l₃ : list nat) : l₁ ~ l₂ → l₂ = l₃ → (true ↔ l₁ ~ l₃) := by blast
3db7a2441699398ddb441fadd0b9a0ad0bec0942
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/derivingRepr.lean
59a83beffa6a37c14b1b9b68386478fa9aa7327d
[ "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
978
lean
structure Foo where name : String val : List Nat lower : Nat := List.length val inv : val.length >= lower flag : Bool deriving Repr #eval { name := "Joe", val := List.iota 40, flag := true, inv := by decide : Foo } inductive Tree (α : Type) where | node : List (Tree α) → Bool → Tree α | leaf : α → Tree α deriving Repr #eval Tree.node (List.iota 10 |>.map fun i => Tree.node [Tree.leaf i] (i%2==0)) true inductive StructureLikeInductive where | field : Nat -> StructureLikeInductive deriving Repr #eval StructureLikeInductive.field 5 namespace Foo mutual inductive Tree (α : Type u) where | node : TreeList α → Tree α | leaf : α → Tree α deriving Repr inductive TreeList (α : Type u) where | nil : TreeList α | cons : Tree α → TreeList α → TreeList α deriving Repr end #eval Tree.node (TreeList.cons (Tree.leaf 30) (TreeList.cons (Tree.leaf 20) (TreeList.cons (Tree.leaf 10) TreeList.nil))) end Foo
fc4715da5b03dda1a063ac180d466b1d9358de31
a339bc2ac96174381fb610f4b2e1ba42df2be819
/hott/types/eq.hlean
ad06226a24cc3648b39026e65d9a1df2c742ba17
[ "Apache-2.0" ]
permissive
kalfsvag/lean2
25b2dccc07a98e5aa20f9a11229831f9d3edf2e7
4d4a0c7c53a9922c5f630f6f8ebdccf7ddef2cc7
refs/heads/master
1,610,513,122,164
1,483,135,198,000
1,483,135,198,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,741
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Partially ported from Coq HoTT Theorems about path types (identity types) -/ import types.sigma open eq sigma sigma.ops equiv is_equiv is_trunc namespace eq /- Path spaces -/ section variables {A B : Type} {a a₁ a₂ a₃ a₄ a' : A} {b b1 b2 : B} {f g : A → B} {h : B → A} {p p' p'' : a₁ = a₂} /- The path spaces of a path space are not, of course, determined; they are just the higher-dimensional structure of the original space. -/ /- some lemmas about whiskering or other higher paths -/ theorem whisker_left_con_right (p : a₁ = a₂) {q q' q'' : a₂ = a₃} (r : q = q') (s : q' = q'') : whisker_left p (r ⬝ s) = whisker_left p r ⬝ whisker_left p s := begin induction p, induction r, induction s, reflexivity end theorem whisker_right_con_right (q : a₂ = a₃) (r : p = p') (s : p' = p'') : whisker_right q (r ⬝ s) = whisker_right q r ⬝ whisker_right q s := begin induction q, induction r, induction s, reflexivity end theorem whisker_left_con_left (p : a₁ = a₂) (p' : a₂ = a₃) {q q' : a₃ = a₄} (r : q = q') : whisker_left (p ⬝ p') r = !con.assoc ⬝ whisker_left p (whisker_left p' r) ⬝ !con.assoc' := begin induction p', induction p, induction r, induction q, reflexivity end theorem whisker_right_con_left {p p' : a₁ = a₂} (q : a₂ = a₃) (q' : a₃ = a₄) (r : p = p') : whisker_right (q ⬝ q') r = !con.assoc' ⬝ whisker_right q' (whisker_right q r) ⬝ !con.assoc := begin induction q', induction q, induction r, induction p, reflexivity end theorem whisker_left_inv_left (p : a₂ = a₁) {q q' : a₂ = a₃} (r : q = q') : !con_inv_cancel_left⁻¹ ⬝ whisker_left p (whisker_left p⁻¹ r) ⬝ !con_inv_cancel_left = r := begin induction p, induction r, induction q, reflexivity end theorem whisker_left_inv (p : a₁ = a₂) {q q' : a₂ = a₃} (r : q = q') : whisker_left p r⁻¹ = (whisker_left p r)⁻¹ := by induction r; reflexivity theorem whisker_right_inv {p p' : a₁ = a₂} (q : a₂ = a₃) (r : p = p') : whisker_right q r⁻¹ = (whisker_right q r)⁻¹ := by induction r; reflexivity theorem ap_eq_apd10 {B : A → Type} {f g : Πa, B a} (p : f = g) (a : A) : ap (λh, h a) p = apd10 p a := by induction p; reflexivity theorem inverse2_right_inv (r : p = p') : r ◾ inverse2 r ⬝ con.right_inv p' = con.right_inv p := by induction r;induction p;reflexivity theorem inverse2_left_inv (r : p = p') : inverse2 r ◾ r ⬝ con.left_inv p' = con.left_inv p := by induction r;induction p;reflexivity theorem ap_con_right_inv (f : A → B) (p : a₁ = a₂) : ap_con f p p⁻¹ ⬝ whisker_left _ (ap_inv f p) ⬝ con.right_inv (ap f p) = ap (ap f) (con.right_inv p) := by induction p;reflexivity theorem ap_con_left_inv (f : A → B) (p : a₁ = a₂) : ap_con f p⁻¹ p ⬝ whisker_right _ (ap_inv f p) ⬝ con.left_inv (ap f p) = ap (ap f) (con.left_inv p) := by induction p;reflexivity theorem idp_con_whisker_left {q q' : a₂ = a₃} (r : q = q') : !idp_con⁻¹ ⬝ whisker_left idp r = r ⬝ !idp_con⁻¹ := by induction r;induction q;reflexivity theorem whisker_left_idp_con {q q' : a₂ = a₃} (r : q = q') : whisker_left idp r ⬝ !idp_con = !idp_con ⬝ r := by induction r;induction q;reflexivity theorem idp_con_idp {p : a = a} (q : p = idp) : idp_con p ⬝ q = ap (λp, idp ⬝ p) q := by cases q;reflexivity definition ap_is_constant [unfold 8] {A B : Type} {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : ap f q = p x ⬝ (p y)⁻¹ := by induction q;exact !con.right_inv⁻¹ definition inv2_inv {p q : a = a'} (r : p = q) : inverse2 r⁻¹ = (inverse2 r)⁻¹ := by induction r;reflexivity definition inv2_con {p p' p'' : a = a'} (r : p = p') (r' : p' = p'') : inverse2 (r ⬝ r') = inverse2 r ⬝ inverse2 r' := by induction r';induction r;reflexivity definition con2_inv {p₁ q₁ : a₁ = a₂} {p₂ q₂ : a₂ = a₃} (r₁ : p₁ = q₁) (r₂ : p₂ = q₂) : (r₁ ◾ r₂)⁻¹ = r₁⁻¹ ◾ r₂⁻¹ := by induction r₁;induction r₂;reflexivity theorem eq_con_inv_of_con_eq_whisker_left {A : Type} {a a₂ a₃ : A} {p : a = a₂} {q q' : a₂ = a₃} {r : a = a₃} (s' : q = q') (s : p ⬝ q' = r) : eq_con_inv_of_con_eq (whisker_left p s' ⬝ s) = eq_con_inv_of_con_eq s ⬝ whisker_left r (inverse2 s')⁻¹ := by induction s';induction q;induction s;reflexivity theorem right_inv_eq_idp {A : Type} {a : A} {p : a = a} (r : p = idpath a) : con.right_inv p = r ◾ inverse2 r := by cases r;reflexivity /- Transporting in path spaces. There are potentially a lot of these lemmas, so we adopt a uniform naming scheme: - `l` means the left endpoint varies - `r` means the right endpoint varies - `F` means application of a function to that (varying) endpoint. -/ definition eq_transport_l (p : a₁ = a₂) (q : a₁ = a₃) : transport (λx, x = a₃) p q = p⁻¹ ⬝ q := by induction p; induction q; reflexivity definition eq_transport_r (p : a₂ = a₃) (q : a₁ = a₂) : transport (λx, a₁ = x) p q = q ⬝ p := by induction p; induction q; reflexivity definition eq_transport_lr (p : a₁ = a₂) (q : a₁ = a₁) : transport (λx, x = x) p q = p⁻¹ ⬝ q ⬝ p := by induction p; rewrite [▸*,idp_con] definition eq_transport_Fl (p : a₁ = a₂) (q : f a₁ = b) : transport (λx, f x = b) p q = (ap f p)⁻¹ ⬝ q := by induction p; induction q; reflexivity definition eq_transport_Fr (p : a₁ = a₂) (q : b = f a₁) : transport (λx, b = f x) p q = q ⬝ (ap f p) := by induction p; reflexivity definition eq_transport_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) : transport (λx, f x = g x) p q = (ap f p)⁻¹ ⬝ q ⬝ (ap g p) := by induction p; rewrite [▸*,idp_con] definition eq_transport_FlFr_D {B : A → Type} {f g : Πa, B a} (p : a₁ = a₂) (q : f a₁ = g a₁) : transport (λx, f x = g x) p q = (apdt f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apdt g p) := by induction p; rewrite [▸*,idp_con,ap_id] definition eq_transport_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) : transport (λx, h (f x) = x) p q = (ap h (ap f p))⁻¹ ⬝ q ⬝ p := by induction p; rewrite [▸*,idp_con] definition eq_transport_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) : transport (λx, x = h (f x)) p q = p⁻¹ ⬝ q ⬝ (ap h (ap f p)) := by induction p; rewrite [▸*,idp_con] /- Pathovers -/ -- In the comment we give the fibration of the pathover -- we should probably try to do everything just with pathover_eq (defined in cubical.square), -- the following definitions may be removed in future. definition eq_pathover_l (p : a₁ = a₂) (q : a₁ = a₃) : q =[p] p⁻¹ ⬝ q := /-(λx, x = a₃)-/ by induction p; induction q; exact idpo definition eq_pathover_r (p : a₂ = a₃) (q : a₁ = a₂) : q =[p] q ⬝ p := /-(λx, a₁ = x)-/ by induction p; induction q; exact idpo definition eq_pathover_lr (p : a₁ = a₂) (q : a₁ = a₁) : q =[p] p⁻¹ ⬝ q ⬝ p := /-(λx, x = x)-/ by induction p; rewrite [▸*,idp_con]; exact idpo definition eq_pathover_Fl (p : a₁ = a₂) (q : f a₁ = b) : q =[p] (ap f p)⁻¹ ⬝ q := /-(λx, f x = b)-/ by induction p; induction q; exact idpo definition eq_pathover_Fl' (p : a₁ = a₂) (q : f a₂ = b) : (ap f p) ⬝ q =[p] q := /-(λx, f x = b)-/ by induction p; induction q; exact idpo definition eq_pathover_Fr (p : a₁ = a₂) (q : b = f a₁) : q =[p] q ⬝ (ap f p) := /-(λx, b = f x)-/ by induction p; exact idpo definition eq_pathover_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) : q =[p] (ap f p)⁻¹ ⬝ q ⬝ (ap g p) := /-(λx, f x = g x)-/ by induction p; rewrite [▸*,idp_con]; exact idpo definition eq_pathover_FlFr_D {B : A → Type} {f g : Πa, B a} (p : a₁ = a₂) (q : f a₁ = g a₁) : q =[p] (apdt f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apdt g p) := /-(λx, f x = g x)-/ by induction p; rewrite [▸*,idp_con,ap_id];exact idpo definition eq_pathover_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) : q =[p] (ap h (ap f p))⁻¹ ⬝ q ⬝ p := /-(λx, h (f x) = x)-/ by induction p; rewrite [▸*,idp_con];exact idpo definition eq_pathover_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) : q =[p] p⁻¹ ⬝ q ⬝ (ap h (ap f p)) := /-(λx, x = h (f x))-/ by induction p; rewrite [▸*,idp_con];exact idpo definition eq_pathover_r_idp (p : a₁ = a₂) : idp =[p] p := /-(λx, a₁ = x)-/ by induction p; exact idpo definition eq_pathover_l_idp (p : a₁ = a₂) : idp =[p] p⁻¹ := /-(λx, x = a₁)-/ by induction p; exact idpo definition eq_pathover_l_idp' (p : a₁ = a₂) : idp =[p⁻¹] p := /-(λx, x = a₂)-/ by induction p; exact idpo -- The Functorial action of paths is [ap]. /- Equivalences between path spaces -/ /- [is_equiv_ap] is in init.equiv -/ definition equiv_ap (f : A → B) [H : is_equiv f] (a₁ a₂ : A) : (a₁ = a₂) ≃ (f a₁ = f a₂) := equiv.mk (ap f) _ /- Path operations are equivalences -/ definition is_equiv_eq_inverse (a₁ a₂ : A) : is_equiv (inverse : a₁ = a₂ → a₂ = a₁) := is_equiv.mk inverse inverse inv_inv inv_inv (λp, eq.rec_on p idp) local attribute is_equiv_eq_inverse [instance] definition eq_equiv_eq_symm (a₁ a₂ : A) : (a₁ = a₂) ≃ (a₂ = a₁) := equiv.mk inverse _ definition is_equiv_concat_left [constructor] [instance] (p : a₁ = a₂) (a₃ : A) : is_equiv (concat p : a₂ = a₃ → a₁ = a₃) := is_equiv.mk (concat p) (concat p⁻¹) (con_inv_cancel_left p) (inv_con_cancel_left p) abstract (λq, by induction p;induction q;reflexivity) end local attribute is_equiv_concat_left [instance] definition equiv_eq_closed_left [constructor] (a₃ : A) (p : a₁ = a₂) : (a₁ = a₃) ≃ (a₂ = a₃) := equiv.mk (concat p⁻¹) _ definition is_equiv_concat_right [constructor] [instance] (p : a₂ = a₃) (a₁ : A) : is_equiv (λq : a₁ = a₂, q ⬝ p) := is_equiv.mk (λq, q ⬝ p) (λq, q ⬝ p⁻¹) (λq, inv_con_cancel_right q p) (λq, con_inv_cancel_right q p) (λq, by induction p;induction q;reflexivity) local attribute is_equiv_concat_right [instance] definition equiv_eq_closed_right [constructor] (a₁ : A) (p : a₂ = a₃) : (a₁ = a₂) ≃ (a₁ = a₃) := equiv.mk (λq, q ⬝ p) _ definition eq_equiv_eq_closed [constructor] (p : a₁ = a₂) (q : a₃ = a₄) : (a₁ = a₃) ≃ (a₂ = a₄) := equiv.trans (equiv_eq_closed_left a₃ p) (equiv_eq_closed_right a₂ q) definition loop_equiv_eq_closed [constructor] {A : Type} {a a' : A} (p : a = a') : (a = a) ≃ (a' = a') := eq_equiv_eq_closed p p definition is_equiv_whisker_left [constructor] (p : a₁ = a₂) (q r : a₂ = a₃) : is_equiv (whisker_left p : q = r → p ⬝ q = p ⬝ r) := begin fapply adjointify, {intro s, apply (!cancel_left s)}, {intro s, apply concat, {apply whisker_left_con_right}, apply concat, rotate_left 1, apply (whisker_left_inv_left p s), apply concat2, {apply concat, {apply whisker_left_con_right}, apply concat2, {induction p, induction q, reflexivity}, {reflexivity}}, {induction p, induction r, reflexivity}}, {intro s, induction s, induction q, induction p, reflexivity} end definition eq_equiv_con_eq_con_left [constructor] (p : a₁ = a₂) (q r : a₂ = a₃) : (q = r) ≃ (p ⬝ q = p ⬝ r) := equiv.mk _ !is_equiv_whisker_left definition is_equiv_whisker_right [constructor] {p q : a₁ = a₂} (r : a₂ = a₃) : is_equiv (λs, whisker_right r s : p = q → p ⬝ r = q ⬝ r) := begin fapply adjointify, {intro s, apply (!cancel_right s)}, {intro s, induction r, cases s, induction q, reflexivity}, {intro s, induction s, induction r, induction p, reflexivity} end definition eq_equiv_con_eq_con_right [constructor] (p q : a₁ = a₂) (r : a₂ = a₃) : (p = q) ≃ (p ⬝ r = q ⬝ r) := equiv.mk _ !is_equiv_whisker_right /- The following proofs can be simplified a bit by concatenating previous equivalences. However, these proofs have the advantage that the inverse is definitionally equal to what we would expect -/ definition is_equiv_con_eq_of_eq_inv_con [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (con_eq_of_eq_inv_con : p = r⁻¹ ⬝ q → r ⬝ p = q) := begin fapply adjointify, { apply eq_inv_con_of_con_eq}, { intro s, induction r, rewrite [↑[con_eq_of_eq_inv_con,eq_inv_con_of_con_eq], con.assoc,con.assoc,con.left_inv,▸*,-con.assoc,con.right_inv,▸* at *,idp_con s]}, { intro s, induction r, rewrite [↑[con_eq_of_eq_inv_con,eq_inv_con_of_con_eq], con.assoc,con.assoc,con.right_inv,▸*,-con.assoc,con.left_inv,▸* at *,idp_con s] }, end definition eq_inv_con_equiv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : (p = r⁻¹ ⬝ q) ≃ (r ⬝ p = q) := equiv.mk _ !is_equiv_con_eq_of_eq_inv_con definition is_equiv_con_eq_of_eq_con_inv [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (con_eq_of_eq_con_inv : r = q ⬝ p⁻¹ → r ⬝ p = q) := begin fapply adjointify, { apply eq_con_inv_of_con_eq}, { intro s, induction p, rewrite [↑[con_eq_of_eq_con_inv,eq_con_inv_of_con_eq]]}, { intro s, induction p, rewrite [↑[con_eq_of_eq_con_inv,eq_con_inv_of_con_eq]] }, end definition eq_con_inv_equiv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : (r = q ⬝ p⁻¹) ≃ (r ⬝ p = q) := equiv.mk _ !is_equiv_con_eq_of_eq_con_inv definition is_equiv_inv_con_eq_of_eq_con [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂) : is_equiv (inv_con_eq_of_eq_con : p = r ⬝ q → r⁻¹ ⬝ p = q) := begin fapply adjointify, { apply eq_con_of_inv_con_eq}, { intro s, induction r, rewrite [↑[inv_con_eq_of_eq_con,eq_con_of_inv_con_eq], con.assoc,con.assoc,con.left_inv,▸*,-con.assoc,con.right_inv,▸* at *,idp_con s]}, { intro s, induction r, rewrite [↑[inv_con_eq_of_eq_con,eq_con_of_inv_con_eq], con.assoc,con.assoc,con.right_inv,▸*,-con.assoc,con.left_inv,▸* at *,idp_con s] }, end definition eq_con_equiv_inv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂) : (p = r ⬝ q) ≃ (r⁻¹ ⬝ p = q) := equiv.mk _ !is_equiv_inv_con_eq_of_eq_con definition is_equiv_con_inv_eq_of_eq_con [constructor] (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (con_inv_eq_of_eq_con : r = q ⬝ p → r ⬝ p⁻¹ = q) := begin fapply adjointify, { apply eq_con_of_con_inv_eq}, { intro s, induction p, rewrite [↑[con_inv_eq_of_eq_con,eq_con_of_con_inv_eq]]}, { intro s, induction p, rewrite [↑[con_inv_eq_of_eq_con,eq_con_of_con_inv_eq]] }, end definition eq_con_equiv_con_inv_eq (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁) : (r = q ⬝ p) ≃ (r ⬝ p⁻¹ = q) := equiv.mk _ !is_equiv_con_inv_eq_of_eq_con local attribute is_equiv_inv_con_eq_of_eq_con is_equiv_con_inv_eq_of_eq_con is_equiv_con_eq_of_eq_con_inv is_equiv_con_eq_of_eq_inv_con [instance] definition is_equiv_eq_con_of_inv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_con_of_inv_con_eq : r⁻¹ ⬝ q = p → q = r ⬝ p) := is_equiv_inv inv_con_eq_of_eq_con definition is_equiv_eq_con_of_con_inv_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_con_of_con_inv_eq : q ⬝ p⁻¹ = r → q = r ⬝ p) := is_equiv_inv con_inv_eq_of_eq_con definition is_equiv_eq_con_inv_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_con_inv_of_con_eq : r ⬝ p = q → r = q ⬝ p⁻¹) := is_equiv_inv con_eq_of_eq_con_inv definition is_equiv_eq_inv_con_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_inv_con_of_con_eq : r ⬝ p = q → p = r⁻¹ ⬝ q) := is_equiv_inv con_eq_of_eq_inv_con definition is_equiv_con_inv_eq_idp [constructor] (p q : a₁ = a₂) : is_equiv (con_inv_eq_idp : p = q → p ⬝ q⁻¹ = idp) := begin fapply adjointify, { apply eq_of_con_inv_eq_idp}, { intro s, induction q, esimp at *, cases s, reflexivity}, { intro s, induction s, induction p, reflexivity}, end definition is_equiv_inv_con_eq_idp [constructor] (p q : a₁ = a₂) : is_equiv (inv_con_eq_idp : p = q → q⁻¹ ⬝ p = idp) := begin fapply adjointify, { apply eq_of_inv_con_eq_idp}, { intro s, induction q, esimp [eq_of_inv_con_eq_idp] at *, eapply is_equiv_rect (eq_equiv_con_eq_con_left idp p idp), clear s, intro s, cases s, reflexivity}, { intro s, induction s, induction p, reflexivity}, end definition eq_equiv_con_inv_eq_idp [constructor] (p q : a₁ = a₂) : (p = q) ≃ (p ⬝ q⁻¹ = idp) := equiv.mk _ !is_equiv_con_inv_eq_idp definition eq_equiv_inv_con_eq_idp [constructor] (p q : a₁ = a₂) : (p = q) ≃ (q⁻¹ ⬝ p = idp) := equiv.mk _ !is_equiv_inv_con_eq_idp /- Pathover Equivalences -/ definition eq_pathover_equiv_l (p : a₁ = a₂) (q : a₁ = a₃) (r : a₂ = a₃) : q =[p] r ≃ q = p ⬝ r := /-(λx, x = a₃)-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ definition eq_pathover_equiv_r (p : a₂ = a₃) (q : a₁ = a₂) (r : a₁ = a₃) : q =[p] r ≃ q ⬝ p = r := /-(λx, a₁ = x)-/ by induction p; apply pathover_idp definition eq_pathover_equiv_lr (p : a₁ = a₂) (q : a₁ = a₁) (r : a₂ = a₂) : q =[p] r ≃ q ⬝ p = p ⬝ r := /-(λx, x = x)-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ definition eq_pathover_equiv_Fl (p : a₁ = a₂) (q : f a₁ = b) (r : f a₂ = b) : q =[p] r ≃ q = ap f p ⬝ r := /-(λx, f x = b)-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ definition eq_pathover_equiv_Fr (p : a₁ = a₂) (q : b = f a₁) (r : b = f a₂) : q =[p] r ≃ q ⬝ ap f p = r := /-(λx, b = f x)-/ by induction p; apply pathover_idp definition eq_pathover_equiv_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) (r : f a₂ = g a₂) : q =[p] r ≃ q ⬝ ap g p = ap f p ⬝ r := /-(λx, f x = g x)-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ definition eq_pathover_equiv_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) (r : h (f a₂) = a₂) : q =[p] r ≃ q ⬝ p = ap h (ap f p) ⬝ r := /-(λx, h (f x) = x)-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ definition eq_pathover_equiv_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) (r : a₂ = h (f a₂)) : q =[p] r ≃ q ⬝ ap h (ap f p) = p ⬝ r := /-(λx, x = h (f x))-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ -- a lot of this library still needs to be ported from Coq HoTT -- the behavior of equality in other types is described in the corresponding type files -- encode decode method open is_trunc definition encode_decode_method' (a₀ a : A) (code : A → Type) (c₀ : code a₀) (decode : Π(a : A) (c : code a), a₀ = a) (encode_decode : Π(a : A) (c : code a), c₀ =[decode a c] c) (decode_encode : decode a₀ c₀ = idp) : (a₀ = a) ≃ code a := begin fapply equiv.MK, { intro p, exact p ▸ c₀}, { apply decode}, { intro c, apply tr_eq_of_pathover, apply encode_decode}, { intro p, induction p, apply decode_encode}, end end section parameters {A : Type} (a₀ : A) (code : A → Type) (H : is_contr (Σa, code a)) (p : (center (Σa, code a)).1 = a₀) include p protected definition encode {a : A} (q : a₀ = a) : code a := (p ⬝ q) ▸ (center (Σa, code a)).2 protected definition decode' {a : A} (c : code a) : a₀ = a := (is_prop.elim ⟨a₀, encode idp⟩ ⟨a, c⟩)..1 protected definition decode {a : A} (c : code a) : a₀ = a := (decode' (encode idp))⁻¹ ⬝ decode' c definition total_space_method (a : A) : (a₀ = a) ≃ code a := begin fapply equiv.MK, { exact encode}, { exact decode}, { intro c, unfold [encode, decode, decode'], induction p, esimp, rewrite [is_prop_elim_self,▸*,+idp_con], apply tr_eq_of_pathover, eapply @sigma.rec_on _ _ (λx, x.2 =[(is_prop.elim ⟨x.1, x.2⟩ ⟨a, c⟩)..1] c) (center (sigma code)), intro a c, apply eq_pr2}, { intro q, induction q, esimp, apply con.left_inv, }, end end definition encode_decode_method {A : Type} (a₀ a : A) (code : A → Type) (c₀ : code a₀) (decode : Π(a : A) (c : code a), a₀ = a) (encode_decode : Π(a : A) (c : code a), c₀ =[decode a c] c) : (a₀ = a) ≃ code a := begin fapply total_space_method, { fapply @is_contr.mk, { exact ⟨a₀, c₀⟩}, { intro p, fapply sigma_eq, apply decode, exact p.2, apply encode_decode}}, { reflexivity} end end eq
cf5294561eb43b7229895eab730c6743fe6e77c8
56762daf61566a2baf390b5d77988c29c75187e3
/src/local_diffeomorph.lean
58334bd7e455a31748fe9dd08a7c2778e46c8401
[]
no_license
Nicknamen/lie_group
de173ce5f1ffccb945ba05dca23ff27daef0e3b4
e0d5c4f859654e3dea092702f1320c3c72a49983
refs/heads/master
1,674,937,428,196
1,607,213,423,000
1,607,213,423,000
275,196,635
0
0
null
null
null
null
UTF-8
Lean
false
false
4,356
lean
import .diffeomorph open function set open_locale topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {F : Type*} [normed_group F] [normed_space 𝕜 F] {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] {H : Type*} [topological_space H] {H' : Type*} [topological_space H'] {G : Type*} [topological_space G] {G' : Type*} [topological_space G'] /-- local diffeomorphisms, defined on open subsets of the space -/ @[nolint has_inhabited_instance] structure local_diffeomorph (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] (M' : Type*) [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] extends local_homeomorph M M' := (smooth_to_fun : smooth_in_charts_on I I' to_fun source) (smooth_inv_fun : smooth_in_charts_on I' I inv_fun target) /-- A diffomorphism induces a local diffeomorphism on the whole space -/ def diffeomorph.to_local_diffeomorph (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] (M' : Type*) [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] (e : diffeomorph I I' M M') : local_diffeomorph I I' M M' := { smooth_to_fun := by { simp only [smooth_in_charts_on], erw times_cont_mdiff_in_charts_on_univ, exact e.smooth_to_fun }, smooth_inv_fun := by { simp only [smooth_in_charts_on], erw times_cont_mdiff_in_charts_on_univ, exact e.smooth_inv_fun }, ..e.to_homeomorph.to_local_homeomorph } namespace local_diffeomorph variables {I : model_with_corners 𝕜 E H} {I' : model_with_corners 𝕜 E' H'} {J : model_with_corners 𝕜 F G} {J' : model_with_corners 𝕜 F' G'} {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {M' : Type*} [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] {N : Type*} [topological_space N] [charted_space G N] [smooth_manifold_with_corners J N] {N' : Type*} [topological_space N'] [charted_space G' N'] [smooth_manifold_with_corners J' N'] (e : local_diffeomorph I I' M M') (e' : local_diffeomorph J J' N N') instance : has_coe (local_diffeomorph I I' M M') (local_homeomorph M M') := ⟨local_diffeomorph.to_local_homeomorph⟩ instance : has_coe_to_fun (local_diffeomorph I I' M M') := ⟨_, λ e, e.to_local_equiv.to_fun⟩ /-- The inverse of a local homeomorphism -/ protected def symm : local_diffeomorph I' I M' M := { smooth_to_fun := e.smooth_inv_fun, smooth_inv_fun := e.smooth_to_fun, ..e.to_local_homeomorph.symm } protected lemma smooth_in_charts_on : smooth_in_charts_on I I' e e.source := e.smooth_to_fun lemma smooth_in_charts_on_symm : smooth_in_charts_on I' I e.symm e.target := e.smooth_inv_fun /- Register a few simp lemmas to make sure that `simp` puts the application of a local diffeomorphism in its normal form, i.e., in terms of its coercion to a function. -/ @[simp, mfld_simps] lemma to_fun_eq_coe (e : local_diffeomorph I I' M M') : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_eq_coe (e : local_diffeomorph I I' M M') : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma coe_coe : (e.to_local_equiv : M → M') = e := rfl @[simp, mfld_simps] lemma coe_coe_symm : (e.to_local_equiv.symm : M' → M) = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : M} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : M'} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : M} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : M'} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h lemma eq_of_local_equiv_eq {e e' : local_diffeomorph I I' M M'} (h : e.to_local_equiv = e'.to_local_equiv) : e = e' := begin cases e, cases e', dsimp at *, induction h, refl end lemma eventually_left_inverse (e : local_diffeomorph I I' M M') {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 x, e.symm (e y) = y := filter.eventually.mono (mem_nhds_sets e.open_source hx) e.left_inv' end local_diffeomorph
9c7544d30706c592c8b73896f29aa16cecfa31e6
8ac070e5078ade6d9ca9577e76883158ced4a937
/Numbers/Equiv/basic.lean
254f7c7ea4e7cc1e29194eac1eae44b3219a9f5d
[]
no_license
kbuzzard/Numbers
2e5cff4c0102e242e30edf47c7d2547c053500f6
c0166915ee06e901bd46c9168a158c4d139211af
refs/heads/master
1,679,975,844,345
1,617,144,136,000
1,617,144,136,000
353,096,483
2
0
null
null
null
null
UTF-8
Lean
false
false
1,845
lean
/- # Equivs Two types α and β are equivalent, written α ≃ β, if there's a bijection between them. -/ structure Equiv (α β : Type) := (to_fun : α → β) (inv_fun : β → α) (left_inv : ∀ a, inv_fun (to_fun a) = a) (right_inv : ∀ b, to_fun (inv_fun b) = b) infix:25 " ≃ " => Equiv def Equiv.symm {α β} (h : α ≃ β) : β ≃ α where to_fun := h.inv_fun inv_fun := h.to_fun left_inv := h.right_inv right_inv := h.left_inv -- #check Option -- #check Unit -- #check Option.none -- #check none def OptionEmptyEquivUnit : Option Empty ≃ Unit where to_fun | none => Unit.unit | some a => Empty.rec (λ _ => _) a inv_fun := λ u => none left_inv | none => rfl | some a => Empty.rec (λ _ => _) a right_inv := λ u => by cases u; rfl; instance : Subsingleton Empty where allEq a := nomatch a -- (a : Empty) so no cases def SubsingletonEquivEmptyOrUnit (α : Type) [Subsingleton α] : (∃ e : α ≃ Empty, True) ∨ (∃ e : α ≃ Unit, True) := by cases Classical.em (∃ a : α, True) with | inl h => { apply Or.inr; let ⟨a, _⟩ := h; exact ⟨{ to_fun := λ x => Unit.unit inv_fun := λ y => a left_inv := λ x => Subsingleton.elim _ _ right_inv := λ y => Subsingleton.elim _ _ }, True.intro⟩ } | inr h => { apply Or.inl; exact ⟨{ to_fun := λ x => False.elim $ h ⟨x, True.intro⟩ inv_fun := λ y => by cases y; left_inv := λ x => Subsingleton.elim _ _ right_inv := λ y => Subsingleton.elim _ _ }, True.intro⟩ } def SumEmptyEquiv (α : Type) : Sum Empty α ≃ α where to_fun | Sum.inl a => nomatch a | Sum.inr a => a inv_fun b := Sum.inr b left_inv | Sum.inl a => nomatch a | Sum.inr a => rfl right_inv b := rfl
1c4ee428b33d811f6d303a083a9d4d6d448b6579
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/connected.lean
26428ebaba439518ba5a6aac24b836311cc0bb78
[ "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
41,193
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, Yury Kudryashov -/ import topology.subset_properties /-! # Connected subsets of topological spaces In this file we define connected subsets of a topological spaces and various other properties and classes related to connectivity. ## Main definitions We define the following properties for sets in a topological space: * `is_connected`: a nonempty set that has no non-trivial open partition. See also the section below in the module doc. * `connected_component` is the connected component of an element in the space. * `is_totally_disconnected`: all of its connected components are singletons. * `is_totally_separated`: any two points can be separated by two disjoint opens that cover the set. For each of these definitions, we also have a class stating that the whole space satisfies that property: `connected_space`, `totally_disconnected_space`, `totally_separated_space`. ## On the definition of connected sets/spaces In informal mathematics, connected spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preconnected`. In other words, the only difference is whether the empty space counts as connected. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set classical topological_space open_locale classical topological_space universes u v variables {α : Type u} {β : Type v} [topological_space α] {s t : set α} section preconnected /-- A preconnected set is one where there is no non-trivial open partition. -/ def is_preconnected (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/ def is_connected (s : set α) : Prop := s.nonempty ∧ is_preconnected s lemma is_connected.nonempty {s : set α} (h : is_connected s) : s.nonempty := h.1 lemma is_connected.is_preconnected {s : set α} (h : is_connected s) : is_preconnected s := h.2 theorem is_preirreducible.is_preconnected {s : set α} (H : is_preirreducible s) : is_preconnected s := λ _ _ hu hv _, H _ _ hu hv theorem is_irreducible.is_connected {s : set α} (H : is_irreducible s) : is_connected s := ⟨H.nonempty, H.is_preirreducible.is_preconnected⟩ theorem is_preconnected_empty : is_preconnected (∅ : set α) := is_preirreducible_empty.is_preconnected theorem is_connected_singleton {x} : is_connected ({x} : set α) := is_irreducible_singleton.is_connected /-- If any point of a set is joined to a fixed point by a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall {s : set α} (x : α) (H : ∀ y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩, have xs : x ∈ s, by { rcases H y ys with ⟨t, ts, xt, yt, ht⟩, exact ts xt }, wlog xu : x ∈ u := hs xs using [u v y z, v u z y], rcases H y ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- If any two points of a set are contained in a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall_pair {s : set α} (H : ∀ x y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, rcases H x y xs ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- A union of a family of preconnected sets with a common point is preconnected as well. -/ theorem is_preconnected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s) (H2 : ∀ s ∈ c, is_preconnected s) : is_preconnected (⋃₀ c) := begin apply is_preconnected_of_forall x, rintros y ⟨s, sc, ys⟩, exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩ end theorem is_preconnected.union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t) (H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) := sUnion_pair s t ▸ is_preconnected_sUnion x {s, t} (by rintro r (rfl | rfl | h); assumption) (by rintro r (rfl | rfl | h); assumption) theorem is_connected.union {s t : set α} (H : (s ∩ t).nonempty) (Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) := begin rcases H with ⟨x, hx⟩, refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, _⟩, exact is_preconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx) Hs.is_preconnected Ht.is_preconnected end theorem is_preconnected.closure {s : set α} (H : is_preconnected s) : is_preconnected (closure s) := λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ theorem is_connected.closure {s : set α} (H : is_connected s) : is_connected (closure s) := ⟨H.nonempty.closure, H.is_preconnected.closure⟩ theorem is_preconnected.image [topological_space β] {s : set α} (H : is_preconnected s) (f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) := begin -- Unfold/destruct definitions in hypotheses rintros u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, -- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'` replace huv : s ⊆ u' ∪ v', { rw [image_subset_iff, preimage_union] at huv, replace huv := subset_inter huv (subset.refl _), rw [inter_distrib_right, u'_eq, v'_eq, ← inter_distrib_right] at huv, exact (subset_inter_iff.1 huv).1 }, -- Now `s ⊆ u' ∪ v'`, so we can apply `‹is_preconnected s›` obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).nonempty, { refine H u' v' hu' hv' huv ⟨x, _⟩ ⟨y, _⟩; rw inter_comm, exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] }, rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc, inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz, exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩ end theorem is_connected.image [topological_space β] {s : set α} (H : is_connected s) (f : α → β) (hf : continuous_on f s) : is_connected (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preconnected.image f hf⟩ theorem is_preconnected_closed_iff {s : set α} : is_preconnected s ↔ ∀ t t', is_closed t → is_closed t' → s ⊆ t ∪ t' → (s ∩ t).nonempty → (s ∩ t').nonempty → (s ∩ (t ∩ t')).nonempty := ⟨begin rintros h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xt' : x ∉ t', from (h' xs).elim (absurd xt) id, have yt : y ∉ t, from (h' ys).elim id (absurd yt'), have := ne_empty_iff_nonempty.2 (h tᶜ t'ᶜ (is_open_compl_iff.2 ht) (is_open_compl_iff.2 ht') h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end, begin rintros h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xv : x ∉ v, from (h' xs).elim (absurd xu) id, have yu : y ∉ u, from (h' ys).elim id (absurd yv), have := ne_empty_iff_nonempty.2 (h uᶜ vᶜ (is_closed_compl_iff.2 hu) (is_closed_compl_iff.2 hv) h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end⟩ /-- The connected component of a point is the maximal connected set that contains this point. -/ def connected_component (x : α) : set α := ⋃₀ { s : set α | is_preconnected s ∧ x ∈ s } /-- The connected component of a point inside a set. -/ def connected_component_in (F : set α) (x : F) : set α := coe '' (connected_component x) theorem mem_connected_component {x : α} : x ∈ connected_component x := mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton.is_preconnected, mem_singleton x⟩ theorem is_preconnected_connected_component {x : α} : is_preconnected (connected_component x) := is_preconnected_sUnion x _ (λ _, and.right) (λ _, and.left) theorem is_connected_connected_component {x : α} : is_connected (connected_component x) := ⟨⟨x, mem_connected_component⟩, is_preconnected_connected_component⟩ theorem is_preconnected.subset_connected_component {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) : s ⊆ connected_component x := λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩ theorem is_connected.subset_connected_component {x : α} {s : set α} (H1 : is_connected s) (H2 : x ∈ s) : s ⊆ connected_component x := H1.2.subset_connected_component H2 theorem connected_component_eq {x y : α} (h : y ∈ connected_component x) : connected_component x = connected_component y := eq_of_subset_of_subset (is_connected_connected_component.subset_connected_component h) (is_connected_connected_component.subset_connected_component (set.mem_of_mem_of_subset mem_connected_component (is_connected_connected_component.subset_connected_component h))) lemma connected_component_disjoint {x y : α} (h : connected_component x ≠ connected_component y) : disjoint (connected_component x) (connected_component y) := set.disjoint_left.2 (λ a h1 h2, h ((connected_component_eq h1).trans (connected_component_eq h2).symm)) theorem is_closed_connected_component {x : α} : is_closed (connected_component x) := closure_eq_iff_is_closed.1 $ subset.antisymm (is_connected_connected_component.closure.subset_connected_component (subset_closure mem_connected_component)) subset_closure lemma continuous.image_connected_component_subset {β : Type*} [topological_space β] {f : α → β} (h : continuous f) (a : α) : f '' connected_component a ⊆ connected_component (f a) := (is_connected_connected_component.image f h.continuous_on).subset_connected_component ((mem_image f (connected_component a) (f a)).2 ⟨a, mem_connected_component, rfl⟩) theorem irreducible_component_subset_connected_component {x : α} : irreducible_component x ⊆ connected_component x := is_irreducible_irreducible_component.is_connected.subset_connected_component mem_irreducible_component /-- A preconnected space is one where there is no non-trivial open partition. -/ class preconnected_space (α : Type u) [topological_space α] : Prop := (is_preconnected_univ : is_preconnected (univ : set α)) export preconnected_space (is_preconnected_univ) /-- A connected space is a nonempty one where there is no non-trivial open partition. -/ class connected_space (α : Type u) [topological_space α] extends preconnected_space α : Prop := (to_nonempty : nonempty α) attribute [instance, priority 50] connected_space.to_nonempty -- see Note [lower instance priority] lemma is_connected_range [topological_space β] [connected_space α] {f : α → β} (h : continuous f) : is_connected (range f) := begin inhabit α, rw ← image_univ, exact ⟨⟨f (default α), mem_image_of_mem _ (mem_univ _)⟩, is_preconnected.image is_preconnected_univ _ h.continuous_on⟩ end lemma connected_space_iff_connected_component : connected_space α ↔ ∃ x : α, connected_component x = univ := begin split, { rintros ⟨h, ⟨x⟩⟩, exactI ⟨x, eq_univ_of_univ_subset $ is_preconnected_univ.subset_connected_component (mem_univ x)⟩ }, { rintros ⟨x, h⟩, haveI : preconnected_space α := ⟨by { rw ← h, exact is_preconnected_connected_component }⟩, exact ⟨⟨x⟩⟩ } end @[priority 100] -- see Note [lower instance priority] instance preirreducible_space.preconnected_space (α : Type u) [topological_space α] [preirreducible_space α] : preconnected_space α := ⟨(preirreducible_space.is_preirreducible_univ α).is_preconnected⟩ @[priority 100] -- see Note [lower instance priority] instance irreducible_space.connected_space (α : Type u) [topological_space α] [irreducible_space α] : connected_space α := { to_nonempty := irreducible_space.to_nonempty α } theorem nonempty_inter [preconnected_space α] {s t : set α} : is_open s → is_open t → s ∪ t = univ → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preconnected_space.is_preconnected_univ α _ _ s t theorem is_clopen_iff [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ := ⟨λ hs, classical.by_contradiction $ λ h, have h1 : s ≠ ∅ ∧ sᶜ ≠ ∅, from ⟨mt or.inl h, mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩, let ⟨_, h2, h3⟩ := nonempty_inter hs.1 hs.2.is_open_compl (union_compl_self s) (ne_empty_iff_nonempty.1 h1.1) (ne_empty_iff_nonempty.1 h1.2) in h3 h2, by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩ lemma eq_univ_of_nonempty_clopen [preconnected_space α] {s : set α} (h : s.nonempty) (h' : is_clopen s) : s = univ := by { rw is_clopen_iff at h', finish [h.ne_empty] } lemma subtype.preconnected_space {s : set α} (h : is_preconnected s) : preconnected_space s := { is_preconnected_univ := begin intros u v hu hv hs hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv _ ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩, intros z hz, rcases hs (mem_univ ⟨z, hz⟩) with hzu|hzv, { left, assumption }, { right, assumption } end } lemma subtype.connected_space {s : set α} (h : is_connected s) : connected_space s := { is_preconnected_univ := (subtype.preconnected_space h.is_preconnected).is_preconnected_univ, to_nonempty := h.nonempty.to_subtype } lemma is_preconnected_iff_preconnected_space {s : set α} : is_preconnected s ↔ preconnected_space s := ⟨subtype.preconnected_space, begin introI, simpa using is_preconnected_univ.image (coe : s → α) continuous_subtype_coe.continuous_on end⟩ lemma is_connected_iff_connected_space {s : set α} : is_connected s ↔ connected_space s := ⟨subtype.connected_space, λ h, ⟨nonempty_subtype.mp h.2, is_preconnected_iff_preconnected_space.mpr h.1⟩⟩ /-- A set `s` is preconnected if and only if for every cover by two open sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ lemma is_preconnected_iff_subset_of_disjoint {s : set α} : is_preconnected s ↔ ∀ (u v : set α) (hu : is_open u) (hv : is_open v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅), s ⊆ u ∨ s ⊆ v := begin split; intro h, { intros u v hu hv hs huv, specialize h u v hu hv hs, contrapose! huv, rw ne_empty_iff_nonempty, simp [not_subset] at huv, rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩, have hxv : x ∈ v := or_iff_not_imp_left.mp (hs hxs) hxu, have hyu : y ∈ u := or_iff_not_imp_right.mp (hs hys) hyv, exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ }, { intros u v hu hv hs hsu hsv, rw ← ne_empty_iff_nonempty, intro H, specialize h u v hu hv hs H, contrapose H, apply ne_empty_iff_nonempty.mpr, cases h, { rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ }, { rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } } end /-- A set `s` is connected if and only if for every cover by a finite collection of open sets that are pairwise disjoint on `s`, it is contained in one of the members of the collection. -/ lemma is_connected_iff_sUnion_disjoint_open {s : set α} : is_connected s ↔ ∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → (s ∩ (u ∩ v)).nonempty → u = v) (hU : ∀ u ∈ U, is_open u) (hs : s ⊆ ⋃₀ ↑U), ∃ u ∈ U, s ⊆ u := begin rw [is_connected, is_preconnected_iff_subset_of_disjoint], split; intro h, { intro U, apply finset.induction_on U, { rcases h.left, suffices : s ⊆ ∅ → false, { simpa }, intro, solve_by_elim }, { intros u U hu IH hs hU H, rw [finset.coe_insert, sUnion_insert] at H, cases h.2 u (⋃₀ ↑U) _ _ H _ with hsu hsU, { exact ⟨u, finset.mem_insert_self _ _, hsu⟩ }, { rcases IH _ _ hsU with ⟨v, hvU, hsv⟩, { exact ⟨v, finset.mem_insert_of_mem hvU, hsv⟩ }, { intros, apply hs; solve_by_elim [finset.mem_insert_of_mem] }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sUnion, intros, solve_by_elim [finset.mem_insert_of_mem] }, { apply eq_empty_of_subset_empty, rintro x ⟨hxs, hxu, hxU⟩, rw mem_sUnion at hxU, rcases hxU with ⟨v, hvU, hxv⟩, rcases hs u v (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hvU) _ with rfl, { contradiction }, { exact ⟨x, hxs, hxu, hxv⟩ } } } }, { split, { rw ← ne_empty_iff_nonempty, by_contradiction hs, push_neg at hs, subst hs, simpa using h ∅ _ _ _; simp }, intros u v hu hv hs hsuv, rcases h {u, v} _ _ _ with ⟨t, ht, ht'⟩, { rw [finset.mem_insert, finset.mem_singleton] at ht, rcases ht with rfl|rfl; tauto }, { intros t₁ t₂ ht₁ ht₂ hst, rw ← ne_empty_iff_nonempty at hst, rw [finset.mem_insert, finset.mem_singleton] at ht₁ ht₂, rcases ht₁ with rfl|rfl; rcases ht₂ with rfl|rfl, all_goals { refl <|> contradiction <|> skip }, rw inter_comm t₁ at hst, contradiction }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using hs } } end /-- Preconnected sets are either contained in or disjoint to any given clopen set. -/ theorem subset_or_disjoint_of_clopen {α : Type*} [topological_space α] {s t : set α} (h : is_preconnected t) (h1 : is_clopen s) : s ∩ t = ∅ ∨ t ⊆ s := begin by_contradiction h2, have h3 : (s ∩ t).nonempty := ne_empty_iff_nonempty.mp (mt or.inl h2), have h4 : (t ∩ sᶜ).nonempty, { apply inter_compl_nonempty_iff.2, push_neg at h2, exact h2.2 }, rw [inter_comm] at h3, apply ne_empty_iff_nonempty.2 (h s sᶜ h1.1 (is_open_compl_iff.2 h1.2) _ h3 h4), { rw [inter_compl_self, inter_empty] }, { rw [union_compl_self], exact subset_univ t }, end /-- A set `s` is preconnected if and only if for every cover by two closed sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ theorem is_preconnected_iff_subset_of_disjoint_closed {α : Type*} {s : set α} [topological_space α] : is_preconnected s ↔ ∀ (u v : set α) (hu : is_closed u) (hv : is_closed v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅), s ⊆ u ∨ s ⊆ v := begin split; intro h, { intros u v hu hv hs huv, rw is_preconnected_closed_iff at h, specialize h u v hu hv hs, contrapose! huv, rw ne_empty_iff_nonempty, simp [not_subset] at huv, rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩, have hxv : x ∈ v := or_iff_not_imp_left.mp (hs hxs) hxu, have hyu : y ∈ u := or_iff_not_imp_right.mp (hs hys) hyv, exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ }, { rw is_preconnected_closed_iff, intros u v hu hv hs hsu hsv, rw ← ne_empty_iff_nonempty, intro H, specialize h u v hu hv hs H, contrapose H, apply ne_empty_iff_nonempty.mpr, cases h, { rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ }, { rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } } end /-- A closed set `s` is preconnected if and only if for every cover by two closed sets that are disjoint, it is contained in one of the two covering sets. -/ theorem is_preconnected_iff_subset_of_fully_disjoint_closed {s : set α} (hs : is_closed s) : is_preconnected s ↔ ∀ (u v : set α) (hu : is_closed u) (hv : is_closed v) (hss : s ⊆ u ∪ v) (huv : u ∩ v = ∅), s ⊆ u ∨ s ⊆ v := begin split, { intros h u v hu hv hss huv, apply is_preconnected_iff_subset_of_disjoint_closed.1 h u v hu hv hss, rw huv, exact inter_empty s }, intro H, rw is_preconnected_iff_subset_of_disjoint_closed, intros u v hu hv hss huv, have H1 := H (u ∩ s) (v ∩ s), rw [subset_inter_iff, subset_inter_iff] at H1, simp only [subset.refl, and_true] at H1, apply H1 (is_closed.inter hu hs) (is_closed.inter hv hs), { rw ←inter_distrib_right, apply subset_inter_iff.2, exact ⟨hss, subset.refl s⟩ }, { rw [inter_comm v s, inter_assoc, ←inter_assoc s, inter_self s, inter_comm, inter_assoc, inter_comm v u, huv] } end /-- The connected component of a point is always a subset of the intersection of all its clopen neighbourhoods. -/ lemma connected_component_subset_Inter_clopen {x : α} : connected_component x ⊆ ⋂ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z := begin apply subset_Inter (λ Z, _), cases (subset_or_disjoint_of_clopen (@is_connected_connected_component _ _ x).2 Z.2.1), { exfalso, apply nonempty.ne_empty (nonempty_of_mem (mem_inter (@mem_connected_component _ _ x) Z.2.2)), rw inter_comm, exact h }, exact h, end /-- A clopen set is the union of its connected components. -/ lemma is_clopen.eq_union_connected_components {Z : set α} (h : is_clopen Z) : Z = (⋃ (x : α) (H : x ∈ Z), connected_component x) := eq_of_subset_of_subset (λ x xZ, mem_Union.2 ⟨x, mem_Union.2 ⟨xZ, mem_connected_component⟩⟩) (Union_subset $ λ x, Union_subset $ λ xZ, (by { apply subset.trans connected_component_subset_Inter_clopen (Inter_subset _ ⟨Z, ⟨h, xZ⟩⟩) })) /-- The preimage of a connected component is preconnected if the function has connected fibers and a subset is closed iff the preimage is. -/ lemma preimage_connected_component_connected {β : Type*} [topological_space β] {f : α → β} (connected_fibers : ∀ t : β, is_connected (f ⁻¹' {t})) (hcl : ∀ (T : set β), is_closed T ↔ is_closed (f ⁻¹' T)) (t : β) : is_connected (f ⁻¹' connected_component t) := begin -- The following proof is essentially https://stacks.math.columbia.edu/tag/0377 -- although the statement is slightly different have hf : function.surjective f := function.surjective.of_comp (λ t : β, (connected_fibers t).1), split, { cases hf t with s hs, use s, rw [mem_preimage, hs], exact mem_connected_component }, have hT : is_closed (f ⁻¹' connected_component t) := (hcl (connected_component t)).1 is_closed_connected_component, -- To show it's preconnected we decompose (f ⁻¹' connected_component t) as a subset of two -- closed disjoint sets in α. We want to show that it's a subset of either. rw is_preconnected_iff_subset_of_fully_disjoint_closed hT, intros u v hu hv huv uv_disj, -- To do this we decompose connected_component t into T₁ and T₂ -- we will show that connected_component t is a subset of either and hence -- (f ⁻¹' connected_component t) is a subset of u or v let T₁ := {t' ∈ connected_component t | f ⁻¹' {t'} ⊆ u}, let T₂ := {t' ∈ connected_component t | f ⁻¹' {t'} ⊆ v}, have fiber_decomp : ∀ t' ∈ connected_component t, f ⁻¹' {t'} ⊆ u ∨ f ⁻¹' {t'} ⊆ v, { intros t' ht', apply is_preconnected_iff_subset_of_disjoint_closed.1 (connected_fibers t').2 u v hu hv, { exact subset.trans (hf.preimage_subset_preimage_iff.2 (singleton_subset_iff.2 ht')) huv }, rw uv_disj, exact inter_empty _ }, have T₁_u : f ⁻¹' T₁ = (f ⁻¹' connected_component t) ∩ u, { apply eq_of_subset_of_subset, { rw ←bUnion_preimage_singleton, refine bUnion_subset (λ t' ht', subset_inter _ ht'.2), rw [hf.preimage_subset_preimage_iff, singleton_subset_iff], exact ht'.1 }, rintros a ⟨hat, hau⟩, constructor, { exact mem_preimage.1 hat }, dsimp only, cases fiber_decomp (f a) (mem_preimage.1 hat), { exact h }, { exfalso, rw ←not_nonempty_iff_eq_empty at uv_disj, exact uv_disj (nonempty_of_mem (mem_inter hau (h rfl))) } }, -- This proof is exactly the same as the above (modulo some symmetry) have T₂_v : f ⁻¹' T₂ = (f ⁻¹' connected_component t) ∩ v, { apply eq_of_subset_of_subset, { rw ←bUnion_preimage_singleton, refine bUnion_subset (λ t' ht', subset_inter _ ht'.2), rw [hf.preimage_subset_preimage_iff, singleton_subset_iff], exact ht'.1 }, rintros a ⟨hat, hav⟩, constructor, { exact mem_preimage.1 hat }, dsimp only, cases fiber_decomp (f a) (mem_preimage.1 hat), { exfalso, rw ←not_nonempty_iff_eq_empty at uv_disj, exact uv_disj (nonempty_of_mem (mem_inter (h rfl) hav)) }, { exact h } }, -- Now we show T₁, T₂ are closed, cover connected_component t and are disjoint. have hT₁ : is_closed T₁ := ((hcl T₁).2 (T₁_u.symm ▸ (is_closed.inter hT hu))), have hT₂ : is_closed T₂ := ((hcl T₂).2 (T₂_v.symm ▸ (is_closed.inter hT hv))), have T_decomp : connected_component t ⊆ T₁ ∪ T₂, { intros t' ht', rw mem_union t' T₁ T₂, cases fiber_decomp t' ht' with htu htv, { left, exact ⟨ht', htu⟩ }, right, exact ⟨ht', htv⟩ }, have T_disjoint : T₁ ∩ T₂ = ∅, { rw ←image_preimage_eq (T₁ ∩ T₂) hf, suffices : f ⁻¹' (T₁ ∩ T₂) = ∅, { rw this, exact image_empty _ }, rw [preimage_inter, T₁_u, T₂_v], rw inter_comm at uv_disj, conv { congr, rw [inter_assoc], congr, skip, rw [←inter_assoc, inter_comm, ←inter_assoc, uv_disj, empty_inter], }, exact inter_empty _ }, -- Now we do cases on whether (connected_component t) is a subset of T₁ or T₂ to show -- that the preimage is a subset of u or v. cases (is_preconnected_iff_subset_of_fully_disjoint_closed is_closed_connected_component).1 is_preconnected_connected_component T₁ T₂ hT₁ hT₂ T_decomp T_disjoint, { left, rw subset.antisymm_iff at T₁_u, suffices : f ⁻¹' connected_component t ⊆ f ⁻¹' T₁, { exact subset.trans (subset.trans this T₁_u.1) (inter_subset_right _ _) }, exact preimage_mono h }, right, rw subset.antisymm_iff at T₂_v, suffices : f ⁻¹' connected_component t ⊆ f ⁻¹' T₂, { exact subset.trans (subset.trans this T₂_v.1) (inter_subset_right _ _) }, exact preimage_mono h, end end preconnected section totally_disconnected /-- A set `s` is called totally disconnected if every subset `t ⊆ s` which is preconnected is a subsingleton, ie either empty or a singleton.-/ def is_totally_disconnected (s : set α) : Prop := ∀ t, t ⊆ s → is_preconnected t → t.subsingleton theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) := λ _ ht _ _ x_in _ _, (ht x_in).elim theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) := λ _ ht _, subsingleton.mono subsingleton_singleton ht /-- A space is totally disconnected if all of its connected components are singletons. -/ class totally_disconnected_space (α : Type u) [topological_space α] : Prop := (is_totally_disconnected_univ : is_totally_disconnected (univ : set α)) lemma is_preconnected.subsingleton [totally_disconnected_space α] {s : set α} (h : is_preconnected s) : s.subsingleton := totally_disconnected_space.is_totally_disconnected_univ s (subset_univ s) h instance pi.totally_disconnected_space {α : Type*} {β : α → Type*} [t₂ : Πa, topological_space (β a)] [∀a, totally_disconnected_space (β a)] : totally_disconnected_space (Π (a : α), β a) := ⟨λ t h1 h2, have this : ∀ a, is_preconnected ((λ x : Π a, β a, x a) '' t), from λ a, h2.image (λ x, x a) (continuous_apply a).continuous_on, λ x x_in y y_in, funext $ λ a, (this a).subsingleton ⟨x, x_in, rfl⟩ ⟨y, y_in, rfl⟩⟩ instance prod.totally_disconnected_space [topological_space β] [totally_disconnected_space α] [totally_disconnected_space β] : totally_disconnected_space (α × β) := ⟨λ t h1 h2, have H1 : is_preconnected (prod.fst '' t), from h2.image prod.fst continuous_fst.continuous_on, have H2 : is_preconnected (prod.snd '' t), from h2.image prod.snd continuous_snd.continuous_on, λ x hx y hy, prod.ext (H1.subsingleton ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩) (H2.subsingleton ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩)⟩ /-- A space is totally disconnected iff its connected components are subsingletons. -/ lemma totally_disconnected_space_iff_connected_component_subsingleton : totally_disconnected_space α ↔ ∀ x : α, (connected_component x).subsingleton := begin split, { intros h x, apply h.1, { exact subset_univ _ }, exact is_preconnected_connected_component }, intro h, constructor, intros s s_sub hs, rcases eq_empty_or_nonempty s with rfl | ⟨x, x_in⟩, { exact subsingleton_empty }, { exact (h x).mono (hs.subset_connected_component x_in) } end /-- A space is totally disconnected iff its connected components are singletons. -/ lemma totally_disconnected_space_iff_connected_component_singleton : totally_disconnected_space α ↔ ∀ x : α, connected_component x = {x} := begin rw totally_disconnected_space_iff_connected_component_subsingleton, apply forall_congr (λ x, _), rw set.subsingleton_iff_singleton, exact mem_connected_component end /-- The image of a connected component in a totally disconnected space is a singleton. -/ @[simp] lemma continuous.image_connected_component_eq_singleton {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) (a : α) : f '' connected_component a = {f a} := (set.subsingleton_iff_singleton $ mem_image_of_mem f mem_connected_component).mp (is_preconnected_connected_component.image f h.continuous_on).subsingleton lemma is_totally_disconnected_of_totally_disconnected_space [totally_disconnected_space α] (s : set α) : is_totally_disconnected s := λ t hts ht, totally_disconnected_space.is_totally_disconnected_univ _ t.subset_univ ht lemma is_totally_disconnected_of_image [topological_space β] {f : α → β} (hf : continuous_on f s) (hf' : function.injective f) (h : is_totally_disconnected (f '' s)) : is_totally_disconnected s := λ t hts ht x x_in y y_in, hf' $ h _ (image_subset f hts) (ht.image f $ hf.mono hts) (mem_image_of_mem f x_in) (mem_image_of_mem f y_in) lemma embedding.is_totally_disconnected [topological_space β] {f : α → β} (hf : embedding f) {s : set α} (h : is_totally_disconnected (f '' s)) : is_totally_disconnected s := is_totally_disconnected_of_image hf.continuous.continuous_on hf.inj h instance subtype.totally_disconnected_space {α : Type*} {p : α → Prop} [topological_space α] [totally_disconnected_space α] : totally_disconnected_space (subtype p) := ⟨embedding_subtype_coe.is_totally_disconnected (is_totally_disconnected_of_totally_disconnected_space _)⟩ end totally_disconnected section totally_separated /-- A set `s` is called totally separated if any two points of this set can be separated by two disjoint open sets covering `s`. -/ def is_totally_separated (s : set α) : Prop := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅ theorem is_totally_separated_empty : is_totally_separated (∅ : set α) := λ x, false.elim theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) := λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim theorem is_totally_disconnected_of_is_totally_separated {s : set α} (H : is_totally_separated s) : is_totally_disconnected s := begin intros t hts ht x x_in y y_in, by_contra h, obtain ⟨u : set α, v : set α, hu : is_open u, hv : is_open v, hxu : x ∈ u, hyv : y ∈ v, hs : s ⊆ u ∪ v, huv : u ∩ v = ∅⟩ := H x (hts x_in) y (hts y_in) h, have : (t ∩ u).nonempty → (t ∩ v).nonempty → (t ∩ (u ∩ v)).nonempty := ht _ _ hu hv (subset.trans hts hs), obtain ⟨z, hz : z ∈ t ∩ (u ∩ v)⟩ := this ⟨x, x_in, hxu⟩ ⟨y, y_in, hyv⟩, simpa [huv] using hz end alias is_totally_disconnected_of_is_totally_separated ← is_totally_separated.is_totally_disconnected /-- A space is totally separated if any two points can be separated by two disjoint open sets covering the whole space. -/ class totally_separated_space (α : Type u) [topological_space α] : Prop := (is_totally_separated_univ [] : is_totally_separated (univ : set α)) @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α] [totally_separated_space α] : totally_disconnected_space α := ⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩ @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.of_discrete (α : Type*) [topological_space α] [discrete_topology α] : totally_separated_space α := ⟨λ a _ b _ h, ⟨{b}ᶜ, {b}, is_open_discrete _, is_open_discrete _, by simpa⟩⟩ lemma exists_clopen_of_totally_separated {α : Type*} [topological_space α] [totally_separated_space α] {x y : α} (hxy : x ≠ y) : ∃ (U : set α) (hU : is_clopen U), x ∈ U ∧ y ∈ Uᶜ := begin obtain ⟨U, V, hU, hV, Ux, Vy, f, disj⟩ := totally_separated_space.is_totally_separated_univ α x (set.mem_univ x) y (set.mem_univ y) hxy, have clopen_U := is_clopen_inter_of_disjoint_cover_clopen (is_clopen_univ) f hU hV disj, rw set.univ_inter _ at clopen_U, rw [←set.subset_compl_iff_disjoint, set.subset_compl_comm] at disj, exact ⟨U, clopen_U, Ux, disj Vy⟩, end end totally_separated section connected_component_setoid /-- The setoid of connected components of a topological space -/ def connected_component_setoid (α : Type*) [topological_space α] : setoid α := ⟨λ x y, connected_component x = connected_component y, ⟨λ x, by trivial, λ x y h1, h1.symm, λ x y z h1 h2, h1.trans h2⟩⟩ -- see Note [lower instance priority] local attribute [instance, priority 100] connected_component_setoid lemma connected_component_rel_iff {x y : α} : ⟦x⟧ = ⟦y⟧ ↔ connected_component x = connected_component y := ⟨λ h, quotient.exact h, λ h, quotient.sound h⟩ lemma connected_component_nrel_iff {x y : α} : ⟦x⟧ ≠ ⟦y⟧ ↔ connected_component x ≠ connected_component y := by { rw not_iff_not, exact connected_component_rel_iff } /-- The quotient of a space by its connected components -/ def connected_components (α : Type u) [topological_space α] := quotient (connected_component_setoid α) instance [inhabited α] : inhabited (connected_components α) := ⟨quotient.mk (default _)⟩ instance connected_components.topological_space : topological_space (connected_components α) := quotient.topological_space lemma continuous.image_eq_of_equiv {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) (a b : α) (hab : a ≈ b) : f a = f b := singleton_eq_singleton_iff.1 $ h.image_connected_component_eq_singleton a ▸ h.image_connected_component_eq_singleton b ▸ hab ▸ rfl /-- The lift to `connected_components α` of a continuous map from `α` to a totally disconnected space -/ def continuous.connected_components_lift {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) : connected_components α → β := quotient.lift f h.image_eq_of_equiv @[continuity] lemma continuous.connected_components_lift_continuous {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) : continuous h.connected_components_lift := continuous_quotient_lift h.image_eq_of_equiv h @[simp] lemma continuous.connected_components_lift_factors {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) : h.connected_components_lift ∘ quotient.mk = f := rfl lemma continuous.connected_components_lift_unique {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) (g : connected_components α → β) (hg : g ∘ quotient.mk = f) : g = h.connected_components_lift := by { subst hg, ext1 x, exact quotient.induction_on x (λ a, refl _) } lemma connected_components_lift_unique' {β : Type*} (g₁ : connected_components α → β) (g₂ : connected_components α → β) (hg : g₁ ∘ quotient.mk = g₂ ∘ quotient.mk ) : g₁ = g₂ := begin ext1 x, refine quotient.induction_on x (λ a, _), change (g₁ ∘ quotient.mk) a = (g₂ ∘ quotient.mk) a, rw hg, end /-- The preimage of a singleton in `connected_components` is the connected component of an element in the equivalence class. -/ lemma connected_components_preimage_singleton {t : α} : connected_component t = quotient.mk ⁻¹' {⟦t⟧} := begin apply set.eq_of_subset_of_subset; intros a ha, { have H : ⟦a⟧ = ⟦t⟧ := quotient.sound (connected_component_eq ha).symm, rw [mem_preimage, H], exact mem_singleton ⟦t⟧ }, rw [mem_preimage, mem_singleton_iff] at ha, have ha' : connected_component a = connected_component t := quotient.exact ha, rw ←ha', exact mem_connected_component, end /-- The preimage of the image of a set under the quotient map to `connected_components α` is the union of the connected components of the elements in it. -/ lemma connected_components_preimage_image (U : set α) : quotient.mk ⁻¹' (quotient.mk '' U) = ⋃ (x : α) (h : x ∈ U), connected_component x := begin apply set.eq_of_subset_of_subset, { rintros a ⟨b, hb, hab⟩, refine mem_Union.2 ⟨b, mem_Union.2 ⟨hb, _⟩⟩, rw connected_component_rel_iff.1 hab, exact mem_connected_component }, refine Union_subset (λ a, Union_subset (λ ha, _)), rw [connected_components_preimage_singleton, (surjective_quotient_mk _).preimage_subset_preimage_iff, singleton_subset_iff], exact ⟨a, ha, refl _⟩, end instance connected_components.totally_disconnected_space : totally_disconnected_space (connected_components α) := begin rw totally_disconnected_space_iff_connected_component_singleton, refine λ x, quotient.induction_on x (λ a, _), apply eq_of_subset_of_subset _ (singleton_subset_iff.2 mem_connected_component), rw subset_singleton_iff, refine λ x, quotient.induction_on x (λ b hb, _), rw [connected_component_rel_iff, connected_component_eq], suffices : is_preconnected (quotient.mk ⁻¹' connected_component ⟦a⟧), { apply mem_of_subset_of_mem (this.subset_connected_component hb), exact mem_preimage.2 mem_connected_component }, apply (@preimage_connected_component_connected _ _ _ _ _ _ _ _).2, { refine λ t, quotient.induction_on t (λ s, _), rw ←connected_components_preimage_singleton, exact is_connected_connected_component }, refine λ T, ⟨λ hT, hT.preimage continuous_quotient_mk, λ hT, _⟩, rwa [← is_open_compl_iff, ← preimage_compl, quotient_map_quotient_mk.is_open_preimage, is_open_compl_iff] at hT, end /-- Functoriality of `connected_components` -/ def continuous.connected_components_map {β : Type*} [topological_space β] {f : α → β} (h : continuous f) : connected_components α → connected_components β := continuous.connected_components_lift (continuous_quotient_mk.comp h) lemma continuous.connected_components_map_continuous {β : Type*} [topological_space β] {f : α → β} (h : continuous f) : continuous h.connected_components_map := continuous.connected_components_lift_continuous (continuous_quotient_mk.comp h) end connected_component_setoid
0e0ab12bad68f013b7373c26a01ce516724d6eb1
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/data/set/finite.lean
6c794158854d04bdd6307d6284d1e5d08282cf9e
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
22,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 Finite sets. -/ import logic.function import data.nat.basic data.fintype data.set.lattice data.set.function open set lattice function universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace set /-- A set is finite if the subtype is a fintype, i.e. there is a list that enumerates its members. -/ def finite (s : set α) : Prop := nonempty (fintype s) /-- A set is infinite if it is not finite. -/ def infinite (s : set α) : Prop := ¬ finite s noncomputable instance finite.fintype {s : set α} (h : finite s) : fintype s := classical.choice h /-- Get a finset from a finite set -/ noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α := @set.to_finset _ _ (finite.fintype h) @[simp] theorem finite.mem_to_finset {s : set α} {h : finite s} {a : α} : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ (finite.fintype h) _ lemma finite.coe_to_finset {α} {s : set α} (h : finite s) : ↑h.to_finset = s := by { ext, apply mem_to_finset } theorem finite.exists_finset {s : set α} : finite s → ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s | ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩ theorem finite.exists_finset_coe {s : set α} (hs : finite s) : ∃ s' : finset α, ↑s' = s := ⟨hs.to_finset, hs.coe_to_finset⟩ /-- Finite sets can be lifted to finsets. -/ instance : can_lift (set α) (finset α) := { coe := coe, cond := finite, prf := λ s hs, hs.exists_finset_coe } theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} := ⟨fintype.of_finset s (λ _, iff.rfl)⟩ theorem finite.of_fintype [fintype α] (s : set α) : finite s := by classical; exact ⟨set_fintype s⟩ /-- Membership of a subset of a finite type is decidable. Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability assumptions, so it should only be declared a local instance. -/ def decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) := decidable_of_iff _ mem_to_finset instance fintype_empty : fintype (∅ : set α) := fintype.of_finset ∅ $ by simp theorem empty_card : fintype.card (∅ : set α) = 0 := rfl @[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} : @fintype.card (∅ : set α) h = 0 := eq.trans (by congr) empty_card @[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩ def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype.of_finset ⟨a :: s.to_finset.1, multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert' s h) = fintype.card s + 1 := by rw [fintype_insert', fintype.card_of_finset]; simp [finset.card, to_finset]; refl @[simp] theorem card_insert {a : α} (s : set α) [fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} : @fintype.card _ d = fintype.card s + 1 := by rw ← card_fintype_insert' s h; congr lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp) ... = s.to_finset.card : finset.card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h section local attribute [instance] decidable_mem_of_fintype instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)] else fintype_insert' _ h end @[simp] theorem finite_insert (a : α) {s : set α} : finite s → finite (insert a s) | ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩ lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) : (finite_insert a hs).to_finset = insert a hs.to_finset := finset.ext.mpr $ by simp @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s := let ⟨t⟩ := h in by exactI match s.to_finset, @mem_to_finset _ s _ with | ⟨l, nd⟩, al := begin change ∀ a, a ∈ l ↔ a ∈ s at al, clear _let_match _match t h, revert s nd al, refine multiset.induction_on l _ (λ a l IH, _); intros s nd al, { rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al), exact H0 }, { rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al), cases multiset.nodup_cons.1 nd with m nd', refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)), exact m } end end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (finite_insert a h)) : C s h := have ∀h:finite s, C s h, from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)), this h instance fintype_singleton (a : α) : fintype ({a} : set α) := fintype_insert' _ (not_mem_empty _) @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := by rw [show fintype.card ({a} : set α) = _, from card_fintype_insert' ∅ (not_mem_empty a)]; refl @[simp] theorem finite_singleton (a : α) : finite ({a} : set α) := ⟨set.fintype_singleton _⟩ instance fintype_pure : ∀ a : α, fintype (pure a : set α) := set.fintype_singleton theorem finite_pure (a : α) : finite (pure a : set α) := ⟨set.fintype_pure a⟩ instance fintype_univ [fintype α] : fintype (@univ α) := fintype.of_equiv α $ (equiv.set.univ α).symm theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩ theorem infinite_univ_iff : (@univ α).infinite ↔ _root_.infinite α := ⟨λ h₁, ⟨λ h₂, h₁ $ @finite_univ α h₂⟩, λ ⟨h₁⟩ ⟨h₂⟩, h₁ $ @fintype.of_equiv _ _ h₂ $ equiv.set.univ _⟩ theorem infinite_univ [h : _root_.infinite α] : infinite (@univ α) := infinite_univ_iff.2 h instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) := fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp theorem finite_union {s t : set α} : finite s → finite t → finite (s ∪ t) | ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩ instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) := fintype.of_finset (s.to_finset.filter p) $ by simp instance fintype_inter (s t : set α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) := set.fintype_sep s t def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred t] (h : t ⊆ s) : fintype t := by rw ← inter_eq_self_of_subset_right h; apply_instance theorem finite_subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t | ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩ instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype.of_finset (s.to_finset.image f) $ by simp instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) := fintype.of_finset (finset.univ.image f) $ by simp [range] theorem finite_range (f : α → β) [fintype α] : finite (range f) := by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩ theorem finite_image {s : set α} (f : α → β) : finite s → finite (f '' s) | ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩ instance fintype_map {α β} [decidable_eq β] : ∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image theorem finite_map {α β} {s : set α} : ∀ (f : α → β), finite s → finite (f <$> s) := finite_image def fintype_of_fintype_image (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype.of_finset ⟨_, @multiset.nodup_filter_map β α g _ (@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a, begin suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s, by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc], rw exists_swap, suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]}, simp [I _, (injective_of_partial_inv I).eq_iff] end theorem finite_of_finite_image_on {s : set α} {f : α → β} (hi : set.inj_on f s) : finite (f '' s) → finite s | ⟨h⟩ := ⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $ assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext.1 eq⟩ theorem finite_image_iff_on {s : set α} {f : α → β} (hi : inj_on f s) : finite (f '' s) ↔ finite s := ⟨finite_of_finite_image_on hi, finite_image _⟩ theorem finite_of_finite_image {s : set α} {f : α → β} (I : set.inj_on f s) : finite (f '' s) → finite s := finite_of_finite_image_on I theorem finite_preimage {s : set β} {f : α → β} (I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) := finite_of_finite_image I (finite_subset h (image_preimage_subset f s)) instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype.of_finset (finset.univ.bind (λ i, (f i).to_finset)) $ by simp theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) := ⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩ def fintype_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) := by rw bUnion_eq_Union; exact @set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi) instance fintype_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) := fintype_bUnion _ (λ i _, H i) theorem finite_sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) := by rw sUnion_eq_Union; haveI := finite.fintype h; apply finite_Union; simpa using H theorem finite_bUnion {α} {ι : Type*} {s : set ι} {f : ι → set α} : finite s → (∀i, finite (f i)) → finite (⋃ i∈s, f i) | ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _) theorem finite_bUnion' {α} {ι : Type*} {s : set ι} (f : ι → set α) : finite s → (∀i ∈ s, finite (f i)) → finite (⋃ i∈s, f i) | ⟨hs⟩ h := by { rw [bUnion_eq_Union], exactI finite_Union (λ i, h i.1 i.2) } instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} := fintype.of_finset (finset.range n) $ by simp instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} := by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1) lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩ lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩ instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) := fintype.of_finset (s.to_finset.product t.to_finset) $ by simp lemma finite_prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t) | ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩ def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) := set.fintype_bUnion _ H instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) := fintype_bind _ _ (λ i _, H i) theorem finite_bind {α β} {s : set α} {f : α → set β} : finite s → (∀ a ∈ s, finite (f a)) → finite (s >>= f) | ⟨hs⟩ H := ⟨@fintype_bind _ _ (classical.dec_eq β) _ hs _ (λ a ha, (H a ha).fintype)⟩ instance fintype_seq {α β : Type u} [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f <*> s) := by rw seq_eq_bind_map; apply set.fintype_bind' theorem finite_seq {α β : Type u} {f : set (α → β)} {s : set α} : finite f → finite s → finite (f <*> s) | ⟨hf⟩ ⟨hs⟩ := by { haveI := classical.dec_eq β, exactI ⟨set.fintype_seq _ _⟩ } /-- There are finitely many subsets of a given finite set -/ lemma finite_subsets_of_finite {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} := begin -- we just need to translate the result, already known for finsets, -- to the language of finite sets let s := coe '' ((finset.powerset (finite.to_finset h)).to_set), have : finite s := finite_image _ (finite_mem_finset _), have : {b | b ⊆ a} ⊆ s := begin assume b hb, rw [set.mem_image], rw [set.mem_set_of_eq] at hb, let b' : finset α := finite.to_finset (finite_subset h hb), have : b' ∈ (finset.powerset (finite.to_finset h)).to_set := show b' ∈ (finset.powerset (finite.to_finset h)), by simp [b', finset.subset_iff]; exact hb, have : coe b' = b := by ext; simp, exact ⟨b', by assumption, by assumption⟩ end, exact finite_subset ‹finite s› this end lemma exists_min [decidable_linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using (finite.to_finset h1).exists_min f ⟨x, finite.mem_to_finset.2 hx⟩ end set namespace finset variables [decidable_eq β] variables {s t u : finset α} {f : α → β} {a : α} lemma finite_to_set (s : finset α) : set.finite (↑s : set α) := set.finite_mem_finset s @[simp] lemma coe_bind {f : α → finset β} : ↑(s.bind f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) := by simp [set.ext_iff] @[simp] lemma coe_to_finset {s : set α} {hs : set.finite s} : ↑(hs.to_finset) = s := by simp [set.ext_iff] @[simp] lemma coe_to_finset' (s : set α) [fintype s] : (↑s.to_finset : set α) = s := by ext; simp end finset namespace set lemma finite_subset_Union {s : set α} (hs : finite s) {ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i := begin unfreezeI, cases hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, _⟩, rintro x hx, simp, exact ⟨_, ⟨_, hx, rfl⟩, hf ⟨x, hx⟩⟩ end lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f)) (hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) := finite_subset (finite_union hf hg) range_ite_subset lemma finite_range_const {c : β} : finite (range (λ x : α, c)) := finite_subset (finite_singleton c) range_const_subset lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}: range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) := by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] } lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} : finite (range (λ x, nat.find_greatest (P x) b)) := finite_subset (finset.finite_to_set $ finset.range (b + 1)) range_find_greatest_subset lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := begin haveI := classical.prop_decidable, rw [← finset.coe_to_finset' s, ← finset.coe_to_finset' t, finset.coe_ssubset] at h, rw [fintype.card_of_finset' _ (λ x, mem_to_finset), fintype.card_of_finset' _ (λ x, mem_to_finset)], exact finset.card_lt_card h, end lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := calc fintype.card s = s.to_finset.card : fintype.card_of_finset' _ (by simp) ... ≤ t.to_finset.card : finset.card_le_of_subset (λ x hx, by simp [set.subset_def, *] at *) ... = fintype.card t : eq.symm (fintype.card_of_finset' _ (by simp)) lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id (λ h, absurd hcard $ not_le_of_lt $ card_lt_card h) lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f) [fintype (range f)] : fintype.card (range f) = fintype.card α := eq.symm $ fintype.card_congr (@equiv.of_bijective _ _ (λ a : α, show range f, from ⟨f a, a, rfl⟩) ⟨λ x y h, hf $ subtype.mk.inj h, λ b, let ⟨a, ha⟩ := b.2 in ⟨a, by simp *⟩⟩) lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) : s ≠ ∅ → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' := begin classical, refine h.induction_on _ _, { assume h, contradiction }, assume a s his _ ih _, by_cases s = ∅, { use a, simp [h] }, rcases ih h with ⟨b, hb, ih⟩, by_cases f b ≤ f a, { refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { refl }, { rwa [← ih c hcs (le_trans h hac)] } }, { refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { exact (h hbc).elim }, { exact ih c hcs hbc } } end section local attribute [instance, priority 1] classical.prop_decidable lemma to_finset_card {α : Type*} [fintype α] (H : set α) : H.to_finset.card = fintype.card H := multiset.card_map subtype.val finset.univ.val lemma to_finset_inter {α : Type*} [fintype α] (s t : set α) [decidable_eq α] : (s ∩ t).to_finset = s.to_finset ∩ t.to_finset := by ext; simp end section variables [semilattice_sup α] [nonempty α] {s : set α} /--A finite set is bounded above.-/ lemma bdd_above_finite (hs : finite s) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _, bdd_above_insert.2 /--A finite union of sets which are all bounded above is still bounded above.-/ lemma bdd_above_finite_union {I : set β} {S : β → set α} (H : finite I) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := ⟨λ (bdd : bdd_above (⋃i∈I, S i)) i (hi : i ∈ I), bdd_above_subset (subset_bUnion_of_mem hi) bdd, show (∀i ∈ I, bdd_above (S i)) → (bdd_above (⋃i∈I, S i)), from finite.induction_on H (λ _, by rw bUnion_empty; exact bdd_above_empty) (λ x s hn hf IH h, by simp only [ set.mem_insert_iff, or_imp_distrib, forall_and_distrib, forall_eq] at h; rw [set.bUnion_insert, bdd_above_union]; exact ⟨h.1, IH h.2⟩)⟩ end section variables [semilattice_inf α] [nonempty α] {s : set α} /--A finite set is bounded below.-/ lemma bdd_below_finite (hs : finite s) : bdd_below s := finite.induction_on hs bdd_below_empty $ λ a s _ _, bdd_below_insert.2 /--A finite union of sets which are all bounded below is still bounded below.-/ lemma bdd_below_finite_union {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := ⟨λ (bdd : bdd_below (⋃i∈I, S i)) i (hi : i ∈ I), bdd_below_subset (subset_bUnion_of_mem hi) bdd, show (∀i ∈ I, bdd_below (S i)) → (bdd_below (⋃i∈I, S i)), from finite.induction_on H (λ _, by rw bUnion_empty; exact bdd_below_empty) (λ x s hn hf IH h, by simp only [ set.mem_insert_iff, or_imp_distrib, forall_and_distrib, forall_eq] at h; rw [set.bUnion_insert, bdd_below_union]; exact ⟨h.1, IH h.2⟩)⟩ end end set namespace finset section preimage noncomputable def preimage {f : α → β} (s : finset β) (hf : set.inj_on f (f ⁻¹' ↑s)) : finset α := set.finite.to_finset (set.finite_preimage hf (set.finite_mem_finset s)) @[simp] lemma mem_preimage {f : α → β} {s : finset β} {hf : set.inj_on f (f ⁻¹' ↑s)} {x : α} : x ∈ preimage s hf ↔ f x ∈ s := by simp [preimage] @[simp] lemma coe_preimage {f : α → β} (s : finset β) (hf : set.inj_on f (f ⁻¹' ↑s)) : (↑(preimage s hf) : set α) = f ⁻¹' ↑s := by simp [set.ext_iff] lemma image_preimage [decidable_eq β] (f : α → β) (s : finset β) (hf : set.bij_on f (f ⁻¹' s.to_set) s.to_set) : image f (preimage s (set.inj_on_of_bij_on hf)) = s := finset.coe_inj.1 $ suffices f '' (f ⁻¹' ↑s) = ↑s, by simpa, (set.subset.antisymm (image_preimage_subset _ _) hf.2.2) end preimage @[to_additive] lemma prod_preimage [comm_monoid β] (f : α → γ) (s : finset γ) (hf : set.bij_on f (f ⁻¹' ↑s) ↑s) (g : γ → β) : (preimage s (set.inj_on_of_bij_on hf)).prod (g ∘ f) = s.prod g := by classical; calc (preimage s (set.inj_on_of_bij_on hf)).prod (g ∘ f) = (image f (preimage s (set.inj_on_of_bij_on hf))).prod g : begin rw prod_image, intros x hx y hy hxy, apply set.inj_on_of_bij_on hf, repeat { try { rw mem_preimage at hx hy, rw [set.mem_preimage, mem_coe] }, assumption }, end ... = s.prod g : by rw image_preimage end finset lemma fintype.exists_max [fintype α] [nonempty α] {β : Type*} [decidable_linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x ≤ f x₀ := begin obtain ⟨y, hy⟩ : ∃ y, y ∈ (set.range f).to_finset, { haveI := classical.inhabited_of_nonempty ‹nonempty α›, exact ⟨f (default α), set.mem_to_finset.mpr $ set.mem_range_self _⟩ }, rcases finset.max_of_mem hy with ⟨y₀, h⟩, rcases set.mem_to_finset.1 (finset.mem_of_max h) with ⟨x₀, rfl⟩, use x₀, intro x, apply finset.le_max_of_mem (set.mem_to_finset.mpr $ set.mem_range_self x) h end
a59720207a66aa6cdda5d40624ff49ebea6433a5
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/matrix/pos_def.lean
b4d9bb628cafad12db3c4f848e3893f553f1a232
[ "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
2,251
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 linear_algebra.matrix.spectrum import linear_algebra.quadratic_form.basic /-! # Positive Definite Matrices This file defines positive definite matrices and connects this notion to positive definiteness of quadratic forms. ## Main definition * `matrix.pos_def` : a matrix `M : matrix n n R` is positive definite if it is hermitian and `xᴴMx` is greater than zero for all nonzero `x`. -/ namespace matrix variables {R : Type*} [ordered_semiring R] [star_ring R] {n : Type*} [fintype n] open_locale matrix /-- A matrix `M : matrix n n R` is positive definite if it is hermitian and `xᴴMx` is greater than zero for all nonzero `x`. -/ def pos_def (M : matrix n n R) := M.is_hermitian ∧ ∀ x : n → R, x ≠ 0 → 0 < dot_product (star x) (M.mul_vec x) lemma pos_def_of_to_quadratic_form' [decidable_eq n] {M : matrix n n ℝ} (hM : M.is_symm) (hMq : M.to_quadratic_form'.pos_def) : M.pos_def := begin refine ⟨hM, λ x hx, _⟩, simp only [to_quadratic_form', quadratic_form.pos_def, bilin_form.to_quadratic_form_apply, matrix.to_bilin'_apply'] at hMq, apply hMq x hx, end lemma pos_def_to_quadratic_form' [decidable_eq n] {M : matrix n n ℝ} (hM : M.pos_def) : M.to_quadratic_form'.pos_def := begin intros x hx, simp only [to_quadratic_form', bilin_form.to_quadratic_form_apply, matrix.to_bilin'_apply'], apply hM.2 x hx, end end matrix namespace quadratic_form variables {n : Type*} [fintype n] lemma pos_def_of_to_matrix' [decidable_eq n] {Q : quadratic_form ℝ (n → ℝ)} (hQ : Q.to_matrix'.pos_def) : Q.pos_def := begin rw [←to_quadratic_form_associated ℝ Q, ←bilin_form.to_matrix'.left_inv ((associated_hom _) Q)], apply matrix.pos_def_to_quadratic_form' hQ end lemma pos_def_to_matrix' [decidable_eq n] {Q : quadratic_form ℝ (n → ℝ)} (hQ : Q.pos_def) : Q.to_matrix'.pos_def := begin rw [←to_quadratic_form_associated ℝ Q, ←bilin_form.to_matrix'.left_inv ((associated_hom _) Q)] at hQ, apply matrix.pos_def_of_to_quadratic_form' (is_symm_to_matrix' Q) hQ, end end quadratic_form
dec0431f841930b77fd45d93deeeca15f42facd4
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/analytic/composition.lean
6b789341b2acd55fcbe420c2c24c2c7b6a74623c
[ "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
58,802
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Johan Commelin -/ import analysis.analytic.basic import combinatorics.composition /-! # Composition of analytic functions in this file we prove that the composition of analytic functions is analytic. The argument is the following. Assume `g z = ∑' qₙ (z, ..., z)` and `f y = ∑' pₖ (y, ..., y)`. Then `g (f y) = ∑' qₙ (∑' pₖ (y, ..., y), ..., ∑' pₖ (y, ..., y)) = ∑' qₙ (p_{i₁} (y, ..., y), ..., p_{iₙ} (y, ..., y))`. For each `n` and `i₁, ..., iₙ`, define a `i₁ + ... + iₙ` multilinear function mapping `(y₀, ..., y_{i₁ + ... + iₙ - 1})` to `qₙ (p_{i₁} (y₀, ..., y_{i₁-1}), p_{i₂} (y_{i₁}, ..., y_{i₁ + i₂ - 1}), ..., p_{iₙ} (....)))`. Then `g ∘ f` is obtained by summing all these multilinear functions. To formalize this, we use compositions of an integer `N`, i.e., its decompositions into a sum `i₁ + ... + iₙ` of positive integers. Given such a composition `c` and two formal multilinear series `q` and `p`, let `q.comp_along_composition p c` be the above multilinear function. Then the `N`-th coefficient in the power series expansion of `g ∘ f` is the sum of these terms over all `c : composition N`. To complete the proof, we need to show that this power series has a positive radius of convergence. This follows from the fact that `composition N` has cardinality `2^(N-1)` and estimates on the norm of `qₙ` and `pₖ`, which give summability. We also need to show that it indeed converges to `g ∘ f`. For this, we note that the composition of partial sums converges to `g ∘ f`, and that it corresponds to a part of the whole sum, on a subset that increases to the whole space. By summability of the norms, this implies the overall convergence. ## Main results * `q.comp p` is the formal composition of the formal multilinear series `q` and `p`. * `has_fpower_series_at.comp` states that if two functions `g` and `f` admit power series expansions `q` and `p`, then `g ∘ f` admits a power series expansion given by `q.comp p`. * `analytic_at.comp` states that the composition of analytic functions is analytic. * `formal_multilinear_series.comp_assoc` states that composition is associative on formal multilinear series. ## Implementation details The main technical difficulty is to write down things. In particular, we need to define precisely `q.comp_along_composition p c` and to show that it is indeed a continuous multilinear function. This requires a whole interface built on the class `composition`. Once this is set, the main difficulty is to reorder the sums, writing the composition of the partial sums as a sum over some subset of `Σ n, composition n`. We need to check that the reordering is a bijection, running over difficulties due to the dependent nature of the types under consideration, that are controlled thanks to the interface for `composition`. The associativity of composition on formal multilinear series is a nontrivial result: it does not follow from the associativity of composition of analytic functions, as there is no uniqueness for the formal multilinear series representing a function (and also, it holds even when the radius of convergence of the series is `0`). Instead, we give a direct proof, which amounts to reordering double sums in a careful way. The change of variables is a canonical (combinatorial) bijection `composition.sigma_equiv_sigma_pi` between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, and is described in more details below in the paragraph on associativity. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] {H : Type*} [normed_group H] [normed_space 𝕜 H] open filter list open_locale topological_space big_operators classical nnreal ennreal /-! ### Composing formal multilinear series -/ namespace formal_multilinear_series /-! In this paragraph, we define the composition of formal multilinear series, by summing over all possible compositions of `n`. -/ /-- Given a formal multilinear series `p`, a composition `c` of `n` and the index `i` of a block of `c`, we may define a function on `fin n → E` by picking the variables in the `i`-th block of `n`, and applying the corresponding coefficient of `p` to these variables. This function is called `p.apply_composition c v i` for `v : fin n → E` and `i : fin c.length`. -/ def apply_composition (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) : (fin n → E) → (fin (c.length) → F) := λ v i, p (c.blocks_fun i) (v ∘ (c.embedding i)) lemma apply_composition_ones (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : p.apply_composition (composition.ones n) = λ v i, p 1 (λ _, v (fin.cast_le (composition.length_le _) i)) := begin funext v i, apply p.congr (composition.ones_blocks_fun _ _), intros j hjn hj1, obtain rfl : j = 0, { linarith }, refine congr_arg v _, rw [fin.ext_iff, fin.coe_cast_le, composition.ones_embedding, fin.coe_mk], end lemma apply_composition_single (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (hn : 0 < n) (v : fin n → E) : p.apply_composition (composition.single n hn) v = λ j, p n v := begin ext j, refine p.congr (by simp) (λ i hi1 hi2, _), dsimp, congr' 1, convert composition.single_embedding hn ⟨i, hi2⟩, cases j, have : j_val = 0 := le_bot_iff.1 (nat.lt_succ_iff.1 j_property), unfold_coes, congr; try { assumption <|> simp }, end @[simp] lemma remove_zero_apply_composition (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) : p.remove_zero.apply_composition c = p.apply_composition c := begin ext v i, simp [apply_composition, zero_lt_one.trans_le (c.one_le_blocks_fun i), remove_zero_of_pos], end /-- Technical lemma stating how `p.apply_composition` commutes with updating variables. This will be the key point to show that functions constructed from `apply_composition` retain multilinearity. -/ lemma apply_composition_update (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) (j : fin n) (v : fin n → E) (z : E) : p.apply_composition c (function.update v j z) = function.update (p.apply_composition c v) (c.index j) (p (c.blocks_fun (c.index j)) (function.update (v ∘ (c.embedding (c.index j))) (c.inv_embedding j) z)) := begin ext k, by_cases h : k = c.index j, { rw h, let r : fin (c.blocks_fun (c.index j)) → fin n := c.embedding (c.index j), simp only [function.update_same], change p (c.blocks_fun (c.index j)) ((function.update v j z) ∘ r) = _, let j' := c.inv_embedding j, suffices B : (function.update v j z) ∘ r = function.update (v ∘ r) j' z, by rw B, suffices C : (function.update v (r j') z) ∘ r = function.update (v ∘ r) j' z, by { convert C, exact (c.embedding_comp_inv j).symm }, exact function.update_comp_eq_of_injective _ (c.embedding _).injective _ _ }, { simp only [h, function.update_eq_self, function.update_noteq, ne.def, not_false_iff], let r : fin (c.blocks_fun k) → fin n := c.embedding k, change p (c.blocks_fun k) ((function.update v j z) ∘ r) = p (c.blocks_fun k) (v ∘ r), suffices B : (function.update v j z) ∘ r = v ∘ r, by rw B, apply function.update_comp_eq_of_not_mem_range, rwa c.mem_range_embedding_iff' } end @[simp] lemma comp_continuous_linear_map_apply_composition {n : ℕ} (p : formal_multilinear_series 𝕜 F G) (f : E →L[𝕜] F) (c : composition n) (v : fin n → E) : (p.comp_continuous_linear_map f).apply_composition c v = p.apply_composition c (f ∘ v) := by simp [apply_composition] end formal_multilinear_series namespace continuous_multilinear_map open formal_multilinear_series /-- Given a formal multilinear series `p`, a composition `c` of `n` and a continuous multilinear map `f` in `c.length` variables, one may form a multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `f` to the resulting vector. It is called `f.comp_along_composition_aux p c`. This function admits a version as a continuous multilinear map, called `f.comp_along_composition p c` below. -/ def comp_along_composition_aux {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) : multilinear_map 𝕜 (λ i : fin n, E) G := { to_fun := λ v, f (p.apply_composition c v), map_add' := λ v i x y, by simp only [apply_composition_update, continuous_multilinear_map.map_add], map_smul' := λ v i c x, by simp only [apply_composition_update, continuous_multilinear_map.map_smul] } /-- The norm of `f.comp_along_composition_aux p c` is controlled by the product of the norms of the relevant bits of `f` and `p`. -/ lemma comp_along_composition_aux_bound {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) (v : fin n → E) : ∥f.comp_along_composition_aux p c v∥ ≤ ∥f∥ * (∏ i, ∥p (c.blocks_fun i)∥) * (∏ i : fin n, ∥v i∥) := calc ∥f.comp_along_composition_aux p c v∥ = ∥f (p.apply_composition c v)∥ : rfl ... ≤ ∥f∥ * ∏ i, ∥p.apply_composition c v i∥ : continuous_multilinear_map.le_op_norm _ _ ... ≤ ∥f∥ * ∏ i, ∥p (c.blocks_fun i)∥ * ∏ j : fin (c.blocks_fun i), ∥(v ∘ (c.embedding i)) j∥ : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), refine finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, _), apply continuous_multilinear_map.le_op_norm, end ... = ∥f∥ * (∏ i, ∥p (c.blocks_fun i)∥) * ∏ i (j : fin (c.blocks_fun i)), ∥(v ∘ (c.embedding i)) j∥ : by rw [finset.prod_mul_distrib, mul_assoc] ... = ∥f∥ * (∏ i, ∥p (c.blocks_fun i)∥) * (∏ i : fin n, ∥v i∥) : by { rw [← c.blocks_fin_equiv.prod_comp, ← finset.univ_sigma_univ, finset.prod_sigma], congr } /-- Given a formal multilinear series `p`, a composition `c` of `n` and a continuous multilinear map `f` in `c.length` variables, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `f` to the resulting vector. It is called `f.comp_along_composition p c`. It is constructed from the analogous multilinear function `f.comp_along_composition_aux p c`, together with a norm control to get the continuity. -/ def comp_along_composition {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) : continuous_multilinear_map 𝕜 (λ i : fin n, E) G := (f.comp_along_composition_aux p c).mk_continuous _ (f.comp_along_composition_aux_bound p c) @[simp] lemma comp_along_composition_apply {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) (v : fin n → E) : (f.comp_along_composition p c) v = f (p.apply_composition c v) := rfl end continuous_multilinear_map namespace formal_multilinear_series /-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `q c.length` to the resulting vector. It is called `q.comp_along_composition p c`. It is constructed from the analogous multilinear function `q.comp_along_composition_aux p c`, together with a norm control to get the continuity. -/ def comp_along_composition {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : continuous_multilinear_map 𝕜 (λ i : fin n, E) G := (q c.length).comp_along_composition p c @[simp] lemma comp_along_composition_apply {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) (v : fin n → E) : (q.comp_along_composition p c) v = q c.length (p.apply_composition c v) := rfl /-- The norm of `q.comp_along_composition p c` is controlled by the product of the norms of the relevant bits of `q` and `p`. -/ lemma comp_along_composition_norm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : ∥q.comp_along_composition p c∥ ≤ ∥q c.length∥ * ∏ i, ∥p (c.blocks_fun i)∥ := multilinear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (finset.prod_nonneg (λ i hi, norm_nonneg _))) _ lemma comp_along_composition_nnnorm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : nnnorm (q.comp_along_composition p c) ≤ nnnorm (q c.length) * ∏ i, nnnorm (p (c.blocks_fun i)) := by { rw ← nnreal.coe_le_coe, push_cast, exact q.comp_along_composition_norm p c } /-- Formal composition of two formal multilinear series. The `n`-th coefficient in the composition is defined to be the sum of `q.comp_along_composition p c` over all compositions of `n`. In other words, this term (as a multilinear function applied to `v_0, ..., v_{n-1}`) is `∑'_{k} ∑'_{i₁ + ... + iₖ = n} pₖ (q_{i_1} (...), ..., q_{i_k} (...))`, where one puts all variables `v_0, ..., v_{n-1}` in increasing order in the dots. In general, the composition `q ∘ p` only makes sense when the constant coefficient of `p` vanishes. We give a general formula but which ignores the value of `p 0` instead. -/ protected def comp (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E G := λ n, ∑ c : composition n, q.comp_along_composition p c /-- The `0`-th coefficient of `q.comp p` is `q 0`. Since these maps are multilinear maps in zero variables, but on different spaces, we can not state this directly, so we state it when applied to arbitrary vectors (which have to be the zero vector). -/ lemma comp_coeff_zero (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) (v' : fin 0 → F) : (q.comp p) 0 v = q 0 v' := begin let c : composition 0 := composition.ones 0, dsimp [formal_multilinear_series.comp], have : {c} = (finset.univ : finset (composition 0)), { apply finset.eq_of_subset_of_card_le; simp [finset.card_univ, composition_card 0] }, rw [← this, finset.sum_singleton, comp_along_composition_apply], symmetry, congr' end @[simp] lemma comp_coeff_zero' (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) : (q.comp p) 0 v = q 0 (λ i, 0) := q.comp_coeff_zero p v _ /-- The `0`-th coefficient of `q.comp p` is `q 0`. When `p` goes from `E` to `E`, this can be expressed as a direct equality -/ lemma comp_coeff_zero'' (q : formal_multilinear_series 𝕜 E F) (p : formal_multilinear_series 𝕜 E E) : (q.comp p) 0 = q 0 := by { ext v, exact q.comp_coeff_zero p _ _ } /-- The first coefficient of a composition of formal multilinear series is the composition of the first coefficients seen as continuous linear maps. -/ lemma comp_coeff_one (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 1 → E) : (q.comp p) 1 v = q 1 (λ i, p 1 v) := begin have : {composition.ones 1} = (finset.univ : finset (composition 1)) := finset.eq_univ_of_card _ (by simp [composition_card]), simp only [formal_multilinear_series.comp, comp_along_composition_apply, ← this, finset.sum_singleton], refine q.congr (by simp) (λ i hi1 hi2, _), simp only [apply_composition_ones], exact p.congr rfl (λ j hj1 hj2, by congr) end lemma remove_zero_comp_of_pos (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (hn : 0 < n) : q.remove_zero.comp p n = q.comp p n := begin ext v, simp only [formal_multilinear_series.comp, comp_along_composition, continuous_multilinear_map.comp_along_composition_apply, continuous_multilinear_map.sum_apply], apply finset.sum_congr rfl (λ c hc, _), rw remove_zero_of_pos _ (c.length_pos_of_pos hn) end @[simp] lemma comp_remove_zero (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : q.comp p.remove_zero = q.comp p := by { ext n, simp [formal_multilinear_series.comp] } /-! ### The identity formal power series We will now define the identity power series, and show that it is a neutral element for left and right composition. -/ section variables (𝕜 E) /-- The identity formal multilinear series, with all coefficients equal to `0` except for `n = 1` where it is (the continuous multilinear version of) the identity. -/ def id : formal_multilinear_series 𝕜 E E | 0 := 0 | 1 := (continuous_multilinear_curry_fin1 𝕜 E E).symm (continuous_linear_map.id 𝕜 E) | _ := 0 /-- The first coefficient of `id 𝕜 E` is the identity. -/ @[simp] lemma id_apply_one (v : fin 1 → E) : (formal_multilinear_series.id 𝕜 E) 1 v = v 0 := rfl /-- The `n`th coefficient of `id 𝕜 E` is the identity when `n = 1`. We state this in a dependent way, as it will often appear in this form. -/ lemma id_apply_one' {n : ℕ} (h : n = 1) (v : fin n → E) : (id 𝕜 E) n v = v ⟨0, h.symm ▸ zero_lt_one⟩ := begin subst n, apply id_apply_one end /-- For `n ≠ 1`, the `n`-th coefficient of `id 𝕜 E` is zero, by definition. -/ @[simp] lemma id_apply_ne_one {n : ℕ} (h : n ≠ 1) : (formal_multilinear_series.id 𝕜 E) n = 0 := by { cases n, { refl }, cases n, { contradiction }, refl } end @[simp] theorem comp_id (p : formal_multilinear_series 𝕜 E F) : p.comp (id 𝕜 E) = p := begin ext1 n, dsimp [formal_multilinear_series.comp], rw finset.sum_eq_single (composition.ones n), show comp_along_composition p (id 𝕜 E) (composition.ones n) = p n, { ext v, rw comp_along_composition_apply, apply p.congr (composition.ones_length n), intros, rw apply_composition_ones, refine congr_arg v _, rw [fin.ext_iff, fin.coe_cast_le, fin.coe_mk, fin.coe_mk], }, show ∀ (b : composition n), b ∈ finset.univ → b ≠ composition.ones n → comp_along_composition p (id 𝕜 E) b = 0, { assume b _ hb, obtain ⟨k, hk, lt_k⟩ : ∃ (k : ℕ) (H : k ∈ composition.blocks b), 1 < k := composition.ne_ones_iff.1 hb, obtain ⟨i, i_lt, hi⟩ : ∃ (i : ℕ) (h : i < b.blocks.length), b.blocks.nth_le i h = k := nth_le_of_mem hk, let j : fin b.length := ⟨i, b.blocks_length ▸ i_lt⟩, have A : 1 < b.blocks_fun j := by convert lt_k, ext v, rw [comp_along_composition_apply, continuous_multilinear_map.zero_apply], apply continuous_multilinear_map.map_coord_zero _ j, dsimp [apply_composition], rw id_apply_ne_one _ _ (ne_of_gt A), refl }, { simp } end @[simp] theorem id_comp (p : formal_multilinear_series 𝕜 E F) (h : p 0 = 0) : (id 𝕜 F).comp p = p := begin ext1 n, by_cases hn : n = 0, { rw [hn, h], ext v, rw [comp_coeff_zero', id_apply_ne_one _ _ zero_ne_one], refl }, { dsimp [formal_multilinear_series.comp], have n_pos : 0 < n := bot_lt_iff_ne_bot.mpr hn, rw finset.sum_eq_single (composition.single n n_pos), show comp_along_composition (id 𝕜 F) p (composition.single n n_pos) = p n, { ext v, rw [comp_along_composition_apply, id_apply_one' _ _ (composition.single_length n_pos)], dsimp [apply_composition], refine p.congr rfl (λ i him hin, congr_arg v $ _), ext, simp }, show ∀ (b : composition n), b ∈ finset.univ → b ≠ composition.single n n_pos → comp_along_composition (id 𝕜 F) p b = 0, { assume b _ hb, have A : b.length ≠ 1, by simpa [composition.eq_single_iff_length] using hb, ext v, rw [comp_along_composition_apply, id_apply_ne_one _ _ A], refl }, { simp } } end /-! ### Summability properties of the composition of formal power series-/ section -- this speeds up the proof below a lot, related to leanprover-community/lean#521 local attribute [-instance] unique.subsingleton /-- If two formal multilinear series have positive radius of convergence, then the terms appearing in the definition of their composition are also summable (when multiplied by a suitable positive geometric term). -/ theorem comp_summable_nnreal (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (hq : 0 < q.radius) (hp : 0 < p.radius) : ∃ r > (0 : ℝ≥0), summable (λ i : Σ n, composition n, nnnorm (q.comp_along_composition p i.2) * r ^ i.1) := begin /- This follows from the fact that the growth rate of `∥qₙ∥` and `∥pₙ∥` is at most geometric, giving a geometric bound on each `∥q.comp_along_composition p op∥`, together with the fact that there are `2^(n-1)` compositions of `n`, giving at most a geometric loss. -/ rcases ennreal.lt_iff_exists_nnreal_btwn.1 (lt_min ennreal.zero_lt_one hq) with ⟨rq, rq_pos, hrq⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 (lt_min ennreal.zero_lt_one hp) with ⟨rp, rp_pos, hrp⟩, simp only [lt_min_iff, ennreal.coe_lt_one_iff, ennreal.coe_pos] at hrp hrq rp_pos rq_pos, obtain ⟨Cq, hCq0, hCq⟩ : ∃ Cq > 0, ∀ n, nnnorm (q n) * rq^n ≤ Cq := q.nnnorm_mul_pow_le_of_lt_radius hrq.2, obtain ⟨Cp, hCp1, hCp⟩ : ∃ Cp ≥ 1, ∀ n, nnnorm (p n) * rp^n ≤ Cp, { rcases p.nnnorm_mul_pow_le_of_lt_radius hrp.2 with ⟨Cp, -, hCp⟩, exact ⟨max Cp 1, le_max_right _ _, λ n, (hCp n).trans (le_max_left _ _)⟩ }, let r0 : ℝ≥0 := (4 * Cp)⁻¹, have r0_pos : 0 < r0 := nnreal.inv_pos.2 (mul_pos zero_lt_four (zero_lt_one.trans_le hCp1)), set r : ℝ≥0 := rp * rq * r0, have r_pos : 0 < r := mul_pos (mul_pos rp_pos rq_pos) r0_pos, have I : ∀ (i : Σ (n : ℕ), composition n), nnnorm (q.comp_along_composition p i.2) * r ^ i.1 ≤ Cq / 4 ^ i.1, { rintros ⟨n, c⟩, have A, calc nnnorm (q c.length) * rq ^ n ≤ nnnorm (q c.length)* rq ^ c.length : mul_le_mul' le_rfl (pow_le_pow_of_le_one rq.2 hrq.1.le c.length_le) ... ≤ Cq : hCq _, have B, calc ((∏ i, nnnorm (p (c.blocks_fun i))) * rp ^ n) = ∏ i, nnnorm (p (c.blocks_fun i)) * rp ^ c.blocks_fun i : by simp only [finset.prod_mul_distrib, finset.prod_pow_eq_pow_sum, c.sum_blocks_fun] ... ≤ ∏ i : fin c.length, Cp : finset.prod_le_prod' (λ i _, hCp _) ... = Cp ^ c.length : by simp ... ≤ Cp ^ n : pow_le_pow hCp1 c.length_le, calc nnnorm (q.comp_along_composition p c) * r ^ n ≤ (nnnorm (q c.length) * ∏ i, nnnorm (p (c.blocks_fun i))) * r ^ n : mul_le_mul' (q.comp_along_composition_nnnorm p c) le_rfl ... = (nnnorm (q c.length) * rq ^ n) * ((∏ i, nnnorm (p (c.blocks_fun i))) * rp ^ n) * r0 ^ n : by { simp only [r, mul_pow], ac_refl } ... ≤ Cq * Cp ^ n * r0 ^ n : mul_le_mul' (mul_le_mul' A B) le_rfl ... = Cq / 4 ^ n : begin simp only [r0], field_simp [mul_pow, (zero_lt_one.trans_le hCp1).ne'], ac_refl end }, refine ⟨r, r_pos, nnreal.summable_of_le I _⟩, simp_rw div_eq_mul_inv, refine summable.mul_left _ _, have : ∀ n : ℕ, has_sum (λ c : composition n, (4 ^ n : ℝ≥0)⁻¹) (2 ^ (n - 1) / 4 ^ n), { intro n, convert has_sum_fintype (λ c : composition n, (4 ^ n : ℝ≥0)⁻¹), simp [finset.card_univ, composition_card, div_eq_mul_inv] }, refine nnreal.summable_sigma.2 ⟨λ n, (this n).summable, (nnreal.summable_nat_add_iff 1).1 _⟩, convert (nnreal.summable_geometric (nnreal.div_lt_one_of_lt one_lt_two)).mul_left (1 / 4), ext1 n, rw [(this _).tsum_eq, add_tsub_cancel_right], field_simp [← mul_assoc, pow_succ', mul_pow, show (4 : ℝ≥0) = 2 * 2, from (two_mul 2).symm, mul_right_comm] end end /-- Bounding below the radius of the composition of two formal multilinear series assuming summability over all compositions. -/ theorem le_comp_radius_of_summable (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (r : ℝ≥0) (hr : summable (λ i : (Σ n, composition n), nnnorm (q.comp_along_composition p i.2) * r ^ i.1)) : (r : ℝ≥0∞) ≤ (q.comp p).radius := begin refine le_radius_of_bound_nnreal _ (∑' i : (Σ n, composition n), nnnorm (comp_along_composition q p i.snd) * r ^ i.fst) (λ n, _), calc nnnorm (formal_multilinear_series.comp q p n) * r ^ n ≤ ∑' (c : composition n), nnnorm (comp_along_composition q p c) * r ^ n : begin rw [tsum_fintype, ← finset.sum_mul], exact mul_le_mul' (nnnorm_sum_le _ _) le_rfl end ... ≤ ∑' (i : Σ (n : ℕ), composition n), nnnorm (comp_along_composition q p i.snd) * r ^ i.fst : nnreal.tsum_comp_le_tsum_of_inj hr sigma_mk_injective end /-! ### Composing analytic functions Now, we will prove that the composition of the partial sums of `q` and `p` up to order `N` is given by a sum over some large subset of `Σ n, composition n` of `q.comp_along_composition p`, to deduce that the series for `q.comp p` indeed converges to `g ∘ f` when `q` is a power series for `g` and `p` is a power series for `f`. This proof is a big reindexing argument of a sum. Since it is a bit involved, we define first the source of the change of variables (`comp_partial_source`), its target (`comp_partial_target`) and the change of variables itself (`comp_change_of_variables`) before giving the main statement in `comp_partial_sum`. -/ /-- Source set in the change of variables to compute the composition of partial sums of formal power series. See also `comp_partial_sum`. -/ def comp_partial_sum_source (m M N : ℕ) : finset (Σ n, (fin n) → ℕ) := finset.sigma (finset.Ico m M) (λ (n : ℕ), fintype.pi_finset (λ (i : fin n), finset.Ico 1 N) : _) @[simp] lemma mem_comp_partial_sum_source_iff (m M N : ℕ) (i : Σ n, (fin n) → ℕ) : i ∈ comp_partial_sum_source m M N ↔ (m ≤ i.1 ∧ i.1 < M) ∧ ∀ (a : fin i.1), 1 ≤ i.2 a ∧ i.2 a < N := by simp only [comp_partial_sum_source, finset.mem_Ico, fintype.mem_pi_finset, finset.mem_sigma, iff_self] /-- Change of variables appearing to compute the composition of partial sums of formal power series -/ def comp_change_of_variables (m M N : ℕ) (i : Σ n, (fin n) → ℕ) (hi : i ∈ comp_partial_sum_source m M N) : (Σ n, composition n) := begin rcases i with ⟨n, f⟩, rw mem_comp_partial_sum_source_iff at hi, refine ⟨∑ j, f j, of_fn (λ a, f a), λ i hi', _, by simp [sum_of_fn]⟩, obtain ⟨j, rfl⟩ : ∃ (j : fin n), f j = i, by rwa [mem_of_fn, set.mem_range] at hi', exact (hi.2 j).1 end @[simp] lemma comp_change_of_variables_length (m M N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source m M N) : composition.length (comp_change_of_variables m M N i hi).2 = i.1 := begin rcases i with ⟨k, blocks_fun⟩, dsimp [comp_change_of_variables], simp only [composition.length, map_of_fn, length_of_fn] end lemma comp_change_of_variables_blocks_fun (m M N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source m M N) (j : fin i.1) : (comp_change_of_variables m M N i hi).2.blocks_fun ⟨j, (comp_change_of_variables_length m M N hi).symm ▸ j.2⟩ = i.2 j := begin rcases i with ⟨n, f⟩, dsimp [composition.blocks_fun, composition.blocks, comp_change_of_variables], simp only [map_of_fn, nth_le_of_fn', function.comp_app], apply congr_arg, exact fin.eta _ _ end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a set. -/ def comp_partial_sum_target_set (m M N : ℕ) : set (Σ n, composition n) := {i | (m ≤ i.2.length) ∧ (i.2.length < M) ∧ (∀ (j : fin i.2.length), i.2.blocks_fun j < N)} lemma comp_partial_sum_target_subset_image_comp_partial_sum_source (m M N : ℕ) (i : Σ n, composition n) (hi : i ∈ comp_partial_sum_target_set m M N) : ∃ j (hj : j ∈ comp_partial_sum_source m M N), i = comp_change_of_variables m M N j hj := begin rcases i with ⟨n, c⟩, refine ⟨⟨c.length, c.blocks_fun⟩, _, _⟩, { simp only [comp_partial_sum_target_set, set.mem_set_of_eq] at hi, simp only [mem_comp_partial_sum_source_iff, hi.left, hi.right, true_and, and_true], exact λ a, c.one_le_blocks' _ }, { dsimp [comp_change_of_variables], rw composition.sigma_eq_iff_blocks_eq, simp only [composition.blocks_fun, composition.blocks, subtype.coe_eta, nth_le_map'], conv_lhs { rw ← of_fn_nth_le c.blocks } } end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a finset. See also `comp_partial_sum`. -/ def comp_partial_sum_target (m M N : ℕ) : finset (Σ n, composition n) := set.finite.to_finset $ ((finset.finite_to_set _).dependent_image _).subset $ comp_partial_sum_target_subset_image_comp_partial_sum_source m M N @[simp] lemma mem_comp_partial_sum_target_iff {m M N : ℕ} {a : Σ n, composition n} : a ∈ comp_partial_sum_target m M N ↔ m ≤ a.2.length ∧ a.2.length < M ∧ (∀ (j : fin a.2.length), a.2.blocks_fun j < N) := by simp [comp_partial_sum_target, comp_partial_sum_target_set] /-- `comp_change_of_variables m M N` is a bijection between `comp_partial_sum_source m M N` and `comp_partial_sum_target m M N`, yielding equal sums for functions that correspond to each other under the bijection. As `comp_change_of_variables m M N` is a dependent function, stating that it is a bijection is not directly possible, but the consequence on sums can be stated more easily. -/ lemma comp_change_of_variables_sum {α : Type*} [add_comm_monoid α] (m M N : ℕ) (f : (Σ (n : ℕ), fin n → ℕ) → α) (g : (Σ n, composition n) → α) (h : ∀ e (he : e ∈ comp_partial_sum_source m M N), f e = g (comp_change_of_variables m M N e he)) : ∑ e in comp_partial_sum_source m M N, f e = ∑ e in comp_partial_sum_target m M N, g e := begin apply finset.sum_bij (comp_change_of_variables m M N), -- We should show that the correspondance we have set up is indeed a bijection -- between the index sets of the two sums. -- 1 - show that the image belongs to `comp_partial_sum_target m N N` { rintros ⟨k, blocks_fun⟩ H, rw mem_comp_partial_sum_source_iff at H, simp only [mem_comp_partial_sum_target_iff, composition.length, composition.blocks, H.left, map_of_fn, length_of_fn, true_and, comp_change_of_variables], assume j, simp only [composition.blocks_fun, (H.right _).right, nth_le_of_fn'] }, -- 2 - show that the composition gives the `comp_along_composition` application { rintros ⟨k, blocks_fun⟩ H, rw h }, -- 3 - show that the map is injective { rintros ⟨k, blocks_fun⟩ ⟨k', blocks_fun'⟩ H H' heq, obtain rfl : k = k', { have := (comp_change_of_variables_length m M N H).symm, rwa [heq, comp_change_of_variables_length] at this, }, congr, funext i, calc blocks_fun i = (comp_change_of_variables m M N _ H).2.blocks_fun _ : (comp_change_of_variables_blocks_fun m M N H i).symm ... = (comp_change_of_variables m M N _ H').2.blocks_fun _ : begin apply composition.blocks_fun_congr; try { rw heq }, refl end ... = blocks_fun' i : comp_change_of_variables_blocks_fun m M N H' i }, -- 4 - show that the map is surjective { assume i hi, apply comp_partial_sum_target_subset_image_comp_partial_sum_source m M N i, simpa [comp_partial_sum_target] using hi } end /-- The auxiliary set corresponding to the composition of partial sums asymptotically contains all possible compositions. -/ lemma comp_partial_sum_target_tendsto_at_top : tendsto (λ N, comp_partial_sum_target 0 N N) at_top at_top := begin apply monotone.tendsto_at_top_finset, { assume m n hmn a ha, have : ∀ i, i < m → i < n := λ i hi, lt_of_lt_of_le hi hmn, tidy }, { rintros ⟨n, c⟩, simp only [mem_comp_partial_sum_target_iff], obtain ⟨n, hn⟩ : bdd_above ↑(finset.univ.image (λ (i : fin c.length), c.blocks_fun i)) := finset.bdd_above _, refine ⟨max n c.length + 1, bot_le, lt_of_le_of_lt (le_max_right n c.length) (lt_add_one _), λ j, lt_of_le_of_lt (le_trans _ (le_max_left _ _)) (lt_add_one _)⟩, apply hn, simp only [finset.mem_image_of_mem, finset.mem_coe, finset.mem_univ] } end /-- Composing the partial sums of two multilinear series coincides with the sum over all compositions in `comp_partial_sum_target 0 N N`. This is precisely the motivation for the definition of `comp_partial_sum_target`. -/ lemma comp_partial_sum (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (N : ℕ) (z : E) : q.partial_sum N (∑ i in finset.Ico 1 N, p i (λ j, z)) = ∑ i in comp_partial_sum_target 0 N N, q.comp_along_composition p i.2 (λ j, z) := begin -- we expand the composition, using the multilinearity of `q` to expand along each coordinate. suffices H : ∑ n in finset.range N, ∑ r in fintype.pi_finset (λ (i : fin n), finset.Ico 1 N), q n (λ (i : fin n), p (r i) (λ j, z)) = ∑ i in comp_partial_sum_target 0 N N, q.comp_along_composition p i.2 (λ j, z), by simpa only [formal_multilinear_series.partial_sum, continuous_multilinear_map.map_sum_finset] using H, -- rewrite the first sum as a big sum over a sigma type, in the finset -- `comp_partial_sum_target 0 N N` rw [finset.range_eq_Ico, finset.sum_sigma'], -- use `comp_change_of_variables_sum`, saying that this change of variables respects sums apply comp_change_of_variables_sum 0 N N, rintros ⟨k, blocks_fun⟩ H, apply congr _ (comp_change_of_variables_length 0 N N H).symm, intros, rw ← comp_change_of_variables_blocks_fun 0 N N H, refl end end formal_multilinear_series open formal_multilinear_series /-- If two functions `g` and `f` have power series `q` and `p` respectively at `f x` and `x`, then `g ∘ f` admits the power series `q.comp p` at `x`. -/ theorem has_fpower_series_at.comp {g : F → G} {f : E → F} {q : formal_multilinear_series 𝕜 F G} {p : formal_multilinear_series 𝕜 E F} {x : E} (hg : has_fpower_series_at g q (f x)) (hf : has_fpower_series_at f p x) : has_fpower_series_at (g ∘ f) (q.comp p) x := begin /- Consider `rf` and `rg` such that `f` and `g` have power series expansion on the disks of radius `rf` and `rg`. -/ rcases hg with ⟨rg, Hg⟩, rcases hf with ⟨rf, Hf⟩, /- The terms defining `q.comp p` are geometrically summable in a disk of some radius `r`. -/ rcases q.comp_summable_nnreal p Hg.radius_pos Hf.radius_pos with ⟨r, r_pos : 0 < r, hr⟩, /- We will consider `y` which is smaller than `r` and `rf`, and also small enough that `f (x + y)` is close enough to `f x` to be in the disk where `g` is well behaved. Let `min (r, rf, δ)` be this new radius.-/ have : continuous_at f x := Hf.analytic_at.continuous_at, obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ℝ≥0∞) (H : 0 < δ), ∀ {z : E}, z ∈ emetric.ball x δ → f z ∈ emetric.ball (f x) rg, { have : emetric.ball (f x) rg ∈ 𝓝 (f x) := emetric.ball_mem_nhds _ Hg.r_pos, rcases emetric.mem_nhds_iff.1 (Hf.analytic_at.continuous_at this) with ⟨δ, δpos, Hδ⟩, exact ⟨δ, δpos, λ z hz, Hδ hz⟩ }, let rf' := min rf δ, have min_pos : 0 < min rf' r, by simp only [r_pos, Hf.r_pos, δpos, lt_min_iff, ennreal.coe_pos, and_self], /- We will show that `g ∘ f` admits the power series `q.comp p` in the disk of radius `min (r, rf', δ)`. -/ refine ⟨min rf' r, _⟩, refine ⟨le_trans (min_le_right rf' r) (formal_multilinear_series.le_comp_radius_of_summable q p r hr), min_pos, λ y hy, _⟩, /- Let `y` satisfy `∥y∥ < min (r, rf', δ)`. We want to show that `g (f (x + y))` is the sum of `q.comp p` applied to `y`. -/ -- First, check that `y` is small enough so that estimates for `f` and `g` apply. have y_mem : y ∈ emetric.ball (0 : E) rf := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_left _ _))) hy, have fy_mem : f (x + y) ∈ emetric.ball (f x) rg, { apply hδ, have : y ∈ emetric.ball (0 : E) δ := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_right _ _))) hy, simpa [edist_eq_coe_nnnorm_sub, edist_eq_coe_nnnorm] }, /- Now the proof starts. To show that the sum of `q.comp p` at `y` is `g (f (x + y))`, we will write `q.comp p` applied to `y` as a big sum over all compositions. Since the sum is summable, to get its convergence it suffices to get the convergence along some increasing sequence of sets. We will use the sequence of sets `comp_partial_sum_target 0 n n`, along which the sum is exactly the composition of the partial sums of `q` and `p`, by design. To show that it converges to `g (f (x + y))`, pointwise convergence would not be enough, but we have uniform convergence to save the day. -/ -- First step: the partial sum of `p` converges to `f (x + y)`. have A : tendsto (λ n, ∑ a in finset.Ico 1 n, p a (λ b, y)) at_top (𝓝 (f (x + y) - f x)), { have L : ∀ᶠ n in at_top, ∑ a in finset.range n, p a (λ b, y) - f x = ∑ a in finset.Ico 1 n, p a (λ b, y), { rw eventually_at_top, refine ⟨1, λ n hn, _⟩, symmetry, rw [eq_sub_iff_add_eq', finset.range_eq_Ico, ← Hf.coeff_zero (λi, y), finset.sum_eq_sum_Ico_succ_bot hn] }, have : tendsto (λ n, ∑ a in finset.range n, p a (λ b, y) - f x) at_top (𝓝 (f (x + y) - f x)) := (Hf.has_sum y_mem).tendsto_sum_nat.sub tendsto_const_nhds, exact tendsto.congr' L this }, -- Second step: the composition of the partial sums of `q` and `p` converges to `g (f (x + y))`. have B : tendsto (λ n, q.partial_sum n (∑ a in finset.Ico 1 n, p a (λ b, y))) at_top (𝓝 (g (f (x + y)))), { -- we use the fact that the partial sums of `q` converge locally uniformly to `g`, and that -- composition passes to the limit under locally uniform convergence. have B₁ : continuous_at (λ (z : F), g (f x + z)) (f (x + y) - f x), { refine continuous_at.comp _ (continuous_const.add continuous_id).continuous_at, simp only [add_sub_cancel'_right, id.def], exact Hg.continuous_on.continuous_at (is_open.mem_nhds (emetric.is_open_ball) fy_mem) }, have B₂ : f (x + y) - f x ∈ emetric.ball (0 : F) rg, by simpa [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] using fy_mem, rw [← emetric.is_open_ball.nhds_within_eq B₂] at A, convert Hg.tendsto_locally_uniformly_on.tendsto_comp B₁.continuous_within_at B₂ A, simp only [add_sub_cancel'_right] }, -- Third step: the sum over all compositions in `comp_partial_sum_target 0 n n` converges to -- `g (f (x + y))`. As this sum is exactly the composition of the partial sum, this is a direct -- consequence of the second step have C : tendsto (λ n, ∑ i in comp_partial_sum_target 0 n n, q.comp_along_composition p i.2 (λ j, y)) at_top (𝓝 (g (f (x + y)))), by simpa [comp_partial_sum] using B, -- Fourth step: the sum over all compositions is `g (f (x + y))`. This follows from the -- convergence along a subsequence proved in the third step, and the fact that the sum is Cauchy -- thanks to the summability properties. have D : has_sum (λ i : (Σ n, composition n), q.comp_along_composition p i.2 (λ j, y)) (g (f (x + y))), { have cau : cauchy_seq (λ (s : finset (Σ n, composition n)), ∑ i in s, q.comp_along_composition p i.2 (λ j, y)), { apply cauchy_seq_finset_of_norm_bounded _ (nnreal.summable_coe.2 hr) _, simp only [coe_nnnorm, nnreal.coe_mul, nnreal.coe_pow], rintros ⟨n, c⟩, calc ∥(comp_along_composition q p c) (λ (j : fin n), y)∥ ≤ ∥comp_along_composition q p c∥ * ∏ j : fin n, ∥y∥ : by apply continuous_multilinear_map.le_op_norm ... ≤ ∥comp_along_composition q p c∥ * (r : ℝ) ^ n : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), rw [finset.prod_const, finset.card_fin], apply pow_le_pow_of_le_left (norm_nonneg _), rw [emetric.mem_ball, edist_eq_coe_nnnorm] at hy, have := (le_trans (le_of_lt hy) (min_le_right _ _)), rwa [ennreal.coe_le_coe, ← nnreal.coe_le_coe, coe_nnnorm] at this end }, exact tendsto_nhds_of_cauchy_seq_of_subseq cau comp_partial_sum_target_tendsto_at_top C }, -- Fifth step: the sum over `n` of `q.comp p n` can be expressed as a particular resummation of -- the sum over all compositions, by grouping together the compositions of the same -- integer `n`. The convergence of the whole sum therefore implies the converence of the sum -- of `q.comp p n` have E : has_sum (λ n, (q.comp p) n (λ j, y)) (g (f (x + y))), { apply D.sigma, assume n, dsimp [formal_multilinear_series.comp], convert has_sum_fintype _, simp only [continuous_multilinear_map.sum_apply], refl }, exact E end /-- If two functions `g` and `f` are analytic respectively at `f x` and `x`, then `g ∘ f` is analytic at `x`. -/ theorem analytic_at.comp {g : F → G} {f : E → F} {x : E} (hg : analytic_at 𝕜 g (f x)) (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (g ∘ f) x := let ⟨q, hq⟩ := hg, ⟨p, hp⟩ := hf in (hq.comp hp).analytic_at /-! ### Associativity of the composition of formal multilinear series In this paragraph, we prove the associativity of the composition of formal power series. By definition, ``` (r.comp q).comp p n v = ∑_{i₁ + ... + iₖ = n} (r.comp q)ₖ (p_{i₁} (v₀, ..., v_{i₁ -1}), p_{i₂} (...), ..., p_{iₖ}(...)) = ∑_{a : composition n} (r.comp q) a.length (apply_composition p a v) ``` decomposing `r.comp q` in the same way, we get ``` (r.comp q).comp p n v = ∑_{a : composition n} ∑_{b : composition a.length} r b.length (apply_composition q b (apply_composition p a v)) ``` On the other hand, ``` r.comp (q.comp p) n v = ∑_{c : composition n} r c.length (apply_composition (q.comp p) c v) ``` Here, `apply_composition (q.comp p) c v` is a vector of length `c.length`, whose `i`-th term is given by `(q.comp p) (c.blocks_fun i) (v_l, v_{l+1}, ..., v_{m-1})` where `{l, ..., m-1}` is the `i`-th block in the composition `c`, of length `c.blocks_fun i` by definition. To compute this term, we expand it as `∑_{dᵢ : composition (c.blocks_fun i)} q dᵢ.length (apply_composition p dᵢ v')`, where `v' = (v_l, v_{l+1}, ..., v_{m-1})`. Therefore, we get ``` r.comp (q.comp p) n v = ∑_{c : composition n} ∑_{d₀ : composition (c.blocks_fun 0), ..., d_{c.length - 1} : composition (c.blocks_fun (c.length - 1))} r c.length (λ i, q dᵢ.length (apply_composition p dᵢ v'ᵢ)) ``` To show that these terms coincide, we need to explain how to reindex the sums to put them in bijection (and then the terms we are summing will correspond to each other). Suppose we have a composition `a` of `n`, and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. Conversely, if one starts from `c` and the `dᵢ`s, one can concatenate the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. An example might be enlightening. Suppose `a = [2, 2, 3, 4, 2]`. It is a composition of length 5 of 13. The content of the blocks may be represented as `0011222333344`. Now take `b = [2, 3]` as a composition of `a.length = 5`. It says that the first 2 blocks of `a` should be merged, and the last 3 blocks of `a` should be merged, giving a new composition of `13` made of two blocks of length `4` and `9`, i.e., `c = [4, 9]`. But one can also remember that the new first block was initially made of two blocks of size `2`, so `d₀ = [2, 2]`, and the new second block was initially made of three blocks of size `3`, `4` and `2`, so `d₁ = [3, 4, 2]`. This equivalence is called `composition.sigma_equiv_sigma_pi n` below. We start with preliminary results on compositions, of a very specialized nature, then define the equivalence `composition.sigma_equiv_sigma_pi n`, and we deduce finally the associativity of composition of formal multilinear series in `formal_multilinear_series.comp_assoc`. -/ namespace composition variable {n : ℕ} /-- Rewriting equality in the dependent type `Σ (a : composition n), composition a.length)` in non-dependent terms with lists, requiring that the blocks coincide. -/ lemma sigma_composition_eq_iff (i j : Σ (a : composition n), composition a.length) : i = j ↔ i.1.blocks = j.1.blocks ∧ i.2.blocks = j.2.blocks := begin refine ⟨by rintro rfl; exact ⟨rfl, rfl⟩, _⟩, rcases i with ⟨a, b⟩, rcases j with ⟨a', b'⟩, rintros ⟨h, h'⟩, have H : a = a', by { ext1, exact h }, induction H, congr, ext1, exact h' end /-- Rewriting equality in the dependent type `Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)` in non-dependent terms with lists, requiring that the lists of blocks coincide. -/ lemma sigma_pi_composition_eq_iff (u v : Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) : u = v ↔ of_fn (λ i, (u.2 i).blocks) = of_fn (λ i, (v.2 i).blocks) := begin refine ⟨λ H, by rw H, λ H, _⟩, rcases u with ⟨a, b⟩, rcases v with ⟨a', b'⟩, dsimp at H, have h : a = a', { ext1, have : map list.sum (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) = map list.sum (of_fn (λ (i : fin (composition.length a')), (b' i).blocks)), by rw H, simp only [map_of_fn] at this, change of_fn (λ (i : fin (composition.length a)), (b i).blocks.sum) = of_fn (λ (i : fin (composition.length a')), (b' i).blocks.sum) at this, simpa [composition.blocks_sum, composition.of_fn_blocks_fun] using this }, induction h, simp only [true_and, eq_self_iff_true, heq_iff_eq], ext i : 2, have : nth_le (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) i (by simp [i.is_lt]) = nth_le (of_fn (λ (i : fin (composition.length a)), (b' i).blocks)) i (by simp [i.is_lt]) := nth_le_of_eq H _, rwa [nth_le_of_fn, nth_le_of_fn] at this end /-- When `a` is a composition of `n` and `b` is a composition of `a.length`, `a.gather b` is the composition of `n` obtained by gathering all the blocks of `a` corresponding to a block of `b`. For instance, if `a = [6, 5, 3, 5, 2]` and `b = [2, 3]`, one should gather together the first two blocks of `a` and its last three blocks, giving `a.gather b = [11, 10]`. -/ def gather (a : composition n) (b : composition a.length) : composition n := { blocks := (a.blocks.split_wrt_composition b).map sum, blocks_pos := begin rw forall_mem_map_iff, intros j hj, suffices H : ∀ i ∈ j, 1 ≤ i, from calc 0 < j.length : length_pos_of_mem_split_wrt_composition hj ... ≤ j.sum : length_le_sum_of_one_le _ H, intros i hi, apply a.one_le_blocks, rw ← a.blocks.join_split_wrt_composition b, exact mem_join_of_mem hj hi, end, blocks_sum := by { rw [← sum_join, join_split_wrt_composition, a.blocks_sum] } } lemma length_gather (a : composition n) (b : composition a.length) : length (a.gather b) = b.length := show (map list.sum (a.blocks.split_wrt_composition b)).length = b.blocks.length, by rw [length_map, length_split_wrt_composition] /-- An auxiliary function used in the definition of `sigma_equiv_sigma_pi` below, associating to two compositions `a` of `n` and `b` of `a.length`, and an index `i` bounded by the length of `a.gather b`, the subcomposition of `a` made of those blocks belonging to the `i`-th block of `a.gather b`. -/ def sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin (a.gather b).length) : composition ((a.gather b).blocks_fun i) := { blocks := nth_le (a.blocks.split_wrt_composition b) i (by { rw [length_split_wrt_composition, ← length_gather], exact i.2 }), blocks_pos := assume i hi, a.blocks_pos (by { rw ← a.blocks.join_split_wrt_composition b, exact mem_join_of_mem (nth_le_mem _ _ _) hi }), blocks_sum := by simp only [composition.blocks_fun, nth_le_map', composition.gather] } lemma length_sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin b.length) : composition.length (composition.sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ i.2⟩) = composition.blocks_fun b i := show list.length (nth_le (split_wrt_composition a.blocks b) i _) = blocks_fun b i, by { rw [nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)], refl } lemma blocks_fun_sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin b.length) (j : fin (blocks_fun b i)) : blocks_fun (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ i.2⟩) ⟨j, (length_sigma_composition_aux a b i).symm ▸ j.2⟩ = blocks_fun a (embedding b i j) := show nth_le (nth_le _ _ _) _ _ = nth_le a.blocks _ _, by { rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take'], refl } /-- Auxiliary lemma to prove that the composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Grouping together some blocks of `a` according to `b` as in `a.gather b`, one can compute the total size of the blocks of `a` up to an index `size_up_to b i + j` (where the `j` corresponds to a set of blocks of `a` that do not fill a whole block of `a.gather b`). The first part corresponds to a sum of blocks in `a.gather b`, and the second one to a sum of blocks in the next block of `sigma_composition_aux a b`. This is the content of this lemma. -/ lemma size_up_to_size_up_to_add (a : composition n) (b : composition a.length) {i j : ℕ} (hi : i < b.length) (hj : j < blocks_fun b ⟨i, hi⟩) : size_up_to a (size_up_to b i + j) = size_up_to (a.gather b) i + (size_up_to (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩) j) := begin induction j with j IHj, { show sum (take ((b.blocks.take i).sum) a.blocks) = sum (take i (map sum (split_wrt_composition a.blocks b))), induction i with i IH, { refl }, { have A : i < b.length := nat.lt_of_succ_lt hi, have B : i < list.length (map list.sum (split_wrt_composition a.blocks b)), by simp [A], have C : 0 < blocks_fun b ⟨i, A⟩ := composition.blocks_pos' _ _ _, rw [sum_take_succ _ _ B, ← IH A C], have : take (sum (take i b.blocks)) a.blocks = take (sum (take i b.blocks)) (take (sum (take (i+1) b.blocks)) a.blocks), { rw [take_take, min_eq_left], apply monotone_sum_take _ (nat.le_succ _) }, rw [this, nth_le_map', nth_le_split_wrt_composition, ← take_append_drop (sum (take i b.blocks)) ((take (sum (take (nat.succ i) b.blocks)) a.blocks)), sum_append], congr, rw [take_append_drop] } }, { have A : j < blocks_fun b ⟨i, hi⟩ := lt_trans (lt_add_one j) hj, have B : j < length (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩), by { convert A, rw [← length_sigma_composition_aux], refl }, have C : size_up_to b i + j < size_up_to b (i + 1), { simp only [size_up_to_succ b hi, add_lt_add_iff_left], exact A }, have D : size_up_to b i + j < length a := lt_of_lt_of_le C (b.size_up_to_le _), have : size_up_to b i + nat.succ j = (size_up_to b i + j).succ := rfl, rw [this, size_up_to_succ _ D, IHj A, size_up_to_succ _ B], simp only [sigma_composition_aux, add_assoc, add_left_inj, fin.coe_mk], rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take _ _ C] } end /-- Natural equivalence between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, that shows up as a change of variables in the proof that composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. The map `⟨a, b⟩ → ⟨c, (d₀, ..., d_{a.length - 1})⟩` is the direct map in the equiv. Conversely, if one starts from `c` and the `dᵢ`s, one can join the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. This is the inverse map of the equiv. -/ def sigma_equiv_sigma_pi (n : ℕ) : (Σ (a : composition n), composition a.length) ≃ (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) := { to_fun := λ i, ⟨i.1.gather i.2, i.1.sigma_composition_aux i.2⟩, inv_fun := λ i, ⟨ { blocks := (of_fn (λ j, (i.2 j).blocks)).join, blocks_pos := begin simp only [and_imp, list.mem_join, exists_imp_distrib, forall_mem_of_fn_iff], exact λ i j hj, composition.blocks_pos _ hj end, blocks_sum := by simp [sum_of_fn, composition.blocks_sum, composition.sum_blocks_fun] }, { blocks := of_fn (λ j, (i.2 j).length), blocks_pos := forall_mem_of_fn_iff.2 (λ j, composition.length_pos_of_pos _ (composition.blocks_pos' _ _ _)), blocks_sum := by { dsimp only [composition.length], simp [sum_of_fn] } }⟩, left_inv := begin -- the fact that we have a left inverse is essentially `join_split_wrt_composition`, -- but we need to massage it to take care of the dependent setting. rintros ⟨a, b⟩, rw sigma_composition_eq_iff, dsimp, split, { have A := length_map list.sum (split_wrt_composition a.blocks b), conv_rhs { rw [← join_split_wrt_composition a.blocks b, ← of_fn_nth_le (split_wrt_composition a.blocks b)] }, congr, { exact A }, { exact (fin.heq_fun_iff A).2 (λ i, rfl) } }, { have B : composition.length (composition.gather a b) = list.length b.blocks := composition.length_gather _ _, conv_rhs { rw [← of_fn_nth_le b.blocks] }, congr' 1, apply (fin.heq_fun_iff B).2 (λ i, _), rw [sigma_composition_aux, composition.length, nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)], refl } end, right_inv := begin -- the fact that we have a right inverse is essentially `split_wrt_composition_join`, -- but we need to massage it to take care of the dependent setting. rintros ⟨c, d⟩, have : map list.sum (of_fn (λ (i : fin (composition.length c)), (d i).blocks)) = c.blocks, by simp [map_of_fn, (∘), composition.blocks_sum, composition.of_fn_blocks_fun], rw sigma_pi_composition_eq_iff, dsimp, congr, { ext1, dsimp [composition.gather], rwa split_wrt_composition_join, simp only [map_of_fn] }, { rw fin.heq_fun_iff, { assume i, dsimp [composition.sigma_composition_aux], rw [nth_le_of_eq (split_wrt_composition_join _ _ _)], { simp only [nth_le_of_fn'] }, { simp only [map_of_fn] } }, { congr, ext1, dsimp [composition.gather], rwa split_wrt_composition_join, simp only [map_of_fn] } } end } end composition namespace formal_multilinear_series open composition theorem comp_assoc (r : formal_multilinear_series 𝕜 G H) (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : (r.comp q).comp p = r.comp (q.comp p) := begin ext n v, /- First, rewrite the two compositions appearing in the theorem as two sums over complicated sigma types, as in the description of the proof above. -/ let f : (Σ (a : composition n), composition a.length) → H := λ c, r c.2.length (apply_composition q c.2 (apply_composition p c.1 v)), let g : (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) → H := λ c, r c.1.length (λ (i : fin c.1.length), q (c.2 i).length (apply_composition p (c.2 i) (v ∘ c.1.embedding i))), suffices : ∑ c, f c = ∑ c, g c, by simpa only [formal_multilinear_series.comp, continuous_multilinear_map.sum_apply, comp_along_composition_apply, continuous_multilinear_map.map_sum, finset.sum_sigma', apply_composition], /- Now, we use `composition.sigma_equiv_sigma_pi n` to change variables in the second sum, and check that we get exactly the same sums. -/ rw ← (sigma_equiv_sigma_pi n).sum_comp, /- To check that we have the same terms, we should check that we apply the same component of `r`, and the same component of `q`, and the same component of `p`, to the same coordinate of `v`. This is true by definition, but at each step one needs to convince Lean that the types one considers are the same, using a suitable congruence lemma to avoid dependent type issues. This dance has to be done three times, one for `r`, one for `q` and one for `p`.-/ apply finset.sum_congr rfl, rintros ⟨a, b⟩ _, dsimp [f, g, sigma_equiv_sigma_pi], -- check that the `r` components are the same. Based on `composition.length_gather` apply r.congr (composition.length_gather a b).symm, intros i hi1 hi2, -- check that the `q` components are the same. Based on `length_sigma_composition_aux` apply q.congr (length_sigma_composition_aux a b _).symm, intros j hj1 hj2, -- check that the `p` components are the same. Based on `blocks_fun_sigma_composition_aux` apply p.congr (blocks_fun_sigma_composition_aux a b _ _).symm, intros k hk1 hk2, -- finally, check that the coordinates of `v` one is using are the same. Based on -- `size_up_to_size_up_to_add`. refine congr_arg v (fin.eq_of_veq _), dsimp [composition.embedding], rw [size_up_to_size_up_to_add _ _ hi1 hj1, add_assoc], end end formal_multilinear_series
9b11d69b22d4df2782d1cb5ca676a30bfe9860fe
675b8263050a5d74b89ceab381ac81ce70535688
/src/field_theory/algebraic_closure.lean
24a1e0c9797d14b8c474587628f90674c8da9e10
[ "Apache-2.0" ]
permissive
vozor/mathlib
5921f55235ff60c05f4a48a90d616ea167068adf
f7e728ad8a6ebf90291df2a4d2f9255a6576b529
refs/heads/master
1,675,607,702,231
1,609,023,279,000
1,609,023,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,130
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.direct_limit import field_theory.splitting_field import analysis.complex.polynomial /-! # Algebraic Closure In this file we define the typeclass for algebraically closed fields and algebraic closures. We also construct an algebraic closure for any field. ## Main Definitions - `is_alg_closed k` is the typeclass saying `k` is an algebraically closed field, i.e. every polynomial in `k` splits. - `is_alg_closure k K` is the typeclass saying `K` is an algebraic closure of `k`. - `algebraic_closure k` is an algebraic closure of `k` (in the same universe). It is constructed by taking the polynomial ring generated by indeterminates `x_f` corresponding to monic irreducible polynomials `f` with coefficients in `k`, and quotienting out by a maximal ideal containing every `f(x_f)`, and then repeating this step countably many times. See Exercise 1.13 in Atiyah--Macdonald. ## TODO Show that any algebraic extension embeds into any algebraically closed extension (via Zorn's lemma). ## Tags algebraic closure, algebraically closed -/ universes u v w noncomputable theory open_locale classical big_operators open polynomial variables (k : Type u) [field k] /-- Typeclass for algebraically closed fields. -/ class is_alg_closed : Prop := (splits : ∀ p : polynomial k, p.splits $ ring_hom.id k) theorem polynomial.splits' {k K : Type*} [field k] [is_alg_closed k] [field K] {f : k →+* K} (p : polynomial k) : p.splits f := polynomial.splits_of_splits_id _ $ is_alg_closed.splits _ namespace is_alg_closed theorem of_exists_root (H : ∀ p : polynomial k, p.monic → irreducible p → ∃ x, p.eval x = 0) : is_alg_closed k := ⟨λ p, or.inr $ λ q hq hqp, have irreducible (q * C (leading_coeff q)⁻¹), by { rw ← coe_norm_unit_of_ne_zero hq.ne_zero, exact irreducible_of_associated associated_normalize hq }, let ⟨x, hx⟩ := H (q * C (leading_coeff q)⁻¹) (monic_mul_leading_coeff_inv hq.ne_zero) this in degree_mul_leading_coeff_inv q hq.ne_zero ▸ degree_eq_one_of_irreducible_of_root this hx⟩ lemma degree_eq_one_of_irreducible [is_alg_closed k] {p : polynomial k} (h_nz : p ≠ 0) (hp : irreducible p) : p.degree = 1 := degree_eq_one_of_irreducible_of_splits h_nz hp (polynomial.splits' _) end is_alg_closed instance complex.is_alg_closed : is_alg_closed ℂ := is_alg_closed.of_exists_root _ $ λ p _ hp, complex.exists_root $ degree_pos_of_irreducible hp /-- Typeclass for an extension being an algebraic closure. -/ @[class] def is_alg_closure (K : Type v) [field K] [algebra k K] : Prop := is_alg_closed K ∧ algebra.is_algebraic k K namespace algebraic_closure open mv_polynomial /-- The subtype of monic irreducible polynomials -/ @[reducible] def monic_irreducible : Type u := { f : polynomial k // monic f ∧ irreducible f } /-- Sends a monic irreducible polynomial `f` to `f(x_f)` where `x_f` is a formal indeterminate. -/ def eval_X_self (f : monic_irreducible k) : mv_polynomial (monic_irreducible k) k := polynomial.eval₂ mv_polynomial.C (X f) f /-- The span of `f(x_f)` across monic irreducible polynomials `f` where `x_f` is an indeterminate. -/ def span_eval : ideal (mv_polynomial (monic_irreducible k) k) := ideal.span $ set.range $ eval_X_self k /-- Given a finset of monic irreducible polynomials, construct an algebra homomorphism to the splitting field of the product of the polynomials sending each indeterminate `x_f` represented by the polynomial `f` in the finset to a root of `f`. -/ def to_splitting_field (s : finset (monic_irreducible k)) : mv_polynomial (monic_irreducible k) k →ₐ[k] splitting_field (∏ x in s, x : polynomial k) := mv_polynomial.aeval $ λ f, if hf : f ∈ s then root_of_splits _ ((splits_prod_iff _ $ λ (j : monic_irreducible k) _, j.2.2.ne_zero).1 (splitting_field.splits _) f hf) (mt is_unit_iff_degree_eq_zero.2 f.2.2.not_unit) else 37 theorem to_splitting_field_eval_X_self {s : finset (monic_irreducible k)} {f} (hf : f ∈ s) : to_splitting_field k s (eval_X_self k f) = 0 := by { rw [to_splitting_field, eval_X_self, ← alg_hom.coe_to_ring_hom, hom_eval₂, alg_hom.coe_to_ring_hom, mv_polynomial.aeval_X, dif_pos hf, ← algebra_map_eq, alg_hom.comp_algebra_map], exact map_root_of_splits _ _ _ } theorem span_eval_ne_top : span_eval k ≠ ⊤ := begin rw [ideal.ne_top_iff_one, span_eval, ideal.span, ← set.image_univ, finsupp.mem_span_iff_total], rintros ⟨v, _, hv⟩, replace hv := congr_arg (to_splitting_field k v.support) hv, rw [alg_hom.map_one, finsupp.total_apply, finsupp.sum, alg_hom.map_sum, finset.sum_eq_zero] at hv, { exact zero_ne_one hv }, intros j hj, rw [smul_eq_mul, alg_hom.map_mul, to_splitting_field_eval_X_self k hj, mul_zero] end /-- A random maximal ideal that contains `span_eval k` -/ def max_ideal : ideal (mv_polynomial (monic_irreducible k) k) := classical.some $ ideal.exists_le_maximal _ $ span_eval_ne_top k instance max_ideal.is_maximal : (max_ideal k).is_maximal := (classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).1 theorem le_max_ideal : span_eval k ≤ max_ideal k := (classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).2 /-- The first step of constructing `algebraic_closure`: adjoin a root of all monic polynomials -/ def adjoin_monic : Type u := (max_ideal k).quotient instance adjoin_monic.field : field (adjoin_monic k) := ideal.quotient.field _ instance adjoin_monic.inhabited : inhabited (adjoin_monic k) := ⟨37⟩ /-- The canonical ring homomorphism to `adjoin_monic k`. -/ def to_adjoin_monic : k →+* adjoin_monic k := (ideal.quotient.mk _).comp C instance adjoin_monic.algebra : algebra k (adjoin_monic k) := (to_adjoin_monic k).to_algebra theorem adjoin_monic.algebra_map : algebra_map k (adjoin_monic k) = (ideal.quotient.mk _).comp C := rfl theorem adjoin_monic.is_integral (z : adjoin_monic k) : is_integral k z := let ⟨p, hp⟩ := ideal.quotient.mk_surjective z in hp ▸ mv_polynomial.induction_on p (λ x, is_integral_algebra_map) (λ p q, is_integral_add) (λ p f ih, @is_integral_mul _ _ _ _ _ _ (ideal.quotient.mk _ _) ih ⟨f, f.2.1, by { erw [adjoin_monic.algebra_map, ← hom_eval₂, ideal.quotient.eq_zero_iff_mem], exact le_max_ideal k (ideal.subset_span ⟨f, rfl⟩) }⟩) theorem adjoin_monic.exists_root {f : polynomial k} (hfm : f.monic) (hfi : irreducible f) : ∃ x : adjoin_monic k, f.eval₂ (to_adjoin_monic k) x = 0 := ⟨ideal.quotient.mk _ $ X (⟨f, hfm, hfi⟩ : monic_irreducible k), by { rw [to_adjoin_monic, ← hom_eval₂, ideal.quotient.eq_zero_iff_mem], exact le_max_ideal k (ideal.subset_span $ ⟨_, rfl⟩) }⟩ /-- The `n`th step of constructing `algebraic_closure`, together with its `field` instance. -/ def step_aux (n : ℕ) : Σ α : Type u, field α := nat.rec_on n ⟨k, infer_instance⟩ $ λ n ih, ⟨@adjoin_monic ih.1 ih.2, @adjoin_monic.field ih.1 ih.2⟩ /-- The `n`th step of constructing `algebraic_closure`. -/ def step (n : ℕ) : Type u := (step_aux k n).1 instance step.field (n : ℕ) : field (step k n) := (step_aux k n).2 instance step.inhabited (n) : inhabited (step k n) := ⟨37⟩ /-- The canonical inclusion to the `0`th step. -/ def to_step_zero : k →+* step k 0 := ring_hom.id k /-- The canonical ring homomorphism to the next step. -/ def to_step_succ (n : ℕ) : step k n →+* step k (n + 1) := @to_adjoin_monic (step k n) (step.field k n) instance step.algebra_succ (n) : algebra (step k n) (step k (n + 1)) := (to_step_succ k n).to_algebra theorem to_step_succ.exists_root {n} {f : polynomial (step k n)} (hfm : f.monic) (hfi : irreducible f) : ∃ x : step k (n + 1), f.eval₂ (to_step_succ k n) x = 0 := @adjoin_monic.exists_root _ (step.field k n) _ hfm hfi /-- The canonical ring homomorphism to a step with a greater index. -/ def to_step_of_le (m n : ℕ) (h : m ≤ n) : step k m →+* step k n := { to_fun := nat.le_rec_on h (λ n, to_step_succ k n), map_one' := begin induction h with n h ih, { exact nat.le_rec_on_self 1 }, rw [nat.le_rec_on_succ h, ih, ring_hom.map_one] end, map_mul' := λ x y, begin induction h with n h ih, { simp_rw nat.le_rec_on_self }, simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_mul] end, map_zero' := begin induction h with n h ih, { exact nat.le_rec_on_self 0 }, rw [nat.le_rec_on_succ h, ih, ring_hom.map_zero] end, map_add' := λ x y, begin induction h with n h ih, { simp_rw nat.le_rec_on_self }, simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_add] end } @[simp] lemma coe_to_step_of_le (m n : ℕ) (h : m ≤ n) : (to_step_of_le k m n h : step k m → step k n) = nat.le_rec_on h (λ n, to_step_succ k n) := rfl instance step.algebra (n) : algebra k (step k n) := (to_step_of_le k 0 n n.zero_le).to_algebra instance step.scalar_tower (n) : is_scalar_tower k (step k n) (step k (n + 1)) := is_scalar_tower.of_algebra_map_eq $ λ z, @nat.le_rec_on_succ (step k) 0 n n.zero_le (n + 1).zero_le (λ n, to_step_succ k n) z theorem step.is_integral (n) : ∀ z : step k n, is_integral k z := nat.rec_on n (λ z, is_integral_algebra_map) $ λ n ih z, is_integral_trans ih _ (adjoin_monic.is_integral (step k n) z : _) instance to_step_of_le.directed_system : directed_system (step k) (λ i j h, to_step_of_le k i j h) := ⟨λ i x h, nat.le_rec_on_self x, λ i₁ i₂ i₃ h₁₂ h₂₃ x, (nat.le_rec_on_trans h₁₂ h₂₃ x).symm⟩ end algebraic_closure /-- The canonical algebraic closure of a field, the direct limit of adding roots to the field for each polynomial over the field. -/ def algebraic_closure : Type u := ring.direct_limit (algebraic_closure.step k) (λ i j h, algebraic_closure.to_step_of_le k i j h) namespace algebraic_closure instance : field (algebraic_closure k) := field.direct_limit.field _ _ instance : inhabited (algebraic_closure k) := ⟨37⟩ /-- The canonical ring embedding from the `n`th step to the algebraic closure. -/ def of_step (n : ℕ) : step k n →+* algebraic_closure k := ring_hom.of $ ring.direct_limit.of _ _ _ instance algebra_of_step (n) : algebra (step k n) (algebraic_closure k) := (of_step k n).to_algebra theorem of_step_succ (n : ℕ) : (of_step k (n + 1)).comp (to_step_succ k n) = of_step k n := ring_hom.ext $ λ x, show ring.direct_limit.of (step k) (λ i j h, to_step_of_le k i j h) _ _ = _, by { convert ring.direct_limit.of_f n.le_succ x, ext x, exact (nat.le_rec_on_succ' x).symm } theorem exists_of_step (z : algebraic_closure k) : ∃ n x, of_step k n x = z := ring.direct_limit.exists_of z -- slow theorem exists_root {f : polynomial (algebraic_closure k)} (hfm : f.monic) (hfi : irreducible f) : ∃ x : algebraic_closure k, f.eval x = 0 := begin have : ∃ n p, polynomial.map (of_step k n) p = f, { convert ring.direct_limit.polynomial.exists_of f }, unfreezingI { obtain ⟨n, p, rfl⟩ := this }, rw monic_map_iff at hfm, have := hfm.irreducible_of_irreducible_map (of_step k n) p hfi, obtain ⟨x, hx⟩ := to_step_succ.exists_root k hfm this, refine ⟨of_step k (n + 1) x, _⟩, rw [← of_step_succ k n, eval_map, ← hom_eval₂, hx, ring_hom.map_zero] end instance : is_alg_closed (algebraic_closure k) := is_alg_closed.of_exists_root _ $ λ f, exists_root k instance : algebra k (algebraic_closure k) := (of_step k 0).to_algebra /-- Canonical algebra embedding from the `n`th step to the algebraic closure. -/ def of_step_hom (n) : step k n →ₐ[k] algebraic_closure k := { commutes' := λ x, ring.direct_limit.of_f n.zero_le x, .. of_step k n } theorem is_algebraic : algebra.is_algebraic k (algebraic_closure k) := λ z, (is_algebraic_iff_is_integral _).2 $ let ⟨n, x, hx⟩ := exists_of_step k z in hx ▸ is_integral_alg_hom (of_step_hom k n) (step.is_integral k n x) instance : is_alg_closure k (algebraic_closure k) := ⟨algebraic_closure.is_alg_closed k, is_algebraic k⟩ end algebraic_closure
8a778e9226caab9780dfabb976cea2a3f2682abd
b147e1312077cdcfea8e6756207b3fa538982e12
/data/vector2.lean
29164990d2a9c04f336a215566f07732b5552f9d
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,586
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Additional theorems about the `vector` type. -/ import data.vector data.list.basic data.array.lemmas namespace vector variables {α : Type*} {n : ℕ} attribute [simp] head_cons tail_cons instance [inhabited α] : inhabited (vector α n) := ⟨of_fn (λ _, default α)⟩ theorem to_list_injective : function.injective (@to_list α n) := subtype.val_injective @[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f | 0 f := rfl | (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn] @[simp] theorem mk_to_list : ∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v | ⟨l, h₁⟩ h₂ := rfl theorem nth_eq_nth_le : ∀ (v : vector α n) (i), nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2) | ⟨l, h⟩ i := rfl @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i := by rw [nth_eq_nth_le, ← list.nth_le_of_fn f]; congr; apply to_list_of_fn @[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v := begin rcases v with ⟨l, rfl⟩, apply to_list_injective, change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i, simp [nth, list.of_fn_nth_le] end @[simp] theorem nth_tail : ∀ (v : vector α n.succ) (i : fin n), nth (tail v) i = nth v i.succ | ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl @[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) : tail (of_fn f) = of_fn (λ i, f i.succ) := (of_fn_nth _).symm.trans $ by congr; funext i; simp theorem head'_to_list : ∀ (v : vector α n.succ), (to_list v).head' = some (head v) | ⟨a::l, e⟩ := rfl def reverse (v : vector α n) : vector α n := ⟨v.to_list.reverse, by simp⟩ @[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v | ⟨a::l, e⟩ := rfl @[simp] theorem head_of_fn {n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 := by rw [← nth_zero, nth_of_fn] @[simp] theorem nth_cons_zero (a : α) (v : vector α n) : nth (a :: v) 0 = a := by simp [nth_zero] @[simp] theorem nth_cons_succ (a : α) (v : vector α n) (i : fin n) : nth (a :: v) i.succ = nth v i := by rw [← nth_tail, tail_cons] def {u} m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n) | 0 f := pure nil | (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a :: v) theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} : ∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f) | 0 f := rfl | (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn] def {u} mmap {m} [monad m] {α} {β : Type u} (f : α → m β) : ∀ {n}, vector α n → m (vector β n) | _ ⟨[], rfl⟩ := pure nil | _ ⟨a::l, rfl⟩ := do h' ← f a, t' ← mmap ⟨l, rfl⟩, pure (h' :: t') @[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) : mmap f nil = pure nil := rfl @[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) : ∀ {n} (v : vector α n), mmap f (a::v) = do h' ← f a, t' ← mmap f v, pure (h' :: t') | _ ⟨l, rfl⟩ := rfl end vector namespace equiv def vector_equiv_fin (α : Type*) (n : ℕ) : vector α n ≃ (fin n → α) := ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩ def vector_equiv_array (α : Type*) (n : ℕ) : vector α n ≃ array n α := (vector_equiv_fin _ _).trans (array_equiv_fin _ _).symm end equiv
67e9b41ed085582909752345e4580d009bc0e059
fbef61907e2e2afef7e1e91395505ed27448a945
/LeanProtocPlugin/ProtoGenM.lean
74c75ca81aec2dafe7f460270f179c9a0c9bfc7b
[ "MIT" ]
permissive
yatima-inc/Protoc.lean
7edecca1f5b33909e6dfef1bcebcbbf9a322ca8c
3ad7839ec911906e19984e5b60958ee9c866b7ec
refs/heads/master
1,682,196,995,576
1,620,507,180,000
1,620,507,180,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,376
lean
import Std.Data.RBMap import LeanProtocPlugin.Helpers import LeanProtocPlugin.Google.Protobuf.Compiler.Plugin import LeanProtocPlugin.Google.Protobuf.Descriptor open LeanProtocPlugin.Google.Protobuf.Compiler open LeanProtocPlugin.Google.Protobuf structure ASTPath where protected mk :: file : FileDescriptorProto revMessages : List DescriptorProto -- reverse-ordered path to this message, revMessages.hd being the actual message leanModule : String leanName : String protoFullPath : String deriving BEq, Inhabited structure ProtoGenContext where namespacePrefix : String fileProtoMap : Std.RBMapC String FileDescriptorProto currentFile : FileDescriptorProto -- These are keyed by protobuf-fully-qualified-name enumDescriptorMap : Std.RBMapC String (ASTPath × EnumDescriptorProto) oneofDescriptorMap : Std.RBMapC String (ASTPath × OneofDescriptorProto) messageDescriptorMap : Std.RBMapC String ASTPath structure ProtoGenState where lines : Array String := #[] abbrev ProtoGenM := ReaderT ProtoGenContext $ StateT ProtoGenState $ IO def addLine (l: String) : ProtoGenM Unit := do let s ← get; set $ ProtoGenState.mk $ s.lines.push l def addLines (l: Array String) : ProtoGenM Unit := do let s ← get; set $ ProtoGenState.mk $ s.lines++l def Option.unwrap (x: Option α) : ProtoGenM α := match x with | some v => v | none => throw $ IO.userError "Tried unwrapping Option that is none" def ctxFindEnum (s: String) : ProtoGenM $ Option (ASTPath × EnumDescriptorProto) := do let ctx ← read; return ctx.enumDescriptorMap.find? s def ctxFindOneof (s: String) : ProtoGenM $ Option (ASTPath × OneofDescriptorProto) := do let ctx ← read; return ctx.oneofDescriptorMap.find? s def ctxFindMessage (s: String) : ProtoGenM $ Option ASTPath := do let ctx ← read; return ctx.messageDescriptorMap.find? s def ASTPath.init (file: FileDescriptorProto) (rootPackage: String): ASTPath := { file := file, revMessages := [], leanModule := rootPackage ++ "." ++ protoPackageToLeanPackagePrefix file.package, leanName := "", protoFullPath := "." ++ file.package} def ASTPath.initM (file: FileDescriptorProto): ProtoGenM ASTPath := do return ASTPath.init file (← read).namespacePrefix def ASTPath.addMessage (m: ASTPath) (m2 : DescriptorProto) : ASTPath := let newMessageName := protoMessageNameToLean m2.name let newPathChunk := if m.leanName == "" then newMessageName else "_" ++ newMessageName { m with file := m.file, revMessages := m2 :: m.revMessages, leanName := m.leanName ++ newPathChunk, protoFullPath := m.protoFullPath ++ "." ++ m2.name } partial def recurseM [Monad μ] (curr: α) (action: α -> μ (List α)) : μ PUnit := do let children ← action curr children.forM fun nested => recurseM nested action def isMapEntry (d: DescriptorProto) := ((DescriptorProto.options d).getD arbitrary).mapEntry == false def wrapRecurseFn [Monad μ] (fn: ASTPath -> σ -> μ σ) (withMaps := false) (new: (ASTPath × σ)) : μ (List (ASTPath × σ)) := do let r ← fn new.fst new.snd; let children := match new.fst.revMessages.head? with | some m => let nested := if withMaps then m.nestedType else m.nestedType.filter isMapEntry nested.toList | none => new.fst.file.messageType.toList return children.map (fun v => (new.fst.addMessage v, r))
1630d18a0a674452d47b8a1c525864d34e58639f
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/tactic/omega/find_ees.lean
8b4af497338e393c458d5797eae56301c92cda7c
[ "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
3,482
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek A tactic for finding a sequence of equality elimination rules for a given set of constraints. -/ import tactic.omega.eq_elim variables {α β : Type} open tactic namespace omega structure ee_state := (eqs : list term) (les : list term) (ees : list ee) @[reducible] meta def eqelim := state_t ee_state tactic meta def abort {α : Type} : eqelim α := ⟨λ x, failed⟩ private meta def mk_eqelim_state (eqs les : list term) : tactic ee_state := return (ee_state.mk eqs les []) meta def get_eqs : eqelim (list term) := ee_state.eqs <$> get meta def get_les : eqelim (list term) := ee_state.les <$> get meta def get_ees : eqelim (list ee) := ee_state.ees <$> get meta def set_eqs (eqs : list term) : eqelim unit := modify $ λ s, {eqs := eqs, ..s} meta def set_les (les : list term) : eqelim unit := modify $ λ s, {les := les, ..s} meta def set_ees (es : list ee) : eqelim unit := modify $ λ s, {ees := es, ..s} meta def add_ee (e : ee) : eqelim unit := do es ← get_ees, set_ees (es ++ [e]) meta def head_eq : eqelim term := do eqs ← get_eqs, match eqs with | [] := abort | (eq::eqs') := set_eqs eqs' >> pure eq end meta def run {α : Type} (eqs les : list term) (r : eqelim α) : tactic α := prod.fst <$> (mk_eqelim_state eqs les >>= r.run) meta def ee_commit (t1 : eqelim α) (t2 : eqelim β) (t3 : α → eqelim β) : eqelim β := do x ← ((t1 >>= return ∘ some) <|> return none), match x with | none := t2 | (some a) := t3 a end local notation t1 `!>>=` t2 `;` t3 := ee_commit t1 t2 t3 private meta def of_tactic {α : Type} : tactic α → eqelim α := state_t.lift def gcd : list int → nat | [] := 0 | (i::is) := nat.gcd i.nat_abs (gcd is) meta def get_gcd (t : term) : eqelim int := pure ↑(gcd t.snd) meta def factor (i : int) (t : term) : eqelim term := if i ∣ t.fst then add_ee (ee.factor i) >> pure (t.div i) else abort /- If list has a nonzero element, return the minimum element (by absolute value) with its index. Otherwise, return none. -/ meta def find_min_coeff_core : list int → eqelim (int × nat) | [] := abort | (i::is) := (do (j,n) ← find_min_coeff_core is, if i ≠ 0 ∧ i.nat_abs ≤ j.nat_abs then pure (i,0) else pure (j,n+1)) <|> (if i = (0 : int) then abort else pure (i,0)) meta def find_min_coeff (t : term) : eqelim (int × nat × term) := do (i,n) ← find_min_coeff_core t.snd, if 0 < i then pure (i,n,t) else add_ee (ee.neg) >> pure (-i,n,t.neg) meta def elim_eq : eqelim unit := do t ← head_eq, i ← get_gcd t, factor i t !>>= (set_eqs [] >> add_ee (ee.nondiv i)) ; λ s, find_min_coeff s !>>= add_ee ee.drop ; λ ⟨i, n, u⟩, if i = 1 then do eqs ← get_eqs, les ← get_les, set_eqs (eqs.map (cancel n u)), set_les (les.map (cancel n u)), add_ee (ee.cancel n) else let v : term := coeffs_reduce n u.fst u.snd in let r : term := rhs n u.fst u.snd in do eqs ← get_eqs, les ← get_les, set_eqs (v::eqs.map (subst n r)), set_les (les.map (subst n r)), add_ee (ee.reduce n), elim_eq meta def elim_eqs : eqelim (list ee) := elim_eq !>>= get_ees ; λ _, elim_eqs meta def find_ees : clause → tactic (list ee) | (eqs,les) := run eqs les elim_eqs end omega