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
f5cd5b358a6d4f6b10b4d205f9e4c3f62bdf860a
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/preserves/shapes/biproducts.lean
e69f4ecaf044ef1346730fd89bf37647867e4e3a
[ "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
18,341
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.limits.shapes.biproducts import category_theory.limits.preserves.shapes.zero /-! # Preservation of biproducts We define the image of a (binary) bicone under a functor that preserves zero morphisms and define classes `preserves_biproduct` and `preserves_binary_biproduct`. We then * show that a functor that preserves biproducts of a two-element type preserves binary biproducts, * give the canonical isomorphism between the image of a biproduct and the biproduct of the images, * show that in a preadditive category, a functor preserves a biproduct if and only if it preserves the corresponding product if and only if it preserves the corresponding coproduct. -/ universes v u u₂ noncomputable theory open category_theory open category_theory.limits namespace category_theory variables {C : Type u} [category.{v} C] {D : Type u₂} [category.{v} D] section has_zero_morphisms variables [has_zero_morphisms C] [has_zero_morphisms D] namespace functor section map variables (F : C ⥤ D) [preserves_zero_morphisms F] section bicone variables {J : Type v} [decidable_eq J] /-- The image of a bicone under a functor. -/ @[simps] def map_bicone {f : J → C} (b : bicone f) : bicone (F.obj ∘ f) := { X := F.obj b.X, π := λ j, F.map (b.π j), ι := λ j, F.map (b.ι j), ι_π := λ j j', begin rw ← F.map_comp, split_ifs, { subst h, simp only [bicone_ι_π_self, category_theory.functor.map_id, eq_to_hom_refl] }, { rw [bicone_ι_π_ne _ h, F.map_zero] } end } end bicone /-- The image of a binary bicone under a functor. -/ @[simps] def map_binary_bicone {X Y : C} (b : binary_bicone X Y) : binary_bicone (F.obj X) (F.obj Y) := { X := F.obj b.X, fst := F.map b.fst, snd := F.map b.snd, inl := F.map b.inl, inr := F.map b.inr, inl_fst' := by rw [← F.map_comp, b.inl_fst, F.map_id], inl_snd' := by rw [← F.map_comp, b.inl_snd, F.map_zero], inr_fst' := by rw [← F.map_comp, b.inr_fst, F.map_zero], inr_snd' := by rw [← F.map_comp, b.inr_snd, F.map_id] } end map end functor open category_theory.functor namespace limits section bicone variables {J : Type v} [decidable_eq J] /-- A functor `F` preserves biproducts of `f` if `F` maps every bilimit bicone over `f` to a bilimit bicone over `F.obj ∘ f`. -/ class preserves_biproduct (f : J → C) (F : C ⥤ D) [preserves_zero_morphisms F] := (preserves : Π {b : bicone f}, b.is_bilimit → (F.map_bicone b).is_bilimit) /-- A functor `F` preserves biproducts of `f` if `F` maps every bilimit bicone over `f` to a bilimit bicone over `F.obj ∘ f`. -/ def is_bilimit_of_preserves {f : J → C} (F : C ⥤ D) [preserves_zero_morphisms F] [preserves_biproduct f F] {b : bicone f} (hb : b.is_bilimit) : (F.map_bicone b).is_bilimit := preserves_biproduct.preserves hb variables (J) /-- A functor `F` preserves biproducts of shape `J` if it preserves biproducts of `f` for every `f : J → C`. -/ class preserves_biproducts_of_shape (F : C ⥤ D) [preserves_zero_morphisms F] := (preserves : Π {f : J → C}, preserves_biproduct f F) attribute [instance, priority 100] preserves_biproducts_of_shape.preserves end bicone /-- A functor `F` preserves finite biproducts if it preserves biproducts of shape `J` whenever `J` is a fintype. -/ class preserves_finite_biproducts (F : C ⥤ D) [preserves_zero_morphisms F] := (preserves : Π {J : Type v} [decidable_eq J] [fintype J], preserves_biproducts_of_shape J F) attribute [instance, priority 100] preserves_finite_biproducts.preserves /-- A functor `F` preserves biproducts if it preserves biproducts of any (small) shape `J`. -/ class preserves_biproducts (F : C ⥤ D) [preserves_zero_morphisms F] := (preserves : Π {J : Type v} [decidable_eq J], preserves_biproducts_of_shape J F) attribute [instance, priority 100] preserves_biproducts.preserves @[priority 100] instance preserves_finite_biproducts_of_preserves_biproducts (F : C ⥤ D) [preserves_zero_morphisms F] [preserves_biproducts F] : preserves_finite_biproducts F := { preserves := λ J _ _, infer_instance } /-- A functor `F` preserves binary biproducts of `X` and `Y` if `F` maps every bilimit bicone over `X` and `Y` to a bilimit bicone over `F.obj X` and `F.obj Y`. -/ class preserves_binary_biproduct (X Y : C) (F : C ⥤ D) [preserves_zero_morphisms F] := (preserves : Π {b : binary_bicone X Y}, b.is_bilimit → (F.map_binary_bicone b).is_bilimit) /-- A functor `F` preserves binary biproducts of `X` and `Y` if `F` maps every bilimit bicone over `X` and `Y` to a bilimit bicone over `F.obj X` and `F.obj Y`. -/ def is_binary_bilimit_of_preserves {X Y : C} (F : C ⥤ D) [preserves_zero_morphisms F] [preserves_binary_biproduct X Y F] {b : binary_bicone X Y} (hb : b.is_bilimit) : (F.map_binary_bicone b).is_bilimit := preserves_binary_biproduct.preserves hb /-- A functor `F` preserves binary biproducts if it preserves the binary biproduct of `X` and `Y` for all `X` and `Y`. -/ class preserves_binary_biproducts (F : C ⥤ D) [preserves_zero_morphisms F] := (preserves : Π {X Y : C}, preserves_binary_biproduct X Y F . tactic.apply_instance) /-- A functor that preserves biproducts of a pair preserves binary biproducts. -/ def preserves_binary_biproduct_of_preserves_biproduct (F : C ⥤ D) [preserves_zero_morphisms F] (X Y : C) [preserves_biproduct (pair X Y).obj F] : preserves_binary_biproduct X Y F := { preserves := λ b hb, { is_limit := is_limit.of_iso_limit ((is_limit.postcompose_hom_equiv (by exact diagram_iso_pair _) _).symm ((is_bilimit_of_preserves F (b.to_bicone_is_bilimit.symm hb)).is_limit)) $ cones.ext (iso.refl _) (λ j, by { cases j, tidy }), is_colimit := is_colimit.of_iso_colimit ((is_colimit.precompose_inv_equiv (by exact diagram_iso_pair _ ) _).symm ((is_bilimit_of_preserves F (b.to_bicone_is_bilimit.symm hb)).is_colimit)) $ cocones.ext (iso.refl _) (λ j, by { cases j, tidy }) } } /-- A functor that preserves biproducts of a pair preserves binary biproducts. -/ def preserves_binary_biproducts_of_preserves_biproducts (F : C ⥤ D) [preserves_zero_morphisms F] [preserves_biproducts_of_shape (discrete walking_pair.{v}) F] : preserves_binary_biproducts F := { preserves := λ X Y, preserves_binary_biproduct_of_preserves_biproduct F X Y } attribute [instance, priority 100] preserves_binary_biproducts.preserves end limits open category_theory.limits namespace functor section bicone variables {J : Type v} [decidable_eq J] (F : C ⥤ D) [preserves_zero_morphisms F] (f : J → C) [has_biproduct f] [preserves_biproduct f F] instance has_biproduct_of_preserves : has_biproduct (F.obj ∘ f) := has_biproduct.mk { bicone := F.map_bicone (biproduct.bicone f), is_bilimit := preserves_biproduct.preserves (biproduct.is_bilimit _) } /-- If `F` preserves a biproduct, we get a definitionally nice isomorphism `F.obj (⨁ f) ≅ ⨁ (F.obj ∘ f)`. -/ @[simp] def map_biproduct : F.obj (⨁ f) ≅ ⨁ (F.obj ∘ f) := biproduct.unique_up_to_iso _ (preserves_biproduct.preserves (biproduct.is_bilimit _)) lemma map_biproduct_hom : (map_biproduct F f).hom = biproduct.lift (λ j, F.map (biproduct.π f j)) := rfl lemma map_biproduct_inv : (map_biproduct F f).inv = biproduct.desc (λ j, F.map (biproduct.ι f j)) := rfl end bicone variables (F : C ⥤ D) [preserves_zero_morphisms F] (X Y : C) [has_binary_biproduct X Y] [preserves_binary_biproduct X Y F] instance has_binary_biproduct_of_preserves : has_binary_biproduct (F.obj X) (F.obj Y) := has_binary_biproduct.mk { bicone := F.map_binary_bicone (binary_biproduct.bicone X Y), is_bilimit := preserves_binary_biproduct.preserves (binary_biproduct.is_bilimit _ _) } /-- If `F` preserves a binary biproduct, we get a definitionally nice isomorphism `F.obj (X ⊞ Y) ≅ F.obj X ⊞ F.obj Y`. -/ @[simp] def map_biprod : F.obj (X ⊞ Y) ≅ F.obj X ⊞ F.obj Y := biprod.unique_up_to_iso _ _ (preserves_binary_biproduct.preserves (binary_biproduct.is_bilimit _ _)) lemma map_biprod_hom : (map_biprod F X Y).hom = biprod.lift (F.map biprod.fst) (F.map biprod.snd) := rfl lemma map_biprod_inv : (map_biprod F X Y).inv = biprod.desc (F.map biprod.inl) (F.map biprod.inr) := rfl end functor namespace limits variables (F : C ⥤ D) [preserves_zero_morphisms F] section bicone variables {J : Type v} [decidable_eq J] (f : J → C) [has_biproduct f] [preserves_biproduct f F] {W : C} lemma biproduct.map_lift_map_biprod (g : Π j, W ⟶ f j) : F.map (biproduct.lift g) ≫ (F.map_biproduct f).hom = biproduct.lift (λ j, F.map (g j)) := by { ext, simp [← F.map_comp] } lemma biproduct.map_biproduct_inv_map_desc (g : Π j, f j ⟶ W) : (F.map_biproduct f).inv ≫ F.map (biproduct.desc g) = biproduct.desc (λ j, F.map (g j)) := by { ext, simp [← F.map_comp] } lemma biproduct.map_biproduct_hom_desc (g : Π j, f j ⟶ W) : (F.map_biproduct f).hom ≫ biproduct.desc (λ j, F.map (g j)) = F.map (biproduct.desc g) := by rw [← biproduct.map_biproduct_inv_map_desc, iso.hom_inv_id_assoc] end bicone section binary_bicone variables (X Y : C) [has_binary_biproduct X Y] [preserves_binary_biproduct X Y F] {W : C} lemma biprod.map_lift_map_biprod (f : W ⟶ X) (g : W ⟶ Y) : F.map (biprod.lift f g) ≫ (F.map_biprod X Y).hom = biprod.lift (F.map f) (F.map g) := by ext; simp [← F.map_comp] lemma biprod.lift_map_biprod (f : W ⟶ X) (g : W ⟶ Y) : biprod.lift (F.map f) (F.map g) ≫ (F.map_biprod X Y).inv = F.map (biprod.lift f g) := by rw [← biprod.map_lift_map_biprod, category.assoc, iso.hom_inv_id, category.comp_id] lemma biprod.map_biprod_inv_map_desc (f : X ⟶ W) (g : Y ⟶ W) : (F.map_biprod X Y).inv ≫ F.map (biprod.desc f g) = biprod.desc (F.map f) (F.map g) := by ext; simp [← F.map_comp] lemma biprod.map_biprod_hom_desc (f : X ⟶ W) (g : Y ⟶ W) : (F.map_biprod X Y).hom ≫ biprod.desc (F.map f) (F.map g) = F.map (biprod.desc f g) := by rw [← biprod.map_biprod_inv_map_desc, iso.hom_inv_id_assoc] end binary_bicone end limits end has_zero_morphisms open category_theory.functor section preadditive variables [preadditive C] [preadditive D] (F : C ⥤ D) [preserves_zero_morphisms F] namespace limits section fintype variables {J : Type v} [decidable_eq J] [fintype J] /-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts preserves finite products. -/ def preserves_product_of_preserves_biproduct {f : J → C} [preserves_biproduct f F] : preserves_limit (discrete.functor f) F := { preserves := λ c hc, is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv (discrete.comp_nat_iso_discrete _ _) _).symm (is_bilimit_of_preserves F (bicone_is_bilimit_of_limit_cone_of_is_limit hc)).is_limit) $ cones.ext (iso.refl _) (by tidy) } section local attribute [instance] preserves_product_of_preserves_biproduct /-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts preserves finite products. -/ def preserves_products_of_shape_of_preserves_biproducts_of_shape [preserves_biproducts_of_shape J F] : preserves_limits_of_shape (discrete J) F := { preserves_limit := λ f, preserves_limit_of_iso_diagram _ discrete.nat_iso_functor.symm } end /-- A functor between preadditive categories that preserves (zero morphisms and) finite products preserves finite biproducts. -/ def preserves_biproduct_of_preserves_product {f : J → C} [preserves_limit (discrete.functor f) F] : preserves_biproduct f F := { preserves := λ b hb, is_bilimit_of_is_limit _ $ is_limit.of_iso_limit ((is_limit.postcompose_hom_equiv (discrete.comp_nat_iso_discrete _ _) (F.map_cone b.to_cone)).symm (is_limit_of_preserves F hb.is_limit)) $ cones.ext (iso.refl _) (by tidy) } /-- A functor between preadditive categories that preserves (zero morphisms and) finite products preserves finite biproducts. -/ def preserves_biproducts_of_shape_of_preserves_products_of_shape [preserves_limits_of_shape (discrete J) F] : preserves_biproducts_of_shape J F := { preserves := λ f, preserves_biproduct_of_preserves_product F } /-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts preserves finite coproducts. -/ def preserves_coproduct_of_preserves_biproduct {f : J → C} [preserves_biproduct f F] : preserves_colimit (discrete.functor f) F := { preserves := λ c hc, is_colimit.of_iso_colimit ((is_colimit.precompose_hom_equiv (discrete.comp_nat_iso_discrete _ _) _).symm (is_bilimit_of_preserves F (bicone_is_bilimit_of_colimit_cocone_of_is_colimit hc)).is_colimit) $ cocones.ext (iso.refl _) (by tidy) } section local attribute [instance] preserves_coproduct_of_preserves_biproduct /-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts preserves finite coproducts. -/ def preserves_coproducts_of_shape_of_preserves_biproducts_of_shape [preserves_biproducts_of_shape J F] : preserves_colimits_of_shape (discrete J) F := { preserves_colimit := λ f, preserves_colimit_of_iso_diagram _ discrete.nat_iso_functor.symm } end /-- A functor between preadditive categories that preserves (zero morphisms and) finite coproducts preserves finite biproducts. -/ def preserves_biproduct_of_preserves_coproduct {f : J → C} [preserves_colimit (discrete.functor f) F] : preserves_biproduct f F := { preserves := λ b hb, is_bilimit_of_is_colimit _ $ is_colimit.of_iso_colimit ((is_colimit.precompose_inv_equiv (discrete.comp_nat_iso_discrete _ _) (F.map_cocone b.to_cocone)).symm (is_colimit_of_preserves F hb.is_colimit)) $ cocones.ext (iso.refl _) (by tidy) } /-- A functor between preadditive categories that preserves (zero morphisms and) finite coproducts preserves finite biproducts. -/ def preserves_biproducts_of_shape_of_preserves_coproducts_of_shape [preserves_colimits_of_shape (discrete J) F] : preserves_biproducts_of_shape J F := { preserves := λ f, preserves_biproduct_of_preserves_coproduct F } end fintype /-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts preserves binary products. -/ def preserves_binary_product_of_preserves_binary_biproduct {X Y : C} [preserves_binary_biproduct X Y F] : preserves_limit (pair X Y) F := { preserves := λ c hc, is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv (by exact diagram_iso_pair _) _).symm (is_binary_bilimit_of_preserves F (binary_bicone_is_bilimit_of_limit_cone_of_is_limit hc)).is_limit) $ cones.ext (iso.refl _) (λ j, by { cases j, tidy }) } section local attribute [instance] preserves_binary_product_of_preserves_binary_biproduct /-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts preserves binary products. -/ def preserves_binary_products_of_preserves_binary_biproducts [preserves_binary_biproducts F] : preserves_limits_of_shape (discrete walking_pair.{v}) F := { preserves_limit := λ K, preserves_limit_of_iso_diagram _ (diagram_iso_pair _).symm } end /-- A functor between preadditive categories that preserves (zero morphisms and) binary products preserves binary biproducts. -/ def preserves_binary_biproduct_of_preserves_binary_product {X Y : C} [preserves_limit (pair X Y) F] : preserves_binary_biproduct X Y F := { preserves := λ b hb, is_binary_bilimit_of_is_limit _ $ is_limit.of_iso_limit ((is_limit.postcompose_hom_equiv (by exact diagram_iso_pair _) (F.map_cone b.to_cone)).symm (is_limit_of_preserves F hb.is_limit)) $ cones.ext (iso.refl _) (λ j, by { cases j, tidy }) } /-- A functor between preadditive categories that preserves (zero morphisms and) binary products preserves binary biproducts. -/ def preserves_binary_biproducts_of_preserves_binary_products [preserves_limits_of_shape (discrete walking_pair.{v}) F] : preserves_binary_biproducts F := { preserves := λ X Y, preserves_binary_biproduct_of_preserves_binary_product F } /-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts preserves binary coproducts. -/ def preserves_binary_coproduct_of_preserves_binary_biproduct {X Y : C} [preserves_binary_biproduct X Y F] : preserves_colimit (pair X Y) F := { preserves := λ c hc, is_colimit.of_iso_colimit ((is_colimit.precompose_hom_equiv (by exact diagram_iso_pair _) _).symm (is_binary_bilimit_of_preserves F (binary_bicone_is_bilimit_of_colimit_cocone_of_is_colimit hc)).is_colimit) $ cocones.ext (iso.refl _) (λ j, by { cases j, tidy }) } section local attribute [instance] preserves_binary_coproduct_of_preserves_binary_biproduct /-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts preserves binary coproducts. -/ def preserves_binary_coproducts_of_preserves_binary_biproducts [preserves_binary_biproducts F] : preserves_colimits_of_shape (discrete walking_pair.{v}) F := { preserves_colimit := λ K, preserves_colimit_of_iso_diagram _ (diagram_iso_pair _).symm } end /-- A functor between preadditive categories that preserves (zero morphisms and) binary coproducts preserves binary biproducts. -/ def preserves_binary_biproduct_of_preserves_binary_coproduct {X Y : C} [preserves_colimit (pair X Y) F] : preserves_binary_biproduct X Y F := { preserves := λ b hb, is_binary_bilimit_of_is_colimit _ $ is_colimit.of_iso_colimit ((is_colimit.precompose_inv_equiv (by exact diagram_iso_pair _) (F.map_cocone b.to_cocone)).symm (is_colimit_of_preserves F hb.is_colimit)) $ cocones.ext (iso.refl _) (λ j, by { cases j, tidy }) } /-- A functor between preadditive categories that preserves (zero morphisms and) binary coproducts preserves binary biproducts. -/ def preserves_binary_biproducts_of_preserves_binary_coproducts [preserves_colimits_of_shape (discrete walking_pair.{v}) F] : preserves_binary_biproducts F := { preserves := λ X Y, preserves_binary_biproduct_of_preserves_binary_coproduct F } end limits end preadditive end category_theory
56dd84fd74d5889cbe09826a42cfcdf5a991d937
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/preadditive/additive_functor.lean
7b8080af28d67761e74df5c60f35a5f542e5414b
[ "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
8,729
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Scott Morrison -/ import category_theory.limits.exact_functor import category_theory.limits.preserves.finite import category_theory.preadditive.biproducts import category_theory.preadditive.functor_category /-! # Additive Functors A functor between two preadditive categories is called *additive* provided that the induced map on hom types is a morphism of abelian groups. An additive functor between preadditive categories creates and preserves biproducts. Conversely, if `F : C ⥤ D` is a functor between preadditive categories, where `C` has binary biproducts, and if `F` preserves binary biproducts, then `F` is additive. We also define the category of bundled additive functors. # Implementation details `functor.additive` is a `Prop`-valued class, defined by saying that for every two objects `X` and `Y`, the map `F.map : (X ⟶ Y) → (F.obj X ⟶ F.obj Y)` is a morphism of abelian groups. -/ universes v₁ v₂ u₁ u₂ namespace category_theory /-- A functor `F` is additive provided `F.map` is an additive homomorphism. -/ class functor.additive {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] (F : C ⥤ D) : Prop := (map_add' : Π {X Y : C} {f g : X ⟶ Y}, F.map (f + g) = F.map f + F.map g . obviously) section preadditive namespace functor section variables {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] (F : C ⥤ D) [functor.additive F] @[simp] lemma map_add {X Y : C} {f g : X ⟶ Y} : F.map (f + g) = F.map f + F.map g := functor.additive.map_add' /-- `F.map_add_hom` is an additive homomorphism whose underlying function is `F.map`. -/ @[simps {fully_applied := ff}] def map_add_hom {X Y : C} : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y) := add_monoid_hom.mk' (λ f, F.map f) (λ f g, F.map_add) lemma coe_map_add_hom {X Y : C} : ⇑(F.map_add_hom : (X ⟶ Y) →+ _) = @map C _ D _ F X Y := rfl @[priority 100] instance preserves_zero_morphisms_of_additive : preserves_zero_morphisms F := { map_zero' := λ X Y, F.map_add_hom.map_zero } instance : additive (𝟭 C) := {} instance {E : Type*} [category E] [preadditive E] (G : D ⥤ E) [functor.additive G] : additive (F ⋙ G) := {} @[simp] lemma map_neg {X Y : C} {f : X ⟶ Y} : F.map (-f) = - F.map f := (F.map_add_hom : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y)).map_neg _ @[simp] lemma map_sub {X Y : C} {f g : X ⟶ Y} : F.map (f - g) = F.map f - F.map g := (F.map_add_hom : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y)).map_sub _ _ lemma map_nsmul {X Y : C} {f : X ⟶ Y} {n : ℕ} : F.map (n • f) = n • F.map f := (F.map_add_hom : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y)).map_nsmul _ _ -- You can alternatively just use `functor.map_smul` here, with an explicit `(r : ℤ)` argument. lemma map_zsmul {X Y : C} {f : X ⟶ Y} {r : ℤ} : F.map (r • f) = r • F.map f := (F.map_add_hom : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y)).map_zsmul _ _ open_locale big_operators @[simp] lemma map_sum {X Y : C} {α : Type*} (f : α → (X ⟶ Y)) (s : finset α) : F.map (∑ a in s, f a) = ∑ a in s, F.map (f a) := (F.map_add_hom : (X ⟶ Y) →+ _).map_sum f s end section induced_category variables {C : Type*} {D : Type*} [category D] [preadditive D] (F : C → D) instance induced_functor_additive : functor.additive (induced_functor F) := {} end induced_category instance full_subcategory_inclusion_additive {C : Type*} [category C] [preadditive C] (Z : C → Prop) : (full_subcategory_inclusion Z).additive := {} section -- To talk about preservation of biproducts we need to specify universes explicitly. noncomputable theory variables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₂} D] [preadditive C] [preadditive D] (F : C ⥤ D) open category_theory.limits open category_theory.preadditive @[priority 100] instance preserves_finite_biproducts_of_additive [additive F] : preserves_finite_biproducts F := { preserves := λ J _, { preserves := λ f, { preserves := λ b hb, by exactI is_bilimit_of_total _ begin simp_rw [F.map_bicone_π, F.map_bicone_ι, ← F.map_comp, ← F.map_sum], dsimp only [map_bicone_X], simp_rw [← F.map_id], refine congr_arg _ (hb.is_limit.hom_ext (λ j, hb.is_colimit.hom_ext (λ j', _))), cases j, cases j', dsimp only [limits.bicone.to_cone_π_app], simp [sum_comp, comp_sum, bicone.ι_π, comp_dite, dite_comp], end } } } lemma additive_of_preserves_binary_biproducts [has_binary_biproducts C] [preserves_zero_morphisms F] [preserves_binary_biproducts F] : additive F := { map_add' := λ X Y f g, by rw [biprod.add_eq_lift_id_desc, F.map_comp, ← biprod.lift_map_biprod, ← biprod.map_biprod_hom_desc, category.assoc, iso.inv_hom_id_assoc, F.map_id, biprod.add_eq_lift_id_desc] } end end functor namespace equivalence variables {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] instance inverse_additive (e : C ≌ D) [e.functor.additive] : e.inverse.additive := { map_add' := λ X Y f g, by { apply e.functor.map_injective, simp, }, } end equivalence section variables (C D : Type*) [category C] [category D] [preadditive C] [preadditive D] /-- Bundled additive functors. -/ @[derive category, nolint has_nonempty_instance] def AdditiveFunctor := full_subcategory (λ (F : C ⥤ D), F.additive) infixr ` ⥤+ `:26 := AdditiveFunctor instance : preadditive (C ⥤+ D) := preadditive.induced_category _ /-- An additive functor is in particular a functor. -/ @[derive full, derive faithful] def AdditiveFunctor.forget : (C ⥤+ D) ⥤ (C ⥤ D) := full_subcategory_inclusion _ variables {C D} /-- Turn an additive functor into an object of the category `AdditiveFunctor C D`. -/ def AdditiveFunctor.of (F : C ⥤ D) [F.additive] : C ⥤+ D := ⟨F, infer_instance⟩ @[simp] lemma AdditiveFunctor.of_fst (F : C ⥤ D) [F.additive] : (AdditiveFunctor.of F).1 = F := rfl @[simp] lemma AdditiveFunctor.forget_obj (F : C ⥤+ D) : (AdditiveFunctor.forget C D).obj F = F.1 := rfl lemma AdditiveFunctor.forget_obj_of (F : C ⥤ D) [F.additive] : (AdditiveFunctor.forget C D).obj (AdditiveFunctor.of F) = F := rfl @[simp] lemma AdditiveFunctor.forget_map (F G : C ⥤+ D) (α : F ⟶ G) : (AdditiveFunctor.forget C D).map α = α := rfl instance : functor.additive (AdditiveFunctor.forget C D) := { map_add' := λ F G α β, rfl } instance (F : C ⥤+ D) : functor.additive F.1 := F.2 end section exact open category_theory.limits variables (C : Type u₁) (D : Type u₂) [category.{v₁} C] [category.{v₂} D] [preadditive C] variables [preadditive D] [has_zero_object C] [has_zero_object D] [has_binary_biproducts C] section local attribute [instance] preserves_binary_biproducts_of_preserves_binary_products local attribute [instance] preserves_binary_biproducts_of_preserves_binary_coproducts /-- Turn a left exact functor into an additive functor. -/ @[derive full, derive faithful] def AdditiveFunctor.of_left_exact : (C ⥤ₗ D) ⥤ (C ⥤+ D) := full_subcategory.map (λ F h, let hF := classical.choice h in by exactI functor.additive_of_preserves_binary_biproducts F) /-- Turn a right exact functor into an additive functor. -/ @[derive full, derive faithful] def AdditiveFunctor.of_right_exact : (C ⥤ᵣ D) ⥤ (C ⥤+ D) := full_subcategory.map (λ F h, let hF := classical.choice h in by exactI functor.additive_of_preserves_binary_biproducts F) /-- Turn an exact functor into an additive functor. -/ @[derive full, derive faithful] def AdditiveFunctor.of_exact : (C ⥤ₑ D) ⥤ (C ⥤+ D) := full_subcategory.map (λ F h, let hF := classical.choice h.1 in by exactI functor.additive_of_preserves_binary_biproducts F) end variables {C D} @[simp] lemma AdditiveFunctor.of_left_exact_obj_fst (F : C ⥤ₗ D) : ((AdditiveFunctor.of_left_exact C D).obj F).obj = F.obj := rfl @[simp] lemma AdditiveFunctor.of_right_exact_obj_fst (F : C ⥤ᵣ D) : ((AdditiveFunctor.of_right_exact C D).obj F).obj = F.obj := rfl @[simp] lemma AdditiveFunctor.of_exact_obj_fst (F : C ⥤ₑ D) : ((AdditiveFunctor.of_exact C D).obj F).obj = F.obj := rfl @[simp] lemma Additive_Functor.of_left_exact_map {F G : C ⥤ₗ D} (α : F ⟶ G) : (AdditiveFunctor.of_left_exact C D).map α = α := rfl @[simp] lemma Additive_Functor.of_right_exact_map {F G : C ⥤ᵣ D} (α : F ⟶ G) : (AdditiveFunctor.of_right_exact C D).map α = α := rfl @[simp] lemma Additive_Functor.of_exact_map {F G : C ⥤ₑ D} (α : F ⟶ G) : (AdditiveFunctor.of_exact C D).map α = α := rfl end exact end preadditive end category_theory
9c6247ef160d999836636445bca65d6a92e719c6
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/test/amc12-2000-p1.lean
b8c3da7c4df1378cd2cc328a84fbfe567dd12827
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
290
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.nat.basic example (i m o : ℕ) (h₀ : i ≠ 0 ∧ m ≠ 0 ∧ o ≠ 0) (h₁ : i*m*o = 2001) : i+m+o ≤ 671 := begin sorry end
a1d2cbef25c0db493691436cf1a81b4c2d992a69
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/category/state.lean
02074d8553a04e9961582679d12fbd6d426e7277
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
3,650
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.interactive universes u v def state (σ α : Type u) : Type u := σ → α × σ section variables {σ α β : Type u} @[inline] def state_return (a : α) : state σ α := λ s, (a, s) @[inline] def state_bind (a : state σ α) (b : α → state σ β) : state σ β := λ s, match (a s) with (a', s') := b a' s' end instance (σ : Type u) : monad (state σ) := {pure := @state_return σ, bind := @state_bind σ, id_map := begin intros, apply funext, intro s, simp [state_bind], cases x s, apply rfl end, pure_bind := by intros; apply rfl, bind_assoc := begin intros, apply funext, intro s, simp [state_bind], cases x s, apply rfl end} end namespace state @[inline] def read {σ : Type u} : state σ σ := λ s, (s, s) @[inline] def write {σ : Type} : σ → state σ unit := λ s' s, ((), s') @[inline] def write' {σ : Type u} : σ → state σ punit := λ s' s, (punit.star, s') end state def state_t (σ : Type u) (m : Type u → Type v) [monad m] (α : Type u) : Type (max u v) := σ → m (α × σ) section variable {σ : Type u} variable {m : Type u → Type v} variable [monad m] variables {α β : Type u} def state_t_return (a : α) : state_t σ m α := λ s, show m (α × σ), from return (a, s) def state_t_bind (act₁ : state_t σ m α) (act₂ : α → state_t σ m β) : state_t σ m β := λ s, show m (β × σ), from do (a, new_s) ← act₁ s, act₂ a new_s end instance (σ : Type u) (m : Type u → Type v) [monad m] : monad (state_t σ m) := {pure := @state_t_return σ m _, bind := @state_t_bind σ m _, id_map := begin intros, apply funext, intro, simp [state_t_bind, state_t_return, function.comp, return], assert h : state_t_bind._match_1 (λ (x : α) (s : σ), @pure m _ _ (x, s)) = pure, { apply funext, intro s, cases s, apply rfl }, { rw h, apply @monad.bind_pure _ σ }, end, pure_bind := begin intros, apply funext, intro, simp [state_t_bind, state_t_return, monad.pure_bind] end, bind_assoc := begin intros, apply funext, intro, simp [state_t_bind, state_t_return, monad.bind_assoc], apply congr_arg, apply funext, intro r, cases r, refl end} section variable {σ : Type u} variable {m : Type u → Type v} variable [monad m] variable [alternative m] variable {α : Type u} def state_t_orelse (act₁ act₂ : state_t σ m α) : state_t σ m α := λ s, act₁ s <|> act₂ s def state_t_failure : state_t σ m α := λ s, failure end instance (σ : Type u) (m : Type u → Type v) [alternative m] [monad m] : alternative (state_t σ m) := { state_t.monad σ m with failure := @state_t_failure σ m _ _, orelse := @state_t_orelse σ m _ _ } namespace state_t def read {σ : Type u} {m : Type u → Type v} [monad m] : state_t σ m σ := λ s, return (s, s) def write {σ : Type} {m : Type → Type v} [monad m] : σ → state_t σ m unit := λ s' s, return ((), s') def write' {σ : Type u} {m : Type u → Type v} [monad m] : σ → state_t σ m punit := λ s' s, return (punit.star, s') def modify {σ : Type} {m : Type → Type v} [monad m] (f : σ → σ) : state_t σ m unit := do s ← read, write (f s) def modify' {σ : Type u} {m : Type u → Type v} [monad m] (f : σ → σ) : state_t σ m punit := do s ← read, write' (f s) def lift {α σ : Type u} {m : Type u → Type v} [monad m] (t : m α) : state_t σ m α := λ s, do a ← t, return (a, s) end state_t
ceb14443a367a07e815ca583d1c39599628b50ed
94e33a31faa76775069b071adea97e86e218a8ee
/src/set_theory/ordinal/principal.lean
3a21f695563bea2a7bfa1f6237b4897a563b0975
[ "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
16,448
lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import set_theory.ordinal.fixed_point /-! ### Principal ordinals We define principal or indecomposable ordinals, and we prove the standard properties about them. ### Main definitions and results * `principal`: A principal or indecomposable ordinal under some binary operation. We include 0 and any other typically excluded edge cases for simplicity. * `unbounded_principal`: Principal ordinals are unbounded. * `principal_add_iff_zero_or_omega_opow`: The main characterization theorem for additive principal ordinals. * `principal_mul_iff_le_two_or_omega_opow_opow`: The main characterization theorem for multiplicative principal ordinals. ### Todo * Prove that exponential principal ordinals are 0, 1, 2, ω, or epsilon numbers, i.e. fixed points of `λ x, ω ^ x`. -/ universe u noncomputable theory open order namespace ordinal local infixr ^ := @pow ordinal ordinal ordinal.has_pow /-! ### Principal ordinals -/ /-- An ordinal `o` is said to be principal or indecomposable under an operation when the set of ordinals less than it is closed under that operation. In standard mathematical usage, this term is almost exclusively used for additive and multiplicative principal ordinals. For simplicity, we break usual convention and regard 0 as principal. -/ def principal (op : ordinal → ordinal → ordinal) (o : ordinal) : Prop := ∀ ⦃a b⦄, a < o → b < o → op a b < o theorem principal_iff_principal_swap {op : ordinal → ordinal → ordinal} {o : ordinal} : principal op o ↔ principal (function.swap op) o := by split; exact λ h a b ha hb, h hb ha theorem principal_zero {op : ordinal → ordinal → ordinal} : principal op 0 := λ a _ h, (ordinal.not_lt_zero a h).elim @[simp] theorem principal_one_iff {op : ordinal → ordinal → ordinal} : principal op 1 ↔ op 0 0 = 0 := begin refine ⟨λ h, _, λ h a b ha hb, _⟩, { rwa ←lt_one_iff_zero, exact h zero_lt_one zero_lt_one }, { rwa [lt_one_iff_zero, ha, hb] at * } end theorem principal.iterate_lt {op : ordinal → ordinal → ordinal} {a o : ordinal} (hao : a < o) (ho : principal op o) (n : ℕ) : (op a)^[n] a < o := begin induction n with n hn, { rwa function.iterate_zero }, { rw function.iterate_succ', exact ho hao hn } end theorem op_eq_self_of_principal {op : ordinal → ordinal → ordinal} {a o : ordinal.{u}} (hao : a < o) (H : is_normal (op a)) (ho : principal op o) (ho' : is_limit o) : op a o = o := begin refine le_antisymm _ (H.self_le _), rw [←is_normal.bsup_eq.{u u} H ho', bsup_le_iff], exact λ b hbo, (ho hao hbo).le end theorem nfp_le_of_principal {op : ordinal → ordinal → ordinal} {a o : ordinal} (hao : a < o) (ho : principal op o) : nfp (op a) a ≤ o := nfp_le $ λ n, (ho.iterate_lt hao n).le /-! ### Principal ordinals are unbounded -/ /-- The least strict upper bound of `op` applied to all pairs of ordinals less than `o`. This is essentially a two-argument version of `ordinal.blsub`. -/ def blsub₂ (op : ordinal → ordinal → ordinal) (o : ordinal) : ordinal := lsub (λ x : o.out.α × o.out.α, op (typein (<) x.1) (typein (<) x.2)) theorem lt_blsub₂ (op : ordinal → ordinal → ordinal) {o : ordinal} {a b : ordinal} (ha : a < o) (hb : b < o) : op a b < blsub₂ op o := begin convert lt_lsub _ (prod.mk (enum (<) a (by rwa type_lt)) (enum (<) b (by rwa type_lt))), simp only [typein_enum] end theorem principal_nfp_blsub₂ (op : ordinal → ordinal → ordinal) (o : ordinal) : principal op (nfp (blsub₂.{u u} op) o) := λ a b ha hb, begin rw lt_nfp at *, cases ha with m hm, cases hb with n hn, cases le_total ((blsub₂.{u u} op)^[m] o) ((blsub₂.{u u} op)^[n] o) with h h, { use n + 1, rw function.iterate_succ', exact lt_blsub₂ op (hm.trans_le h) hn }, { use m + 1, rw function.iterate_succ', exact lt_blsub₂ op hm (hn.trans_le h) }, end theorem unbounded_principal (op : ordinal → ordinal → ordinal) : set.unbounded (<) {o | principal op o} := λ o, ⟨_, principal_nfp_blsub₂ op o, (le_nfp _ o).not_lt⟩ /-! #### Additive principal ordinals -/ theorem principal_add_one : principal (+) 1 := principal_one_iff.2 $ zero_add 0 theorem principal_add_of_le_one {o : ordinal} (ho : o ≤ 1) : principal (+) o := begin rcases le_one_iff.1 ho with rfl | rfl, { exact principal_zero }, { exact principal_add_one } end theorem principal_add_is_limit {o : ordinal} (ho₁ : 1 < o) (ho : principal (+) o) : o.is_limit := begin refine ⟨λ ho₀, _, λ a hao, _⟩, { rw ho₀ at ho₁, exact not_lt_of_gt ordinal.zero_lt_one ho₁ }, { cases eq_or_ne a 0 with ha ha, { rw [ha, succ_zero], exact ho₁ }, { refine lt_of_le_of_lt _ (ho hao hao), rwa [←add_one_eq_succ, add_le_add_iff_left, one_le_iff_ne_zero] } } end theorem principal_add_iff_add_left_eq_self {o : ordinal} : principal (+) o ↔ ∀ a < o, a + o = o := begin refine ⟨λ ho a hao, _, λ h a b hao hbo, _⟩, { cases lt_or_le 1 o with ho₁ ho₁, { exact op_eq_self_of_principal hao (add_is_normal a) ho (principal_add_is_limit ho₁ ho) }, { rcases le_one_iff.1 ho₁ with rfl | rfl, { exact (ordinal.not_lt_zero a hao).elim }, { rw lt_one_iff_zero at hao, rw [hao, zero_add] }}}, { rw ←h a hao, exact (add_is_normal a).strict_mono hbo } end theorem exists_lt_add_of_not_principal_add {a} (ha : ¬ principal (+) a) : ∃ (b c) (hb : b < a) (hc : c < a), b + c = a := begin unfold principal at ha, push_neg at ha, rcases ha with ⟨b, c, hb, hc, H⟩, refine ⟨b, _, hb, lt_of_le_of_ne (sub_le_self a b) (λ hab, _), ordinal.add_sub_cancel_of_le hb.le⟩, rw [←sub_le, hab] at H, exact H.not_lt hc end theorem principal_add_iff_add_lt_ne_self {a} : principal (+) a ↔ ∀ ⦃b c⦄, b < a → c < a → b + c ≠ a := ⟨λ ha b c hb hc, (ha hb hc).ne, λ H, begin by_contra' ha, rcases exists_lt_add_of_not_principal_add ha with ⟨b, c, hb, hc, rfl⟩, exact (H hb hc).irrefl end⟩ theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega := begin rcases lt_omega.1 h with ⟨n, rfl⟩, clear h, induction n with n IH, { rw [nat.cast_zero, zero_add] }, { rwa [nat.cast_succ, add_assoc, one_add_of_omega_le (le_refl _)] } end theorem principal_add_omega : principal (+) omega := principal_add_iff_add_left_eq_self.2 (λ a, add_omega) theorem add_omega_opow {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b := begin refine le_antisymm _ (le_add_left _ _), revert h, refine limit_rec_on b (λ h, _) (λ b _ h, _) (λ b l IH h, _), { rw [opow_zero, ← succ_zero, lt_succ_iff, ordinal.le_zero] at h, rw [h, zero_add] }, { rw opow_succ at h, rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩, refine le_trans (add_le_add_right (le_of_lt ax) _) _, rw [opow_succ, ← mul_add, add_omega xo] }, { rcases (lt_opow_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩, exact (((add_is_normal a).trans (opow_is_normal one_lt_omega)).limit_le l).2 (λ y yb, (add_le_add_left (opow_le_opow_right omega_pos (le_max_right _ _)) _).trans (le_trans (IH _ (max_lt xb yb) (ax.trans_le $ opow_le_opow_right omega_pos (le_max_left _ _))) (opow_le_opow_right omega_pos $ le_of_lt $ max_lt xb yb))) } end theorem principal_add_omega_opow (o : ordinal) : principal (+) (omega ^ o) := principal_add_iff_add_left_eq_self.2 (λ a, add_omega_opow) /-- The main characterization theorem for additive principal ordinals. -/ theorem principal_add_iff_zero_or_omega_opow {o : ordinal} : principal (+) o ↔ o = 0 ∨ ∃ a, o = omega ^ a := begin rcases eq_or_ne o 0 with rfl | ho, { simp only [principal_zero, or.inl] }, { rw [principal_add_iff_add_left_eq_self], simp only [ho, false_or], refine ⟨λ H, ⟨_, ((lt_or_eq_of_le (opow_log_le_self _ (ordinal.pos_iff_ne_zero.2 ho))) .resolve_left $ λ h, _).symm⟩, λ ⟨b, e⟩, e.symm ▸ λ a, add_omega_opow⟩, have := H _ h, have := lt_opow_succ_log_self one_lt_omega o, rw [opow_succ, lt_mul_of_limit omega_is_limit] at this, rcases this with ⟨a, ao, h'⟩, rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao, revert h', apply not_lt_of_le, suffices e : omega ^ log omega o * ↑n + o = o, { simpa only [e] using le_add_right (omega ^ log omega o * ↑n) o }, induction n with n IH, {simp only [nat.cast_zero, mul_zero, zero_add]}, simp only [nat.cast_succ, mul_add_one, add_assoc, this, IH] } end theorem opow_principal_add_of_principal_add {a} (ha : principal (+) a) (b : ordinal) : principal (+) (a ^ b) := begin rcases principal_add_iff_zero_or_omega_opow.1 ha with rfl | ⟨c, rfl⟩, { rcases eq_or_ne b 0 with rfl | hb, { rw opow_zero, exact principal_add_one }, { rwa zero_opow hb } }, { rw ←opow_mul, exact principal_add_omega_opow _ } end theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (h₂ : omega ^ b ≤ c) : a + c = c := by rw [← ordinal.add_sub_cancel_of_le h₂, ← add_assoc, add_omega_opow h₁] theorem mul_principal_add_is_principal_add (a : ordinal.{u}) {b : ordinal.{u}} (hb₁ : b ≠ 1) (hb : principal (+) b) : principal (+) (a * b) := begin rcases eq_zero_or_pos a with rfl | ha, { rw zero_mul, exact principal_zero }, { rcases eq_zero_or_pos b with rfl | hb₁', { rw mul_zero, exact principal_zero }, { rw [← succ_le_iff, succ_zero] at hb₁', intros c d hc hd, rw lt_mul_of_limit (principal_add_is_limit (lt_of_le_of_ne hb₁' hb₁.symm) hb) at *, { rcases hc with ⟨x, hx, hx'⟩, rcases hd with ⟨y, hy, hy'⟩, use [x + y, hb hx hy], rw mul_add, exact left.add_lt_add hx' hy' }, assumption' } } end /-! #### Multiplicative principal ordinals -/ theorem principal_mul_one : principal (*) 1 := by { rw principal_one_iff, exact zero_mul _ } theorem principal_mul_two : principal (*) 2 := λ a b ha hb, begin have h₂ : succ (1 : ordinal) = 2 := rfl, rw [←h₂, lt_succ_iff] at *, convert mul_le_mul' ha hb, exact (mul_one 1).symm end theorem principal_mul_of_le_two {o : ordinal} (ho : o ≤ 2) : principal (*) o := begin rcases lt_or_eq_of_le ho with ho | rfl, { have h₂ : succ (1 : ordinal) = 2 := rfl, rw [←h₂, lt_succ_iff] at ho, rcases lt_or_eq_of_le ho with ho | rfl, { rw lt_one_iff_zero.1 ho, exact principal_zero }, { exact principal_mul_one } }, { exact principal_mul_two } end theorem principal_add_of_principal_mul {o : ordinal} (ho : principal (*) o) (ho₂ : o ≠ 2) : principal (+) o := begin cases lt_or_gt_of_ne ho₂ with ho₁ ho₂, { change o < succ 1 at ho₁, rw lt_succ_iff at ho₁, exact principal_add_of_le_one ho₁ }, { refine λ a b hao hbo, lt_of_le_of_lt _ (ho (max_lt hao hbo) ho₂), rw mul_two, exact add_le_add (le_max_left a b) (le_max_right a b) } end theorem principal_mul_is_limit {o : ordinal.{u}} (ho₂ : 2 < o) (ho : principal (*) o) : o.is_limit := principal_add_is_limit ((lt_succ 1).trans ho₂) (principal_add_of_principal_mul ho (ne_of_gt ho₂)) theorem principal_mul_iff_mul_left_eq {o : ordinal} : principal (*) o ↔ ∀ a, 0 < a → a < o → a * o = o := begin refine ⟨λ h a ha₀ hao, _, λ h a b hao hbo, _⟩, { cases le_or_gt o 2 with ho ho, { convert one_mul o, apply le_antisymm, { have : a < succ 1 := hao.trans_le ho, rwa lt_succ_iff at this }, { rwa [←succ_le_iff, succ_zero] at ha₀ } }, { exact op_eq_self_of_principal hao (mul_is_normal ha₀) h (principal_mul_is_limit ho h) } }, { rcases eq_or_ne a 0 with rfl | ha, { rwa zero_mul }, rw ←ordinal.pos_iff_ne_zero at ha, rw ←h a ha hao, exact (mul_is_normal ha).strict_mono hbo } end theorem principal_mul_omega : principal (*) omega := λ a b ha hb, match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by { rw [← nat_cast_mul], apply nat_lt_omega } end theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega := principal_mul_iff_mul_left_eq.1 (principal_mul_omega) a a0 ha theorem mul_lt_omega_opow {a b c : ordinal} (c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c := begin rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l, { exact (lt_irrefl _).elim c0 }, { rw opow_succ at ha, rcases ((mul_is_normal $ opow_pos _ omega_pos).limit_lt omega_is_limit).1 ha with ⟨n, hn, an⟩, apply (mul_le_mul_right' (le_of_lt an) _).trans_lt, rw [opow_succ, mul_assoc, mul_lt_mul_iff_left (opow_pos _ omega_pos)], exact principal_mul_omega hn hb }, { rcases ((opow_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩, refine (mul_le_mul' (le_of_lt ax) (le_of_lt hb)).trans_lt _, rw [← opow_succ, opow_lt_opow_iff_right one_lt_omega], exact l.2 _ hx } end theorem mul_omega_opow_opow {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) : a * omega ^ omega ^ b = omega ^ omega ^ b := begin by_cases b0 : b = 0, {rw [b0, opow_zero, opow_one] at h ⊢, exact mul_omega a0 h}, refine le_antisymm _ (by simpa only [one_mul] using mul_le_mul_right' (one_le_iff_pos.2 a0) (omega ^ omega ^ b)), rcases (lt_opow_of_limit omega_ne_zero (opow_is_limit_left omega_is_limit b0)).1 h with ⟨x, xb, ax⟩, apply (mul_le_mul_right' (le_of_lt ax) _).trans, rw [← opow_add, add_omega_opow xb] end theorem principal_mul_omega_opow_opow (o : ordinal) : principal (*) (omega ^ omega ^ o) := principal_mul_iff_mul_left_eq.2 (λ a, mul_omega_opow_opow) theorem principal_add_of_principal_mul_opow {o b : ordinal} (hb : 1 < b) (ho : principal (*) (b ^ o)) : principal (+) o := λ x y hx hy, begin have := ho ((opow_lt_opow_iff_right hb).2 hx) ((opow_lt_opow_iff_right hb).2 hy), rwa [←opow_add, opow_lt_opow_iff_right hb] at this end /-- The main characterization theorem for multiplicative principal ordinals. -/ theorem principal_mul_iff_le_two_or_omega_opow_opow {o : ordinal} : principal (*) o ↔ o ≤ 2 ∨ ∃ a, o = omega ^ omega ^ a := begin refine ⟨λ ho, _, _⟩, { cases le_or_lt o 2 with ho₂ ho₂, { exact or.inl ho₂ }, rcases principal_add_iff_zero_or_omega_opow.1 (principal_add_of_principal_mul ho ho₂.ne') with rfl | ⟨a, rfl⟩, { exact (ordinal.not_lt_zero 2 ho₂).elim }, rcases principal_add_iff_zero_or_omega_opow.1 (principal_add_of_principal_mul_opow one_lt_omega ho) with rfl | ⟨b, rfl⟩, { rw opow_zero at ho₂, exact ((lt_succ 1).not_le ho₂.le).elim }, exact or.inr ⟨b, rfl⟩ }, { rintro (ho₂ | ⟨a, rfl⟩), { exact principal_mul_of_le_two ho₂ }, { exact principal_mul_omega_opow_opow a } } end theorem mul_omega_dvd {a : ordinal} (a0 : 0 < a) (ha : a < omega) : ∀ {b}, omega ∣ b → a * b = b | _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha] theorem mul_eq_opow_log_succ {a b : ordinal.{u}} (ha : 0 < a) (hb : principal (*) b) (hb₂ : 2 < b) : a * b = b ^ succ (log b a) := begin apply le_antisymm, { have hbl := principal_mul_is_limit hb₂ hb, rw [←is_normal.bsup_eq.{u u} (mul_is_normal ha) hbl, bsup_le_iff], intros c hcb, have hb₁ : 1 < b := (lt_succ 1).trans hb₂, have hbo₀ : b ^ b.log a ≠ 0 := ordinal.pos_iff_ne_zero.1 (opow_pos _ (zero_lt_one.trans hb₁)), apply le_trans (mul_le_mul_right' (le_of_lt (lt_mul_succ_div a hbo₀)) c), rw [mul_assoc, opow_succ], refine mul_le_mul_left' (le_of_lt (hb (hbl.2 _ _) hcb)) _, rw [div_lt hbo₀, ←opow_succ], exact lt_opow_succ_log_self hb₁ _ }, { rw opow_succ, exact mul_le_mul_right' (opow_log_le_self b ha) b } end /-! #### Exponential principal ordinals -/ theorem principal_opow_omega : principal (^) omega := λ a b ha hb, match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by { simp_rw ←nat_cast_opow, apply nat_lt_omega } end theorem opow_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega := le_antisymm ((opow_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2 (λ b hb, (principal_opow_omega h hb).le)) (right_le_opow _ a1) end ordinal
cd2808dc46b43dcebb5b3b05300b642d481870a2
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/measure_theory/function/strongly_measurable.lean
89fe9e0cc7b41234cf298d2aee59b00a5130d0fb
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,492
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.function.simple_func_dense /-! # Strongly measurable and finitely strongly measurable functions A function `f` is said to be strongly measurable if `f` is the sequential limit of simple functions. It is said to be finitely strongly measurable with respect to a measure `μ` if the supports of those simple functions have finite measure. If the target space has a second countable topology, strongly measurable and measurable are equivalent. Functions in `Lp` for `0 < p < ∞` are finitely strongly measurable. If the measure is sigma-finite, strongly measurable and finitely strongly measurable are equivalent. The main property of finitely strongly measurable functions is `fin_strongly_measurable.exists_set_sigma_finite`: there exists a measurable set `t` such that the function is supported on `t` and `μ.restrict t` is sigma-finite. As a consequence, we can prove some results for those functions as if the measure was sigma-finite. ## Main definitions * `strongly_measurable f`: `f : α → β` is the limit of a sequence `fs : ℕ → simple_func α β`. * `fin_strongly_measurable f μ`: `f : α → β` is the limit of a sequence `fs : ℕ → simple_func α β` such that for all `n ∈ ℕ`, the measure of the support of `fs n` is finite. * `ae_fin_strongly_measurable f μ`: `f` is almost everywhere equal to a `fin_strongly_measurable` function. * `ae_fin_strongly_measurable.sigma_finite_set`: a measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `μ.restrict t` is sigma-finite. ## Main statements * `ae_fin_strongly_measurable.exists_set_sigma_finite`: there exists a measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `μ.restrict t` is sigma-finite. * `mem_ℒp.ae_fin_strongly_measurable`: if `mem_ℒp f p μ` with `0 < p < ∞`, then `ae_fin_strongly_measurable f μ`. * `Lp.fin_strongly_measurable`: for `0 < p < ∞`, `Lp` functions are finitely strongly measurable. ## References * Hytönen, Tuomas, Jan Van Neerven, Mark Veraar, and Lutz Weis. Analysis in Banach spaces. Springer, 2016. -/ open measure_theory filter topological_space function open_locale ennreal topological_space measure_theory namespace measure_theory local infixr ` →ₛ `:25 := simple_func section definitions variables {α β : Type*} [topological_space β] /-- A function is `strongly_measurable` if it is the limit of simple functions. -/ def strongly_measurable [measurable_space α] (f : α → β) : Prop := ∃ fs : ℕ → α →ₛ β, ∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x)) /-- A function is `fin_strongly_measurable` with respect to a measure if it is the limit of simple functions with support with finite measure. -/ def fin_strongly_measurable [has_zero β] {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ fs : ℕ → α →ₛ β, (∀ n, μ (support (fs n)) < ∞) ∧ (∀ x, tendsto (λ n, fs n x) at_top (𝓝 (f x))) /-- A function is `ae_fin_strongly_measurable` with respect to a measure if it is almost everywhere equal to the limit of a sequence of simple functions with support with finite measure. -/ def ae_fin_strongly_measurable [has_zero β] {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ g, fin_strongly_measurable g μ ∧ f =ᵐ[μ] g end definitions /-! ## Strongly measurable functions -/ lemma subsingleton.strongly_measurable {α β} [measurable_space α] [topological_space β] [subsingleton β] (f : α → β) : strongly_measurable f := begin let f_sf : α →ₛ β := ⟨f, λ x, _, set.subsingleton.finite set.subsingleton_of_subsingleton⟩, { exact ⟨λ n, f_sf, λ x, tendsto_const_nhds⟩, }, { have h_univ : f ⁻¹' {x} = set.univ, by { ext1 y, simp, }, rw h_univ, exact measurable_set.univ, }, end namespace strongly_measurable variables {α β : Type*} {f : α → β} /-- A sequence of simple functions such that `∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x))`. That property is given by `strongly_measurable.tendsto_approx`. -/ protected noncomputable def approx [measurable_space α] [topological_space β] (hf : strongly_measurable f) : ℕ → α →ₛ β := hf.some protected lemma tendsto_approx [measurable_space α] [topological_space β] (hf : strongly_measurable f) : ∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x)) := hf.some_spec lemma fin_strongly_measurable_of_set_sigma_finite [topological_space β] [has_zero β] {m : measurable_space α} {μ : measure α} (hf_meas : strongly_measurable f) {t : set α} (ht : measurable_set t) (hft_zero : ∀ x ∈ tᶜ, f x = 0) (htμ : sigma_finite (μ.restrict t)) : fin_strongly_measurable f μ := begin haveI : sigma_finite (μ.restrict t) := htμ, let S := spanning_sets (μ.restrict t), have hS_meas : ∀ n, measurable_set (S n), from measurable_spanning_sets (μ.restrict t), let f_approx := hf_meas.approx, let fs := λ n, simple_func.restrict (f_approx n) (S n ∩ t), have h_fs_t_compl : ∀ n, ∀ x ∉ t, fs n x = 0, { intros n x hxt, rw simple_func.restrict_apply _ ((hS_meas n).inter ht), refine set.indicator_of_not_mem _ _, simp [hxt], }, refine ⟨fs, _, λ x, _⟩, { simp_rw simple_func.support_eq, refine λ n, (measure_bUnion_finset_le _ _).trans_lt _, refine ennreal.sum_lt_top_iff.mpr (λ y hy, _), rw simple_func.restrict_preimage_singleton _ ((hS_meas n).inter ht), swap, { rw finset.mem_filter at hy, exact hy.2, }, refine (measure_mono (set.inter_subset_left _ _)).trans_lt _, have h_lt_top := measure_spanning_sets_lt_top (μ.restrict t) n, rwa measure.restrict_apply' ht at h_lt_top, }, { by_cases hxt : x ∈ t, swap, { rw [funext (λ n, h_fs_t_compl n x hxt), hft_zero x hxt], exact tendsto_const_nhds, }, have h : tendsto (λ n, (f_approx n) x) at_top (𝓝 (f x)), from hf_meas.tendsto_approx x, obtain ⟨n₁, hn₁⟩ : ∃ n, ∀ m, n ≤ m → fs m x = f_approx m x, { obtain ⟨n, hn⟩ : ∃ n, ∀ m, n ≤ m → x ∈ S m ∩ t, { suffices : ∃ n, ∀ m, n ≤ m → x ∈ S m, { obtain ⟨n, hn⟩ := this, exact ⟨n, λ m hnm, set.mem_inter (hn m hnm) hxt⟩, }, suffices : ∃ n, x ∈ S n, { rcases this with ⟨n, hn⟩, exact ⟨n, λ m hnm, monotone_spanning_sets (μ.restrict t) hnm hn⟩, }, rw [← set.mem_Union, Union_spanning_sets (μ.restrict t)], trivial, }, refine ⟨n, λ m hnm, _⟩, simp_rw [fs, simple_func.restrict_apply _ ((hS_meas m).inter ht), set.indicator_of_mem (hn m hnm)], }, rw tendsto_at_top' at h ⊢, intros s hs, obtain ⟨n₂, hn₂⟩ := h s hs, refine ⟨max n₁ n₂, λ m hm, _⟩, rw hn₁ m ((le_max_left _ _).trans hm.le), exact hn₂ m ((le_max_right _ _).trans hm.le), }, end /-- If the measure is sigma-finite, all strongly measurable functions are `fin_strongly_measurable`. -/ protected lemma fin_strongly_measurable [topological_space β] [has_zero β] {m0 : measurable_space α} (hf : strongly_measurable f) (μ : measure α) [sigma_finite μ] : fin_strongly_measurable f μ := hf.fin_strongly_measurable_of_set_sigma_finite measurable_set.univ (by simp) (by rwa measure.restrict_univ) /-- A strongly measurable function is measurable. -/ protected lemma measurable [measurable_space α] [metric_space β] [measurable_space β] [borel_space β] (hf : strongly_measurable f) : measurable f := measurable_of_tendsto_metric (λ n, (hf.approx n).measurable) (tendsto_pi.mpr hf.tendsto_approx) end strongly_measurable section second_countable_strongly_measurable variables {α β : Type*} [measurable_space α] [measurable_space β] {f : α → β} /-- In a space with second countable topology, measurable implies strongly measurable. -/ lemma _root_.measurable.strongly_measurable [emetric_space β] [opens_measurable_space β] [second_countable_topology β] (hf : measurable f) : strongly_measurable f := begin rcases is_empty_or_nonempty β; resetI, { exact subsingleton.strongly_measurable f, }, { inhabit β, exact ⟨simple_func.approx_on f hf set.univ (default β) (set.mem_univ _), λ x, simple_func.tendsto_approx_on hf (set.mem_univ _) (by simp)⟩, }, end /-- In a space with second countable topology, strongly measurable and measurable are equivalent. -/ lemma strongly_measurable_iff_measurable [metric_space β] [borel_space β] [second_countable_topology β] : strongly_measurable f ↔ measurable f := ⟨λ h, h.measurable, λ h, measurable.strongly_measurable h⟩ end second_countable_strongly_measurable /-! ## Finitely strongly measurable functions -/ namespace fin_strongly_measurable variables {α β : Type*} [has_zero β] {m0 : measurable_space α} {μ : measure α} {f : α → β} lemma ae_fin_strongly_measurable [topological_space β] (hf : fin_strongly_measurable f μ) : ae_fin_strongly_measurable f μ := ⟨f, hf, ae_eq_refl f⟩ section sequence variables [topological_space β] (hf : fin_strongly_measurable f μ) /-- A sequence of simple functions such that `∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x))` and `∀ n, μ (support (hf.approx n)) < ∞`. These properties are given by `fin_strongly_measurable.tendsto_approx` and `fin_strongly_measurable.fin_support_approx`. -/ protected noncomputable def approx : ℕ → α →ₛ β := hf.some protected lemma fin_support_approx : ∀ n, μ (support (hf.approx n)) < ∞ := hf.some_spec.1 protected lemma tendsto_approx : ∀ x, tendsto (λ n, hf.approx n x) at_top (𝓝 (f x)) := hf.some_spec.2 end sequence protected lemma strongly_measurable [topological_space β] (hf : fin_strongly_measurable f μ) : strongly_measurable f := ⟨hf.approx, hf.tendsto_approx⟩ lemma exists_set_sigma_finite [topological_space β] [t2_space β] (hf : fin_strongly_measurable f μ) : ∃ t, measurable_set t ∧ (∀ x ∈ tᶜ, f x = 0) ∧ sigma_finite (μ.restrict t) := begin rcases hf with ⟨fs, hT_lt_top, h_approx⟩, let T := λ n, support (fs n), have hT_meas : ∀ n, measurable_set (T n), from λ n, simple_func.measurable_set_support (fs n), let t := ⋃ n, T n, refine ⟨t, measurable_set.Union hT_meas, _, _⟩, { have h_fs_zero : ∀ n, ∀ x ∈ tᶜ, fs n x = 0, { intros n x hxt, rw [set.mem_compl_iff, set.mem_Union, not_exists] at hxt, simpa using (hxt n), }, refine λ x hxt, tendsto_nhds_unique (h_approx x) _, rw funext (λ n, h_fs_zero n x hxt), exact tendsto_const_nhds, }, { refine measure.finite_spanning_sets_in.sigma_finite _ _, { exact set.range (λ n, tᶜ ∪ T n), }, { refine ⟨λ n, tᶜ ∪ T n, λ n, set.mem_range_self _, λ n, _, _⟩, { rw [measure.restrict_apply' (measurable_set.Union hT_meas), set.union_inter_distrib_right, set.compl_inter_self t, set.empty_union], exact (measure_mono (set.inter_subset_left _ _)).trans_lt (hT_lt_top n), }, rw ← set.union_Union tᶜ T, exact set.compl_union_self _, }, { intros s hs, rw set.mem_range at hs, cases hs with n hsn, rw ← hsn, exact (measurable_set.compl (measurable_set.Union hT_meas)).union (hT_meas n), }, }, end /-- A finitely strongly measurable function is measurable. -/ protected lemma measurable [metric_space β] [measurable_space β] [borel_space β] (hf : fin_strongly_measurable f μ) : measurable f := measurable_of_tendsto_metric (λ n, (hf.some n).measurable) (tendsto_pi.mpr hf.some_spec.2) end fin_strongly_measurable namespace ae_fin_strongly_measurable variables {α β : Type*} {m : measurable_space α} {μ : measure α} [has_zero β] [topological_space β] [t2_space β] {f : α → β} lemma exists_set_sigma_finite (hf : ae_fin_strongly_measurable f μ) : ∃ t, measurable_set t ∧ f =ᵐ[μ.restrict tᶜ] 0 ∧ sigma_finite (μ.restrict t) := begin rcases hf with ⟨g, hg, hfg⟩, obtain ⟨t, ht, hgt_zero, htμ⟩ := hg.exists_set_sigma_finite, refine ⟨t, ht, _, htμ⟩, refine eventually_eq.trans (ae_restrict_of_ae hfg) _, rw [eventually_eq, ae_restrict_iff' ht.compl], exact eventually_of_forall hgt_zero, end /-- A measurable set `t` such that `f =ᵐ[μ.restrict tᶜ] 0` and `sigma_finite (μ.restrict t)`. -/ def sigma_finite_set (hf : ae_fin_strongly_measurable f μ) : set α := hf.exists_set_sigma_finite.some protected lemma measurable_set (hf : ae_fin_strongly_measurable f μ) : measurable_set hf.sigma_finite_set := hf.exists_set_sigma_finite.some_spec.1 lemma ae_eq_zero_compl (hf : ae_fin_strongly_measurable f μ) : f =ᵐ[μ.restrict hf.sigma_finite_setᶜ] 0 := hf.exists_set_sigma_finite.some_spec.2.1 instance sigma_finite_restrict (hf : ae_fin_strongly_measurable f μ) : sigma_finite (μ.restrict hf.sigma_finite_set) := hf.exists_set_sigma_finite.some_spec.2.2 end ae_fin_strongly_measurable variables {α G : Type*} {p : ℝ≥0∞} {m m0 : measurable_space α} {μ : measure α} [normed_group G] [measurable_space G] [borel_space G] [second_countable_topology G] {f : α → G} /-- In a space with second countable topology and a sigma-finite measure, `fin_strongly_measurable` and `measurable` are equivalent. -/ lemma fin_strongly_measurable_iff_measurable {m0 : measurable_space α} (μ : measure α) [sigma_finite μ] : fin_strongly_measurable f μ ↔ measurable f := ⟨λ h, h.measurable, λ h, (measurable.strongly_measurable h).fin_strongly_measurable μ⟩ /-- In a space with second countable topology and a sigma-finite measure, `ae_fin_strongly_measurable` and `ae_measurable` are equivalent. -/ lemma ae_fin_strongly_measurable_iff_ae_measurable {m0 : measurable_space α} (μ : measure α) [sigma_finite μ] : ae_fin_strongly_measurable f μ ↔ ae_measurable f μ := by simp_rw [ae_fin_strongly_measurable, ae_measurable, fin_strongly_measurable_iff_measurable] lemma mem_ℒp.fin_strongly_measurable_of_measurable (hf : mem_ℒp f p μ) (hf_meas : measurable f) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : fin_strongly_measurable f μ := begin let fs := simple_func.approx_on f hf_meas set.univ 0 (set.mem_univ _), refine ⟨fs, _, _⟩, { have h_fs_Lp : ∀ n, mem_ℒp (fs n) p μ, from simple_func.mem_ℒp_approx_on_univ hf_meas hf, exact λ n, (fs n).measure_support_lt_top_of_mem_ℒp (h_fs_Lp n) hp_ne_zero hp_ne_top, }, { exact λ x, simple_func.tendsto_approx_on hf_meas (set.mem_univ 0) (by simp), }, end lemma mem_ℒp.ae_fin_strongly_measurable (hf : mem_ℒp f p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : ae_fin_strongly_measurable f μ := ⟨hf.ae_measurable.mk f, ((mem_ℒp_congr_ae hf.ae_measurable.ae_eq_mk).mp hf).fin_strongly_measurable_of_measurable hf.ae_measurable.measurable_mk hp_ne_zero hp_ne_top, hf.ae_measurable.ae_eq_mk⟩ lemma integrable.ae_fin_strongly_measurable (hf : integrable f μ) : ae_fin_strongly_measurable f μ := (mem_ℒp_one_iff_integrable.mpr hf).ae_fin_strongly_measurable one_ne_zero ennreal.coe_ne_top lemma Lp.fin_strongly_measurable (f : Lp G p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : fin_strongly_measurable f μ := (Lp.mem_ℒp f).fin_strongly_measurable_of_measurable (Lp.measurable f) hp_ne_zero hp_ne_top end measure_theory
356b7899ab644ea0689d3dc03ad8ebe463d19f4f
649957717d58c43b5d8d200da34bf374293fe739
/src/category_theory/whiskering.lean
9a27ddbc696b8a6bcd36076fdd2c4b9ec2f3e801
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
7,853
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.natural_isomorphism namespace category_theory universes u₁ v₁ u₂ v₂ u₃ v₃ u₄ v₄ section variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] (E : Type u₃) [ℰ : category.{v₃} E] include 𝒞 𝒟 ℰ def whiskering_left : (C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E)) := { obj := λ F, { obj := λ G, F ⋙ G, map := λ G H α, { app := λ c, α.app (F.obj c), naturality' := by intros X Y f; rw [functor.comp_map, functor.comp_map, α.naturality] } }, map := λ F G τ, { app := λ H, { app := λ c, H.map (τ.app c), naturality' := λ X Y f, begin dsimp, rw [←H.map_comp, ←H.map_comp, ←τ.naturality] end }, naturality' := λ X Y f, begin ext1, dsimp, rw [f.naturality] end } } def whiskering_right : (D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E)) := { obj := λ H, { obj := λ F, F ⋙ H, map := λ _ _ α, { app := λ c, H.map (α.app c), naturality' := by intros X Y f; rw [functor.comp_map, functor.comp_map, ←H.map_comp, ←H.map_comp, α.naturality] } }, map := λ G H τ, { app := λ F, { app := λ c, τ.app (F.obj c), naturality' := λ X Y f, begin dsimp, rw [τ.naturality] end }, naturality' := λ X Y f, begin ext1, dsimp, rw [←nat_trans.naturality] end } } variables {C} {D} {E} def whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) : (F ⋙ G) ⟶ (F ⋙ H) := ((whiskering_left C D E).obj F).map α @[simp] lemma whiskering_left_obj_obj (F : C ⥤ D) (G : D ⥤ E) : ((whiskering_left C D E).obj F).obj G = F ⋙ G := rfl @[simp] lemma whiskering_left_obj_map (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) : ((whiskering_left C D E).obj F).map α = whisker_left F α := rfl @[simp] lemma whiskering_left_map_app_app {F G : C ⥤ D} (τ : F ⟶ G) (H : D ⥤ E) (c) : (((whiskering_left C D E).map τ).app H).app c = H.map (τ.app c) := rfl @[simp] lemma whisker_left.app (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) (X : C) : (whisker_left F α).app X = α.app (F.obj X) := rfl def whisker_right {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) : (G ⋙ F) ⟶ (H ⋙ F) := ((whiskering_right C D E).obj F).map α @[simp] lemma whiskering_right_obj_obj (G : C ⥤ D) (F : D ⥤ E) : ((whiskering_right C D E).obj F).obj G = G ⋙ F := rfl @[simp] lemma whiskering_right_obj_map {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) : ((whiskering_right C D E).obj F).map α = whisker_right α F := rfl @[simp] lemma whiskering_right_map_app_app (F : C ⥤ D) {G H : D ⥤ E} (τ : G ⟶ H) (c) : (((whiskering_right C D E).map τ).app F).app c = τ.app (F.obj c) := rfl @[simp] lemma whisker_right.app {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) (X : C) : (whisker_right α F).app X = F.map (α.app X) := rfl @[simp] lemma whisker_left_id (F : C ⥤ D) {G : D ⥤ E} : whisker_left F (nat_trans.id G) = nat_trans.id (F.comp G) := rfl @[simp] lemma whisker_left_id' (F : C ⥤ D) {G : D ⥤ E} : whisker_left F (𝟙 G) = 𝟙 (F.comp G) := rfl @[simp] lemma whisker_right_id {G : C ⥤ D} (F : D ⥤ E) : whisker_right (nat_trans.id G) F = nat_trans.id (G.comp F) := ((whiskering_right C D E).obj F).map_id _ @[simp] lemma whisker_right_id' {G : C ⥤ D} (F : D ⥤ E) : whisker_right (𝟙 G) F = 𝟙 (G.comp F) := ((whiskering_right C D E).obj F).map_id _ @[simp] lemma whisker_left_comp (F : C ⥤ D) {G H K : D ⥤ E} (α : G ⟶ H) (β : H ⟶ K) : whisker_left F (α ≫ β) = (whisker_left F α) ≫ (whisker_left F β) := rfl @[simp] lemma whisker_right_comp {G H K : C ⥤ D} (α : G ⟶ H) (β : H ⟶ K) (F : D ⥤ E) : whisker_right (α ≫ β) F = (whisker_right α F) ≫ (whisker_right β F) := ((whiskering_right C D E).obj F).map_comp α β def iso_whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (F ⋙ G) ≅ (F ⋙ H) := ((whiskering_left C D E).obj F).map_iso α @[simp] lemma iso_whisker_left_hom (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (iso_whisker_left F α).hom = whisker_left F α.hom := rfl @[simp] lemma iso_whisker_left_inv (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (iso_whisker_left F α).inv = whisker_left F α.inv := rfl def iso_whisker_right {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (G ⋙ F) ≅ (H ⋙ F) := ((whiskering_right C D E).obj F).map_iso α @[simp] lemma iso_whisker_right_hom {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (iso_whisker_right α F).hom = whisker_right α.hom F := rfl @[simp] lemma iso_whisker_right_inv {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (iso_whisker_right α F).inv = whisker_right α.inv F := rfl instance is_iso_whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) [is_iso α] : is_iso (whisker_left F α) := { .. iso_whisker_left F (as_iso α) } instance is_iso_whisker_right {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) [is_iso α] : is_iso (whisker_right α F) := { .. iso_whisker_right (as_iso α) F } variables {B : Type u₄} [ℬ : category.{v₄} B] include ℬ local attribute [elab_simple] whisker_left whisker_right @[simp] lemma whisker_left_twice (F : B ⥤ C) (G : C ⥤ D) {H K : D ⥤ E} (α : H ⟶ K) : whisker_left F (whisker_left G α) = whisker_left (F ⋙ G) α := rfl @[simp] lemma whisker_right_twice {H K : B ⥤ C} (F : C ⥤ D) (G : D ⥤ E) (α : H ⟶ K) : whisker_right (whisker_right α F) G = whisker_right α (F ⋙ G) := rfl lemma whisker_right_left (F : B ⥤ C) {G H : C ⥤ D} (α : G ⟶ H) (K : D ⥤ E) : whisker_right (whisker_left F α) K = whisker_left F (whisker_right α K) := rfl end namespace functor universes u₅ v₅ variables {A : Type u₁} [𝒜 : category.{v₁} A] variables {B : Type u₂} [ℬ : category.{v₂} B] include 𝒜 ℬ def left_unitor (F : A ⥤ B) : ((functor.id _) ⋙ F) ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } @[simp] lemma left_unitor_hom_app {F : A ⥤ B} {X} : F.left_unitor.hom.app X = 𝟙 _ := rfl @[simp] lemma left_unitor_inv_app {F : A ⥤ B} {X} : F.left_unitor.inv.app X = 𝟙 _ := rfl def right_unitor (F : A ⥤ B) : (F ⋙ (functor.id _)) ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } @[simp] lemma right_unitor_hom_app {F : A ⥤ B} {X} : F.right_unitor.hom.app X = 𝟙 _ := rfl @[simp] lemma right_unitor_inv_app {F : A ⥤ B} {X} : F.right_unitor.inv.app X = 𝟙 _ := rfl variables {C : Type u₃} [𝒞 : category.{v₃} C] variables {D : Type u₄} [𝒟 : category.{v₄} D] include 𝒞 𝒟 def associator (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) : ((F ⋙ G) ⋙ H) ≅ (F ⋙ (G ⋙ H)) := { hom := { app := λ _, 𝟙 _ }, inv := { app := λ _, 𝟙 _ } } @[simp] lemma associator_hom_app {F : A ⥤ B} {G : B ⥤ C} {H : C ⥤ D} {X} : (associator F G H).hom.app X = 𝟙 _ := rfl @[simp] lemma associator_inv_app {F : A ⥤ B} {G : B ⥤ C} {H : C ⥤ D} {X} : (associator F G H).inv.app X = 𝟙 _ := rfl omit 𝒟 lemma triangle (F : A ⥤ B) (G : B ⥤ C) : (associator F (functor.id B) G).hom ≫ (whisker_left F (left_unitor G).hom) = (whisker_right (right_unitor F).hom G) := begin ext1, dsimp [associator, left_unitor, right_unitor], simp end variables {E : Type u₅} [ℰ : category.{v₅} E] include 𝒟 ℰ variables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) (K : D ⥤ E) lemma pentagon : (whisker_right (associator F G H).hom K) ≫ (associator F (G ⋙ H) K).hom ≫ (whisker_left F (associator G H K).hom) = ((associator (F ⋙ G) H K).hom ≫ (associator F G (H ⋙ K)).hom) := begin ext1, dsimp [associator], simp, end end functor end category_theory
60d1d58fa7f093aea82c50ee0492cf13506a7e10
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/sheaves/sheaf_condition/equalizer_products.lean
991aa7e5d3a5e567fe82c622baaf5d44e98e118b
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,615
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.full_subcategory import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.products import tactic.elementwise import topology.sheaves.presheaf /-! # The sheaf condition in terms of an equalizer of products Here we set up the machinery for the "usual" definition of the sheaf condition, e.g. as in https://stacks.math.columbia.edu/tag/0072 in terms of an equalizer diagram where the two objects are `∏ F.obj (U i)` and `∏ F.obj (U i) ⊓ (U j)`. -/ universes v u noncomputable theory open category_theory open category_theory.limits open topological_space open opposite open topological_space.opens namespace Top variables {C : Type u} [category.{v} C] [has_products C] variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X) namespace presheaf namespace sheaf_condition_equalizer_products /-- The product of the sections of a presheaf over a family of open sets. -/ def pi_opens : C := ∏ (λ i : ι, F.obj (op (U i))) /-- The product of the sections of a presheaf over the pairwise intersections of a family of open sets. -/ def pi_inters : C := ∏ (λ p : ι × ι, F.obj (op (U p.1 ⊓ U p.2))) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U i` to `U i ⊓ U j`. -/ def left_res : pi_opens F U ⟶ pi_inters F U := pi.lift (λ p : ι × ι, pi.π _ p.1 ≫ F.map (inf_le_left (U p.1) (U p.2)).op) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def right_res : pi_opens F U ⟶ pi_inters F U := pi.lift (λ p : ι × ι, pi.π _ p.2 ≫ F.map (inf_le_right (U p.1) (U p.2)).op) /-- The morphism `F.obj U ⟶ Π F.obj (U i)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def res : F.obj (op (supr U)) ⟶ pi_opens F U := pi.lift (λ i : ι, F.map (topological_space.opens.le_supr U i).op) @[simp, elementwise] lemma res_π (i : ι) : res F U ≫ limit.π _ i = F.map (opens.le_supr U i).op := by rw [res, limit.lift_π, fan.mk_π_app] @[elementwise] lemma w : res F U ≫ left_res F U = res F U ≫ right_res F U := begin dsimp [res, left_res, right_res], ext, simp only [limit.lift_π, limit.lift_π_assoc, fan.mk_π_app, category.assoc], rw [←F.map_comp], rw [←F.map_comp], congr, end /-- The equalizer diagram for the sheaf condition. -/ @[reducible] def diagram : walking_parallel_pair.{v} ⥤ C := parallel_pair (left_res F U) (right_res F U) /-- The restriction map `F.obj U ⟶ Π F.obj (U i)` gives a cone over the equalizer diagram for the sheaf condition. The sheaf condition asserts this cone is a limit cone. -/ def fork : fork.{v} (left_res F U) (right_res F U) := fork.of_ι _ (w F U) @[simp] lemma fork_X : (fork F U).X = F.obj (op (supr U)) := rfl @[simp] lemma fork_ι : (fork F U).ι = res F U := rfl @[simp] lemma fork_π_app_walking_parallel_pair_zero : (fork F U).π.app walking_parallel_pair.zero = res F U := rfl @[simp] lemma fork_π_app_walking_parallel_pair_one : (fork F U).π.app walking_parallel_pair.one = res F U ≫ left_res F U := rfl variables {F} {G : presheaf C X} /-- Isomorphic presheaves have isomorphic `pi_opens` for any cover `U`. -/ @[simp] def pi_opens.iso_of_iso (α : F ≅ G) : pi_opens F U ≅ pi_opens G U := pi.map_iso (λ X, α.app _) /-- Isomorphic presheaves have isomorphic `pi_inters` for any cover `U`. -/ @[simp] def pi_inters.iso_of_iso (α : F ≅ G) : pi_inters F U ≅ pi_inters G U := pi.map_iso (λ X, α.app _) /-- Isomorphic presheaves have isomorphic sheaf condition diagrams. -/ def diagram.iso_of_iso (α : F ≅ G) : diagram F U ≅ diagram G U := nat_iso.of_components begin rintro ⟨⟩, exact pi_opens.iso_of_iso U α, exact pi_inters.iso_of_iso U α end begin rintro ⟨⟩ ⟨⟩ ⟨⟩, { simp, }, { ext, simp [left_res], }, { ext, simp [right_res], }, { simp, }, end. /-- If `F G : presheaf C X` are isomorphic presheaves, then the `fork F U`, the canonical cone of the sheaf condition diagram for `F`, is isomorphic to `fork F G` postcomposed with the corresponding isomorphism between sheaf condition diagrams. -/ def fork.iso_of_iso (α : F ≅ G) : fork F U ≅ (cones.postcompose (diagram.iso_of_iso U α).inv).obj (fork G U) := begin fapply fork.ext, { apply α.app, }, { ext, dunfold fork.ι, -- Ugh, `simp` can't unfold abbreviations. simp [res, diagram.iso_of_iso], } end section open_embedding variables {V : Top.{v}} {j : V ⟶ X} (oe : open_embedding j) variables (𝒰 : ι → opens V) /-- Push forward a cover along an open embedding. -/ @[simp] def cover.of_open_embedding : ι → opens X := (λ i, oe.is_open_map.functor.obj (𝒰 i)) /-- The isomorphism between `pi_opens` corresponding to an open embedding. -/ @[simp] def pi_opens.iso_of_open_embedding : pi_opens (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ pi_opens F (cover.of_open_embedding oe 𝒰) := pi.map_iso (λ X, F.map_iso (iso.refl _)) /-- The isomorphism between `pi_inters` corresponding to an open embedding. -/ @[simp] def pi_inters.iso_of_open_embedding : pi_inters (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ pi_inters F (cover.of_open_embedding oe 𝒰) := pi.map_iso (λ X, F.map_iso begin dsimp [is_open_map.functor], exact iso.op { hom := hom_of_le (by { simp only [oe.to_embedding.inj, set.image_inter], exact le_rfl, }), inv := hom_of_le (by { simp only [oe.to_embedding.inj, set.image_inter], exact le_rfl, }), }, end) /-- The isomorphism of sheaf condition diagrams corresponding to an open embedding. -/ def diagram.iso_of_open_embedding : diagram (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ diagram F (cover.of_open_embedding oe 𝒰) := nat_iso.of_components begin rintro ⟨⟩, exact pi_opens.iso_of_open_embedding oe 𝒰, exact pi_inters.iso_of_open_embedding oe 𝒰 end begin rintro ⟨⟩ ⟨⟩ ⟨⟩, { simp, }, { ext, dsimp [left_res, is_open_map.functor], simp only [limit.lift_π, cones.postcompose_obj_π, iso.op_hom, discrete.nat_iso_hom_app, functor.map_iso_refl, functor.map_iso_hom, lim_map_π_assoc, limit.lift_map, fan.mk_π_app, nat_trans.comp_app, category.assoc], dsimp, rw [category.id_comp, ←F.map_comp], refl, }, { ext, dsimp [right_res, is_open_map.functor], simp only [limit.lift_π, cones.postcompose_obj_π, iso.op_hom, discrete.nat_iso_hom_app, functor.map_iso_refl, functor.map_iso_hom, lim_map_π_assoc, limit.lift_map, fan.mk_π_app, nat_trans.comp_app, category.assoc], dsimp, rw [category.id_comp, ←F.map_comp], refl, }, { simp, }, end. /-- If `F : presheaf C X` is a presheaf, and `oe : U ⟶ X` is an open embedding, then the sheaf condition fork for a cover `𝒰` in `U` for the composition of `oe` and `F` is isomorphic to sheaf condition fork for `oe '' 𝒰`, precomposed with the isomorphism of indexing diagrams `diagram.iso_of_open_embedding`. We use this to show that the restriction of sheaf along an open embedding is still a sheaf. -/ def fork.iso_of_open_embedding : fork (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ (cones.postcompose (diagram.iso_of_open_embedding oe 𝒰).inv).obj (fork F (cover.of_open_embedding oe 𝒰)) := begin fapply fork.ext, { dsimp [is_open_map.functor], exact F.map_iso (iso.op { hom := hom_of_le (by simp only [supr_s, supr_mk, le_def, subtype.coe_mk, set.le_eq_subset, set.image_Union]), inv := hom_of_le (by simp only [supr_s, supr_mk, le_def, subtype.coe_mk, set.le_eq_subset, set.image_Union]) }), }, { ext, dunfold fork.ι, -- Ugh, it is unpleasant that we need this. simp only [res, diagram.iso_of_open_embedding, discrete.nat_iso_inv_app, functor.map_iso_inv, limit.lift_π, cones.postcompose_obj_π, functor.comp_map, fork_π_app_walking_parallel_pair_zero, pi_opens.iso_of_open_embedding, nat_iso.of_components.inv_app, functor.map_iso_refl, functor.op_map, limit.lift_map, fan.mk_π_app, nat_trans.comp_app, quiver.hom.unop_op, category.assoc, lim_map_eq_lim_map], dsimp, rw [category.comp_id, ←F.map_comp], refl, }, end end open_embedding end sheaf_condition_equalizer_products end presheaf end Top
f00e5c5d1fc343f376dce3426a70acf6c02540d7
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/topology/bases.lean
b6501fc31817a7b15fe42ec38234a19ea2c5083c
[ "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
16,194
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.continuous_on open set filter classical open_locale topological_space filter noncomputable theory 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).nonempty}) := let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty} 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₂, ⟨hft₁.union hft₂, union_subset ht₁b ht₂b, ie.symm ▸ ⟨_, h⟩⟩, ie⟩, h, subset.refl _⟩, eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, ⟨finite_empty, empty_subset _, by rw sInter_empty; exact ⟨a, mem_univ 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, s.eq_empty_or_nonempty.elim (assume : s = ∅, by rw [this]; apply @is_open_empty _ _) (assume : s.nonempty, 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, is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → 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, binfi_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_topological_basis.nhds_has_basis {b : set (set α)} (hb : is_topological_basis b) {a : α} : (𝓝 a).has_basis (λ t : set α, t ∈ b ∧ a ∈ t) (λ t, t) := ⟨λ s, (mem_nhds_of_is_topological_basis hb).trans $ by simp only [exists_prop, and_assoc]⟩ lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : 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 : 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 : 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 : 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, available through `topological_space.exists_countable_dense`. If `α` is also known to be nonempty, then `topological_space.dense_seq` provides a sequence `ℕ → α` with dense range, see `topological_space.dense_range_dense_seq`. If `α` is a uniform space with countably generated uniformity filter (e.g., an `emetric_space`), then this condition is equivalent to `topological_space.second_countable_topology α`. In this case the latter should be used as a typeclass argument in theorems because Lean can automatically deduce `separable_space` from `second_countable_topology` but it can't deduce `second_countable_topology` and `emetric_space`. -/ class separable_space : Prop := (exists_countable_dense : ∃s:set α, countable s ∧ dense s) lemma exists_countable_dense [separable_space α] : ∃ s : set α, countable s ∧ dense s := separable_space.exists_countable_dense /-- A nonempty separable space admits a sequence with dense range. Instead of running `cases` on the conclusion of this lemma, you might want to use `topological_space.dense_seq` and `topological_space.dense_range_dense_seq`. If `α` might be empty, then `exists_countable_dense` is the main way to use separability of `α`. -/ lemma exists_dense_seq [separable_space α] [nonempty α] : ∃ u : ℕ → α, dense_range u := begin obtain ⟨s : set α, hs, s_dense⟩ := exists_countable_dense α, cases countable_iff_exists_surjective.mp hs with u hu, exact ⟨u, s_dense.mono hu⟩, end /-- A sequence dense in a non-empty separable topological space. If `α` might be empty, then `exists_countable_dense` is the main way to use separability of `α`. -/ def dense_seq [separable_space α] [nonempty α] : ℕ → α := classical.some (exists_dense_seq α) /-- The sequence `dense_seq α` has dense range. -/ @[simp] lemma dense_range_dense_seq [separable_space α] [nonempty α] : dense_range (dense_seq α) := classical.some_spec (exists_dense_seq α) end topological_space open topological_space /-- If `α` is a separable space and `f : α → β` is a continuous map with dense range, then `β` is a separable space as well. E.g., the completion of a separable uniform space is separable. -/ protected lemma dense_range.separable_space {α β : Type*} [topological_space α] [separable_space α] [topological_space β] {f : α → β} (h : dense_range f) (h' : continuous f) : separable_space β := let ⟨s, s_cnt, s_dense⟩ := exists_countable_dense α in ⟨⟨f '' s, countable.image s_cnt f, h.dense_image h' s_dense⟩⟩ namespace topological_space universe u variables (α : Type u) [t : topological_space α] include t /-- 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).is_countably_generated) namespace first_countable_topology variable {α} lemma tendsto_subseq [first_countable_topology α] {u : ℕ → α} {x : α} (hx : map_cluster_pt x at_top u) : ∃ (ψ : ℕ → ℕ), (strict_mono ψ) ∧ (tendsto (u ∘ ψ) at_top (𝓝 x)) := (nhds_generated_countable x).subseq_tendsto hx end first_countable_topology variables {α} lemma is_countably_generated_nhds [first_countable_topology α] (x : α) : is_countably_generated (𝓝 x) := first_countable_topology.nhds_generated_countable x lemma is_countably_generated_nhds_within [first_countable_topology α] (x : α) (s : set α) : is_countably_generated (𝓝[s] x) := (is_countably_generated_nhds x).inf_principal s variable (α) /-- 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) @[priority 100] -- see Note [lower instance priority] 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 ⟨begin intros, rw [eq, nhds_generate_from], exact is_countably_generated_binfi_principal (hb.mono (assume x, and.right)), end⟩ 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, hb.image _, _⟩ }, 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).nonempty} in ⟨b', ((countable_set_of_finite_subset hb₁).mono (by { simp only [← and_assoc], apply inter_subset_left })).image _, assume ⟨s, ⟨_, _, hn⟩, hp⟩, absurd hn (not_nonempty_iff_eq_empty.2 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 (ha₁.bUnion $ assume u hu, hb₁.bUnion $ 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 with f, simp [pi, eq_comm] }, exact assume a, (hg a).2.2.2.1 end @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := begin rcases is_open_generated_countable_inter α with ⟨b, hbc, hbne, hb, hbU, eq⟩, set S : α → set (set α) := λ a, {s : set α | a ∈ s ∧ s ∈ b}, have nhds_eq : ∀a, 𝓝 a = (⨅ s ∈ S a, 𝓟 s), { intro a, rw [eq, nhds_generate_from] }, have : ∀ s ∈ b, set.nonempty s := assume s hs, ne_empty_iff_nonempty.1 $ λ eq, absurd hs (eq.symm ▸ hbne), choose f hf, refine ⟨⟨⋃ s ∈ b, {f s ‹_›}, hbc.bUnion (λ _ _, countable_singleton _), λ a, _⟩⟩, suffices : (⨅ s ∈ S a, 𝓟 (s ∩ ⋃ t ∈ b, {f t ‹_›})).ne_bot, { obtain ⟨t, htb, hta⟩ : a ∈ ⋃₀ b, { simp only [hbU] }, have A : ∃ s, s ∈ S a := ⟨t, hta, htb⟩, simpa only [← inf_principal, mem_closure_iff_cluster_pt, cluster_pt, nhds_eq, binfi_inf A] using this }, rw [infi_subtype'], haveI : nonempty α := ⟨a⟩, refine infi_ne_bot_of_directed _ _, { rintros ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩, obtain ⟨t, htb, hta, ht⟩ : ∃ t ∈ b, a ∈ t ∧ t ⊆ s₁ ∩ s₂, from hb _ hs₁ _ hs₂ a ⟨has₁, has₂⟩, refine ⟨⟨t, hta, htb⟩, _⟩, simp only [subset_inter_iff] at ht, simp only [principal_mono, subtype.coe_mk, (≥)], exact ⟨inter_subset_inter_left _ ht.1, inter_subset_inter_left _ ht.2⟩ }, rintros ⟨s, hsa, hsb⟩, suffices : (s ∩ ⋃ t ∈ b, {f t ‹_›}).nonempty, { simpa [principal_ne_bot_iff] }, refine ⟨_, hf _ hsb, _⟩, simp only [mem_Union], exact ⟨s, hsb, rfl⟩ end variables {α} lemma is_open_Union_countable [second_countable_topology α] {ι} (s : ι → set α) (H : ∀ i, 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' := (cB.mono (sep_subset _ _)).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, 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, cT.image _, image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs, by rwa [sUnion_image, sUnion_eq_Union]⟩ /-- In a topological space with second countable topology, if `f` is a function that sends each point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`, `x ∈ s`, cover the whole space. -/ lemma countable_cover_nhds [second_countable_topology α] {f : α → set α} (hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, countable s ∧ (⋃ x ∈ s, f x) = univ := begin rcases is_open_Union_countable (λ x, interior (f x)) (λ x, is_open_interior) with ⟨s, hsc, hsU⟩, suffices : (⋃ x ∈ s, interior (f x)) = univ, from ⟨s, hsc, flip eq_univ_of_subset this (bUnion_mono $ λ _ _, interior_subset)⟩, simp only [hsU, eq_univ_iff_forall, mem_Union], exact λ x, ⟨x, mem_interior_iff_mem_nhds.2 (hf x)⟩ end end topological_space
4753d55338c11dfc97e14ee0d3964423841b698e
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/measure_theory/bochner_integration.lean
5dd066624689621ee270b657c5a436c4fbca6056
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
3,632
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou Bochner integral on real normed space -/ import measure_theory.simple_func_dense noncomputable theory local attribute [instance, priority 0] classical.prop_decidable set_option class.instance_max_depth 100 namespace measure_theory open set lattice filter topological_space ennreal emetric universes u v variables {α : Type u} {β : Type v} [measure_space α] {γ : Type*} [normed_group γ] [second_countable_topology γ] namespace l1 variables (α γ) def simple_func : Type* := { f : α →₁ γ // ∃ (s : simple_func α γ) (hs : integrable s), mk s s.measurable hs = f} variables {α γ} local infixr ` →ₛ `:25 := simple_func namespace simple_func open ae_eq_fun def mk (f : measure_theory.simple_func α γ) : integrable f → (α →ₛ γ) := assume h, ⟨l1.mk f f.measurable h , ⟨f, ⟨h, rfl⟩⟩⟩ instance : has_coe (α →ₛ γ) (α →₁ γ) := ⟨subtype.val⟩ instance : metric_space (α →ₛ γ) := metric_space.induced (coe : (α →ₛ γ) → (α →₁ γ)) subtype.val_injective l1.metric_space lemma exists_simple_func_near (f : α →₁ γ) {ε : ℝ} (ε0 : ε > 0) : ∃ s : α →ₛ γ, dist f s < ε := begin rcases f with ⟨⟨f, hfm⟩, hfi⟩, simp only [integrable_mk, quot_mk_eq_mk] at hfi, rcases simple_func_sequence_tendsto' hfm hfi with ⟨F, ⟨h₁, h₂⟩⟩, rw ennreal.tendsto_at_top at h₂, rcases h₂ (ennreal.of_real (ε/2)) (of_real_pos.2 $ half_pos ε0) with ⟨N, hN⟩, have : (∫⁻ (x : α), nndist (F N x) (f x)) < ennreal.of_real ε := calc (∫⁻ (x : α), nndist (F N x) (f x)) ≤ 0 + ennreal.of_real (ε/2) : (hN N (le_refl _)).2 ... < ennreal.of_real ε : by { simp only [zero_add, of_real_lt_of_real_iff ε0], exact half_lt_self ε0 }, { refine ⟨mk (F N) (h₁ N), _⟩, rw dist_comm, rw lt_of_real_iff_to_real_lt _ at this, { simpa [edist_mk_mk', mk, l1.mk, dist_def] }, rw ← lt_top_iff_ne_top, exact lt_trans this (by simp [lt_top_iff_ne_top, of_real_ne_top]) }, { exact zero_ne_top } end lemma uniform_continuous_of_simple_func : uniform_continuous (coe : (α →ₛ γ) → (α →₁ γ)) := uniform_continuous_comap lemma uniform_embedding_of_simple_func : uniform_embedding (coe : (α →ₛ γ) → (α →₁ γ)) := uniform_embedding_comap subtype.val_injective lemma dense_embedding_of_simple_func : dense_embedding (coe : (α →ₛ γ) → (α →₁ γ)) := uniform_embedding_of_simple_func.dense_embedding $ λ f, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨s, h⟩ := exists_simple_func_near f ε0 in ne_empty_iff_exists_mem.2 ⟨_, hε (metric.mem_ball'.2 h), s, rfl⟩ section integral variables [normed_space ℝ γ] def to_simple_func (f : α →ₛ γ) : measure_theory.simple_func α γ := classical.some f.2 -- bochner integration over simple functions in l1 space def integral (f : α →ₛ γ) : γ := (f.to_simple_func).range.sum (λ (x : γ), (ennreal.to_real (volume ((f.to_simple_func) ⁻¹' {x}))) • x) end integral end simple_func open simple_func variables [normed_space ℝ γ] -- bochner integration over functions in l1 space def integral (f : α →₁ γ) : γ := dense_embedding_of_simple_func.to_dense_inducing.extend simple_func.integral f end l1 variables [normed_space ℝ γ] def integral (f : α → γ) : γ := if hf : measurable f ∧ integrable f then (l1.mk f hf.1 hf.2).integral else 0 end measure_theory
14a93f00f05188d8d7219a54c25ddec7684bd556
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/control/state_auto.lean
bfa0e62e8651d54aecb740d57d37c6cf152f10ce
[]
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
9,409
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, Sebastian Ullrich The state monad transformer. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.control.alternative import Mathlib.Lean3Lib.init.control.lift import Mathlib.Lean3Lib.init.control.id import Mathlib.Lean3Lib.init.control.except universes u v l u_1 u_2 u_3 w namespace Mathlib structure state_t (σ : Type u) (m : Type u → Type v) (α : Type u) where run : σ → m (α × σ) def state (σ : Type u) (α : Type u) := state_t σ id α namespace state_t protected def pure {σ : Type u} {m : Type u → Type v} [Monad m] {α : Type u} (a : α) : state_t σ m α := mk fun (s : σ) => pure (a, s) protected def bind {σ : Type u} {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} (x : state_t σ m α) (f : α → state_t σ m β) : state_t σ m β := mk fun (s : σ) => do run x s sorry protected instance monad {σ : Type u} {m : Type u → Type v} [Monad m] : Monad (state_t σ m) := sorry protected def orelse {σ : Type u} {m : Type u → Type v} [Monad m] [alternative m] {α : Type u} (x₁ : state_t σ m α) (x₂ : state_t σ m α) : state_t σ m α := mk fun (s : σ) => run x₁ s <|> run x₂ s protected def failure {σ : Type u} {m : Type u → Type v} [Monad m] [alternative m] {α : Type u} : state_t σ m α := mk fun (s : σ) => failure protected instance alternative {σ : Type u} {m : Type u → Type v} [Monad m] [alternative m] : alternative (state_t σ m) := alternative.mk state_t.failure protected def get {σ : Type u} {m : Type u → Type v} [Monad m] : state_t σ m σ := mk fun (s : σ) => pure (s, s) protected def put {σ : Type u} {m : Type u → Type v} [Monad m] : σ → state_t σ m PUnit := fun (s' : σ) => mk fun (s : σ) => pure (PUnit.unit, s') protected def modify {σ : Type u} {m : Type u → Type v} [Monad m] (f : σ → σ) : state_t σ m PUnit := mk fun (s : σ) => pure (PUnit.unit, f s) protected def lift {σ : Type u} {m : Type u → Type v} [Monad m] {α : Type u} (t : m α) : state_t σ m α := mk fun (s : σ) => do let a ← t pure (a, s) protected instance has_monad_lift {σ : Type u} {m : Type u → Type v} [Monad m] : has_monad_lift m (state_t σ m) := has_monad_lift.mk state_t.lift protected def monad_map {σ : Type u_1} {m : Type u_1 → Type u_2} {m' : Type u_1 → Type u_3} [Monad m] [Monad m'] {α : Type u_1} (f : {α : Type u_1} → m α → m' α) : state_t σ m α → state_t σ m' α := fun (x : state_t σ m α) => mk fun (st : σ) => f (run x st) protected instance monad_functor (σ : Type u_1) (m : Type u_1 → Type u_2) (m' : Type u_1 → Type u_2) [Monad m] [Monad m'] : monad_functor m m' (state_t σ m) (state_t σ m') := monad_functor.mk state_t.monad_map protected def adapt {σ : Type u} {σ' : Type u} {σ'' : Type u} {α : Type u} {m : Type u → Type v} [Monad m] (split : σ → σ' × σ'') (join : σ' → σ'' → σ) (x : state_t σ' m α) : state_t σ m α := mk fun (st : σ) => sorry protected instance monad_except {σ : Type u} {m : Type u → Type v} [Monad m] (ε : outParam (Type u_1)) [monad_except ε m] : monad_except ε (state_t σ m) := monad_except.mk (fun (α : Type u) => state_t.lift ∘ throw) fun (α : Type u) (x : state_t σ m α) (c : ε → state_t σ m α) => mk fun (s : σ) => catch (run x s) fun (e : ε) => run (c e) s end state_t /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monad_lift`. Note: This class can be seen as a simplification of the more "principled" definition ``` class monad_state_lift (σ : out_param (Type u)) (n : Type u → Type u) := (lift {α : Type u} : (∀ {m : Type u → Type u} [monad m], state_t σ m α) → n α) ``` which better describes the intent of "we can lift a `state_t` from anywhere in the monad stack". However, by parametricity the types `∀ m [monad m], σ → m (α × σ)` and `σ → α × σ` should be equivalent because the only way to obtain an `m` is through `pure`. -/ class monad_state (σ : outParam (Type u)) (m : Type u → Type v) where lift : {α : Type u} → state σ α → m α -- NOTE: The ordering of the following two instances determines that the top-most `state_t` monad layer -- will be picked first protected instance monad_state_trans {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [monad_state σ m] [has_monad_lift m n] : monad_state σ n := monad_state.mk fun (α : Type u) (x : state σ α) => monad_lift (monad_state.lift x) protected instance state_t.monad_state {σ : Type u} {m : Type u → Type v} [Monad m] : monad_state σ (state_t σ m) := monad_state.mk fun (α : Type u) (x : state σ α) => state_t.mk fun (s : σ) => pure (state_t.run x s) /-- Obtain the top-most state of a monad stack. -/ def get {σ : Type u} {m : Type u → Type v} [Monad m] [monad_state σ m] : m σ := monad_state.lift state_t.get /-- Set the top-most state of a monad stack. -/ def put {σ : Type u} {m : Type u → Type v} [Monad m] [monad_state σ m] (st : σ) : m PUnit := monad_state.lift (state_t.put st) /-- Map the top-most state of a monad stack. Note: `modify f` may be preferable to `f <$> get >>= put` because the latter does not use the state linearly (without sufficient inlining). -/ def modify {σ : Type u} {m : Type u → Type v} [Monad m] [monad_state σ m] (f : σ → σ) : m PUnit := monad_state.lift (state_t.modify f) /-- Adapt a monad stack, changing the type of its top-most state. This class is comparable to [Control.Lens.Zoom](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Zoom), but does not use lenses (yet?), and is derived automatically for any transformer implementing `monad_functor`. For zooming into a part of the state, the `split` function should split σ into the part σ' and the "context" σ'' so that the potentially modified σ' and the context can be rejoined by `join` in the end. In the simplest case, the context can be chosen as the full outer state (ie. `σ'' = σ`), which makes `split` and `join` simpler to define. However, note that the state will not be used linearly in this case. Example: ``` def zoom_fst {α σ σ' : Type} : state σ α → state (σ × σ') α := adapt_state id prod.mk ``` The function can also zoom out into a "larger" state, where the new parts are supplied by `split` and discarded by `join` in the end. The state is therefore not used linearly anymore but merely affinely, which is not a practically relevant distinction in Lean. Example: ``` def with_snd {α σ σ' : Type} (snd : σ') : state (σ × σ') α → state σ α := adapt_state (λ st, ((st, snd), ())) (λ ⟨st,snd⟩ _, st) ``` Note: This class can be seen as a simplification of the more "principled" definition ``` class monad_state_functor (σ σ' : out_param (Type u)) (n n' : Type u → Type u) := (map {α : Type u} : (∀ {m : Type u → Type u} [monad m], state_t σ m α → state_t σ' m α) → n α → n' α) ``` which better describes the intent of "we can map a `state_t` anywhere in the monad stack". If we look at the unfolded type of the first argument `∀ m [monad m], (σ → m (α × σ)) → σ' → m (α × σ')`, we see that it has the lens type `∀ f [functor f], (α → f α) → β → f β` with `f` specialized to `λ σ, m (α × σ)` (exercise: show that this is a lawful functor). We can build all lenses we are insterested in from the functions `split` and `join` as ``` λ f _ st, let (st, ctx) := split st in (λ st', join st' ctx) <$> f st ``` -/ class monad_state_adapter (σ : outParam (Type u)) (σ' : outParam (Type u)) (m : Type u → Type v) (m' : Type u → Type v) where adapt_state : {σ'' α : Type u} → (σ' → σ × σ'') → (σ → σ'' → σ') → m α → m' α protected instance monad_state_adapter_trans {σ : Type u} {σ' : Type u} {m : Type u → Type v} {m' : Type u → Type v} {n : Type u → Type v} {n' : Type u → Type v} [monad_functor m m' n n'] [monad_state_adapter σ σ' m m'] : monad_state_adapter σ σ' n n' := monad_state_adapter.mk fun (σ'' α : Type u) (split : σ' → σ × σ'') (join : σ → σ'' → σ') => monad_map fun (α : Type u) => adapt_state split join protected instance state_t.monad_state_adapter {σ : Type u} {σ' : Type u} {m : Type u → Type v} [Monad m] : monad_state_adapter σ σ' (state_t σ m) (state_t σ' m) := monad_state_adapter.mk fun (σ'' α : Type u) => state_t.adapt protected instance state_t.monad_run (σ : Type u_1) (m : Type u_1 → Type u_2) (out : outParam (Type u_1 → Type u_2)) [monad_run out m] : monad_run (fun (α : Type u_1) => σ → out (α × σ)) (state_t σ m) := monad_run.mk fun (α : Type u_1) (x : state_t σ m α) => run ∘ fun (σ_1 : σ) => state_t.run x σ_1 end Mathlib
0c188df2a486a7010ad04233218bd165b2d9868a
61ccc57f9d72048e493dd6969b56ebd7f0a8f9e8
/src/topology/instances/ennreal.lean
56f5da319d30c4cf8cf5148c8d24119d798497d5
[ "Apache-2.0" ]
permissive
jtristan/mathlib
375b3c8682975df28f79f53efcb7c88840118467
8fa8f175271320d675277a672f59ec53abd62f10
refs/heads/master
1,651,072,765,551
1,588,255,641,000
1,588,255,641,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,614
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 -/ import topology.instances.nnreal /-! # Extended non-negative reals -/ noncomputable theory open classical set filter metric open_locale classical open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} open_locale ennreal namespace ennreal variables {a b c d : ennreal} {r p q : nnreal} variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} section topological_space open topological_space /-- Topology on `ennreal`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊤}`, while this topology doesn't have singleton elements. -/ instance : topological_space ennreal := preorder.topology ennreal instance : order_topology ennreal := ⟨rfl⟩ instance : t2_space ennreal := by apply_instance -- short-circuit type class inference instance : second_countable_topology ennreal := ⟨⟨⋃q ≥ (0:ℚ), {{a : ennreal | a < nnreal.of_real q}, {a : ennreal | ↑(nnreal.of_real q) < a}}, countable_bUnion (countable_encodable _) $ assume a ha, countable_insert (countable_singleton _), le_antisymm (le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt}) (le_generate_from $ λ s h, begin rcases h with ⟨a, hs | hs⟩; [ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < nnreal.of_real q}, {b | ↑(nnreal.of_real q) < b}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]), rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(nnreal.of_real q) < a}, {b | b < ↑(nnreal.of_real q)}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])]; { apply is_open_Union, intro q, apply is_open_Union, intro hq, exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) } end)⟩⟩ lemma embedding_coe : embedding (coe : nnreal → ennreal) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ennreal _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : nnreal | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : nnreal | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }, { rw [@order_topology.topology_eq_generate_intervals nnreal _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, coe_eq_coe.1⟩ lemma is_open_ne_top : is_open {a : ennreal | a ≠ ⊤} := is_open_ne lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio} lemma coe_range_mem_nhds : range (coe : nnreal → ennreal) ∈ 𝓝 (r : ennreal) := have {a : ennreal | a ≠ ⊤} = range (coe : nnreal → ennreal), from set.ext $ assume a, by cases a; simp [none_eq_top, some_eq_coe], this ▸ mem_nhds_sets is_open_ne_top coe_ne_top @[norm_cast] lemma tendsto_coe {f : filter α} {m : α → nnreal} {a : nnreal} : tendsto (λa, (m a : ennreal)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe {α} [topological_space α] {f : α → nnreal} : continuous (λa, (f a : ennreal)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : nnreal} : 𝓝 (r : ennreal) = (𝓝 r).map coe := by rw [embedding_coe.induced, map_nhds_induced_eq coe_range_mem_nhds] lemma nhds_coe_coe {r p : nnreal} : 𝓝 ((r : ennreal), (p : ennreal)) = (𝓝 (r, p)).map (λp:nnreal×nnreal, (p.1, p.2)) := begin rw [(embedding_coe.prod_mk embedding_coe).map_nhds_eq], rw [← prod_range_range_eq], exact prod_mem_nhds_sets coe_range_mem_nhds coe_range_mem_nhds end lemma continuous_of_real : continuous ennreal.of_real := (continuous_coe.2 continuous_id).comp nnreal.continuous_of_real lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) : tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) := tendsto.comp (continuous.tendsto continuous_of_real _) h lemma tendsto_to_nnreal {a : ennreal} : a ≠ ⊤ → tendsto (ennreal.to_nnreal) (𝓝 a) (𝓝 a.to_nnreal) := begin cases a; simp [some_eq_coe, none_eq_top, nhds_coe, tendsto_map'_iff, (∘)], exact tendsto_id end lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} := continuous_on_iff_continuous_restrict.2 $ continuous_iff_continuous_at.2 $ λ x, (tendsto_to_nnreal x.2).comp continuous_at_subtype_val lemma tendsto_to_real {a : ennreal} : a ≠ ⊤ → tendsto (ennreal.to_real) (𝓝 a) (𝓝 a.to_real) := λ ha, tendsto.comp ((@nnreal.tendsto_coe _ (𝓝 a.to_nnreal) id (a.to_nnreal)).2 tendsto_id) (tendsto_to_nnreal ha) lemma tendsto_nhds_top {m : α → ennreal} {f : filter α} (h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) := tendsto_nhds_generate_from $ assume s hs, match s, hs with | _, ⟨none, or.inl rfl⟩, hr := (lt_irrefl ⊤ hr).elim | _, ⟨some r, or.inl rfl⟩, hr := let ⟨n, hrn⟩ := exists_nat_gt r in mem_sets_of_superset (h n) $ assume a hnma, show ↑r < m a, from lt_trans (show (r : ennreal) < n, from (coe_nat n) ▸ coe_lt_coe.2 hrn) hnma | _, ⟨a, or.inr rfl⟩, hr := (not_top_lt $ show ⊤ < a, from hr).elim end lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) := tendsto_nhds_top $ λ n, mem_at_top_sets.2 ⟨n+1, λ m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩ lemma nhds_top : 𝓝 ∞ = ⨅a ≠ ∞, principal (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_zero : 𝓝 (0 : ennreal) = ⨅a ≠ 0, principal (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] /-- The set of finite `ennreal` numbers is homeomorphic to `nnreal`. -/ def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ nnreal := { to_fun := λ x, ennreal.to_nnreal x, inv_fun := λ x, ⟨x, coe_ne_top⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx, right_inv := λ x, to_nnreal_coe, continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal, continuous_inv_fun := continuous_subtype_mk _ (continuous_coe.2 continuous_id) } /-- The set of finite `ennreal` numbers is homeomorphic to `nnreal`. -/ def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ nnreal := by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal; simp only [mem_set_of_eq, lt_top_iff_ne_top] -- using Icc because -- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0 -- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not lemma Icc_mem_nhds : x ≠ ⊤ → ε > 0 → Icc (x - ε) (x + ε) ∈ 𝓝 x := begin assume xt ε0, rw mem_nhds_sets_iff, by_cases x0 : x = 0, { use Iio (x + ε), have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt, use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ }, { use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self, exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ } end lemma nhds_of_ne_top : x ≠ ⊤ → 𝓝 x = ⨅ε > 0, principal (Icc (x - ε) (x + ε)) := begin assume xt, refine le_antisymm _ _, -- first direction simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0, -- second direction rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _), simp only [mem_set_of_eq] at hs, rcases hs with ⟨xs, ⟨a, ha⟩⟩, cases ha, { rw ha at *, rcases dense xs with ⟨b, ⟨ab, bx⟩⟩, have xb_pos : x - b > 0 := zero_lt_sub_iff_lt.2 bx, have xxb : x - (x - b) = b := sub_sub_cancel (by rwa lt_top_iff_ne_top) (le_of_lt bx), refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _), simp only [mem_principal_sets, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ }, { rw ha at *, rcases dense xs with ⟨b, ⟨xb, ba⟩⟩, have bx_pos : b - x > 0 := zero_lt_sub_iff_lt.2 xb, have xbx : x + (b - x) = b := add_sub_cancel_of_le (le_of_lt xb), refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _), simp only [mem_principal_sets, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba }, end /-- Characterization of neighborhoods for `ennreal` numbers. See also `tendsto_order` for a version with strict inequalities. -/ protected theorem tendsto_nhds {f : filter α} {u : α → ennreal} {a : ennreal} (ha : a ≠ ⊤) : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) := by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc] protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ennreal} {a : ennreal} (ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) := by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually] lemma tendsto_coe_nnreal_nhds_top {α} {l : filter α} {f : α → nnreal} (h : tendsto f l at_top) : tendsto (λa, (f a : ennreal)) l (𝓝 ∞) := tendsto_nhds_top $ assume n, have ∀ᶠ a in l, ↑(n+1) ≤ f a := h $ mem_at_top _, mem_sets_of_superset this $ assume a (ha : ↑(n+1) ≤ f a), begin rw [← coe_nat], dsimp, exact coe_lt_coe.2 (lt_of_lt_of_le (nat.cast_lt.2 (nat.lt_succ_self _)) ha) end instance : topological_add_monoid ennreal := ⟨ continuous_iff_continuous_at.2 $ have hl : ∀a:ennreal, tendsto (λ (p : ennreal × ennreal), p.fst + p.snd) (𝓝 (⊤, a)) (𝓝 ⊤), from assume a, tendsto_nhds_top $ assume n, have set.prod {a | ↑n < a } univ ∈ 𝓝 ((⊤:ennreal), a), from prod_mem_nhds_sets (lt_mem_nhds $ coe_nat n ▸ coe_lt_top) univ_mem_sets, show {a : ennreal × ennreal | ↑n < a.fst + a.snd} ∈ 𝓝 (⊤, a), begin filter_upwards [this] assume ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, lt_of_lt_of_le h₁ (le_add_right $ le_refl _) end, begin rintro ⟨a₁, a₂⟩, cases a₁, { simp [continuous_at, none_eq_top, hl a₂], }, cases a₂, { simp [continuous_at, none_eq_top, some_eq_coe, nhds_swap (a₁ : ennreal) ⊤, tendsto_map'_iff, (∘)], convert hl a₁, simp [add_comm] }, simp [continuous_at, some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_add.symm, tendsto_coe, tendsto_add] end ⟩ protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λp:ennreal×ennreal, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) := have ht : ∀b:ennreal, b ≠ 0 → tendsto (λp:ennreal×ennreal, p.1 * p.2) (𝓝 ((⊤:ennreal), b)) (𝓝 ⊤), begin refine assume b hb, tendsto_nhds_top $ assume n, _, rcases dense (zero_lt_iff_ne_zero.2 hb) with ⟨ε', hε', hεb'⟩, rcases ennreal.lt_iff_exists_coe.1 hεb' with ⟨ε, rfl, h⟩, rcases exists_nat_gt (↑n / ε) with ⟨m, hm⟩, have hε : ε > 0, from coe_lt_coe.1 hε', refine mem_sets_of_superset (prod_mem_nhds_sets (lt_mem_nhds $ @coe_lt_top m) (lt_mem_nhds $ h)) _, rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, dsimp at h₁ h₂ ⊢, calc (n:ennreal) = ↑(((n:nnreal) / ε) * ε) : begin simp [nnreal.div_def], rw [mul_assoc, ← coe_mul, nnreal.inv_mul_cancel, coe_one, ← coe_nat, mul_one], exact zero_lt_iff_ne_zero.1 hε end ... < (↑m * ε : nnreal) : coe_lt_coe.2 $ mul_lt_mul hm (le_refl _) hε (nat.cast_nonneg _) ... ≤ a₁ * a₂ : by rw [coe_mul]; exact canonically_ordered_semiring.mul_le_mul (le_of_lt h₁) (le_of_lt h₂) end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, simp [*, nhds_swap (a : ennreal) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul] end protected lemma tendsto.mul {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λa, ma a * mb a) f (𝓝 (a * b)) := show tendsto ((λp:ennreal×ennreal, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb) protected lemma tendsto.const_mul {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb) protected lemma tendsto.mul_const {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) := by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha protected lemma continuous_const_mul {a : ennreal} (ha : a < ⊤) : continuous ((*) a) := continuous_iff_continuous_at.2 $ λ x, tendsto.const_mul tendsto_id $ or.inr $ ne_of_lt ha protected lemma continuous_mul_const {a : ennreal} (ha : a < ⊤) : continuous (λ x, x * a) := by simpa only [mul_comm] using ennreal.continuous_const_mul ha protected lemma continuous_inv : continuous (has_inv.inv : ennreal → ennreal) := continuous_iff_continuous_at.2 $ λ a, tendsto_order.2 ⟨begin assume b hb, simp only [@ennreal.lt_inv_iff_lt_inv b], exact gt_mem_nhds (ennreal.lt_inv_iff_lt_inv.1 hb), end, begin assume b hb, simp only [gt_iff_lt, @ennreal.inv_lt_iff_inv_lt _ b], exact lt_mem_nhds (ennreal.inv_lt_iff_inv_lt.1 hb) end⟩ @[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ennreal} {a : ennreal} : tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) := ⟨λ h, by simpa only [function.comp, ennreal.inv_inv] using (ennreal.continuous_inv.tendsto a⁻¹).comp h, (ennreal.continuous_inv.tendsto a).comp⟩ protected lemma tendsto.div {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λa, ma a / mb a) f (𝓝 (a / b)) := by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] } protected lemma tendsto.const_div {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) := by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] } protected lemma tendsto.div_const {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) := by { apply tendsto.mul_const hm, simp [ha] } protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ennreal)⁻¹) at_top (𝓝 0) := ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top lemma Sup_add {s : set ennreal} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a := have Sup ((λb, b + a) '' s) = Sup s + a, from is_lub.Sup_eq (is_lub_of_is_lub_of_tendsto (assume x _ y _ h, add_le_add' h (le_refl _)) (is_lub_Sup s) hs (tendsto.add (tendsto_id' inf_le_left) tendsto_const_nhds)), by simp [Sup_image, -add_comm] at this; exact this.symm lemma supr_add {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : supr s + a = ⨆b, s b + a := let ⟨x⟩ := h in calc supr s + a = Sup (range s) + a : by simp [Sup_range] ... = (⨆b∈range s, b + a) : Sup_add ⟨s x, x, rfl⟩ ... = _ : supr_range lemma add_supr {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp [add_comm] lemma supr_add_supr {ι : Sort*} {f g : ι → ennreal} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin by_cases hι : nonempty ι, { letI := hι, refine le_antisymm _ (supr_le $ λ a, add_le_add' (le_supr _ _) (le_supr _ _)), simpa [add_supr, supr_add] using λ i j:ι, show f i + g j ≤ ⨆ a, f a + g a, from let ⟨k, hk⟩ := h i j in le_supr_of_le k hk }, { have : ∀f:ι → ennreal, (⨆i, f i) = 0 := assume f, bot_unique (supr_le $ assume i, (hι ⟨i⟩).elim), rw [this, this, this, zero_add] } end lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι] {f g : ι → ennreal} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add' (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ennreal} (hf : ∀a, monotone (f a)) : s.sum (λa, supr (f a)) = (⨆ n, s.sum (λa, f a n)) := begin refine finset.induction_on s _ _, { simp, exact (bot_unique $ supr_le $ assume i, le_refl ⊥).symm }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum $ assume a ha, hf a h) } end section priority -- for some reason the next proof fails without changing the priority of this instance local attribute [instance, priority 1000] classical.prop_decidable lemma mul_Sup {s : set ennreal} {a : ennreal} : a * Sup s = ⨆i∈s, a * i := begin by_cases hs : ∀x∈s, x = (0:ennreal), { have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm ▸ le_refl 0), have h₂ : (⨆i ∈ s, a * i) = 0 := (bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]), rw [h₁, h₂, mul_zero] }, { simp only [not_forall] at hs, rcases hs with ⟨x, hx, hx0⟩, have s₁ : Sup s ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_lt_of_le (zero_lt_iff_ne_zero.2 hx0) (le_Sup hx)), have : Sup ((λb, a * b) '' s) = a * Sup s := is_lub.Sup_eq (is_lub_of_is_lub_of_tendsto (assume x _ y _ h, canonically_ordered_semiring.mul_le_mul (le_refl _) h) (is_lub_Sup _) ⟨x, hx⟩ (ennreal.tendsto.const_mul (tendsto_id' inf_le_left) (or.inl s₁))), rw [this.symm, Sup_image] } end end priority lemma mul_supr {ι : Sort*} {f : ι → ennreal} {a : ennreal} : a * supr f = ⨆i, a * f i := by rw [← Sup_range, mul_Sup, supr_range] lemma supr_mul {ι : Sort*} {f : ι → ennreal} {a : ennreal} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] protected lemma tendsto_coe_sub : ∀{b:ennreal}, tendsto (λb:ennreal, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) := begin refine (forall_ennreal.2 $ and.intro (assume a, _) _), { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm], exact nnreal.tendsto.sub tendsto_const_nhds tendsto_id }, simp, exact (tendsto.congr' (mem_sets_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ι : Sort*} [hι : nonempty ι] {b : ι → ennreal} (hr : a < ⊤) : a - (⨆i, b i) = (⨅i, a - b i) := let ⟨i⟩ := hι in let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb.Inf_eq $ is_glb_of_is_lub_of_tendsto (assume x _ y _, sub_le_sub (le_refl _)) is_lub_supr ⟨_, i, rfl⟩ (tendsto.comp ennreal.tendsto_coe_sub (tendsto_id' inf_le_left)), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _ end topological_space section tsum variables {f g : α → ennreal} @[norm_cast] protected lemma has_sum_coe {f : α → nnreal} {r : nnreal} : has_sum (λa, (f a : ennreal)) ↑r ↔ has_sum f r := have (λs:finset α, s.sum (coe ∘ f)) = (coe : nnreal → ennreal) ∘ (λs:finset α, s.sum f), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold has_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : α → nnreal} (h : has_sum f r) : (∑'a, (f a : ennreal)) = r := tsum_eq_has_sum $ ennreal.has_sum_coe.2 $ h protected lemma coe_tsum {f : α → nnreal} : summable f → ↑(tsum f) = (∑'a, (f a : ennreal)) | ⟨r, hr⟩ := by rw [tsum_eq_has_sum hr, ennreal.tsum_coe_eq hr] protected lemma has_sum : has_sum f (⨆s:finset α, s.sum f) := tendsto_order.2 ⟨assume a' ha', let ⟨s, hs⟩ := lt_supr_iff.mp ha' in mem_at_top_sets.mpr ⟨s, assume t ht, lt_of_lt_of_le hs $ finset.sum_le_sum_of_subset ht⟩, assume a' ha', univ_mem_sets' $ assume s, have s.sum f ≤ ⨆(s : finset α), s.sum f, from le_supr (λ(s : finset α), s.sum f) s, lt_of_le_of_lt this ha'⟩ @[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩ lemma tsum_coe_ne_top_iff_summable {f : β → nnreal} : (∑' b, (f b:ennreal)) ≠ ∞ ↔ summable f := begin refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩, lift (∑' b, (f b:ennreal)) to nnreal using h with a ha, refine ⟨a, ennreal.has_sum_coe.1 _⟩, rw ha, exact ennreal.summable.has_sum end protected lemma tsum_eq_supr_sum : (∑'a, f a) = (⨆s:finset α, s.sum f) := tsum_eq_has_sum ennreal.has_sum protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → (∑' a, f a) = ∞ | ⟨a, ha⟩ := begin rw [ennreal.tsum_eq_supr_sum], apply le_antisymm le_top, convert le_supr (λ s:finset α, s.sum f) (finset.singleton a), rw [finset.sum_singleton, ha] end protected lemma ne_top_of_tsum_ne_top (h : (∑' a, f a) ≠ ∞) (a : α) : f a ≠ ∞ := λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩ protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ennreal) : (∑'p:Σa, β a, f p.1 p.2) = (∑'a b, f a b) := tsum_sigma (assume b, ennreal.summable) ennreal.summable protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ennreal) : (∑'p:(Σa, β a), f p) = (∑'a b, f ⟨a, b⟩) := tsum_sigma (assume b, ennreal.summable) ennreal.summable protected lemma tsum_prod {f : α → β → ennreal} : (∑'p:α×β, f p.1 p.2) = (∑'a, ∑'b, f a b) := let j : α × β → (Σa:α, β) := λp, sigma.mk p.1 p.2 in let i : (Σa:α, β) → α × β := λp, (p.1, p.2) in let f' : (Σa:α, β) → ennreal := λp, f p.1 p.2 in calc (∑'p:α×β, f' (j p)) = (∑'p:Σa:α, β, f p.1 p.2) : tsum_eq_tsum_of_iso j i (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl) ... = (∑'a, ∑'b, f a b) : ennreal.tsum_sigma f protected lemma tsum_comm {f : α → β → ennreal} : (∑'a, ∑'b, f a b) = (∑'b, ∑'a, f a b) := let f' : α×β → ennreal := λp, f p.1 p.2 in calc (∑'a, ∑'b, f a b) = (∑'p:α×β, f' p) : ennreal.tsum_prod.symm ... = (∑'p:β×α, f' (prod.swap p)) : (tsum_eq_tsum_of_iso prod.swap (@prod.swap α β) (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl)).symm ... = (∑'b, ∑'a, f' (prod.swap (b, a))) : @ennreal.tsum_prod β α (λb a, f' (prod.swap (b, a))) protected lemma tsum_add : (∑'a, f a + g a) = (∑'a, f a) + (∑'a, g a) := tsum_add ennreal.summable ennreal.summable protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : (∑'a, f a) ≤ (∑'a, g a) := tsum_le_tsum h ennreal.summable ennreal.summable protected lemma tsum_eq_supr_nat {f : ℕ → ennreal} : (∑'i:ℕ, f i) = (⨆i:ℕ, (finset.range i).sum f) := calc _ = (⨆s:finset ℕ, s.sum f) : ennreal.tsum_eq_supr_sum ... = (⨆i:ℕ, (finset.range i).sum f) : le_antisymm (supr_le_supr2 $ assume s, let ⟨n, hn⟩ := finset.exists_nat_subset_range s in ⟨n, finset.sum_le_sum_of_subset hn⟩) (supr_le_supr2 $ assume i, ⟨finset.range i, le_refl _⟩) protected lemma le_tsum (a : α) : f a ≤ (∑'a, f a) := calc f a = ({a} : finset α).sum f : by simp ... ≤ (⨆s:finset α, s.sum f) : le_supr (λs:finset α, s.sum f) _ ... = (∑'a, f a) : by rw [ennreal.tsum_eq_supr_sum] protected lemma tsum_mul_left : (∑'i, a * f i) = a * (∑'i, f i) := if h : ∀i, f i = 0 then by simp [h] else let ⟨i, (hi : f i ≠ 0)⟩ := classical.not_forall.mp h in have sum_ne_0 : (∑'i, f i) ≠ 0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≤ (∑'i, f i) : ennreal.le_tsum _, have tendsto (λs:finset α, s.sum ((*) a ∘ f)) at_top (𝓝 (a * (∑'i, f i))), by rw [← show (*) a ∘ (λs:finset α, s.sum f) = λs, s.sum ((*) a ∘ f), from funext $ λ s, finset.mul_sum]; exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0), tsum_eq_has_sum this protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a := by simp [mul_comm, ennreal.tsum_mul_left] @[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ennreal} : (∑'b:α, ⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc s.sum (λb, ⨆ (h : a = b), f b) ≤ (finset.singleton a).sum (λb, ⨆ (h : a = b), f b) : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl ... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma has_sum_iff_tendsto_nat {f : ℕ → ennreal} (r : ennreal) : has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (𝓝 r) := begin refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact ennreal.summable.has_sum }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end end tsum end ennreal namespace nnreal lemma exists_le_has_sum_of_le {f g : β → nnreal} {r : nnreal} (hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p := have (∑'b, (g b : ennreal)) ≤ r, begin refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩ lemma summable_of_le {f g : β → nnreal} (hgf : ∀b, g b ≤ f b) : summable f → summable g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable lemma has_sum_iff_tendsto_nat {f : ℕ → nnreal} (r : nnreal) : has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (𝓝 r) := begin rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → nnreal} (hf : summable f) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_refl _) (summable_comp_injective hf hi) hf end nnreal lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := begin let g : α → nnreal := λ a, ⟨f a, hn a⟩, have hg : summable g, by rwa ← nnreal.summable_coe, convert nnreal.coe_le_coe.2 (nnreal.tsum_comp_le_tsum_of_inj hg hi); { rw nnreal.coe_tsum, congr } end lemma summable_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g := let f' (b : β) : nnreal := ⟨f b, le_trans (hg b) (hgf b)⟩ in let g' (b : β) : nnreal := ⟨g b, hg b⟩ in have summable f', from nnreal.summable_coe.1 hf, have summable g', from nnreal.summable_of_le (assume b, (@nnreal.coe_le_coe (g' b) (f' b)).2 $ hgf b) this, show summable (λb, g' b : β → ℝ), from nnreal.summable_coe.2 this lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) : has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (𝓝 r) := ⟨has_sum.tendsto_sum_nat, assume hfr, have 0 ≤ r := ge_of_tendsto at_top_ne_bot hfr $ univ_mem_sets' $ assume i, show 0 ≤ (finset.range i).sum f, from finset.sum_nonneg $ assume i _, hf i, let f' (n : ℕ) : nnreal := ⟨f n, hf n⟩, r' : nnreal := ⟨r, this⟩ in have f_eq : f = (λi:ℕ, (f' i : ℝ)) := rfl, have r_eq : r = r' := rfl, begin rw [f_eq, r_eq, nnreal.has_sum_coe, nnreal.has_sum_iff_tendsto_nat, ← nnreal.tendsto_coe], simp only [nnreal.coe_sum], exact hfr end⟩ lemma infi_real_pos_eq_infi_nnreal_pos {α : Type*} [complete_lattice α] {f : ℝ → α} : (⨅(n:ℝ) (h : n > 0), f n) = (⨅(n:nnreal) (h : n > 0), f n) := le_antisymm (le_infi $ assume n, le_infi $ assume hn, infi_le_of_le n $ infi_le _ (nnreal.coe_pos.2 hn)) (le_infi $ assume r, le_infi $ assume hr, infi_le_of_le ⟨r, le_of_lt hr⟩ $ infi_le _ hr) section variables [emetric_space β] open ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : β} {r : ennreal} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ := lt_top_iff_ne_top.1 $ calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≤ ⊤ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : β) (r : ennreal) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ennreal) (h : x ∈ ball a r) : 𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) := (map_nhds_subtype_val_eq _ $ mem_nhds_sets emetric.is_open_ball h).symm end section variable [emetric_space α] open emetric lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} : tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) := by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball, @tendsto_order ennreal β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and] /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔ (∃ (b: β → ennreal), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ (tendsto b at_top (𝓝 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/ let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, { refine λm n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (𝓝 0), { refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩, rcases dense εpos with ⟨δ, δpos, δlt⟩, rcases hs δ δpos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩, have : b n ≤ δ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN p q (le_trans hn hp) (le_trans hn hq)) end, simpa using lt_of_le_of_lt this δlt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, b_lim : tendsto b at_top (𝓝 0)-/ refine emetric.cauchy_seq_iff.2 (λε εpos, _), have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, λm n hm hn, calc edist (s m) (s n) ≤ b N : b_bound m n N hm hn ... < ε : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : α → ennreal} (C : ennreal) (hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f := begin refine continuous_iff_continuous_at.2 (λx, tendsto_order.2 ⟨_, _⟩), show ∀e, e < f x → ∀ᶠ y in 𝓝 x, e < f y, { assume e he, let ε := min (f x - e) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, hC, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, ennreal.mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, { simp [C_zero, ‹0 < ε›] }, { calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (bot_lt_iff_ne_bot.1 ‹0 < ε›) (lt_top_iff_ne_top.1 ‹ε < ⊤›) }}, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | e < f y}, { rintros y hy, by_cases htop : f y = ⊤, { simp [htop, lt_top_iff_ne_top, ne_top_of_lt he] }, { simp at hy, have : e + ε < f y + ε := calc e + ε ≤ e + (f x - e) : add_le_add_left' (min_le_left _ _) ... = f x : by simp [le_of_lt he] ... ≤ f y + C * edist x y : h x y ... = f y + C * edist y x : by simp [edist_comm] ... ≤ f y + C * (C⁻¹ * (ε/2)) : add_le_add_left' $ canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy) ... < f y + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I, show e < f y, from (ennreal.add_lt_add_iff_right ‹ε < ⊤›).1 this }}, apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, show ∀e, f x < e → ∀ᶠ y in 𝓝 x, f y < e, { assume e he, let ε := min (e - f x) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, ennreal.mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, simp [C_zero, ‹0 < ε›], calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (bot_lt_iff_ne_bot.1 ‹0 < ε›) (lt_top_iff_ne_top.1 ‹ε < ⊤›) }, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | f y < e}, { rintros y hy, have htop : f x ≠ ⊤ := ne_top_of_lt he, show f y < e, from calc f y ≤ f x + C * edist y x : h y x ... ≤ f x + C * (C⁻¹ * (ε/2)) : add_le_add_left' $ canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy) ... < f x + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I ... ≤ f x + (e - f x) : add_le_add_left' (min_le_left _ _) ... = e : by simp [le_of_lt he] }, apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, end theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by simp), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc ... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl])) ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end theorem continuous.edist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) := continuous_edist.comp (hf.prod_mk hg) theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) := (continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) : cauchy_seq f := begin lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i), rw ennreal.tsum_coe_ne_top_iff_summable at hd, exact cauchy_seq_of_edist_le_of_summable d hf hd end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ennreal`, then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto at_top_ne_bot (tendsto_const_nhds.edist ha) (mem_at_top_sets.2 ⟨n, λ m hnm, _⟩), refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _, rw [finset.sum_Ico_eq_sum_range], exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ennreal`, then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ ∑' m, d m := by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0 end --section
f90b42d480d2c3ef06f06acc813f1aef54d3864a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/ring_hom/finite_type.lean
6f6f5ab0c978a2f54f409bdc22526994df88fca0
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,722
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import ring_theory.local_properties import ring_theory.localization.inv_submonoid /-! # The meta properties of finite-type ring homomorphisms. The main result is `ring_hom.finite_is_local`. -/ namespace ring_hom open_locale pointwise lemma finite_type_stable_under_composition : stable_under_composition @finite_type := by { introv R hf hg, exactI hg.comp hf } lemma finite_type_holds_for_localization_away : holds_for_localization_away @finite_type := begin introv R _, resetI, suffices : algebra.finite_type R S, { change algebra.finite_type _ _, convert this, ext, rw algebra.smul_def, refl }, exact is_localization.finite_type_of_monoid_fg (submonoid.powers r) S, end lemma finite_type_of_localization_span_target : of_localization_span_target @finite_type := begin -- Setup algebra intances. rw of_localization_span_target_iff_finite, introv R hs H, resetI, classical, letI := f.to_algebra, replace H : ∀ r : s, algebra.finite_type R (localization.away (r : S)), { intro r, convert H r, ext, rw algebra.smul_def, refl }, replace H := λ r, (H r).1, constructor, -- Suppose `s : finset S` spans `S`, and each `Sᵣ` is finitely generated as an `R`-algebra. -- Say `t r : finset Sᵣ` generates `Sᵣ`. By assumption, we may find `lᵢ` such that -- `∑ lᵢ * sᵢ = 1`. I claim that all `s` and `l` and the numerators of `t` and generates `S`. choose t ht using H, obtain ⟨l, hl⟩ := (finsupp.mem_span_iff_total S (s : set S) 1).mp (show (1 : S) ∈ ideal.span (s : set S), by { rw hs, trivial }), let sf := λ (x : s), is_localization.finset_integer_multiple (submonoid.powers (x : S)) (t x), use s.attach.bUnion sf ∪ s ∪ l.support.image l, rw eq_top_iff, -- We need to show that every `x` falls in the subalgebra generated by those elements. -- Since all `s` and `l` are in the subalgebra, it suffices to check that `sᵢ ^ nᵢ • x` falls in -- the algebra for each `sᵢ` and some `nᵢ`. rintro x -, apply subalgebra.mem_of_span_eq_top_of_smul_pow_mem _ (s : set S) l hl _ _ x _, { intros x hx, apply algebra.subset_adjoin, rw [finset.coe_union, finset.coe_union], exact or.inl (or.inr hx) }, { intros i, by_cases h : l i = 0, { rw h, exact zero_mem _ }, apply algebra.subset_adjoin, rw [finset.coe_union, finset.coe_image], exact or.inr (set.mem_image_of_mem _ (finsupp.mem_support_iff.mpr h)) }, { intro r, rw [finset.coe_union, finset.coe_union, finset.coe_bUnion], -- Since all `sᵢ` and numerators of `t r` are in the algebra, it suffices to show that the -- image of `x` in `Sᵣ` falls in the `R`-adjoin of `t r`, which is of course true. obtain ⟨⟨_, n₂, rfl⟩, hn₂⟩ := is_localization.exists_smul_mem_of_mem_adjoin (submonoid.powers (r : S)) x (t r) (algebra.adjoin R _) _ _ _, { exact ⟨n₂, hn₂⟩ }, { intros x hx, apply algebra.subset_adjoin, refine or.inl (or.inl ⟨_, ⟨r, rfl⟩, _, ⟨s.mem_attach r, rfl⟩, hx⟩) }, { rw [submonoid.powers_eq_closure, submonoid.closure_le, set.singleton_subset_iff], apply algebra.subset_adjoin, exact or.inl (or.inr r.2) }, { rw ht, trivial } } end lemma finite_type_is_local : property_is_local @finite_type := ⟨localization_finite_type, finite_type_of_localization_span_target, finite_type_stable_under_composition, finite_type_holds_for_localization_away⟩ lemma finite_type_respects_iso : ring_hom.respects_iso @ring_hom.finite_type := ring_hom.finite_type_is_local.respects_iso end ring_hom
9424548cd1619fff6f0463beb18fc260b9e7495c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/imo/imo2011_q3.lean
67b4845b530184665ec5cab2468fd1cc8ec6a865
[ "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
2,517
lean
/- Copyright (c) 2021 David Renshaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Renshaw -/ import data.real.basic /-! # IMO 2011 Q3 > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let f : ℝ → ℝ be a function that satisfies f(x + y) ≤ y * f(x) + f(f(x)) for all x and y. Prove that f(x) = 0 for all x ≤ 0. # Solution Direct translation of the solution found in https://www.imo-official.org/problems/IMO2011SL.pdf -/ theorem imo2011_q3 (f : ℝ → ℝ) (hf : ∀ x y, f (x + y) ≤ y * f x + f (f x)) : ∀ x ≤ 0, f x = 0 := begin -- reparameterize have hxt : ∀ x t, f t ≤ t * f x - x * f x + f (f x), { intros x t, calc f t = f (x + (t - x)) : by rw (add_eq_of_eq_sub' rfl) ... ≤ (t - x) * f x + f (f x) : hf x (t - x) ... = t * f x - x * f x + f (f x) : by rw sub_mul }, have h_ab_combined : ∀ a b, a * f a + b * f b ≤ 2 * f a * f b, { intros a b, linarith [hxt b (f a), hxt a (f b)] }, have h_f_nonneg_of_pos : ∀ a < 0, 0 ≤ f a, { intros a han, suffices : a * f a ≤ 0, from nonneg_of_mul_nonpos_right this han, exact add_le_iff_nonpos_left.mp (h_ab_combined a (2 * f a)) }, have h_f_nonpos : ∀ x, f x ≤ 0, { intros x, by_contra h_suppose_not, -- If we choose a small enough argument for f, then we get a contradiction. let s := (x * f x - f (f x)) / (f x), have hm : min 0 s - 1 < s := (sub_one_lt _).trans_le (min_le_right 0 s), have hml : min 0 s - 1 < 0 := (sub_one_lt _).trans_le (min_le_left 0 s), suffices : f (min 0 s - 1) < 0, from not_le.mpr this (h_f_nonneg_of_pos (min 0 s - 1) hml), have hp : 0 < f x := not_le.mp h_suppose_not, calc f (min 0 s - 1) ≤ (min 0 s - 1) * f x - x * f x + f (f x) : hxt x (min 0 s - 1) ... < s * f x - x * f x + f (f x) : by linarith [(mul_lt_mul_right hp).mpr hm] ... = 0 : by { rw [(eq_div_iff hp.ne.symm).mp rfl], linarith } }, have h_fx_zero_of_neg : ∀ x < 0, f x = 0, { intros x hxz, exact (h_f_nonpos x).antisymm (h_f_nonneg_of_pos x hxz) }, intros x hx, obtain (h_x_neg : x < 0) | (rfl : x = 0) := hx.lt_or_eq, { exact h_fx_zero_of_neg _ h_x_neg }, { suffices : 0 ≤ f 0, from le_antisymm (h_f_nonpos 0) this, have hno : f (-1) = 0 := h_fx_zero_of_neg (-1) neg_one_lt_zero, have hp := hxt (-1) (-1), rw hno at hp, linarith }, end
9bdd192f8b1792759444b793fa13941816924a6f
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/group/defs.lean
7b171b1e64c6b3afc628eca9bd8cecf6861106ef
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
14,661
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, Simon Hudon, Mario Carneiro -/ import algebra.group.to_additive import tactic.basic /-! # Typeclasses for (semi)groups and monoid In this file we define typeclasses for algebraic structures with one binary operation. The classes are named `(add_)?(comm_)?(semigroup|monoid|group)`, where `add_` means that the class uses additive notation and `comm_` means that the class assumes that the binary operation is commutative. The file does not contain any lemmas except for * axioms of typeclasses restated in the root namespace; * lemmas required for instances. For basic lemmas about these classes see `algebra.group.basic`. -/ set_option old_structure_cmd true universe u /- Additive "sister" structures. Example, add_semigroup mirrors semigroup. These structures exist just to help automation. In an alternative design, we could have the binary operation as an extra argument for semigroup, monoid, group, etc. However, the lemmas would be hard to index since they would not contain any constant. For example, mul_assoc would be lemma mul_assoc {α : Type u} {op : α → α → α} [semigroup α op] : ∀ a b c : α, op (op a b) c = op a (op b c) := semigroup.mul_assoc The simplifier cannot effectively use this lemma since the pattern for the left-hand-side would be ?op (?op ?a ?b) ?c Remark: we use a tactic for transporting theorems from the multiplicative fragment to the additive one. -/ section has_mul variables {G : Type u} [has_mul G] /-- `left_mul g` denotes left multiplication by `g` -/ @[to_additive "`left_add g` denotes left addition by `g`"] def left_mul : G → G → G := λ g : G, λ x : G, g * x /-- `right_mul g` denotes right multiplication by `g` -/ @[to_additive "`right_add g` denotes right addition by `g`"] def right_mul : G → G → G := λ g : G, λ x : G, x * g end has_mul /-- A semigroup is a type with an associative `(*)`. -/ @[protect_proj, ancestor has_mul] class semigroup (G : Type u) extends has_mul G := (mul_assoc : ∀ a b c : G, a * b * c = a * (b * c)) /-- An additive semigroup is a type with an associative `(+)`. -/ @[protect_proj, ancestor has_add] class add_semigroup (G : Type u) extends has_add G := (add_assoc : ∀ a b c : G, a + b + c = a + (b + c)) attribute [to_additive] semigroup section semigroup variables {G : Type u} [semigroup G] @[no_rsimp, to_additive] lemma mul_assoc : ∀ a b c : G, a * b * c = a * (b * c) := semigroup.mul_assoc attribute [no_rsimp] add_assoc -- TODO(Mario): find out why this isn't copying @[to_additive] instance semigroup.to_is_associative : is_associative G (*) := ⟨mul_assoc⟩ end semigroup /-- A commutative semigroup is a type with an associative commutative `(*)`. -/ @[protect_proj, ancestor semigroup] class comm_semigroup (G : Type u) extends semigroup G := (mul_comm : ∀ a b : G, a * b = b * a) /-- A commutative additive semigroup is a type with an associative commutative `(+)`. -/ @[protect_proj, ancestor add_semigroup] class add_comm_semigroup (G : Type u) extends add_semigroup G := (add_comm : ∀ a b : G, a + b = b + a) attribute [to_additive] comm_semigroup section comm_semigroup variables {G : Type u} [comm_semigroup G] @[no_rsimp, to_additive] lemma mul_comm : ∀ a b : G, a * b = b * a := comm_semigroup.mul_comm attribute [no_rsimp] add_comm @[to_additive] instance comm_semigroup.to_is_commutative : is_commutative G (*) := ⟨mul_comm⟩ end comm_semigroup /-- A `left_cancel_semigroup` is a semigroup such that `a * b = a * c` implies `b = c`. -/ @[protect_proj, ancestor semigroup] class left_cancel_semigroup (G : Type u) extends semigroup G := (mul_left_cancel : ∀ a b c : G, a * b = a * c → b = c) /-- An `add_left_cancel_semigroup` is an additive semigroup such that `a + b = a + c` implies `b = c`. -/ @[protect_proj, ancestor add_semigroup] class add_left_cancel_semigroup (G : Type u) extends add_semigroup G := (add_left_cancel : ∀ a b c : G, a + b = a + c → b = c) attribute [to_additive add_left_cancel_semigroup] left_cancel_semigroup section left_cancel_semigroup variables {G : Type u} [left_cancel_semigroup G] {a b c : G} @[to_additive] lemma mul_left_cancel : a * b = a * c → b = c := left_cancel_semigroup.mul_left_cancel a b c @[to_additive] lemma mul_left_cancel_iff : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congr_arg _⟩ @[to_additive] theorem mul_right_injective (a : G) : function.injective ((*) a) := λ b c, mul_left_cancel @[simp, to_additive] theorem mul_right_inj (a : G) {b c : G} : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congr_arg _⟩ end left_cancel_semigroup /-- A `right_cancel_semigroup` is a semigroup such that `a * b = c * b` implies `a = c`. -/ @[protect_proj, ancestor semigroup] class right_cancel_semigroup (G : Type u) extends semigroup G := (mul_right_cancel : ∀ a b c : G, a * b = c * b → a = c) /-- An `add_right_cancel_semigroup` is an additive semigroup such that `a + b = c + b` implies `a = c`. -/ @[protect_proj, ancestor add_semigroup] class add_right_cancel_semigroup (G : Type u) extends add_semigroup G := (add_right_cancel : ∀ a b c : G, a + b = c + b → a = c) attribute [to_additive add_right_cancel_semigroup] right_cancel_semigroup section right_cancel_semigroup variables {G : Type u} [right_cancel_semigroup G] {a b c : G} @[to_additive] lemma mul_right_cancel : a * b = c * b → a = c := right_cancel_semigroup.mul_right_cancel a b c @[to_additive] lemma mul_right_cancel_iff : b * a = c * a ↔ b = c := ⟨mul_right_cancel, congr_arg _⟩ @[to_additive] theorem mul_left_injective (a : G) : function.injective (λ x, x * a) := λ b c, mul_right_cancel @[simp, to_additive] theorem mul_left_inj (a : G) {b c : G} : b * a = c * a ↔ b = c := ⟨mul_right_cancel, congr_arg _⟩ end right_cancel_semigroup /-- A `monoid` is a `semigroup` with an element `1` such that `1 * a = a * 1 = a`. -/ @[ancestor semigroup has_one] class monoid (M : Type u) extends semigroup M, has_one M := (one_mul : ∀ a : M, 1 * a = a) (mul_one : ∀ a : M, a * 1 = a) /-- An `add_monoid` is an `add_semigroup` with an element `0` such that `0 + a = a + 0 = a`. -/ @[ancestor add_semigroup has_zero] class add_monoid (M : Type u) extends add_semigroup M, has_zero M := (zero_add : ∀ a : M, 0 + a = a) (add_zero : ∀ a : M, a + 0 = a) attribute [to_additive] monoid section monoid variables {M : Type u} [monoid M] @[ematch, simp, to_additive] lemma one_mul : ∀ a : M, 1 * a = a := monoid.one_mul @[ematch, simp, to_additive] lemma mul_one : ∀ a : M, a * 1 = a := monoid.mul_one attribute [ematch] add_zero zero_add -- TODO(Mario): Make to_additive transfer this @[to_additive] instance monoid_to_is_left_id : is_left_id M (*) 1 := ⟨ monoid.one_mul ⟩ @[to_additive] instance monoid_to_is_right_id : is_right_id M (*) 1 := ⟨ monoid.mul_one ⟩ @[to_additive] lemma left_inv_eq_right_inv {a b c : M} (hba : b * a = 1) (hac : a * c = 1) : b = c := by rw [←one_mul c, ←hba, mul_assoc, hac, mul_one b] end monoid /-- A commutative monoid is a monoid with commutative `(*)`. -/ @[protect_proj, ancestor monoid comm_semigroup] class comm_monoid (M : Type u) extends monoid M, comm_semigroup M /-- An additive commutative monoid is an additive monoid with commutative `(+)`. -/ @[protect_proj, ancestor add_monoid add_comm_semigroup] class add_comm_monoid (M : Type u) extends add_monoid M, add_comm_semigroup M attribute [to_additive] comm_monoid section left_cancel_monoid /-- An additive monoid in which addition is left-cancellative. Main examples are `ℕ` and groups. This is the right typeclass for many sum lemmas, as having a zero is useful to define the sum over the empty set, so `add_left_cancel_semigroup` is not enough. -/ @[protect_proj, ancestor add_left_cancel_semigroup add_monoid] class add_left_cancel_monoid (M : Type u) extends add_left_cancel_semigroup M, add_monoid M -- TODO: I found 1 (one) lemma assuming `[add_left_cancel_monoid]`. -- Should we port more lemmas to this typeclass? /-- A monoid in which multiplication is left-cancellative. -/ @[protect_proj, ancestor left_cancel_semigroup monoid, to_additive add_left_cancel_monoid] class left_cancel_monoid (M : Type u) extends left_cancel_semigroup M, monoid M /-- Commutative version of add_left_cancel_monoid. -/ @[protect_proj, ancestor add_left_cancel_monoid add_comm_monoid] class add_left_cancel_comm_monoid (M : Type u) extends add_left_cancel_monoid M, add_comm_monoid M /-- Commutative version of left_cancel_monoid. -/ @[protect_proj, ancestor left_cancel_monoid comm_monoid, to_additive add_left_cancel_comm_monoid] class left_cancel_comm_monoid (M : Type u) extends left_cancel_monoid M, comm_monoid M end left_cancel_monoid section right_cancel_monoid /-- An additive monoid in which addition is right-cancellative. Main examples are `ℕ` and groups. This is the right typeclass for many sum lemmas, as having a zero is useful to define the sum over the empty set, so `add_right_cancel_semigroup` is not enough. -/ @[protect_proj, ancestor add_right_cancel_semigroup add_monoid] class add_right_cancel_monoid (M : Type u) extends add_right_cancel_semigroup M, add_monoid M /-- A monoid in which multiplication is right-cancellative. -/ @[protect_proj, ancestor right_cancel_semigroup monoid, to_additive add_right_cancel_monoid] class right_cancel_monoid (M : Type u) extends right_cancel_semigroup M, monoid M /-- Commutative version of add_right_cancel_monoid. -/ @[protect_proj, ancestor add_right_cancel_monoid add_comm_monoid] class add_right_cancel_comm_monoid (M : Type u) extends add_right_cancel_monoid M, add_comm_monoid M /-- Commutative version of right_cancel_monoid. -/ @[protect_proj, ancestor right_cancel_monoid comm_monoid, to_additive add_right_cancel_comm_monoid] class right_cancel_comm_monoid (M : Type u) extends right_cancel_monoid M, comm_monoid M end right_cancel_monoid section cancel_monoid /-- An additive monoid in which addition is cancellative on both sides. Main examples are `ℕ` and groups. This is the right typeclass for many sum lemmas, as having a zero is useful to define the sum over the empty set, so `add_right_cancel_semigroup` is not enough. -/ @[protect_proj, ancestor add_left_cancel_monoid add_right_cancel_monoid] class add_cancel_monoid (M : Type u) extends add_left_cancel_monoid M, add_right_cancel_monoid M /-- A monoid in which multiplication is cancellative. -/ @[protect_proj, ancestor left_cancel_monoid right_cancel_monoid, to_additive add_cancel_monoid] class cancel_monoid (M : Type u) extends left_cancel_monoid M, right_cancel_monoid M /-- Commutative version of add_cancel_monoid. -/ @[protect_proj, ancestor add_left_cancel_comm_monoid add_right_cancel_comm_monoid] class add_cancel_comm_monoid (M : Type u) extends add_left_cancel_comm_monoid M, add_right_cancel_comm_monoid M /-- Commutative version of cancel_monoid. -/ @[protect_proj, ancestor right_cancel_comm_monoid left_cancel_comm_monoid, to_additive add_cancel_comm_monoid] class cancel_comm_monoid (M : Type u) extends left_cancel_comm_monoid M, right_cancel_comm_monoid M end cancel_monoid /-- A `group` is a `monoid` with an operation `⁻¹` satisfying `a⁻¹ * a = 1`. -/ @[protect_proj, ancestor monoid has_inv] class group (α : Type u) extends monoid α, has_inv α := (mul_left_inv : ∀ a : α, a⁻¹ * a = 1) /-- An `add_group` is an `add_monoid` with a unary `-` satisfying `-a + a = 0`. -/ @[protect_proj, ancestor add_monoid has_neg] class add_group (α : Type u) extends add_monoid α, has_neg α := (add_left_neg : ∀ a : α, -a + a = 0) attribute [to_additive] group section group variables {G : Type u} [group G] {a b c : G} @[simp, to_additive] lemma mul_left_inv : ∀ a : G, a⁻¹ * a = 1 := group.mul_left_inv @[to_additive] lemma inv_mul_self (a : G) : a⁻¹ * a = 1 := mul_left_inv a @[simp, to_additive] lemma inv_mul_cancel_left (a b : G) : a⁻¹ * (a * b) = b := by rw [← mul_assoc, mul_left_inv, one_mul] @[simp, to_additive] lemma inv_eq_of_mul_eq_one (h : a * b = 1) : a⁻¹ = b := left_inv_eq_right_inv (inv_mul_self a) h @[simp, to_additive] lemma inv_inv (a : G) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul_left_inv a) @[simp, to_additive] lemma mul_right_inv (a : G) : a * a⁻¹ = 1 := have a⁻¹⁻¹ * a⁻¹ = 1 := mul_left_inv a⁻¹, by rwa [inv_inv] at this @[to_additive] lemma mul_inv_self (a : G) : a * a⁻¹ = 1 := mul_right_inv a @[simp, to_additive] lemma mul_inv_cancel_right (a b : G) : a * b * b⁻¹ = a := by rw [mul_assoc, mul_right_inv, mul_one] @[priority 100, to_additive] -- see Note [lower instance priority] instance group.to_left_cancel_semigroup : left_cancel_semigroup G := { mul_left_cancel := λ a b c h, by rw [← inv_mul_cancel_left a b, h, inv_mul_cancel_left], ..‹group G› } @[priority 100, to_additive] -- see Note [lower instance priority] instance group.to_right_cancel_semigroup : right_cancel_semigroup G := { mul_right_cancel := λ a b c h, by rw [← mul_inv_cancel_right a b, h, mul_inv_cancel_right], ..‹group G› } @[priority 100, to_additive] -- see Note [lower instance priority] instance group.to_cancel_monoid : cancel_monoid G := { ..‹group G›, .. group.to_left_cancel_semigroup, ..group.to_right_cancel_semigroup } end group section add_group variables {G : Type u} [add_group G] /-- The subtraction operation on an `add_group` -/ @[reducible] protected def algebra.sub (a b : G) : G := a + -b @[priority 100] -- see Note [lower instance priority] instance add_group_has_sub : has_sub G := ⟨algebra.sub⟩ lemma sub_eq_add_neg (a b : G) : a - b = a + -b := rfl end add_group /-- A commutative group is a group with commutative `(*)`. -/ @[protect_proj, ancestor group comm_monoid] class comm_group (G : Type u) extends group G, comm_monoid G /-- An additive commutative group is an additive group with commutative `(+)`. -/ @[protect_proj, ancestor add_group add_comm_monoid] class add_comm_group (G : Type u) extends add_group G, add_comm_monoid G attribute [to_additive] comm_group attribute [instance, priority 300] add_comm_group.to_add_comm_monoid section comm_group variables {G : Type u} [comm_group G] @[priority 100, to_additive] -- see Note [lower instance priority] instance comm_group.to_cancel_comm_monoid : cancel_comm_monoid G := { ..‹comm_group G›, ..group.to_left_cancel_semigroup, ..group.to_right_cancel_semigroup } end comm_group
4378b7f1a8b7b7b8043a952174333a22256a2f83
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/examples/NFM2022/nfm9.lean
85a4886975c08dda552391be32d067a9c28f8714
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,304
lean
/- Mutual recursion -/ inductive Term where | const : String → Term | app : String → List Term → Term namespace Term mutual def numConsts : Term → Nat | const _ => 1 | app _ cs => numConstsLst cs def numConstsLst : List Term → Nat | [] => 0 | c :: cs => numConsts c + numConstsLst cs end mutual def replaceConst (a b : String) : Term → Term | const c => if a = c then const b else const c | app f cs => app f (replaceConstLst a b cs) def replaceConstLst (a b : String) : List Term → List Term | [] => [] | c :: cs => replaceConst a b c :: replaceConstLst a b cs end /- Mutual recursion in theorems -/ mutual theorem numConsts_replaceConst (a b : String) (e : Term) : numConsts (replaceConst a b e) = numConsts e := by match e with | const c => simp [replaceConst]; split <;> simp [numConsts] | app f cs => simp [replaceConst, numConsts, numConsts_replaceConstLst a b cs] theorem numConsts_replaceConstLst (a b : String) (es : List Term) : numConstsLst (replaceConstLst a b es) = numConstsLst es := by match es with | [] => simp [replaceConstLst, numConstsLst] | c :: cs => simp [replaceConstLst, numConstsLst, numConsts_replaceConst a b c, numConsts_replaceConstLst a b cs] end
c6e6d5673407cc209729482b6e189ec99da9055b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/semidirect_product.lean
6ce04626068ccc15f406da009e6853a4b626d846
[ "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
8,487
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.hom.aut import logic.function.basic import group_theory.subgroup.basic /-! # Semidirect product This file defines semidirect products of groups, and the canonical maps in and out of the semidirect product. The semidirect product of `N` and `G` given a hom `φ` from `G` to the automorphism group of `N` is the product of sets with the group `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` ## Key definitions There are two homs into the semidirect product `inl : N →* N ⋊[φ] G` and `inr : G →* N ⋊[φ] G`, and `lift` can be used to define maps `N ⋊[φ] G →* H` out of the semidirect product given maps `f₁ : N →* H` and `f₂ : G →* H` that satisfy the condition `∀ n g, f₁ (φ g n) = f₂ g * f₁ n * f₂ g⁻¹` ## Notation This file introduces the global notation `N ⋊[φ] G` for `semidirect_product N G φ` ## Tags group, semidirect product -/ variables (N : Type*) (G : Type*) {H : Type*} [group N] [group G] [group H] /-- The semidirect product of groups `N` and `G`, given a map `φ` from `G` to the automorphism group of `N`. It the product of sets with the group operation `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` -/ @[ext, derive decidable_eq] structure semidirect_product (φ : G →* mul_aut N) := (left : N) (right : G) attribute [pp_using_anonymous_constructor] semidirect_product notation N` ⋊[`:35 φ:35`] `:0 G :35 := semidirect_product N G φ namespace semidirect_product variables {N G} {φ : G →* mul_aut N} instance : group (N ⋊[φ] G) := { one := ⟨1, 1⟩, mul := λ a b, ⟨a.1 * φ a.2 b.1, a.2 * b.2⟩, inv := λ x, ⟨φ x.2⁻¹ x.1⁻¹, x.2⁻¹⟩, mul_assoc := λ a b c, by ext; simp [mul_assoc], one_mul := λ a, ext _ _ (by simp) (one_mul a.2), mul_one := λ a, ext _ _ (by simp) (mul_one _), mul_left_inv := λ ⟨a, b⟩, ext _ _ (show φ b⁻¹ a⁻¹ * φ b⁻¹ a = 1, by simp) (mul_left_inv b) } instance : inhabited (N ⋊[φ] G) := ⟨1⟩ @[simp] lemma one_left : (1 : N ⋊[φ] G).left = 1 := rfl @[simp] lemma one_right : (1 : N ⋊[φ] G).right = 1 := rfl @[simp] lemma inv_left (a : N ⋊[φ] G) : (a⁻¹).left = φ a.right⁻¹ a.left⁻¹ := rfl @[simp] lemma inv_right (a : N ⋊[φ] G) : (a⁻¹).right = a.right⁻¹ := rfl @[simp] lemma mul_left (a b : N ⋊[φ] G) : (a * b).left = a.left * φ a.right b.left := rfl @[simp] lemma mul_right (a b : N ⋊[φ] G) : (a * b).right = a.right * b.right := rfl /-- The canonical map `N →* N ⋊[φ] G` sending `n` to `⟨n, 1⟩` -/ def inl : N →* N ⋊[φ] G := { to_fun := λ n, ⟨n, 1⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inl (n : N) : (inl n : N ⋊[φ] G).left = n := rfl @[simp] lemma right_inl (n : N) : (inl n : N ⋊[φ] G).right = 1 := rfl lemma inl_injective : function.injective (inl : N → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨left, left_inl⟩ @[simp] lemma inl_inj {n₁ n₂ : N} : (inl n₁ : N ⋊[φ] G) = inl n₂ ↔ n₁ = n₂ := inl_injective.eq_iff /-- The canonical map `G →* N ⋊[φ] G` sending `g` to `⟨1, g⟩` -/ def inr : G →* N ⋊[φ] G := { to_fun := λ g, ⟨1, g⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inr (g : G) : (inr g : N ⋊[φ] G).left = 1 := rfl @[simp] lemma right_inr (g : G) : (inr g : N ⋊[φ] G).right = g := rfl lemma inr_injective : function.injective (inr : G → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨right, right_inr⟩ @[simp] lemma inr_inj {g₁ g₂ : G} : (inr g₁ : N ⋊[φ] G) = inr g₂ ↔ g₁ = g₂ := inr_injective.eq_iff lemma inl_aut (g : G) (n : N) : (inl (φ g n) : N ⋊[φ] G) = inr g * inl n * inr g⁻¹ := by ext; simp lemma inl_aut_inv (g : G) (n : N) : (inl ((φ g)⁻¹ n) : N ⋊[φ] G) = inr g⁻¹ * inl n * inr g := by rw [← monoid_hom.map_inv, inl_aut, inv_inv] @[simp] lemma mk_eq_inl_mul_inr (g : G) (n : N) : (⟨n, g⟩ : N ⋊[φ] G) = inl n * inr g := by ext; simp @[simp] lemma inl_left_mul_inr_right (x : N ⋊[φ] G) : inl x.left * inr x.right = x := by ext; simp /-- The canonical projection map `N ⋊[φ] G →* G`, as a group hom. -/ def right_hom : N ⋊[φ] G →* G := { to_fun := semidirect_product.right, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp] lemma right_hom_eq_right : (right_hom : N ⋊[φ] G → G) = right := rfl @[simp] lemma right_hom_comp_inl : (right_hom : N ⋊[φ] G →* G).comp inl = 1 := by ext; simp [right_hom] @[simp] lemma right_hom_comp_inr : (right_hom : N ⋊[φ] G →* G).comp inr = monoid_hom.id _ := by ext; simp [right_hom] @[simp] lemma right_hom_inl (n : N) : right_hom (inl n : N ⋊[φ] G) = 1 := by simp [right_hom] @[simp] lemma right_hom_inr (g : G) : right_hom (inr g : N ⋊[φ] G) = g := by simp [right_hom] lemma right_hom_surjective : function.surjective (right_hom : N ⋊[φ] G → G) := function.surjective_iff_has_right_inverse.2 ⟨inr, right_hom_inr⟩ lemma range_inl_eq_ker_right_hom : (inl : N →* N ⋊[φ] G).range = right_hom.ker := le_antisymm (λ _, by simp [monoid_hom.mem_ker, eq_comm] {contextual := tt}) (λ x hx, ⟨x.left, by ext; simp [*, monoid_hom.mem_ker] at *⟩) section lift variables (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) /-- Define a group hom `N ⋊[φ] G →* H`, by defining maps `N →* H` and `G →* H` -/ def lift (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* H := { to_fun := λ a, f₁ a.1 * f₂ a.2, map_one' := by simp, map_mul' := λ a b, begin have := λ n g, monoid_hom.ext_iff.1 (h n) g, simp only [mul_aut.conj_apply, monoid_hom.comp_apply, mul_equiv.coe_to_monoid_hom] at this, simp [this, mul_assoc] end } @[simp] lemma lift_inl (n : N) : lift f₁ f₂ h (inl n) = f₁ n := by simp [lift] @[simp] lemma lift_comp_inl : (lift f₁ f₂ h).comp inl = f₁ := by ext; simp @[simp] lemma lift_inr (g : G) : lift f₁ f₂ h (inr g) = f₂ g := by simp [lift] @[simp] lemma lift_comp_inr : (lift f₁ f₂ h).comp inr = f₂ := by ext; simp lemma lift_unique (F : N ⋊[φ] G →* H) : F = lift (F.comp inl) (F.comp inr) (λ _, by ext; simp [inl_aut]) := begin ext, simp only [lift, monoid_hom.comp_apply, monoid_hom.coe_mk], rw [← F.map_mul, inl_left_mul_inr_right], end /-- Two maps out of the semidirect product are equal if they're equal after composition with both `inl` and `inr` -/ lemma hom_ext {f g : (N ⋊[φ] G) →* H} (hl : f.comp inl = g.comp inl) (hr : f.comp inr = g.comp inr) : f = g := by { rw [lift_unique f, lift_unique g], simp only * } end lift section map variables {N₁ : Type*} {G₁ : Type*} [group N₁] [group G₁] {φ₁ : G₁ →* mul_aut N₁} /-- Define a map from `N ⋊[φ] G` to `N₁ ⋊[φ₁] G₁` given maps `N →* N₁` and `G →* G₁` that satisfy a commutativity condition `∀ n g, f₁ (φ g n) = φ₁ (f₂ g) (f₁ n)`. -/ def map (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* N₁ ⋊[φ₁] G₁ := { to_fun := λ x, ⟨f₁ x.1, f₂ x.2⟩, map_one' := by simp, map_mul' := λ x y, begin replace h := monoid_hom.ext_iff.1 (h x.right) y.left, ext; simp * at *, end } variables (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) @[simp] lemma map_left (g : N ⋊[φ] G) : (map f₁ f₂ h g).left = f₁ g.left := rfl @[simp] lemma map_right (g : N ⋊[φ] G) : (map f₁ f₂ h g).right = f₂ g.right := rfl @[simp] lemma right_hom_comp_map : right_hom.comp (map f₁ f₂ h) = f₂.comp right_hom := rfl @[simp] lemma map_inl (n : N) : map f₁ f₂ h (inl n) = inl (f₁ n) := by simp [map] @[simp] lemma map_comp_inl : (map f₁ f₂ h).comp inl = inl.comp f₁ := by ext; simp @[simp] lemma map_inr (g : G) : map f₁ f₂ h (inr g) = inr (f₂ g) := by simp [map] @[simp] lemma map_comp_inr : (map f₁ f₂ h).comp inr = inr.comp f₂ := by ext; simp [map] end map end semidirect_product
8b51a32c82981defd019c444705354ee4f4f2f48
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/nat/gcd.lean
e67884123c92a0d34160d4350613addcdf13a889
[ "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
15,581
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 Definitions and properties of gcd, lcm, and coprime. -/ import .div open eq.ops well_founded decidable prod namespace nat /- gcd -/ private definition pair_nat.lt : nat × nat → nat × nat → Prop := measure pr₂ private definition pair_nat.lt.wf : well_founded pair_nat.lt := intro_k (measure.wf pr₂) 20 -- we use intro_k to be able to execute gcd efficiently in the kernel local attribute pair_nat.lt.wf [instance] -- instance will not be saved in .olean local infixl ` ≺ `:50 := pair_nat.lt private definition gcd.lt.dec (x y₁ : nat) : (succ y₁, x % succ y₁) ≺ (x, succ y₁) := !mod_lt (succ_pos y₁) definition gcd.F : Π (p₁ : nat × nat), (Π p₂ : nat × nat, p₂ ≺ p₁ → nat) → nat | (x, 0) f := x | (x, succ y) f := f (succ y, x % succ y) !gcd.lt.dec definition gcd (x y : nat) := fix gcd.F (x, y) theorem gcd_zero_right [simp] (x : nat) : gcd x 0 = x := rfl theorem gcd_succ [simp] (x y : nat) : gcd x (succ y) = gcd (succ y) (x % succ y) := well_founded.fix_eq gcd.F (x, succ y) theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 := calc gcd n 1 = gcd 1 (n % 1) : gcd_succ ... = gcd 1 0 : mod_one theorem gcd_def (x : ℕ) : Π (y : ℕ), gcd x y = if y = 0 then x else gcd y (x % y) | 0 := !gcd_zero_right | (succ y) := !gcd_succ ⬝ (if_neg !succ_ne_zero)⁻¹ theorem gcd_self : Π (n : ℕ), gcd n n = n | 0 := rfl | (succ n₁) := calc gcd (succ n₁) (succ n₁) = gcd (succ n₁) (succ n₁ % succ n₁) : gcd_succ ... = gcd (succ n₁) 0 : mod_self theorem gcd_zero_left : Π (n : ℕ), gcd 0 n = n | 0 := rfl | (succ n₁) := calc gcd 0 (succ n₁) = gcd (succ n₁) (0 % succ n₁) : gcd_succ ... = gcd (succ n₁) 0 : zero_mod theorem gcd_of_pos (m : ℕ) {n : ℕ} (H : n > 0) : gcd m n = gcd n (m % n) := gcd_def m n ⬝ if_neg (ne_zero_of_pos H) theorem gcd_rec (m n : ℕ) : gcd m n = gcd n (m % n) := by_cases_zero_pos n (calc m = gcd 0 m : gcd_zero_left ... = gcd 0 (m % 0) : mod_zero) (take n, assume H : 0 < n, gcd_of_pos m H) theorem gcd.induction {P : ℕ → ℕ → Prop} (m n : ℕ) (H0 : ∀m, P m 0) (H1 : ∀m n, 0 < n → P n (m % n) → P m n) : P m n := induction (m, n) (prod.rec (λm, nat.rec (λ IH, H0 m) (λ n₁ v (IH : ∀p₂, p₂ ≺ (m, succ n₁) → P (pr₁ p₂) (pr₂ p₂)), H1 m (succ n₁) !succ_pos (IH _ !gcd.lt.dec)))) theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) := gcd.induction m n (take m, and.intro (!one_mul ▸ !dvd_mul_left) !dvd_zero) (take m n (npos : 0 < n), and.rec (assume (IH₁ : gcd n (m % n) ∣ n) (IH₂ : gcd n (m % n) ∣ (m % n)), have H : (gcd n (m % n) ∣ (m / n * n + m % n)), from dvd_add (dvd.trans IH₁ !dvd_mul_left) IH₂, have H1 : (gcd n (m % n) ∣ m), from !eq_div_mul_add_mod⁻¹ ▸ H, show (gcd m n ∣ m) ∧ (gcd m n ∣ n), from !gcd_rec⁻¹ ▸ (and.intro H1 IH₁))) theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := and.left !gcd_dvd theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := and.right !gcd_dvd theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := gcd.induction m n (take m, imp.intro) (take m n (npos : n > 0) (IH : k ∣ n → k ∣ m % n → k ∣ gcd n (m % n)) (H1 : k ∣ m) (H2 : k ∣ n), have H3 : k ∣ m / n * n + m % n, from !eq_div_mul_add_mod ▸ H1, have H4 : k ∣ m % n, from nat.dvd_of_dvd_add_left H3 (dvd.trans H2 !dvd_mul_left), !gcd_rec⁻¹ ▸ IH H2 H4) theorem gcd.comm (m n : ℕ) : gcd m n = gcd n m := dvd.antisymm (dvd_gcd !gcd_dvd_right !gcd_dvd_left) (dvd_gcd !gcd_dvd_right !gcd_dvd_left) theorem gcd.assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := dvd.antisymm (dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_left) (dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_right) !gcd_dvd_right)) (dvd_gcd (dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !gcd_dvd_left)) (dvd.trans !gcd_dvd_right !gcd_dvd_right)) theorem gcd_one_left (m : ℕ) : gcd 1 m = 1 := !gcd.comm ⬝ !gcd_one_right theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := gcd.induction n k (take n, calc gcd (m * n) (m * 0) = gcd (m * n) 0 : mul_zero) (take n k, assume H : 0 < k, assume IH : gcd (m * k) (m * (n % k)) = m * gcd k (n % k), calc gcd (m * n) (m * k) = gcd (m * k) (m * n % (m * k)) : !gcd_rec ... = gcd (m * k) (m * (n % k)) : mul_mod_mul_left ... = m * gcd k (n % k) : IH ... = m * gcd n k : !gcd_rec) theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := calc gcd (m * n) (k * n) = gcd (n * m) (k * n) : mul.comm ... = gcd (n * m) (n * k) : mul.comm ... = n * gcd m k : gcd_mul_left ... = gcd m k * n : mul.comm theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : m > 0) : gcd m n > 0 := pos_of_dvd_of_pos !gcd_dvd_left mpos theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : n > 0) : gcd m n > 0 := pos_of_dvd_of_pos !gcd_dvd_right 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) (assume H1, H1) (assume H1 : m > 0, absurd H⁻¹ (ne_of_lt (!gcd_pos_of_pos_left 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 (!gcd.comm ▸ H) theorem gcd_div {m n k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m / k) (n / k) = gcd m n / k := or.elim (eq_zero_or_pos k) (assume H3 : k = 0, by subst k; rewrite *nat.div_zero) (assume H3 : k > 0, (nat.div_eq_of_eq_mul_left H3 (calc gcd m n = gcd m (n / k * k) : nat.div_mul_cancel H2 ... = gcd (m / k * k) (n / k * k) : nat.div_mul_cancel H1 ... = gcd (m / k) (n / k) * k : gcd_mul_right))⁻¹) theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n := dvd_gcd (dvd.trans !gcd_dvd_left !dvd_mul_left) !gcd_dvd_right theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n := !mul.comm ▸ !gcd_dvd_gcd_mul_left theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) := dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !dvd_mul_left) theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) := !mul.comm ▸ !gcd_dvd_gcd_mul_left_right /- lcm -/ definition lcm (m n : ℕ) : ℕ := m * n / (gcd m n) theorem lcm.comm (m n : ℕ) : lcm m n = lcm n m := calc lcm m n = m * n / gcd m n : rfl ... = n * m / gcd m n : mul.comm ... = n * m / gcd n m : gcd.comm ... = lcm n m : rfl theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 := calc lcm 0 m = 0 * m / gcd 0 m : rfl ... = 0 / gcd 0 m : zero_mul ... = 0 : nat.zero_div theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := !lcm.comm ▸ !lcm_zero_left theorem lcm_one_left (m : ℕ) : lcm 1 m = m := calc lcm 1 m = 1 * m / gcd 1 m : rfl ... = m / gcd 1 m : one_mul ... = m / 1 : gcd_one_left ... = m : nat.div_one theorem lcm_one_right (m : ℕ) : lcm m 1 = m := !lcm.comm ▸ !lcm_one_left theorem lcm_self (m : ℕ) : lcm m m = m := have H : m * m / m = m, from by_cases_zero_pos m !nat.div_zero (take m, assume H1 : m > 0, !nat.mul_div_cancel H1), calc lcm m m = m * m / gcd m m : rfl ... = m * m / m : gcd_self ... = m : H theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n := have H : lcm m n = m * (n / gcd m n), from nat.mul_div_assoc _ !gcd_dvd_right, dvd.intro H⁻¹ theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n := !lcm.comm ▸ !dvd_lcm_left theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n := eq.symm (nat.eq_mul_of_div_eq_right (dvd.trans !gcd_dvd_left !dvd_mul_right) rfl) theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := or.elim (eq_zero_or_pos k) (assume kzero : k = 0, !kzero⁻¹ ▸ !dvd_zero) (assume kpos : k > 0, have mpos : m > 0, from pos_of_dvd_of_pos H1 kpos, have npos : n > 0, from pos_of_dvd_of_pos H2 kpos, have gcd_pos : gcd m n > 0, from !gcd_pos_of_pos_left mpos, obtain p (km : k = m * p), from exists_eq_mul_right_of_dvd H1, obtain q (kn : k = n * q), from exists_eq_mul_right_of_dvd H2, have ppos : p > 0, from pos_of_mul_pos_left (km ▸ kpos), have qpos : q > 0, from pos_of_mul_pos_left (kn ▸ kpos), have H3 : p * q * (m * n * gcd p q) = p * q * (gcd m n * k), from calc p * q * (m * n * gcd p q) = m * p * (n * q * gcd p q) : by rewrite [*mul.assoc, *mul.left_comm q, mul.left_comm p] ... = k * (k * gcd p q) : by rewrite [-kn, -km] ... = k * gcd (k * p) (k * q) : by rewrite gcd_mul_left ... = k * gcd (n * q * p) (m * p * q) : by rewrite [-kn, -km] ... = k * (gcd n m * (p * q)) : by rewrite [*mul.assoc, mul.comm q, gcd_mul_right] ... = p * q * (gcd m n * k) : by rewrite [mul.comm, mul.comm (gcd n m), gcd.comm, *mul.assoc], have H4 : m * n * gcd p q = gcd m n * k, from !eq_of_mul_eq_mul_left (mul_pos ppos qpos) H3, have H5 : gcd m n * (lcm m n * gcd p q) = gcd m n * k, from !mul.assoc ▸ !gcd_mul_lcm⁻¹ ▸ H4, have H6 : lcm m n * gcd p q = k, from !eq_of_mul_eq_mul_left gcd_pos H5, dvd.intro H6) theorem lcm.assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := dvd.antisymm (lcm_dvd (lcm_dvd !dvd_lcm_left (dvd.trans !dvd_lcm_left !dvd_lcm_right)) (dvd.trans !dvd_lcm_right !dvd_lcm_right)) (lcm_dvd (dvd.trans !dvd_lcm_left !dvd_lcm_left) (lcm_dvd (dvd.trans !dvd_lcm_right !dvd_lcm_left) !dvd_lcm_right)) /- coprime -/ definition coprime [reducible] (m n : ℕ) : Prop := gcd m n = 1 lemma gcd_eq_one_of_coprime {m n : ℕ} : coprime m n → gcd m n = 1 := λ h, h theorem coprime_swap {m n : ℕ} (H : coprime n m) : coprime m n := !gcd.comm ▸ H theorem dvd_of_coprime_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := have H3 : gcd (m * k) (m * n) = m, from calc gcd (m * k) (m * n) = m * gcd k n : gcd_mul_left ... = m * 1 : H1 ... = m : mul_one, have H4 : (k ∣ gcd (m * k) (m * n)), from dvd_gcd !dvd_mul_left H2, H3 ▸ H4 theorem dvd_of_coprime_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n := dvd_of_coprime_of_dvd_mul_right H1 (!mul.comm ▸ H2) theorem gcd_mul_left_cancel_of_coprime {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := have H1 : coprime (gcd (k * m) n) k, from calc gcd (gcd (k * m) n) k = gcd (k * gcd 1 m) n : by rewrite [-gcd_mul_left, mul_one, gcd.comm, gcd.assoc] ... = 1 : by rewrite [gcd_one_left, mul_one, ↑coprime at H, H], dvd.antisymm (dvd_gcd (dvd_of_coprime_of_dvd_mul_left H1 !gcd_dvd_left) !gcd_dvd_right) (dvd_gcd (dvd.trans !gcd_dvd_left !dvd_mul_left) !gcd_dvd_right) theorem gcd_mul_right_cancel_of_coprime (m : ℕ) {k n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n := !mul.comm ▸ !gcd_mul_left_cancel_of_coprime H theorem gcd_mul_left_cancel_of_coprime_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := !gcd.comm ▸ !gcd.comm ▸ !gcd_mul_left_cancel_of_coprime H theorem gcd_mul_right_cancel_of_coprime_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n := !gcd.comm ▸ !gcd.comm ▸ !gcd_mul_right_cancel_of_coprime H theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : gcd m n > 0) : coprime (m / gcd m n) (n / gcd m n) := calc gcd (m / gcd m n) (n / gcd m n) = gcd m n / gcd m n : gcd_div !gcd_dvd_left !gcd_dvd_right ... = 1 : nat.div_self H theorem not_coprime_of_dvd_of_dvd {m n d : ℕ} (dgt1 : d > 1) (Hm : d ∣ m) (Hn : d ∣ n) : ¬ coprime m n := assume co : coprime m n, have d ∣ gcd m n, from dvd_gcd Hm Hn, have d ∣ 1, by rewrite [↑coprime at co, co at this]; apply this, have d ≤ 1, from le_of_dvd dec_trivial this, show false, from not_lt_of_ge `d ≤ 1` `d > 1` theorem exists_coprime {m n : ℕ} (H : gcd m n > 0) : exists m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := have H1 : m = (m / gcd m n) * gcd m n, from (nat.div_mul_cancel !gcd_dvd_left)⁻¹, have H2 : n = (n / gcd m n) * gcd m n, from (nat.div_mul_cancel !gcd_dvd_right)⁻¹, exists.intro _ (exists.intro _ (and.intro (coprime_div_gcd_div_gcd H) (and.intro H1 H2))) theorem coprime_mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k := calc gcd (m * n) k = gcd n k : !gcd_mul_left_cancel_of_coprime H1 ... = 1 : H2 theorem coprime_mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) := coprime_swap (coprime_mul (coprime_swap H1) (coprime_swap H2)) theorem coprime_of_coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n := have H1 : (gcd m n ∣ gcd (k * m) n), from !gcd_dvd_gcd_mul_left, eq_one_of_dvd_one (H ▸ H1) theorem coprime_of_coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n := coprime_of_coprime_mul_left (!mul.comm ▸ H) theorem coprime_of_coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n := coprime_swap (coprime_of_coprime_mul_left (coprime_swap H)) theorem coprime_of_coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n := coprime_of_coprime_mul_left_right (!mul.comm ▸ H) theorem comprime_one_left : ∀ n, coprime 1 n := λ n, !gcd_one_left theorem comprime_one_right : ∀ n, coprime n 1 := λ n, !gcd_one_right theorem exists_eq_prod_and_dvd_and_dvd {m n k : nat} (H : k ∣ m * n) : ∃ m' n', k = m' * n' ∧ m' ∣ m ∧ n' ∣ n := or.elim (eq_zero_or_pos (gcd k m)) (assume H1 : gcd k m = 0, have H2 : k = 0, from eq_zero_of_gcd_eq_zero_left H1, have H3 : m = 0, from eq_zero_of_gcd_eq_zero_right H1, have H4 : k = 0 * n, from H2 ⬝ !zero_mul⁻¹, have H5 : 0 ∣ m, from H3⁻¹ ▸ !dvd.refl, have H6 : n ∣ n, from !dvd.refl, exists.intro _ (exists.intro _ (and.intro H4 (and.intro H5 H6)))) (assume H1 : gcd k m > 0, have H2 : gcd k m ∣ k, from !gcd_dvd_left, have H3 : k / gcd k m ∣ (m * n) / gcd k m, from nat.div_dvd_div H2 H, have H4 : (m * n) / gcd k m = (m / gcd k m) * n, from calc m * n / gcd k m = n * m / gcd k m : mul.comm ... = n * (m / gcd k m) : !nat.mul_div_assoc !gcd_dvd_right ... = m / gcd k m * n : mul.comm, have H5 : k / gcd k m ∣ (m / gcd k m) * n, from H4 ▸ H3, have H6 : coprime (k / gcd k m) (m / gcd k m), from coprime_div_gcd_div_gcd H1, have H7 : k / gcd k m ∣ n, from dvd_of_coprime_of_dvd_mul_left H6 H5, have H8 : k = gcd k m * (k / gcd k m), from (nat.mul_div_cancel' H2)⁻¹, exists.intro _ (exists.intro _ (and.intro H8 (and.intro !gcd_dvd_right H7)))) end nat
025ddefc11d0272170fabe68ab6569d1aec0c62b
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/ordered_group.lean
157f3f18923d8f294d5d964d6e5a1e67eae2465b
[ "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
65,804
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.group.with_one import algebra.group.type_tags import order.bounded_lattice set_option old_structure_cmd true set_option default_priority 100 -- see Note [default priority] /-! # Ordered monoids and groups This file develops the basics of ordered monoids and groups. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ universe u variable {α : Type u} /-- An ordered commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c * a ≤ c * b` (multiplication is monotone) * `a * b < a * c → b < c`. -/ @[protect_proj, ancestor comm_monoid partial_order] class ordered_comm_monoid (α : Type*) extends comm_monoid α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (lt_of_mul_lt_mul_left : ∀ a b c : α, a * b < a * c → b < c) /-- An ordered (additive) commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c + a ≤ c + b` (addition is monotone) * `a + b < a + c → b < c`. -/ @[protect_proj, ancestor add_comm_monoid partial_order] class ordered_add_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c) attribute [to_additive ordered_add_comm_monoid] ordered_comm_monoid section ordered_comm_monoid variables [ordered_comm_monoid α] {a b c d : α} @[to_additive add_le_add_left] lemma mul_le_mul_left' (h : a ≤ b) (c) : c * a ≤ c * b := ordered_comm_monoid.mul_le_mul_left a b h c @[to_additive add_le_add_right] lemma mul_le_mul_right' (h : a ≤ b) (c) : a * c ≤ b * c := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left' h c @[to_additive lt_of_add_lt_add_left] lemma lt_of_mul_lt_mul_left' : a * b < a * c → b < c := ordered_comm_monoid.lt_of_mul_lt_mul_left a b c @[to_additive add_le_add] lemma mul_le_mul' (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := le_trans (mul_le_mul_right' h₁ _) (mul_le_mul_left' h₂ _) @[to_additive] lemma mul_le_mul_three {a b c d e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a * b * c ≤ d * e * f := mul_le_mul' (mul_le_mul' h₁ h₂) h₃ @[to_additive] lemma le_mul_of_one_le_right (h : 1 ≤ b) : a ≤ a * b := have a * 1 ≤ a * b, from mul_le_mul_left' h _, by rwa mul_one at this @[to_additive] lemma le_mul_of_one_le_left (h : 1 ≤ b) : a ≤ b * a := have 1 * a ≤ b * a, from mul_le_mul_right' h a, by rwa one_mul at this @[to_additive lt_of_add_lt_add_right] lemma lt_of_mul_lt_mul_right' (h : a * b < c * b) : a < c := lt_of_mul_lt_mul_left' (show b * a < b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) -- here we start using properties of one. @[to_additive] lemma le_mul_of_one_le_of_le (ha : 1 ≤ a) (hbc : b ≤ c) : b ≤ a * c := one_mul b ▸ mul_le_mul' ha hbc @[to_additive] lemma le_mul_of_le_of_one_le (hbc : b ≤ c) (ha : 1 ≤ a) : b ≤ c * a := mul_one b ▸ mul_le_mul' hbc ha @[to_additive add_nonneg] lemma one_le_mul (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := le_mul_of_one_le_of_le ha hb @[to_additive add_pos_of_pos_of_nonneg] lemma one_lt_mul_of_lt_of_le' (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := lt_of_lt_of_le ha $ le_mul_of_one_le_right hb @[to_additive add_pos_of_nonneg_of_pos] lemma one_lt_mul_of_le_of_lt' (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := lt_of_lt_of_le hb $ le_mul_of_one_le_left ha @[to_additive add_pos] lemma one_lt_mul' (ha : 1 < a) (hb : 1 < b) : 1 < a * b := one_lt_mul_of_lt_of_le' ha $ le_of_lt hb @[to_additive add_nonpos] lemma mul_le_one' (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := one_mul (1:α) ▸ (mul_le_mul' ha hb) @[to_additive] lemma mul_le_of_le_one_of_le' (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one' (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one' (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := lt_of_le_of_lt (mul_le_of_le_of_le_one' (le_refl _) hb) ha @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one' (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := lt_of_le_of_lt (mul_le_of_le_one_of_le' ha (le_refl _)) hb @[to_additive] lemma mul_lt_one' (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_one_of_le_one_of_lt_one' (le_of_lt ha) hb @[to_additive] lemma lt_mul_of_one_le_of_lt' (ha : 1 ≤ a) (hbc : b < c) : b < a * c := lt_of_lt_of_le hbc $ le_mul_of_one_le_left ha @[to_additive] lemma lt_mul_of_lt_of_one_le' (hbc : b < c) (ha : 1 ≤ a) : b < c * a := lt_of_lt_of_le hbc $ le_mul_of_one_le_right ha @[to_additive] lemma lt_mul_of_one_lt_of_lt' (ha : 1 < a) (hbc : b < c) : b < a * c := lt_mul_of_one_le_of_lt' (le_of_lt ha) hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt' (hbc : b < c) (ha : 1 < a) : b < c * a := lt_mul_of_lt_of_one_le' hbc (le_of_lt ha) @[to_additive] lemma mul_lt_of_le_one_of_lt' (ha : a ≤ 1) (hbc : b < c) : a * b < c := lt_of_le_of_lt (mul_le_of_le_one_of_le' ha (le_refl _)) hbc @[to_additive] lemma mul_lt_of_lt_of_le_one' (hbc : b < c) (ha : a ≤ 1) : b * a < c := lt_of_le_of_lt (mul_le_of_le_of_le_one' (le_refl _) ha) hbc @[to_additive] lemma mul_lt_of_lt_one_of_lt' (ha : a < 1) (hbc : b < c) : a * b < c := mul_lt_of_le_one_of_lt' (le_of_lt ha) hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one' (hbc : b < c) (ha : a < 1) : b * a < c := mul_lt_of_lt_of_le_one' hbc (le_of_lt ha) @[to_additive] lemma mul_eq_one_iff' (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := iff.intro (assume hab : a * b = 1, have a ≤ 1, from hab ▸ le_mul_of_le_of_one_le (le_refl _) hb, have a = 1, from le_antisymm this ha, have b ≤ 1, from hab ▸ le_mul_of_one_le_of_le ha (le_refl _), have b = 1, from le_antisymm this hb, and.intro ‹a = 1› ‹b = 1›) (assume ⟨ha', hb'⟩, by rw [ha', hb', mul_one]) section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add] lemma monotone.mul' (hf : monotone f) (hg : monotone g) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul' (hf h) (hg h) @[to_additive monotone.add_const] lemma monotone.mul_const' (hf : monotone f) (a : α) : monotone (λ x, f x * a) := hf.mul' monotone_const @[to_additive monotone.const_add] lemma monotone.const_mul' (hf : monotone f) (a : α) : monotone (λ x, a * f x) := monotone_const.mul' hf end mono end ordered_comm_monoid lemma bit0_pos [ordered_add_comm_monoid α] {a : α} (h : 0 < a) : 0 < bit0 a := add_pos h h namespace units @[to_additive] instance [monoid α] [preorder α] : preorder (units α) := preorder.lift (coe : units α → α) @[simp, to_additive, norm_cast] theorem coe_le_coe [monoid α] [preorder α] {a b : units α} : (a : α) ≤ b ↔ a ≤ b := iff.rfl @[simp, to_additive, norm_cast] theorem coe_lt_coe [monoid α] [preorder α] {a b : units α} : (a : α) < b ↔ a < b := iff.rfl @[to_additive] instance [monoid α] [partial_order α] : partial_order (units α) := partial_order.lift coe units.ext @[to_additive] instance [monoid α] [linear_order α] : linear_order (units α) := linear_order.lift coe units.ext @[to_additive] instance [monoid α] [decidable_linear_order α] : decidable_linear_order (units α) := decidable_linear_order.lift coe units.ext @[simp, to_additive, norm_cast] theorem max_coe [monoid α] [decidable_linear_order α] {a b : units α} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [max, h] @[simp, to_additive, norm_cast] theorem min_coe [monoid α] [decidable_linear_order α] {a b : units α} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [min, h] end units namespace with_zero instance [preorder α] : preorder (with_zero α) := with_bot.preorder instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order instance [partial_order α] : order_bot (with_zero α) := with_bot.order_bot instance [lattice α] : lattice (with_zero α) := with_bot.lattice instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order instance [decidable_linear_order α] : decidable_linear_order (with_zero α) := with_bot.decidable_linear_order /-- If `0` is the least element in `α`, then `with_zero α` is an `ordered_add_comm_monoid`. -/ def ordered_add_comm_monoid [ordered_add_comm_monoid α] (zero_le : ∀ a : α, 0 ≤ a) : ordered_add_comm_monoid (with_zero α) := begin suffices, refine { add_le_add_left := this, ..with_zero.partial_order, ..with_zero.add_comm_monoid, .. }, { intros a b c h, have h' := lt_iff_le_not_le.1 h, rw lt_iff_le_not_le at ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases c with c, { cases h'.2 (this _ _ bot_le a) }, { refine ⟨_, rfl, _⟩, cases a with a, { exact with_bot.some_le_some.1 h'.1 }, { exact le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h), } } }, { intros a b h c ca h₂, cases b with b, { rw le_antisymm h bot_le at h₂, exact ⟨_, h₂, le_refl _⟩ }, cases a with a, { change c + 0 = some ca at h₂, simp at h₂, simp [h₂], exact ⟨_, rfl, by simpa using add_le_add_left (zero_le b) _⟩ }, { simp at h, cases c with c; change some _ = _ at h₂; simp [-add_comm] at h₂; subst ca; refine ⟨_, rfl, _⟩, { exact h }, { exact add_le_add_left h _ } } } end end with_zero namespace with_top section has_one variables [has_one α] @[to_additive] instance : has_one (with_top α) := ⟨(1 : α)⟩ @[simp, to_additive] lemma coe_one : ((1 : α) : with_top α) = 1 := rfl @[simp, to_additive] lemma coe_eq_one {a : α} : (a : with_top α) = 1 ↔ a = 1 := coe_eq_coe @[simp, to_additive] theorem one_eq_coe {a : α} : 1 = (a : with_top α) ↔ a = 1 := by rw [eq_comm, coe_eq_one] attribute [norm_cast] coe_one coe_eq_one coe_zero coe_eq_zero one_eq_coe zero_eq_coe @[simp, to_additive] theorem top_ne_one : ⊤ ≠ (1 : with_top α) . @[simp, to_additive] theorem one_ne_top : (1 : with_top α) ≠ ⊤ . end has_one instance [has_add α] : has_add (with_top α) := ⟨λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a + b))⟩ instance [add_semigroup α] : add_semigroup (with_top α) := { add := (+), ..@additive.add_semigroup _ $ @with_zero.semigroup (multiplicative α) _ } @[norm_cast] lemma coe_add [has_add α] {a b : α} : ((a + b : α) : with_top α) = a + b := rfl @[norm_cast] lemma coe_bit0 [has_add α] {a : α} : ((bit0 a : α) : with_top α) = bit0 a := rfl @[norm_cast] lemma coe_bit1 [has_add α] [has_one α] {a : α} : ((bit1 a : α) : with_top α) = bit1 a := rfl instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) := { ..@additive.add_comm_semigroup _ $ @with_zero.comm_semigroup (multiplicative α) _ } instance [add_monoid α] : add_monoid (with_top α) := { zero := some 0, add := (+), ..@additive.add_monoid _ $ @monoid_with_zero.to_monoid _ $ @with_zero.monoid_with_zero (multiplicative α) _ } instance [add_comm_monoid α] : add_comm_monoid (with_top α) := { zero := 0, add := (+), ..@additive.add_comm_monoid _ $ @comm_monoid_with_zero.to_comm_monoid _ $ @with_zero.comm_monoid_with_zero (multiplicative α) _ } instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_top α) := begin suffices, refine { add_le_add_left := this, ..with_top.partial_order, ..with_top.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ c h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim le_top }, cases b with b, { exact (not_le_of_lt h).elim le_top }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $ with_top.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases b with b; cases h₂, cases a with a, {cases le_antisymm h le_top }, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end @[simp] lemma zero_lt_top [ordered_add_comm_monoid α] : (0 : with_top α) < ⊤ := coe_lt_top 0 @[simp, norm_cast] lemma zero_lt_coe [ordered_add_comm_monoid α] (a : α) : (0 : with_top α) < a ↔ 0 < a := coe_lt_coe @[simp] lemma add_top [ordered_add_comm_monoid α] : ∀{a : with_top α}, a + ⊤ = ⊤ | none := rfl | (some a) := rfl @[simp] lemma top_add [ordered_add_comm_monoid α] {a : with_top α} : ⊤ + a = ⊤ := rfl lemma add_eq_top [ordered_add_comm_monoid α] (a b : with_top α) : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by cases a; cases b; simp [none_eq_top, some_eq_coe, coe_add.symm] lemma add_lt_top [ordered_add_comm_monoid α] (a b : with_top α) : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ := by simp [lt_top_iff_ne_top, add_eq_top, not_or_distrib] end with_top namespace with_bot instance [has_zero α] : has_zero (with_bot α) := with_top.has_zero instance [has_one α] : has_one (with_bot α) := with_top.has_one instance [add_semigroup α] : add_semigroup (with_bot α) := with_top.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (with_bot α) := with_top.add_comm_semigroup instance [add_monoid α] : add_monoid (with_bot α) := with_top.add_monoid instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_bot α) := begin suffices, refine { add_le_add_left := this, ..with_bot.partial_order, ..with_bot.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim bot_le }, cases c with c, { exact (not_le_of_lt h).elim bot_le }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases a with a; cases h₂, cases b with b, {cases le_antisymm h bot_le}, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_zero [has_zero α] : ((0 : α) : with_bot α) = 0 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_one [has_one α] : ((1 : α) : with_bot α) = 1 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_eq_zero {α : Type*} [add_monoid α] {a : α} : (a : with_bot α) = 0 ↔ a = 0 := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_add [add_semigroup α] (a b : α) : ((a + b : α) : with_bot α) = a + b := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit0 [add_semigroup α] {a : α} : ((bit0 a : α) : with_bot α) = bit0 a := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit1 [add_semigroup α] [has_one α] {a : α} : ((bit1 a : α) : with_bot α) = bit1 a := by norm_cast @[simp] lemma bot_add [ordered_add_comm_monoid α] (a : with_bot α) : ⊥ + a = ⊥ := rfl @[simp] lemma add_bot [ordered_add_comm_monoid α] (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl end with_bot /-- A canonically ordered additive monoid is an ordered commutative additive monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ @[protect_proj] class canonically_ordered_add_monoid (α : Type*) extends ordered_add_comm_monoid α, order_bot α := (le_iff_exists_add : ∀a b:α, a ≤ b ↔ ∃c, b = a + c) section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] {a b c d : α} lemma le_iff_exists_add : a ≤ b ↔ ∃c, b = a + c := canonically_ordered_add_monoid.le_iff_exists_add a b @[simp] lemma zero_le (a : α) : 0 ≤ a := le_iff_exists_add.mpr ⟨a, by simp⟩ @[simp] lemma bot_eq_zero : (⊥ : α) = 0 := le_antisymm bot_le (zero_le ⊥) @[simp] lemma add_eq_zero_iff : a + b = 0 ↔ a = 0 ∧ b = 0 := add_eq_zero_iff' (zero_le _) (zero_le _) @[simp] lemma le_zero_iff_eq : a ≤ 0 ↔ a = 0 := iff.intro (assume h, le_antisymm h (zero_le a)) (assume h, h ▸ le_refl a) lemma zero_lt_iff_ne_zero : 0 < a ↔ a ≠ 0 := iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (zero_le _) hne.symm @[nolint ge_or_gt] lemma exists_pos_add_of_lt (h : a < b) : ∃ c > 0, a + c = b := begin obtain ⟨c, hc⟩ := le_iff_exists_add.1 (le_of_lt h), refine ⟨c, zero_lt_iff_ne_zero.2 _, hc.symm⟩, rintro rfl, simpa [hc, lt_irrefl] using h end lemma le_add_left (h : a ≤ c) : a ≤ b + c := calc a = 0 + a : by simp ... ≤ b + c : add_le_add (zero_le _) h lemma le_add_right (h : a ≤ b) : a ≤ b + c := calc a = a + 0 : by simp ... ≤ b + c : add_le_add h (zero_le _) instance with_zero.canonically_ordered_add_monoid : canonically_ordered_add_monoid (with_zero α) := { le_iff_exists_add := λ a b, begin cases a with a, { exact iff_of_true bot_le ⟨b, (zero_add b).symm⟩ }, cases b with b, { exact iff_of_false (mt (le_antisymm bot_le) (by simp)) (λ ⟨c, h⟩, by cases c; cases h) }, { simp [le_iff_exists_add, -add_comm], split; intro h; rcases h with ⟨c, h⟩, { exact ⟨some c, congr_arg some h⟩ }, { cases c; cases h, { exact ⟨_, (add_zero _).symm⟩ }, { exact ⟨_, rfl⟩ } } } end, bot := 0, bot_le := assume a a' h, option.no_confusion h, .. with_zero.ordered_add_comm_monoid zero_le } instance with_top.canonically_ordered_add_monoid : canonically_ordered_add_monoid (with_top α) := { le_iff_exists_add := assume a b, match a, b with | a, none := show a ≤ ⊤ ↔ ∃c, ⊤ = a + c, by simp; refine ⟨⊤, _⟩; cases a; refl | (some a), (some b) := show (a:with_top α) ≤ ↑b ↔ ∃c:with_top α, ↑b = ↑a + c, begin simp [canonically_ordered_add_monoid.le_iff_exists_add, -add_comm], split, { rintro ⟨c, rfl⟩, refine ⟨c, _⟩, norm_cast }, { exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end } end | none, some b := show (⊤ : with_top α) ≤ b ↔ ∃c:with_top α, ↑b = ⊤ + c, by simp end, .. with_top.order_bot, .. with_top.ordered_add_comm_monoid } end canonically_ordered_add_monoid /-- A canonically linear-ordered additive monoid is a canonically ordered additive monoid whose ordering is a decidable linear order. -/ @[protect_proj] class canonically_linear_ordered_add_monoid (α : Type*) extends canonically_ordered_add_monoid α, decidable_linear_order α section canonically_linear_ordered_add_monoid variables [canonically_linear_ordered_add_monoid α] instance canonically_linear_ordered_add_monoid.semilattice_sup_bot : semilattice_sup_bot α := { ..lattice_of_decidable_linear_order, ..canonically_ordered_add_monoid.to_order_bot α } end canonically_linear_ordered_add_monoid /-- An ordered cancellative additive commutative monoid is an additive commutative monoid with a partial order, in which addition is cancellative and strictly monotone. -/ @[protect_proj, ancestor add_comm_monoid add_left_cancel_semigroup add_right_cancel_semigroup partial_order] class ordered_cancel_add_comm_monoid (α : Type u) extends add_comm_monoid α, add_left_cancel_semigroup α, add_right_cancel_semigroup α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (le_of_add_le_add_left : ∀ a b c : α, a + b ≤ a + c → b ≤ c) /-- An ordered cancellative commutative monoid is a commutative monoid with a partial order, in which multiplication is cancellative and strictly monotone. -/ @[protect_proj, ancestor comm_monoid left_cancel_semigroup right_cancel_semigroup partial_order] class ordered_cancel_comm_monoid (α : Type u) extends comm_monoid α, left_cancel_semigroup α, right_cancel_semigroup α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (le_of_mul_le_mul_left : ∀ a b c : α, a * b ≤ a * c → b ≤ c) attribute [to_additive ordered_cancel_add_comm_monoid] ordered_cancel_comm_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] {a b c d : α} @[to_additive] instance ordered_cancel_comm_monoid.to_left_cancel_monoid : left_cancel_monoid α := { ..‹ordered_cancel_comm_monoid α› } @[to_additive le_of_add_le_add_left] lemma le_of_mul_le_mul_left' : ∀ {a b c : α}, a * b ≤ a * c → b ≤ c := ordered_cancel_comm_monoid.le_of_mul_le_mul_left @[to_additive] instance ordered_cancel_comm_monoid.to_ordered_comm_monoid : ordered_comm_monoid α := { lt_of_mul_lt_mul_left := λ a b c h, lt_of_le_not_le (le_of_mul_le_mul_left' (le_of_lt h)) $ mt (λ h, ordered_cancel_comm_monoid.mul_le_mul_left _ _ h _) (not_le_of_gt h), ..‹ordered_cancel_comm_monoid α› } @[to_additive add_lt_add_left] lemma mul_lt_mul_left' (h : a < b) (c : α) : c * a < c * b := lt_of_le_not_le (mul_le_mul_left' (le_of_lt h) _) $ mt le_of_mul_le_mul_left' (not_le_of_gt h) @[to_additive add_lt_add_right] lemma mul_lt_mul_right' (h : a < b) (c : α) : a * c < b * c := begin rw [mul_comm a c, mul_comm b c], exact (mul_lt_mul_left' h c) end @[to_additive add_lt_add] lemma mul_lt_mul''' (h₁ : a < b) (h₂ : c < d) : a * c < b * d := lt_trans (mul_lt_mul_right' h₁ c) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_le_of_lt (h₁ : a ≤ b) (h₂ : c < d) : a * c < b * d := lt_of_le_of_lt (mul_le_mul_right' h₁ _) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_lt_of_le (h₁ : a < b) (h₂ : c ≤ d) : a * c < b * d := lt_of_lt_of_le (mul_lt_mul_right' h₁ c) (mul_le_mul_left' h₂ _) @[to_additive] lemma lt_mul_of_one_lt_right (a : α) {b : α} (h : 1 < b) : a < a * b := have a * 1 < a * b, from mul_lt_mul_left' h a, by rwa [mul_one] at this @[to_additive] lemma lt_mul_of_one_lt_left (a : α) {b : α} (h : 1 < b) : a < b * a := have 1 * a < b * a, from mul_lt_mul_right' h a, by rwa [one_mul] at this @[to_additive le_of_add_le_add_right] lemma le_of_mul_le_mul_right' (h : a * b ≤ c * b) : a ≤ c := le_of_mul_le_mul_left' (show b * a ≤ b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) @[to_additive] lemma mul_lt_one (ha : a < 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul''' ha hb) @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_lt_of_le ha hb) @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_le_of_lt ha hb) @[to_additive] lemma lt_mul_of_one_lt_of_le (ha : 1 < a) (hbc : b ≤ c) : b < a * c := one_mul b ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma lt_mul_of_le_of_one_lt (hbc : b ≤ c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma mul_le_of_le_one_of_le (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_le (ha : a < 1) (hbc : b ≤ c) : a * b < c := one_mul c ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma mul_lt_of_le_of_lt_one (hbc : b ≤ c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma lt_mul_of_one_le_of_lt (ha : 1 ≤ a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_le (hbc : b < c) (ha : 1 ≤ a) : b < c * a := mul_one b ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma lt_mul_of_one_lt_of_lt (ha : 1 < a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul''' ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt (hbc : b < c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul''' hbc ha @[to_additive] lemma mul_lt_of_le_one_of_lt (ha : a ≤ 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma mul_lt_of_lt_of_le_one (hbc : b < c) (ha : a ≤ 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_lt (ha : a < 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul''' ha hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one (hbc : b < c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul''' hbc ha @[simp, to_additive] lemma mul_le_mul_iff_left (a : α) {b c : α} : a * b ≤ a * c ↔ b ≤ c := ⟨le_of_mul_le_mul_left', λ h, mul_le_mul_left' h _⟩ @[simp, to_additive] lemma mul_le_mul_iff_right (c : α) : a * c ≤ b * c ↔ a ≤ b := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_iff_left c @[simp, to_additive] lemma mul_lt_mul_iff_left (a : α) {b c : α} : a * b < a * c ↔ b < c := ⟨lt_of_mul_lt_mul_left', λ h, mul_lt_mul_left' h _⟩ @[simp, to_additive] lemma mul_lt_mul_iff_right (c : α) : a * c < b * c ↔ a < b := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_iff_left c @[simp, to_additive le_add_iff_nonneg_right] lemma le_mul_iff_one_le_right' (a : α) {b : α} : a ≤ a * b ↔ 1 ≤ b := have a * 1 ≤ a * b ↔ 1 ≤ b, from mul_le_mul_iff_left a, by rwa mul_one at this @[simp, to_additive le_add_iff_nonneg_left] lemma le_mul_iff_one_le_left' (a : α) {b : α} : a ≤ b * a ↔ 1 ≤ b := by rw [mul_comm, le_mul_iff_one_le_right'] @[simp, to_additive lt_add_iff_pos_right] lemma lt_mul_iff_one_lt_right' (a : α) {b : α} : a < a * b ↔ 1 < b := have a * 1 < a * b ↔ 1 < b, from mul_lt_mul_iff_left a, by rwa mul_one at this @[simp, to_additive lt_add_iff_pos_left] lemma lt_mul_iff_one_lt_left' (a : α) {b : α} : a < b * a ↔ 1 < b := by rw [mul_comm, lt_mul_iff_one_lt_right'] @[simp, to_additive add_le_iff_nonpos_left] lemma mul_le_iff_le_one_left' : a * b ≤ b ↔ a ≤ 1 := by { convert mul_le_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_le_iff_nonpos_right] lemma mul_le_iff_le_one_right' : a * b ≤ a ↔ b ≤ 1 := by { convert mul_le_mul_iff_left a, rw [mul_one] } @[simp, to_additive add_lt_iff_neg_right] lemma mul_lt_iff_lt_one_right' : a * b < b ↔ a < 1 := by { convert mul_lt_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_lt_iff_neg_left] lemma mul_lt_iff_lt_one_left' : a * b < a ↔ b < 1 := by { convert mul_lt_mul_iff_left a, rw [mul_one] } @[to_additive] lemma mul_eq_one_iff_eq_one_of_one_le (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := ⟨λ hab : a * b = 1, by split; apply le_antisymm; try {assumption}; rw ← hab; simp [ha, hb], λ ⟨ha', hb'⟩, by rw [ha', hb', mul_one]⟩ section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add_strict_mono] lemma monotone.mul_strict_mono' (hf : monotone f) (hg : strict_mono g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_le_of_lt (hf $ le_of_lt h) (hg h) @[to_additive strict_mono.add_monotone] lemma strict_mono.mul_monotone' (hf : strict_mono f) (hg : monotone g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_lt_of_le (hf h) (hg $ le_of_lt h) @[to_additive strict_mono.add_const] lemma strict_mono.mul_const' (hf : strict_mono f) (c : α) : strict_mono (λ x, f x * c) := hf.mul_monotone' monotone_const @[to_additive strict_mono.const_add] lemma strict_mono.const_mul' (hf : strict_mono f) (c : α) : strict_mono (λ x, c * f x) := monotone_const.mul_strict_mono' hf end mono end ordered_cancel_comm_monoid section ordered_cancel_add_comm_monoid variable [ordered_cancel_add_comm_monoid α] lemma with_top.add_lt_add_iff_left : ∀{a b c : with_top α}, a < ⊤ → (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊤ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe], { norm_cast, exact with_top.coe_lt_top _ }, { norm_cast, exact add_lt_add_iff_left _ } end lemma with_top.add_lt_add_iff_right {a b c : with_top α} : a < ⊤ → (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c end ordered_cancel_add_comm_monoid /-- An ordered additive commutative group is an additive commutative group with a partial order in which addition is strictly monotone. -/ @[protect_proj, ancestor add_comm_group partial_order] class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) /-- An ordered commutative group is an commutative group with a partial order in which multiplication is strictly monotone. -/ @[protect_proj, ancestor comm_group partial_order] class ordered_comm_group (α : Type u) extends comm_group α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) attribute [to_additive ordered_add_comm_group] ordered_comm_group /--The units of an ordered commutative monoid form an ordered commutative group. -/ @[to_additive] instance units.ordered_comm_group [ordered_comm_monoid α] : ordered_comm_group (units α) := { mul_le_mul_left := λ a b h c, mul_le_mul_left' h _, .. units.partial_order, .. (infer_instance : comm_group (units α)) } section ordered_comm_group variables [ordered_comm_group α] {a b c d : α} @[to_additive ordered_add_comm_group.add_lt_add_left] lemma ordered_comm_group.mul_lt_mul_left' (a b : α) (h : a < b) (c : α) : c * a < c * b := begin rw lt_iff_le_not_le at h ⊢, split, { apply ordered_comm_group.mul_le_mul_left _ _ h.1 }, { intro w, replace w : c⁻¹ * (c * b) ≤ c⁻¹ * (c * a) := ordered_comm_group.mul_le_mul_left _ _ w _, simp only [mul_one, mul_comm, mul_left_inv, mul_left_comm] at w, exact h.2 w }, end @[to_additive ordered_add_comm_group.le_of_add_le_add_left] lemma ordered_comm_group.le_of_mul_le_mul_left (h : a * b ≤ a * c) : b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * (a * c), from ordered_comm_group.mul_le_mul_left _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end @[to_additive] lemma ordered_comm_group.lt_of_mul_lt_mul_left (h : a * b < a * c) : b < c := have a⁻¹ * (a * b) < a⁻¹ * (a * c), from ordered_comm_group.mul_lt_mul_left' _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end @[to_additive] instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := { mul_left_cancel := @mul_left_cancel α _, mul_right_cancel := @mul_right_cancel α _, le_of_mul_le_mul_left := @ordered_comm_group.le_of_mul_le_mul_left α _, ..s } @[to_additive neg_le_neg] lemma inv_le_inv' (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := have 1 ≤ a⁻¹ * b, from mul_left_inv a ▸ mul_le_mul_left' h _, have 1 * b⁻¹ ≤ a⁻¹ * b * b⁻¹, from mul_le_mul_right' this _, by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma le_of_inv_le_inv (h : b⁻¹ ≤ a⁻¹) : a ≤ b := suffices (a⁻¹)⁻¹ ≤ (b⁻¹)⁻¹, from begin simp [inv_inv] at this, assumption end, inv_le_inv' h @[to_additive] lemma one_le_of_inv_le_one (h : a⁻¹ ≤ 1) : 1 ≤ a := have a⁻¹ ≤ 1⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive] lemma inv_le_one_of_one_le (h : 1 ≤ a) : a⁻¹ ≤ 1 := have a⁻¹ ≤ 1⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive nonpos_of_neg_nonneg] lemma le_one_of_one_le_inv (h : 1 ≤ a⁻¹) : a ≤ 1 := have 1⁻¹ ≤ a⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive neg_nonneg_of_nonpos] lemma one_le_inv_of_le_one (h : a ≤ 1) : 1 ≤ a⁻¹ := have 1⁻¹ ≤ a⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive neg_lt_neg] lemma inv_lt_inv' (h : a < b) : b⁻¹ < a⁻¹ := have 1 < a⁻¹ * b, from mul_left_inv a ▸ mul_lt_mul_left' h (a⁻¹), have 1 * b⁻¹ < a⁻¹ * b * b⁻¹, from mul_lt_mul_right' this (b⁻¹), by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma lt_of_inv_lt_inv (h : b⁻¹ < a⁻¹) : a < b := inv_inv a ▸ inv_inv b ▸ inv_lt_inv' h @[to_additive] lemma one_lt_of_inv_inv (h : a⁻¹ < 1) : 1 < a := have a⁻¹ < 1⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive] lemma inv_inv_of_one_lt (h : 1 < a) : a⁻¹ < 1 := have a⁻¹ < 1⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive neg_of_neg_pos] lemma inv_of_one_lt_inv (h : 1 < a⁻¹) : a < 1 := have 1⁻¹ < a⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive neg_pos_of_neg] lemma one_lt_inv_of_inv (h : a < 1) : 1 < a⁻¹ := have 1⁻¹ < a⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive] lemma le_inv_of_le_inv (h : a ≤ b⁻¹) : b ≤ a⁻¹ := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_le_of_inv_le (h : a⁻¹ ≤ b) : b⁻¹ ≤ a := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma lt_inv_of_lt_inv (h : a < b⁻¹) : b < a⁻¹ := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_lt_of_inv_lt (h : a⁻¹ < b) : b⁻¹ < a := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma mul_le_of_le_inv_mul (h : b ≤ a⁻¹ * c) : a * b ≤ c := begin have h := mul_le_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma le_inv_mul_of_mul_le (h : a * b ≤ c) : b ≤ a⁻¹ * c := begin have h := mul_le_mul_left' h a⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le (h : b⁻¹ * a ≤ c) : a ≤ b * c := begin have h := mul_le_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_le_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c := begin have h := mul_le_mul_left' h b⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le_left (h : b⁻¹ * a ≤ c) : a ≤ b * c := le_mul_of_inv_mul_le h @[to_additive] lemma inv_mul_le_left_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c := inv_mul_le_of_le_mul h @[to_additive] lemma le_mul_of_inv_mul_le_right (h : c⁻¹ * a ≤ b) : a ≤ b * c := by { rw mul_comm, exact le_mul_of_inv_mul_le h } @[to_additive] lemma inv_mul_le_right_of_le_mul (h : a ≤ b * c) : c⁻¹ * a ≤ b := by { rw mul_comm at h, apply inv_mul_le_left_of_le_mul h } @[to_additive] lemma mul_lt_of_lt_inv_mul (h : b < a⁻¹ * c) : a * b < c := begin have h := mul_lt_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma lt_inv_mul_of_mul_lt (h : a * b < c) : b < a⁻¹ * c := begin have h := mul_lt_mul_left' h (a⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt (h : b⁻¹ * a < c) : a < b * c := begin have h := mul_lt_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_lt_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := begin have h := mul_lt_mul_left' h (b⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt_left (h : b⁻¹ * a < c) : a < b * c := lt_mul_of_inv_mul_lt h @[to_additive] lemma inv_mul_lt_left_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := inv_mul_lt_of_lt_mul h @[to_additive] lemma lt_mul_of_inv_mul_lt_right (h : c⁻¹ * a < b) : a < b * c := by { rw mul_comm, exact lt_mul_of_inv_mul_lt h } @[to_additive] lemma inv_mul_lt_right_of_lt_mul (h : a < b * c) : c⁻¹ * a < b := by { rw mul_comm at h, exact inv_mul_lt_of_lt_mul h } @[simp, to_additive] lemma inv_lt_one_iff_one_lt : a⁻¹ < 1 ↔ 1 < a := ⟨ one_lt_of_inv_inv, inv_inv_of_one_lt ⟩ @[simp, to_additive] lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := have a * b * a⁻¹ ≤ a * b * b⁻¹ ↔ a⁻¹ ≤ b⁻¹, from mul_le_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_le] lemma inv_le' : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := have a⁻¹ ≤ (b⁻¹)⁻¹ ↔ b⁻¹ ≤ a, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive le_neg] lemma le_inv' : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := have (a⁻¹)⁻¹ ≤ b⁻¹ ↔ b ≤ a⁻¹, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive neg_le_iff_add_nonneg] lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ a * b := (mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_iff_mul_le_one : a ≤ b⁻¹ ↔ a * b ≤ 1 := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive neg_nonpos] lemma inv_le_one' : a⁻¹ ≤ 1 ↔ 1 ≤ a := have a⁻¹ ≤ 1⁻¹ ↔ 1 ≤ a, from inv_le_inv_iff, by rwa one_inv at this @[simp, to_additive neg_nonneg] lemma one_le_inv' : 1 ≤ a⁻¹ ↔ a ≤ 1 := have 1⁻¹ ≤ a⁻¹ ↔ a ≤ 1, from inv_le_inv_iff, by rwa one_inv at this @[to_additive] lemma inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (inv_le_one'.2 h) h @[to_additive] lemma self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (one_le_inv'.2 h) @[simp, to_additive] lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a := have a * b * a⁻¹ < a * b * b⁻¹ ↔ a⁻¹ < b⁻¹, from mul_lt_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_lt_zero] lemma inv_lt_one' : a⁻¹ < 1 ↔ 1 < a := have a⁻¹ < 1⁻¹ ↔ 1 < a, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_pos] lemma one_lt_inv' : 1 < a⁻¹ ↔ a < 1 := have 1⁻¹ < a⁻¹ ↔ a < 1, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_lt] lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a := have a⁻¹ < (b⁻¹)⁻¹ ↔ b⁻¹ < a, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive lt_neg] lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ := have (a⁻¹)⁻¹ < b⁻¹ ↔ b < a⁻¹, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive] lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * c ↔ a * b ≤ c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c := have b⁻¹ * a ≤ b⁻¹ * (b * c) ↔ a ≤ b * c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma mul_inv_le_iff_le_mul : a * c⁻¹ ≤ b ↔ a ≤ b * c := by rw [mul_comm a, mul_comm b, inv_mul_le_iff_le_mul] @[simp, to_additive] lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [← inv_mul_le_iff_le_mul, mul_comm] @[to_additive] lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c := by rw [inv_mul_le_iff_le_mul, mul_comm] @[simp, to_additive] lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c := have a⁻¹ * (a * b) < a⁻¹ * c ↔ a * b < c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c := have b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma inv_mul_lt_iff_lt_mul_right : c⁻¹ * a < b ↔ a < b * c := by rw [inv_mul_lt_iff_lt_mul, mul_comm] @[to_additive sub_le_sub_iff] lemma div_le_div_iff' (a b c d : α) : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := begin split ; intro h, have := mul_le_mul_right' (mul_le_mul_right' h b) d, rwa [inv_mul_cancel_right, mul_assoc _ _ b, mul_comm _ b, ← mul_assoc, inv_mul_cancel_right] at this, have := mul_le_mul_right' (mul_le_mul_right' h d⁻¹) b⁻¹, rwa [mul_inv_cancel_right, _root_.mul_assoc, _root_.mul_comm d⁻¹ b⁻¹, ← mul_assoc, mul_inv_cancel_right] at this, end end ordered_comm_group section ordered_add_comm_group variables [ordered_add_comm_group α] {a b c d : α} lemma sub_nonneg_of_le (h : b ≤ a) : 0 ≤ a - b := begin have h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonneg (h : 0 ≤ a - b) : b ≤ a := begin have h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_nonpos_of_le (h : a ≤ b) : a - b ≤ 0 := begin have h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonpos (h : a - b ≤ 0) : a ≤ b := begin have h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_pos_of_lt (h : b < a) : 0 < a - b := begin have h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_pos (h : 0 < a - b) : b < a := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_neg_of_lt (h : a < b) : a - b < 0 := begin have h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_neg (h : a - b < 0) : a < b := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma add_le_of_le_sub_left (h : b ≤ c - a) : a + b ≤ c := begin have h := add_le_add_left h a, rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma le_sub_left_of_add_le (h : a + b ≤ c) : b ≤ c - a := begin have h := add_le_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_le_of_le_sub_right (h : a ≤ c - b) : a + b ≤ c := begin have h := add_le_add_right h b, rwa sub_add_cancel at h end lemma le_sub_right_of_add_le (h : a + b ≤ c) : a ≤ c - b := begin have h := add_le_add_right h (-b), rwa add_neg_cancel_right at h end lemma le_add_of_sub_left_le (h : a - b ≤ c) : a ≤ b + c := begin have h := add_le_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_le_of_le_add (h : a ≤ b + c) : a - b ≤ c := begin have h := add_le_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma le_add_of_sub_right_le (h : a - c ≤ b) : a ≤ b + c := begin have h := add_le_add_right h c, rwa sub_add_cancel at h end lemma sub_right_le_of_le_add (h : a ≤ b + c) : a - c ≤ b := begin have h := add_le_add_right h (-c), rwa add_neg_cancel_right at h end lemma le_add_of_neg_le_sub_left (h : -a ≤ b - c) : c ≤ a + b := le_add_of_neg_add_le_left (add_le_of_le_sub_right h) lemma neg_le_sub_left_of_le_add (h : c ≤ a + b) : -a ≤ b - c := begin have h := le_neg_add_of_add_le (sub_left_le_of_le_add h), rwa add_comm at h end lemma le_add_of_neg_le_sub_right (h : -b ≤ a - c) : c ≤ a + b := le_add_of_sub_right_le (add_le_of_le_sub_left h) lemma neg_le_sub_right_of_le_add (h : c ≤ a + b) : -b ≤ a - c := le_sub_left_of_add_le (sub_right_le_of_le_add h) lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := sub_left_le_of_le_add (le_add_of_sub_right_le h) lemma sub_le_sub_left (h : a ≤ b) (c : α) : c - b ≤ c - a := add_le_add_left (neg_le_neg h) c lemma sub_le_sub_right (h : a ≤ b) (c : α) : a - c ≤ b - c := add_le_add_right h (-c) lemma sub_le_sub (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := add_le_add hab (neg_le_neg hcd) lemma add_lt_of_lt_sub_left (h : b < c - a) : a + b < c := begin have h := add_lt_add_left h a, rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma lt_sub_left_of_add_lt (h : a + b < c) : b < c - a := begin have h := add_lt_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_lt_of_lt_sub_right (h : a < c - b) : a + b < c := begin have h := add_lt_add_right h b, rwa sub_add_cancel at h end lemma lt_sub_right_of_add_lt (h : a + b < c) : a < c - b := begin have h := add_lt_add_right h (-b), rwa add_neg_cancel_right at h end lemma lt_add_of_sub_left_lt (h : a - b < c) : a < b + c := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_lt_of_lt_add (h : a < b + c) : a - b < c := begin have h := add_lt_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma lt_add_of_sub_right_lt (h : a - c < b) : a < b + c := begin have h := add_lt_add_right h c, rwa sub_add_cancel at h end lemma sub_right_lt_of_lt_add (h : a < b + c) : a - c < b := begin have h := add_lt_add_right h (-c), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_lt_sub_left (h : -a < b - c) : c < a + b := lt_add_of_neg_add_lt_left (add_lt_of_lt_sub_right h) lemma neg_lt_sub_left_of_lt_add (h : c < a + b) : -a < b - c := begin have h := lt_neg_add_of_add_lt (sub_left_lt_of_lt_add h), rwa add_comm at h end lemma lt_add_of_neg_lt_sub_right (h : -b < a - c) : c < a + b := lt_add_of_sub_right_lt (add_lt_of_lt_sub_left h) lemma neg_lt_sub_right_of_lt_add (h : c < a + b) : -b < a - c := lt_sub_left_of_add_lt (sub_right_lt_of_lt_add h) lemma sub_lt_of_sub_lt (h : a - b < c) : a - c < b := sub_left_lt_of_lt_add (lt_add_of_sub_right_lt h) lemma sub_lt_sub_left (h : a < b) (c : α) : c - b < c - a := add_lt_add_left (neg_lt_neg h) c lemma sub_lt_sub_right (h : a < b) (c : α) : a - c < b - c := add_lt_add_right h (-c) lemma sub_lt_sub (hab : a < b) (hcd : c < d) : a - d < b - c := add_lt_add hab (neg_lt_neg hcd) lemma sub_lt_sub_of_le_of_lt (hab : a ≤ b) (hcd : c < d) : a - d < b - c := add_lt_add_of_le_of_lt hab (neg_lt_neg hcd) lemma sub_lt_sub_of_lt_of_le (hab : a < b) (hcd : c ≤ d) : a - d < b - c := add_lt_add_of_lt_of_le hab (neg_le_neg hcd) lemma sub_le_self (a : α) {b : α} (h : 0 ≤ b) : a - b ≤ a := calc a - b = a + -b : rfl ... ≤ a + 0 : add_le_add_left (neg_nonpos_of_nonneg h) _ ... = a : by rw add_zero lemma sub_lt_self (a : α) {b : α} (h : 0 < b) : a - b < a := calc a - b = a + -b : rfl ... < a + 0 : add_lt_add_left (neg_neg_of_pos h) _ ... = a : by rw add_zero @[simp] lemma sub_le_sub_iff_left (a : α) {b c : α} : a - b ≤ a - c ↔ c ≤ b := (add_le_add_iff_left _).trans neg_le_neg_iff @[simp] lemma sub_le_sub_iff_right (c : α) : a - c ≤ b - c ↔ a ≤ b := add_le_add_iff_right _ @[simp] lemma sub_lt_sub_iff_left (a : α) {b c : α} : a - b < a - c ↔ c < b := (add_lt_add_iff_left _).trans neg_lt_neg_iff @[simp] lemma sub_lt_sub_iff_right (c : α) : a - c < b - c ↔ a < b := add_lt_add_iff_right _ @[simp] lemma sub_nonneg : 0 ≤ a - b ↔ b ≤ a := have a - a ≤ a - b ↔ b ≤ a, from sub_le_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_nonpos : a - b ≤ 0 ↔ a ≤ b := have a - b ≤ b - b ↔ a ≤ b, from sub_le_sub_iff_right b, by rwa sub_self at this @[simp] lemma sub_pos : 0 < a - b ↔ b < a := have a - a < a - b ↔ b < a, from sub_lt_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b := have a - b < b - b ↔ a < b, from sub_lt_sub_iff_right b, by rwa sub_self at this lemma le_sub_iff_add_le' : b ≤ c - a ↔ a + b ≤ c := by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le] lemma le_sub_iff_add_le : a ≤ c - b ↔ a + b ≤ c := by rw [le_sub_iff_add_le', add_comm] lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add] lemma sub_le_iff_le_add : a - c ≤ b ↔ a ≤ b + c := by rw [sub_le_iff_le_add', add_comm] @[simp] lemma neg_le_sub_iff_le_add : -b ≤ a - c ↔ c ≤ a + b := le_sub_iff_add_le.trans neg_add_le_iff_le_add' lemma neg_le_sub_iff_le_add' : -a ≤ b - c ↔ c ≤ a + b := by rw [neg_le_sub_iff_le_add, add_comm] lemma sub_le : a - b ≤ c ↔ a - c ≤ b := sub_le_iff_le_add'.trans sub_le_iff_le_add.symm theorem le_sub : a ≤ b - c ↔ c ≤ b - a := le_sub_iff_add_le'.trans le_sub_iff_add_le.symm lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c := by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt] lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c := by rw [lt_sub_iff_add_lt', add_comm] lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c := by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add] lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c := by rw [sub_lt_iff_lt_add', add_comm] @[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b := lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b := by rw [neg_lt_sub_iff_lt_add, add_comm] lemma sub_lt : a - b < c ↔ a - c < b := sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm theorem lt_sub : a < b - c ↔ c < b - a := lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm lemma sub_le_self_iff (a : α) {b : α} : a - b ≤ a ↔ 0 ≤ b := sub_le_iff_le_add'.trans (le_add_iff_nonneg_left _) lemma sub_lt_self_iff (a : α) {b : α} : a - b < a ↔ 0 < b := sub_lt_iff_lt_add'.trans (lt_add_iff_pos_left _) end ordered_add_comm_group /- TODO: The `add_lt_add_left` field of `ordered_add_comm_group` is redundant, and it is no longer in core so we can remove it now. This alternative constructor is a workaround until someone fixes this. -/ /-- Alternative constructor for ordered commutative groups, that avoids the field `mul_lt_mul_left`. -/ @[to_additive "Alternative constructor for ordered commutative groups, that avoids the field `mul_lt_mul_left`."] def ordered_comm_group.mk' {α : Type u} [comm_group α] [partial_order α] (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) : ordered_comm_group α := { mul_le_mul_left := mul_le_mul_left, ..(by apply_instance : comm_group α), ..(by apply_instance : partial_order α) } /-- A decidable linearly ordered cancellative additive commutative monoid is an additive commutative monoid with a decidable linear order in which addition is cancellative and strictly monotone. -/ @[protect_proj] class decidable_linear_ordered_cancel_add_comm_monoid (α : Type u) extends ordered_cancel_add_comm_monoid α, decidable_linear_order α section decidable_linear_ordered_cancel_add_comm_monoid variables [decidable_linear_ordered_cancel_add_comm_monoid α] lemma min_add_add_left (a b c : α) : min (a + b) (a + c) = a + min b c := eq.symm (eq_min (show a + min b c ≤ a + b, from add_le_add_left (min_le_left _ _) _) (show a + min b c ≤ a + c, from add_le_add_left (min_le_right _ _) _) (assume d, assume : d ≤ a + b, assume : d ≤ a + c, decidable.by_cases (assume : b ≤ c, by rwa [min_eq_left this]) (assume : ¬ b ≤ c, by rwa [min_eq_right (le_of_lt (lt_of_not_ge this))]))) lemma min_add_add_right (a b c : α) : min (a + c) (b + c) = min a b + c := begin rw [add_comm a c, add_comm b c, add_comm _ c], apply min_add_add_left end lemma max_add_add_left (a b c : α) : max (a + b) (a + c) = a + max b c := eq.symm (eq_max (add_le_add_left (le_max_left _ _) _) (add_le_add_left (le_max_right _ _) _) (assume d, assume : a + b ≤ d, assume : a + c ≤ d, decidable.by_cases (assume : b ≤ c, by rwa [max_eq_right this]) (assume : ¬ b ≤ c, by rwa [max_eq_left (le_of_lt (lt_of_not_ge this))]))) lemma max_add_add_right (a b c : α) : max (a + c) (b + c) = max a b + c := begin rw [add_comm a c, add_comm b c, add_comm _ c], apply max_add_add_left end end decidable_linear_ordered_cancel_add_comm_monoid /-- A decidable linearly ordered additive commutative group is an additive commutative group with a decidable linear order in which addition is strictly monotone. -/ @[protect_proj] class decidable_linear_ordered_add_comm_group (α : Type u) extends add_comm_group α, decidable_linear_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) instance decidable_linear_ordered_comm_group.to_ordered_add_comm_group (α : Type u) [s : decidable_linear_ordered_add_comm_group α] : ordered_add_comm_group α := { add := s.add, ..s } section decidable_linear_ordered_add_comm_group variables [decidable_linear_ordered_add_comm_group α] @[priority 100] -- see Note [lower instance priority] instance decidable_linear_ordered_add_comm_group.to_decidable_linear_ordered_cancel_add_comm_monoid : decidable_linear_ordered_cancel_add_comm_monoid α := { le_of_add_le_add_left := λ x y z, le_of_add_le_add_left, add_left_cancel := λ x y z, add_left_cancel, add_right_cancel := λ x y z, add_right_cancel, ..‹decidable_linear_ordered_add_comm_group α› } lemma decidable_linear_ordered_add_comm_group.add_lt_add_left (a b : α) (h : a < b) (c : α) : c + a < c + b := ordered_add_comm_group.add_lt_add_left a b h c lemma max_neg_neg (a b : α) : max (-a) (-b) = - min a b := eq.symm (eq_max (show -a ≤ -(min a b), from neg_le_neg $ min_le_left a b) (show -b ≤ -(min a b), from neg_le_neg $ min_le_right a b) (assume d, assume H₁ : -a ≤ d, assume H₂ : -b ≤ d, have H : -d ≤ min a b, from le_min (neg_le_of_neg_le H₁) (neg_le_of_neg_le H₂), show -(min a b) ≤ d, from neg_le_of_neg_le H)) lemma min_eq_neg_max_neg_neg (a b : α) : min a b = - max (-a) (-b) := by rw [max_neg_neg, neg_neg] lemma min_neg_neg (a b : α) : min (-a) (-b) = - max a b := by rw [min_eq_neg_max_neg_neg, neg_neg, neg_neg] lemma max_eq_neg_min_neg_neg (a b : α) : max a b = - min (-a) (-b) := by rw [min_neg_neg, neg_neg] /-- `abs a` is the absolute value of `a`. -/ def abs (a : α) : α := max a (-a) lemma abs_of_nonneg {a : α} (h : 0 ≤ a) : abs a = a := have h' : -a ≤ a, from le_trans (neg_nonpos_of_nonneg h) h, max_eq_left h' lemma abs_of_pos {a : α} (h : 0 < a) : abs a = a := abs_of_nonneg (le_of_lt h) lemma abs_of_nonpos {a : α} (h : a ≤ 0) : abs a = -a := have h' : a ≤ -a, from le_trans h (neg_nonneg_of_nonpos h), max_eq_right h' lemma abs_of_neg {a : α} (h : a < 0) : abs a = -a := abs_of_nonpos (le_of_lt h) lemma abs_zero : abs 0 = (0:α) := abs_of_nonneg (le_refl _) lemma abs_neg (a : α) : abs (-a) = abs a := begin unfold abs, rw [max_comm, neg_neg] end lemma abs_pos_of_pos {a : α} (h : 0 < a) : 0 < abs a := by rwa (abs_of_pos h) lemma abs_pos_of_neg {a : α} (h : a < 0) : 0 < abs a := abs_neg a ▸ abs_pos_of_pos (neg_pos_of_neg h) lemma abs_sub (a b : α) : abs (a - b) = abs (b - a) := by rw [← neg_sub, abs_neg] lemma ne_zero_of_abs_ne_zero {a : α} (h : abs a ≠ 0) : a ≠ 0 := assume ha, h (eq.symm ha ▸ abs_zero) /- these assume a linear order -/ lemma eq_zero_of_neg_eq {a : α} (h : -a = a) : a = 0 := match lt_trichotomy a 0 with | or.inl h₁ := have 0 < a, from h ▸ neg_pos_of_neg h₁, absurd h₁ (lt_asymm this) | or.inr (or.inl h₁) := h₁ | or.inr (or.inr h₁) := have a < 0, from h ▸ neg_neg_of_pos h₁, absurd h₁ (lt_asymm this) end lemma abs_nonneg (a : α) : 0 ≤ abs a := or.elim (le_total 0 a) (assume h : 0 ≤ a, by rwa (abs_of_nonneg h)) (assume h : a ≤ 0, calc 0 ≤ -a : neg_nonneg_of_nonpos h ... = abs a : eq.symm (abs_of_nonpos h)) lemma abs_abs (a : α) : abs (abs a) = abs a := abs_of_nonneg $ abs_nonneg a lemma le_abs_self (a : α) : a ≤ abs a := or.elim (le_total 0 a) (assume h : 0 ≤ a, begin rw [abs_of_nonneg h] end) (assume h : a ≤ 0, le_trans h $ abs_nonneg a) lemma neg_le_abs_self (a : α) : -a ≤ abs a := abs_neg a ▸ le_abs_self (-a) lemma eq_zero_of_abs_eq_zero {a : α} (h : abs a = 0) : a = 0 := have h₁ : a ≤ 0, from h ▸ le_abs_self a, have h₂ : -a ≤ 0, from h ▸ abs_neg a ▸ le_abs_self (-a), le_antisymm h₁ (nonneg_of_neg_nonpos h₂) lemma eq_of_abs_sub_eq_zero {a b : α} (h : abs (a - b) = 0) : a = b := have a - b = 0, from eq_zero_of_abs_eq_zero h, show a = b, from eq_of_sub_eq_zero this lemma abs_pos_of_ne_zero {a : α} (h : a ≠ 0) : 0 < abs a := or.elim (lt_or_gt_of_ne h) abs_pos_of_neg abs_pos_of_pos lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) := or.elim (le_total 0 a) (assume h : 0 ≤ a, eq.symm (abs_of_nonneg h) ▸ h1) (assume h : a ≤ 0, eq.symm (abs_of_nonpos h) ▸ h2) lemma abs_le_of_le_of_neg_le {a b : α} (h1 : a ≤ b) (h2 : -a ≤ b) : abs a ≤ b := abs_by_cases (λ x : α, x ≤ b) h1 h2 lemma abs_lt_of_lt_of_neg_lt {a b : α} (h1 : a < b) (h2 : -a < b) : abs a < b := abs_by_cases (λ x : α, x < b) h1 h2 private lemma aux1 {a b : α} (h1 : 0 ≤ a + b) (h2 : 0 ≤ a) : abs (a + b) ≤ abs a + abs b := decidable.by_cases (assume h3 : 0 ≤ b, calc abs (a + b) ≤ abs (a + b) : by apply le_refl ... = a + b : by rw (abs_of_nonneg h1) ... = abs a + b : by rw (abs_of_nonneg h2) ... = abs a + abs b : by rw (abs_of_nonneg h3)) (assume h3 : ¬ 0 ≤ b, have h4 : b ≤ 0, from le_of_lt (lt_of_not_ge h3), calc abs (a + b) = a + b : by rw (abs_of_nonneg h1) ... = abs a + b : by rw (abs_of_nonneg h2) ... ≤ abs a + 0 : add_le_add_left h4 _ ... ≤ abs a + -b : add_le_add_left (neg_nonneg_of_nonpos h4) _ ... = abs a + abs b : by rw (abs_of_nonpos h4)) private lemma aux2 {a b : α} (h1 : 0 ≤ a + b) : abs (a + b) ≤ abs a + abs b := or.elim (le_total b 0) (assume h2 : b ≤ 0, have h3 : ¬ a < 0, from assume h4 : a < 0, have h5 : a + b < 0, begin have aux := add_lt_add_of_lt_of_le h4 h2, rwa [add_zero] at aux end, not_lt_of_ge h1 h5, aux1 h1 (le_of_not_gt h3)) (assume h2 : 0 ≤ b, begin have h3 : abs (b + a) ≤ abs b + abs a, begin rw add_comm at h1, exact aux1 h1 h2 end, rw [add_comm, add_comm (abs a)], exact h3 end) lemma abs_add_le_abs_add_abs (a b : α) : abs (a + b) ≤ abs a + abs b := or.elim (le_total 0 (a + b)) (assume h2 : 0 ≤ a + b, aux2 h2) (assume h2 : a + b ≤ 0, have h3 : -a + -b = -(a + b), by rw neg_add, have h4 : 0 ≤ -(a + b), from neg_nonneg_of_nonpos h2, have h5 : 0 ≤ -a + -b, begin rw [← h3] at h4, exact h4 end, calc abs (a + b) = abs (-a + -b) : by rw [← abs_neg, neg_add] ... ≤ abs (-a) + abs (-b) : aux2 h5 ... = abs a + abs b : by rw [abs_neg, abs_neg]) lemma abs_sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) := have h1 : abs a - abs b + abs b ≤ abs (a - b) + abs b, from calc abs a - abs b + abs b = abs a : by rw sub_add_cancel ... = abs (a - b + b) : by rw sub_add_cancel ... ≤ abs (a - b) + abs b : by apply abs_add_le_abs_add_abs, le_of_add_le_add_right h1 lemma abs_sub_le (a b c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) := calc abs (a - c) = abs (a - b + (b - c)) : by rw [sub_eq_add_neg, sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left] ... ≤ abs (a - b) + abs (b - c) : by apply abs_add_le_abs_add_abs lemma abs_add_three (a b c : α) : abs (a + b + c) ≤ abs a + abs b + abs c := begin apply le_trans, apply abs_add_le_abs_add_abs, apply le_trans, apply add_le_add_right, apply abs_add_le_abs_add_abs, apply le_refl end lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb := begin cases (decidable.em (b ≤ a)) with hba hba, rw (abs_of_nonneg (sub_nonneg_of_le hba)), apply sub_le_sub, apply hau, apply hbl, rw [abs_of_neg (sub_neg_of_lt (lt_of_not_ge hba)), neg_sub], apply sub_le_sub, apply hbu, apply hal end lemma decidable_linear_ordered_add_comm_group.eq_of_abs_sub_nonpos {a b : α} (h : abs (a - b) ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) end decidable_linear_ordered_add_comm_group set_option old_structure_cmd true section prio set_option default_priority 100 -- see Note [default priority] /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_add_comm_group (α : Type*) extends add_comm_group α := (nonneg : α → Prop) (pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a)) (pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b)) (nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0) end prio namespace nonneg_add_comm_group variable [s : nonneg_add_comm_group α] include s @[reducible, priority 100] -- see Note [lower instance priority] instance to_ordered_add_comm_group : ordered_add_comm_group α := { le := λ a b, nonneg (b - a), lt := λ a b, pos (b - a), lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp, le_refl := λ a, by simp [zero_nonneg], le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact add_nonneg nbc nab, le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $ nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab, ..s } theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem pos_def {a : α} : pos a ↔ 0 < a := show _ ↔ pos _, by simp theorem not_zero_pos : ¬ pos (0 : α) := mt pos_def.1 (lt_irrefl _) theorem zero_lt_iff_nonneg_nonneg {a : α} : 0 < a ↔ nonneg a ∧ ¬ nonneg (-a) := pos_def.symm.trans (pos_iff _) theorem nonneg_total_iff : (∀ a : α, nonneg a ∨ nonneg (-a)) ↔ (∀ a b : α, a ≤ b ∨ b ≤ a) := ⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this, λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩ /-- A `nonneg_add_comm_group` is a `decidable_linear_ordered_add_comm_group` if `nonneg` is total and decidable. -/ def to_decidable_linear_ordered_add_comm_group [decidable_pred (@nonneg α _)] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : decidable_linear_ordered_add_comm_group α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..@nonneg_add_comm_group.to_ordered_add_comm_group _ s } end nonneg_add_comm_group namespace order_dual instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (order_dual α) := { add_le_add_left := λ a b h c, @add_le_add_left α _ b a h _, lt_of_add_lt_add_left := λ a b c h, @lt_of_add_lt_add_left α _ a c b h, ..order_dual.partial_order α, ..show add_comm_monoid α, by apply_instance } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_add_comm_monoid (order_dual α) := { le_of_add_le_add_left := λ a b c : α, le_of_add_le_add_left, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, ..order_dual.ordered_add_comm_monoid } instance [ordered_add_comm_group α] : ordered_add_comm_group (order_dual α) := { add_left_neg := λ a : α, add_left_neg a, ..order_dual.ordered_add_comm_monoid, ..show add_comm_group α, by apply_instance } end order_dual section type_tags instance : Π [preorder α], preorder (multiplicative α) := id instance : Π [preorder α], preorder (additive α) := id instance : Π [partial_order α], partial_order (multiplicative α) := id instance : Π [partial_order α], partial_order (additive α) := id instance : Π [linear_order α], linear_order (multiplicative α) := id instance : Π [linear_order α], linear_order (additive α) := id instance : Π [decidable_linear_order α], decidable_linear_order (multiplicative α) := id instance : Π [decidable_linear_order α], decidable_linear_order (additive α) := id instance [ordered_add_comm_monoid α] : ordered_comm_monoid (multiplicative α) := { mul_le_mul_left := @ordered_add_comm_monoid.add_le_add_left α _, lt_of_mul_lt_mul_left := @ordered_add_comm_monoid.lt_of_add_lt_add_left α _, ..multiplicative.partial_order, ..multiplicative.comm_monoid } instance [ordered_comm_monoid α] : ordered_add_comm_monoid (additive α) := { add_le_add_left := @ordered_comm_monoid.mul_le_mul_left α _, lt_of_add_lt_add_left := @ordered_comm_monoid.lt_of_mul_lt_mul_left α _, ..additive.partial_order, ..additive.add_comm_monoid } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_comm_monoid (multiplicative α) := { le_of_mul_le_mul_left := @ordered_cancel_add_comm_monoid.le_of_add_le_add_left α _, ..multiplicative.right_cancel_semigroup, ..multiplicative.left_cancel_semigroup, ..multiplicative.ordered_comm_monoid } instance [ordered_cancel_comm_monoid α] : ordered_cancel_add_comm_monoid (additive α) := { le_of_add_le_add_left := @ordered_cancel_comm_monoid.le_of_mul_le_mul_left α _, ..additive.add_right_cancel_semigroup, ..additive.add_left_cancel_semigroup, ..additive.ordered_add_comm_monoid } instance [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) := { ..multiplicative.comm_group, ..multiplicative.ordered_comm_monoid } instance [ordered_comm_group α] : ordered_add_comm_group (additive α) := { ..additive.add_comm_group, ..additive.ordered_add_comm_monoid } end type_tags
ce7d42672973c2096b50449bd3b7746f38400e30
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/counterexamples/girard.lean
b3164be15e9ed3cf8a39e6ff05bf0940a8a5355e
[ "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
2,182
lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import logic.basic /-! # Girard's paradox Girard's paradox is a proof that `Type : Type` entails a contradiction. We can't say this directly in Lean because `Type : Type 1` and it's not possible to give `Type` a different type via an axiom, so instead we axiomatize the behavior of the Pi type and application if the typing rule for Pi was `(Type → Type) → Type` instead of `(Type → Type) → Type 1`. Furthermore, we don't actually want false axioms in mathlib, so rather than introducing the axioms using `axiom` or `constant` declarations, we take them as assumptions to the `girard` theorem. Based on Watkins' LF implementation of Hurkens' simplification of Girard's paradox: <http://www.cs.cmu.edu/~kw/research/hurkens95tlca.elf>. ## Main statements * `girard`: there are no Girard universes. -/ /-- Girard's paradox: there are no universes `u` such that `Type u : Type u`. Since we can't actually change the type of Lean's `Π` operator, we assume the existence of `pi`, `lam`, `app` and the `beta` rule equivalent to the `Π` and `app` constructors of type theory. -/ theorem {u} girard (pi : (Type u → Type u) → Type u) (lam : ∀ {A : Type u → Type u}, (∀ x, A x) → pi A) (app : ∀ {A}, pi A → ∀ x, A x) (beta : ∀ {A : Type u → Type u} (f : ∀ x, A x) (x), app (lam f) x = f x) : false := let F (X) := (set (set X) → X) → set (set X), U := pi F in let G (T : set (set U)) (X) : F X := λ f, {p | {x : U | f (app x X f) ∈ p} ∈ T} in let τ (T : set (set U)) : U := lam (G T) in let σ (S : U) : set (set U) := app S U τ in have στ : ∀ {s S}, s ∈ σ (τ S) ↔ {x | τ (σ x) ∈ s} ∈ S := λ s S, iff_of_eq (congr_arg (λ f : F U, s ∈ f τ) (beta (G S) U) : _), let ω : set (set U) := {p | ∀ x, p ∈ σ x → x ∈ p} in let δ (S : set (set U)) := ∀ p, p ∈ S → τ S ∈ p in have δ ω := λ p d, d (τ ω) $ στ.2 $ λ x h, d (τ (σ x)) (στ.2 h), this {y | ¬ δ (σ y)} (λ x e f, f _ e (λ p h, f _ (στ.1 h))) (λ p h, this _ (στ.1 h))
35269fd49f9cb24aed3fb5b382b5fe694acc838a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/sums/basic_auto.lean
31f1a104a8e6d3d62e8ff6371b59b00976c24a19
[]
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
5,528
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.eq_to_hom import Mathlib.PostPort universes u₁ v₁ namespace Mathlib /-# Disjoint unions of categories, functors, and natural transformations. -/ namespace category_theory /-- `sum C D` gives the direct sum of two categories. -/ protected instance sum (C : Type u₁) [category C] (D : Type u₁) [category D] : category (C ⊕ D) := category.mk @[simp] theorem sum_comp_inl (C : Type u₁) [category C] (D : Type u₁) [category D] {P : C} {Q : C} {R : C} (f : sum.inl P ⟶ sum.inl Q) (g : sum.inl Q ⟶ sum.inl R) : f ≫ g = f ≫ g := rfl @[simp] theorem sum_comp_inr (C : Type u₁) [category C] (D : Type u₁) [category D] {P : D} {Q : D} {R : D} (f : sum.inr P ⟶ sum.inr Q) (g : sum.inr Q ⟶ sum.inr R) : f ≫ g = f ≫ g := rfl namespace sum /-- `inl_` is the functor `X ↦ inl X`. -/ -- Unfortunate naming here, suggestions welcome. def inl_ (C : Type u₁) [category C] (D : Type u₁) [category D] : C ⥤ C ⊕ D := functor.mk (fun (X : C) => sum.inl X) fun (X Y : C) (f : X ⟶ Y) => f /-- `inr_` is the functor `X ↦ inr X`. -/ def inr_ (C : Type u₁) [category C] (D : Type u₁) [category D] : D ⥤ C ⊕ D := functor.mk (fun (X : D) => sum.inr X) fun (X Y : D) (f : X ⟶ Y) => f /-- The functor exchanging two direct summand categories. -/ def swap (C : Type u₁) [category C] (D : Type u₁) [category D] : C ⊕ D ⥤ D ⊕ C := functor.mk (fun (X : C ⊕ D) => sorry) fun (X Y : C ⊕ D) (f : X ⟶ Y) => sorry @[simp] theorem swap_obj_inl (C : Type u₁) [category C] (D : Type u₁) [category D] (X : C) : functor.obj (swap C D) (sum.inl X) = sum.inr X := rfl @[simp] theorem swap_obj_inr (C : Type u₁) [category C] (D : Type u₁) [category D] (X : D) : functor.obj (swap C D) (sum.inr X) = sum.inl X := rfl @[simp] theorem swap_map_inl (C : Type u₁) [category C] (D : Type u₁) [category D] {X : C} {Y : C} {f : sum.inl X ⟶ sum.inl Y} : functor.map (swap C D) f = f := rfl @[simp] theorem swap_map_inr (C : Type u₁) [category C] (D : Type u₁) [category D] {X : D} {Y : D} {f : sum.inr X ⟶ sum.inr Y} : functor.map (swap C D) f = f := rfl namespace swap /-- `swap` gives an equivalence between `C ⊕ D` and `D ⊕ C`. -/ def equivalence (C : Type u₁) [category C] (D : Type u₁) [category D] : C ⊕ D ≌ D ⊕ C := equivalence.mk (swap C D) (swap D C) (nat_iso.of_components (fun (X : C ⊕ D) => eq_to_iso sorry) sorry) (nat_iso.of_components (fun (X : D ⊕ C) => eq_to_iso sorry) sorry) protected instance is_equivalence (C : Type u₁) [category C] (D : Type u₁) [category D] : is_equivalence (swap C D) := is_equivalence.of_equivalence (equivalence C D) /-- The double swap on `C ⊕ D` is naturally isomorphic to the identity functor. -/ def symmetry (C : Type u₁) [category C] (D : Type u₁) [category D] : swap C D ⋙ swap D C ≅ 𝟭 := iso.symm (equivalence.unit_iso (equivalence C D)) end swap end sum namespace functor /-- The sum of two functors. -/ def sum {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] (F : A ⥤ B) (G : C ⥤ D) : A ⊕ C ⥤ B ⊕ D := mk (fun (X : A ⊕ C) => sorry) fun (X Y : A ⊕ C) (f : X ⟶ Y) => sorry @[simp] theorem sum_obj_inl {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] (F : A ⥤ B) (G : C ⥤ D) (a : A) : obj (sum F G) (sum.inl a) = sum.inl (obj F a) := rfl @[simp] theorem sum_obj_inr {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] (F : A ⥤ B) (G : C ⥤ D) (c : C) : obj (sum F G) (sum.inr c) = sum.inr (obj G c) := rfl @[simp] theorem sum_map_inl {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] (F : A ⥤ B) (G : C ⥤ D) {a : A} {a' : A} (f : sum.inl a ⟶ sum.inl a') : map (sum F G) f = map F f := rfl @[simp] theorem sum_map_inr {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] (F : A ⥤ B) (G : C ⥤ D) {c : C} {c' : C} (f : sum.inr c ⟶ sum.inr c') : map (sum F G) f = map G f := rfl end functor namespace nat_trans /-- The sum of two natural transformations. -/ def sum {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] {F : A ⥤ B} {G : A ⥤ B} {H : C ⥤ D} {I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) : functor.sum F H ⟶ functor.sum G I := mk fun (X : A ⊕ C) => sorry @[simp] theorem sum_app_inl {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] {F : A ⥤ B} {G : A ⥤ B} {H : C ⥤ D} {I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) (a : A) : app (sum α β) (sum.inl a) = app α a := rfl @[simp] theorem sum_app_inr {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] {F : A ⥤ B} {G : A ⥤ B} {H : C ⥤ D} {I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) (c : C) : app (sum α β) (sum.inr c) = app β c := rfl end Mathlib
d271219624deaa46672cab2fefd011822839d417
9cba98daa30c0804090f963f9024147a50292fa0
/geom/geom_test.lean
c9a89885cfa593369fc34a250aefeb057b84fa3c
[]
no_license
kevinsullivan/phys
dcb192f7b3033797541b980f0b4a7e75d84cea1a
ebc2df3779d3605ff7a9b47eeda25c2a551e011f
refs/heads/master
1,637,490,575,500
1,629,899,064,000
1,629,899,064,000
168,012,884
0
3
null
1,629,644,436,000
1,548,699,832,000
Lean
UTF-8
Lean
false
false
2,512
lean
import data.real.basic import .geom /- Comments in rest of file are out of date, written for time not geom. But same reasoning applies. -/ open geom abbreviation K := ℝ -- or try ℚ for a computable version (but no square roots) -- assume unit vector is one second in standard time space noncomputable def t1 : position (std_space K) := mk_position (std_space K) 1 -- t=0 + 1 second noncomputable def t2 := mk_position (std_space K) 3 -- t=0 + 3 seconds noncomputable def d1 : translation (std_space K) := t2 -ᵥ t1 -- 2 seconds noncomputable def t3 := 5 • d1 +ᵥ t1 -- t=0 + 11 seconds -- new frame with origin at t=0 + 1hr and unit duration of 1 minute noncomputable def t1' : position (std_space K) := mk_position (std_space K) 3600 -- t=0 + 1hr noncomputable def d1' := 60 • (mk_duration (std_space K) 1) -- one minute noncomputable def new_fm := mk_frame t1'.to_point d1'.to_vectr -- TODO: fix noncomputable def new_space := mk_space K new_fm -- create some points and vectors in new space noncomputable def t1'' : position new_space := mk_position new_space 1 -- t=0 + 1 second (3660) noncomputable def t2'' := mk_position new_space 3 -- t=0 + 3 seconds (3600 + 180) noncomputable def d1'' := t2'' -ᵥ t1'' -- 2 seconds noncomputable def t3'' := 5 • d1'' +ᵥ t1'' -- 11 in the new space, what old? -- check for type errors across difference coordinate systems on time noncomputable def d_good := t1' -ᵥ t1 -- time - time = duration noncomputable def t_good := 8 • d1' +ᵥ t1 -- scalar * duration + time = time noncomputable def d_bad := t1'' -ᵥ t1 -- error: type mismatch in aff coord spaces noncomputable def t_bad := 8 • d1'' +ᵥ t1 -- error: no impl of +ᵥ across aff coord spaces /- Afterthoughts -/ -- #1: support end-to-end in Peirce (schedule discussion for lang-level design) -- #2: get transforms working in this design (design proposal needed) -- #3: re-imagine a tf-like API based on work in this style -- fill in the proofs (low risk, low priority; postpone) -- add helper functions to access coordinate values -- get affine combinations working (not high priority) -- fix that one problem where I break an abstraction boundry for lack of an at-level mk function
28aba1a82c4de1b5b543df94542558a4ae949f37
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/SimpLemmas.lean
9460e3d958073ad6553070eeddb8640f8303222f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
9,421
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 notation, basic datatypes and type classes -/ prelude import Init.Core set_option linter.missingDocs true -- keep it documented theorem of_eq_true (h : p = True) : p := h ▸ trivial theorem eq_true (h : p) : p = True := propext ⟨fun _ => trivial, fun _ => h⟩ theorem eq_false (h : ¬ p) : p = False := propext ⟨fun h' => absurd h' h, fun h' => False.elim h'⟩ theorem eq_false' (h : p → False) : p = False := eq_false h theorem eq_true_of_decide {p : Prop} {_ : Decidable p} (h : decide p = true) : p = True := eq_true (of_decide_eq_true h) theorem eq_false_of_decide {p : Prop} {_ : Decidable p} (h : decide p = false) : p = False := eq_false (of_decide_eq_false h) @[simp] theorem eq_self (a : α) : (a = a) = True := eq_true rfl theorem implies_congr {p₁ p₂ : Sort u} {q₁ q₂ : Sort v} (h₁ : p₁ = p₂) (h₂ : q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) := h₁ ▸ h₂ ▸ rfl theorem implies_dep_congr_ctx {p₁ p₂ q₁ : Prop} (h₁ : p₁ = p₂) {q₂ : p₂ → Prop} (h₂ : (h : p₂) → q₁ = q₂ h) : (p₁ → q₁) = ((h : p₂) → q₂ h) := propext ⟨ fun hl hp₂ => (h₂ hp₂).mp (hl (h₁.mpr hp₂)), fun hr hp₁ => (h₂ (h₁.mp hp₁)).mpr (hr (h₁.mp hp₁))⟩ theorem implies_congr_ctx {p₁ p₂ q₁ q₂ : Prop} (h₁ : p₁ = p₂) (h₂ : p₂ → q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) := implies_dep_congr_ctx h₁ h₂ theorem forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, p a = q a) : (∀ a, p a) = (∀ a, q a) := (funext h : p = q) ▸ rfl theorem let_congr {α : Sort u} {β : Sort v} {a a' : α} {b b' : α → β} (h₁ : a = a') (h₂ : ∀ x, b x = b' x) : (let x := a; b x) = (let x := a'; b' x) := h₁ ▸ (funext h₂ : b = b') ▸ rfl theorem let_val_congr {α : Sort u} {β : Sort v} {a a' : α} (b : α → β) (h : a = a') : (let x := a; b x) = (let x := a'; b x) := h ▸ rfl theorem let_body_congr {α : Sort u} {β : α → Sort v} {b b' : (a : α) → β a} (a : α) (h : ∀ x, b x = b' x) : (let x := a; b x) = (let x := a; b' x) := (funext h : b = b') ▸ rfl @[congr] theorem ite_congr {x y u v : α} {s : Decidable b} [Decidable c] (h₁ : b = c) (h₂ : c → x = u) (h₃ : ¬ c → y = v) : ite b x y = ite c u v := by cases Decidable.em c with | inl h => rw [if_pos h]; subst b; rw [if_pos h]; exact h₂ h | inr h => rw [if_neg h]; subst b; rw [if_neg h]; exact h₃ h theorem Eq.mpr_prop {p q : Prop} (h₁ : p = q) (h₂ : q) : p := h₁ ▸ h₂ theorem Eq.mpr_not {p q : Prop} (h₁ : p = q) (h₂ : ¬q) : ¬p := h₁ ▸ h₂ @[congr] theorem dite_congr {_ : Decidable b} [Decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h₁ : b = c) (h₂ : (h : c) → x (h₁.mpr_prop h) = u h) (h₃ : (h : ¬c) → y (h₁.mpr_not h) = v h) : dite b x y = dite c u v := by cases Decidable.em c with | inl h => rw [dif_pos h]; subst b; rw [dif_pos h]; exact h₂ h | inr h => rw [dif_neg h]; subst b; rw [dif_neg h]; exact h₃ h @[simp] theorem ne_eq (a b : α) : (a ≠ b) = ¬(a = b) := rfl @[simp] theorem ite_true (a b : α) : (if True then a else b) = a := rfl @[simp] theorem ite_false (a b : α) : (if False then a else b) = b := rfl @[simp] theorem dite_true {α : Sort u} {t : True → α} {e : ¬ True → α} : (dite True t e) = t True.intro := rfl @[simp] theorem dite_false {α : Sort u} {t : False → α} {e : ¬ False → α} : (dite False t e) = e not_false := rfl @[simp] theorem ite_self {α : Sort u} {c : Prop} {d : Decidable c} (a : α) : ite c a a = a := by cases d <;> rfl @[simp] theorem and_self (p : Prop) : (p ∧ p) = p := propext ⟨(·.1), fun h => ⟨h, h⟩⟩ @[simp] theorem and_true (p : Prop) : (p ∧ True) = p := propext ⟨(·.1), (⟨·, trivial⟩)⟩ @[simp] theorem true_and (p : Prop) : (True ∧ p) = p := propext ⟨(·.2), (⟨trivial, ·⟩)⟩ @[simp] theorem and_false (p : Prop) : (p ∧ False) = False := eq_false (·.2) @[simp] theorem false_and (p : Prop) : (False ∧ p) = False := eq_false (·.1) @[simp] theorem or_self (p : Prop) : (p ∨ p) = p := propext ⟨fun | .inl h | .inr h => h, .inl⟩ @[simp] theorem or_true (p : Prop) : (p ∨ True) = True := eq_true (.inr trivial) @[simp] theorem true_or (p : Prop) : (True ∨ p) = True := eq_true (.inl trivial) @[simp] theorem or_false (p : Prop) : (p ∨ False) = p := propext ⟨fun (.inl h) => h, .inl⟩ @[simp] theorem false_or (p : Prop) : (False ∨ p) = p := propext ⟨fun (.inr h) => h, .inr⟩ @[simp] theorem iff_self (p : Prop) : (p ↔ p) = True := eq_true .rfl @[simp] theorem iff_true (p : Prop) : (p ↔ True) = p := propext ⟨(·.2 trivial), fun h => ⟨fun _ => trivial, fun _ => h⟩⟩ @[simp] theorem true_iff (p : Prop) : (True ↔ p) = p := propext ⟨(·.1 trivial), fun h => ⟨fun _ => h, fun _ => trivial⟩⟩ @[simp] theorem iff_false (p : Prop) : (p ↔ False) = ¬p := propext ⟨(·.1), (⟨·, False.elim⟩)⟩ @[simp] theorem false_iff (p : Prop) : (False ↔ p) = ¬p := propext ⟨(·.2), (⟨False.elim, ·⟩)⟩ @[simp] theorem false_implies (p : Prop) : (False → p) = True := eq_true False.elim @[simp] theorem implies_true (α : Sort u) : (α → True) = True := eq_true fun _ => trivial @[simp] theorem true_implies (p : Prop) : (True → p) = p := propext ⟨(· trivial), (fun _ => ·)⟩ @[simp] theorem not_false_eq_true : (¬ False) = True := eq_true False.elim @[simp] theorem Bool.or_false (b : Bool) : (b || false) = b := by cases b <;> rfl @[simp] theorem Bool.or_true (b : Bool) : (b || true) = true := by cases b <;> rfl @[simp] theorem Bool.false_or (b : Bool) : (false || b) = b := by cases b <;> rfl @[simp] theorem Bool.true_or (b : Bool) : (true || b) = true := by cases b <;> rfl @[simp] theorem Bool.or_self (b : Bool) : (b || b) = b := by cases b <;> rfl @[simp] theorem Bool.or_eq_true (a b : Bool) : ((a || b) = true) = (a = true ∨ b = true) := by cases a <;> cases b <;> decide @[simp] theorem Bool.and_false (b : Bool) : (b && false) = false := by cases b <;> rfl @[simp] theorem Bool.and_true (b : Bool) : (b && true) = b := by cases b <;> rfl @[simp] theorem Bool.false_and (b : Bool) : (false && b) = false := by cases b <;> rfl @[simp] theorem Bool.true_and (b : Bool) : (true && b) = b := by cases b <;> rfl @[simp] theorem Bool.and_self (b : Bool) : (b && b) = b := by cases b <;> rfl @[simp] theorem Bool.and_eq_true (a b : Bool) : ((a && b) = true) = (a = true ∧ b = true) := by cases a <;> cases b <;> decide theorem Bool.and_assoc (a b c : Bool) : (a && b && c) = (a && (b && c)) := by cases a <;> cases b <;> cases c <;> decide theorem Bool.or_assoc (a b c : Bool) : (a || b || c) = (a || (b || c)) := by cases a <;> cases b <;> cases c <;> decide @[simp] theorem Bool.not_not (b : Bool) : (!!b) = b := by cases b <;> rfl @[simp] theorem Bool.not_true : (!true) = false := by decide @[simp] theorem Bool.not_false : (!false) = true := by decide @[simp] theorem Bool.not_beq_true (b : Bool) : (!(b == true)) = (b == false) := by cases b <;> rfl @[simp] theorem Bool.not_beq_false (b : Bool) : (!(b == false)) = (b == true) := by cases b <;> rfl @[simp] theorem Bool.not_eq_true' (b : Bool) : ((!b) = true) = (b = false) := by cases b <;> simp @[simp] theorem Bool.not_eq_false' (b : Bool) : ((!b) = false) = (b = true) := by cases b <;> simp @[simp] theorem Bool.beq_to_eq (a b : Bool) : (a == b) = (a = b) := by cases a <;> cases b <;> decide @[simp] theorem Bool.not_beq_to_not_eq (a b : Bool) : (!(a == b)) = ¬(a = b) := by cases a <;> cases b <;> decide @[simp] theorem Bool.not_eq_true (b : Bool) : (¬(b = true)) = (b = false) := by cases b <;> decide @[simp] theorem Bool.not_eq_false (b : Bool) : (¬(b = false)) = (b = true) := by cases b <;> decide @[simp] theorem decide_eq_true_eq [Decidable p] : (decide p = true) = p := propext <| Iff.intro of_decide_eq_true decide_eq_true @[simp] theorem decide_not [h : Decidable p] : decide (¬ p) = !decide p := by cases h <;> rfl @[simp] theorem not_decide_eq_true [h : Decidable p] : ((!decide p) = true) = ¬ p := by cases h <;> simp [decide, *] @[simp] theorem heq_eq_eq {α : Sort u} (a b : α) : HEq a b = (a = b) := propext <| Iff.intro eq_of_heq heq_of_eq @[simp] theorem cond_true (a b : α) : cond true a b = a := rfl @[simp] theorem cond_false (a b : α) : cond false a b = b := rfl @[simp] theorem beq_self_eq_true [BEq α] [LawfulBEq α] (a : α) : (a == a) = true := LawfulBEq.rfl @[simp] theorem beq_self_eq_true' [DecidableEq α] (a : α) : (a == a) = true := by simp [BEq.beq] @[simp] theorem bne_self_eq_false [BEq α] [LawfulBEq α] (a : α) : (a != a) = false := by simp [bne] @[simp] theorem bne_self_eq_false' [DecidableEq α] (a : α) : (a != a) = false := by simp [bne] @[simp] theorem Nat.le_zero_eq (a : Nat) : (a ≤ 0) = (a = 0) := propext ⟨fun h => Nat.le_antisymm h (Nat.zero_le ..), fun h => by simp [h]⟩ @[simp] theorem decide_False : decide False = false := rfl @[simp] theorem decide_True : decide True = true := rfl @[simp] theorem bne_iff_ne [BEq α] [LawfulBEq α] (a b : α) : a != b ↔ a ≠ b := by simp [bne]; rw [← beq_iff_eq a b]; simp [-beq_iff_eq]
ef8d773bf8284da77ffe2b8f46d9ffd127749800
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Structure.lean
8e183222d786a1eed36d793d832122cb5f8089e1
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,631
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Helper functions for retrieving structure information. -/ import Lean.Environment import Lean.ProjFns /- TODO: We currently assume that the projection function for field `fieldName` at structure `structName` is `structName ++ fieldName`. This is incorrect for private projections. We will fix this by storing a mapping from `structure` + `fieldName` to projection function name in the environment. This modification will impact functions such as `getStructureFields` and `getProjFnForField?` -/ namespace Lean /-- Return true iff `constName` is the a non-recursive inductive datatype that has only one constructor. -/ def isStructureLike (env : Environment) (constName : Name) : Bool := match env.find? constName with | some (ConstantInfo.inductInfo { isRec := false, ctors := [ctor], .. }) => true | _ => false /-- We mark subobject fields by prefixing them with "_" in the structure's intro rule. -/ def mkInternalSubobjectFieldName (fieldName : Name) : Name := fieldName.appendBefore "_" def isInternalSubobjectFieldName : Name → Bool | Name.str _ s _ => s.length > 0 && s.get 0 == '_' | _ => false def deinternalizeFieldName : Name → Name | n@(Name.str p s _) => if s.length > 0 && s.get 0 == '_' then mkNameStr p (s.drop 1) else n | n => n def getStructureCtor (env : Environment) (constName : Name) : ConstructorVal := match env.find? constName with | some (ConstantInfo.inductInfo { nparams := nparams, isRec := false, ctors := [ctorName], .. }) => match env.find? ctorName with | some (ConstantInfo.ctorInfo val) => val | _ => panic! "ill-formed environment" | _ => panic! "structure expected" private def getStructureFieldsAux (nparams : Nat) : Nat → Expr → Array Name → Array Name | i, Expr.forallE n d b _, fieldNames => if i < nparams then getStructureFieldsAux (i+1) b fieldNames else getStructureFieldsAux (i+1) b (fieldNames.push $ deinternalizeFieldName n) | _, _, fieldNames => fieldNames -- TODO: fix. See comment in the beginning of the file def getStructureFields (env : Environment) (structName : Name) : Array Name := let ctor := getStructureCtor env structName; getStructureFieldsAux ctor.nparams 0 ctor.type #[] private def isSubobjectFieldAux (nparams : Nat) (target : Name) : Nat → Expr → Option Name | i, Expr.forallE n d b _ => if i < nparams then isSubobjectFieldAux (i+1) b else if n == target then match d.getAppFn with | Expr.const parentStructName _ _ => some parentStructName | _ => panic! "ill-formed structure" else isSubobjectFieldAux (i+1) b | _, _ => none -- TODO: fix. See comment in the beginning of the file /-- If `fieldName` represents the relation to a parent structure `S`, return `S` -/ def isSubobjectField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := let ctor := getStructureCtor env structName; isSubobjectFieldAux ctor.nparams (mkInternalSubobjectFieldName fieldName) 0 ctor.type /-- Return immediate parent structures -/ def getParentStructures (env : Environment) (structName : Name) : Array Name := let fieldNames := getStructureFields env structName; fieldNames.foldl (fun (acc : Array Name) fieldName => match isSubobjectField? env structName fieldName with | some parentStructName => acc.push parentStructName | none => acc) #[] /-- `findField? env S fname`. If `fname` is defined in a parent `S'` of `S`, return `S'` -/ partial def findField? (env : Environment) : Name → Name → Option Name | structName, fieldName => if (getStructureFields env structName).contains fieldName then some structName else (getParentStructures env structName).findSome? $ fun parentStructName => findField? parentStructName fieldName private partial def getStructureFieldsFlattenedAux (env : Environment) : Name → Array Name → Array Name | structName, fullNames => (getStructureFields env structName).foldl (fun (fullNames : Array Name) (fieldName : Name) => let fullNames := fullNames.push fieldName; match isSubobjectField? env structName fieldName with | some parentStructName => getStructureFieldsFlattenedAux parentStructName fullNames | none => fullNames) fullNames def getStructureFieldsFlattened (env : Environment) (structName : Name) : Array Name := getStructureFieldsFlattenedAux env structName #[] -- TODO: fix. See comment in the beginning of the file private def hasProjFn (env : Environment) (structName : Name) (nparams : Nat) : Nat → Expr → Bool | i, Expr.forallE n d b _ => if i < nparams then hasProjFn (i+1) b else let fullFieldName := structName ++ deinternalizeFieldName n; env.isProjectionFn fullFieldName | _, _ => false /-- Return true if `constName` is the name of an inductive datatype created using the `structure` or `class` commands. We perform the check by testing whether auxiliary projection functions have been created. -/ def isStructure (env : Environment) (constName : Name) : Bool := if isStructureLike env constName then let ctor := getStructureCtor env constName; hasProjFn env constName ctor.nparams 0 ctor.type else false -- TODO: fix. See comment in the beginning of the file def getProjFnForField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := let fieldNames := getStructureFields env structName; if fieldNames.any fun n => fieldName == n then some (structName ++ fieldName) else none partial def getPathToBaseStructureAux (env : Environment) (baseStructName : Name) : Name → List Name → Option (List Name) | structName, path => if baseStructName == structName then some path.reverse else let fieldNames := getStructureFields env structName; fieldNames.findSome? $ fun fieldName => match isSubobjectField? env structName fieldName with | none => none | some parentStructName => match getProjFnForField? env structName fieldName with | none => none | some projFn => getPathToBaseStructureAux parentStructName (projFn :: path) /-- If `baseStructName` is an ancestor structure for `structName`, then return a sequence of projection functions to go from `structName` to `baseStructName`. -/ def getPathToBaseStructure? (env : Environment) (baseStructName : Name) (structName : Name) : Option (List Name) := getPathToBaseStructureAux env baseStructName structName [] end Lean
c7eaa256b17a69b176ac2357a20d9c82ab4bc345
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/finset/gcd.lean
158b3a7a49854b4aa94cd41d55a566a63f1aac00
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,508
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.finset.fold import Mathlib.data.multiset.gcd import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # GCD and LCM operations on finsets ## Main definitions - `finset.gcd` - the greatest common denominator of a `finset` of elements of a `gcd_monoid` - `finset.lcm` - the least common multiple of a `finset` of elements of a `gcd_monoid` ## Implementation notes Many of the proofs use the lemmas `gcd.def` and `lcm.def`, which relate `finset.gcd` and `finset.lcm` to `multiset.gcd` and `multiset.lcm`. TODO: simplify with a tactic and `data.finset.lattice` ## Tags finset, gcd -/ namespace finset /-! ### lcm -/ /-- Least common multiple of a finite set -/ def lcm {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (s : finset β) (f : β → α) : α := fold lcm 1 f s theorem lcm_def {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} : lcm s f = multiset.lcm (multiset.map f (val s)) := rfl @[simp] theorem lcm_empty {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {f : β → α} : lcm ∅ f = 1 := fold_empty @[simp] theorem lcm_dvd_iff {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} {a : α} : lcm s f ∣ a ↔ ∀ (b : β), b ∈ s → f b ∣ a := sorry theorem lcm_dvd {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} {a : α} : (∀ (b : β), b ∈ s → f b ∣ a) → lcm s f ∣ a := iff.mpr lcm_dvd_iff theorem dvd_lcm {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} {b : β} (hb : b ∈ s) : f b ∣ lcm s f := iff.mp lcm_dvd_iff (dvd_refl (lcm s f)) b hb @[simp] theorem lcm_insert {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} [DecidableEq β] {b : β} : lcm (insert b s) f = lcm (f b) (lcm s f) := sorry @[simp] theorem lcm_singleton {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {f : β → α} {b : β} : lcm (singleton b) f = coe_fn normalize (f b) := multiset.lcm_singleton @[simp] theorem normalize_lcm {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} : coe_fn normalize (lcm s f) = lcm s f := sorry theorem lcm_union {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s₁ : finset β} {s₂ : finset β} {f : β → α} [DecidableEq β] : lcm (s₁ ∪ s₂) f = lcm (lcm s₁ f) (lcm s₂ f) := sorry theorem lcm_congr {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s₁ : finset β} {s₂ : finset β} {f : β → α} {g : β → α} (hs : s₁ = s₂) (hfg : ∀ (a : β), a ∈ s₂ → f a = g a) : lcm s₁ f = lcm s₂ g := Eq._oldrec (fun (hfg : ∀ (a : β), a ∈ s₁ → f a = g a) => fold_congr hfg) hs hfg theorem lcm_mono_fun {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} {g : β → α} (h : ∀ (b : β), b ∈ s → f b ∣ g b) : lcm s f ∣ lcm s g := lcm_dvd fun (b : β) (hb : b ∈ s) => dvd_trans (h b hb) (dvd_lcm hb) theorem lcm_mono {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s₁ : finset β} {s₂ : finset β} {f : β → α} (h : s₁ ⊆ s₂) : lcm s₁ f ∣ lcm s₂ f := lcm_dvd fun (b : β) (hb : b ∈ s₁) => dvd_lcm (h hb) /-! ### gcd -/ /-- Greatest common divisor of a finite set -/ def gcd {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (s : finset β) (f : β → α) : α := fold gcd 0 f s theorem gcd_def {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} : gcd s f = multiset.gcd (multiset.map f (val s)) := rfl @[simp] theorem gcd_empty {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {f : β → α} : gcd ∅ f = 0 := fold_empty theorem dvd_gcd_iff {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} {a : α} : a ∣ gcd s f ↔ ∀ (b : β), b ∈ s → a ∣ f b := sorry theorem gcd_dvd {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} {b : β} (hb : b ∈ s) : gcd s f ∣ f b := iff.mp dvd_gcd_iff (dvd_refl (gcd s f)) b hb theorem dvd_gcd {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} {a : α} : (∀ (b : β), b ∈ s → a ∣ f b) → a ∣ gcd s f := iff.mpr dvd_gcd_iff @[simp] theorem gcd_insert {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} [DecidableEq β] {b : β} : gcd (insert b s) f = gcd (f b) (gcd s f) := sorry @[simp] theorem gcd_singleton {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {f : β → α} {b : β} : gcd (singleton b) f = coe_fn normalize (f b) := multiset.gcd_singleton @[simp] theorem normalize_gcd {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} : coe_fn normalize (gcd s f) = gcd s f := sorry theorem gcd_union {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s₁ : finset β} {s₂ : finset β} {f : β → α} [DecidableEq β] : gcd (s₁ ∪ s₂) f = gcd (gcd s₁ f) (gcd s₂ f) := sorry theorem gcd_congr {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s₁ : finset β} {s₂ : finset β} {f : β → α} {g : β → α} (hs : s₁ = s₂) (hfg : ∀ (a : β), a ∈ s₂ → f a = g a) : gcd s₁ f = gcd s₂ g := Eq._oldrec (fun (hfg : ∀ (a : β), a ∈ s₁ → f a = g a) => fold_congr hfg) hs hfg theorem gcd_mono_fun {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} {g : β → α} (h : ∀ (b : β), b ∈ s → f b ∣ g b) : gcd s f ∣ gcd s g := dvd_gcd fun (b : β) (hb : b ∈ s) => dvd_trans (gcd_dvd hb) (h b hb) theorem gcd_mono {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s₁ : finset β} {s₂ : finset β} {f : β → α} (h : s₁ ⊆ s₂) : gcd s₂ f ∣ gcd s₁ f := dvd_gcd fun (b : β) (hb : b ∈ s₁) => gcd_dvd (h hb) theorem gcd_eq_zero_iff {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} : gcd s f = 0 ↔ ∀ (x : β), x ∈ s → f x = 0 := sorry theorem gcd_eq_gcd_filter_ne_zero {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} [decidable_pred fun (x : β) => f x = 0] : gcd s f = gcd (filter (fun (x : β) => f x ≠ 0) s) f := sorry theorem gcd_mul_left {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} {a : α} : (gcd s fun (x : β) => a * f x) = coe_fn normalize a * gcd s f := sorry theorem gcd_mul_right {α : Type u_1} {β : Type u_2} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : finset β} {f : β → α} {a : α} : (gcd s fun (x : β) => f x * a) = gcd s f * coe_fn normalize a := sorry end finset namespace finset theorem gcd_eq_of_dvd_sub {α : Type u_1} {β : Type u_2} [nontrivial β] [integral_domain α] [gcd_monoid α] {s : finset β} {f : β → α} {g : β → α} {a : α} (h : ∀ (x : β), x ∈ s → a ∣ f x - g x) : gcd a (gcd s f) = gcd a (gcd s g) := sorry
c4d110611339aec7d2b9d9d97afb67b3a5033a00
d406927ab5617694ec9ea7001f101b7c9e3d9702
/archive/imo/imo2021_q1.lean
4a123aeaa0f513b89fec7d2c4ed759ebe799b80d
[ "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
8,298
lean
/- Copyright (c) 2021 Mantas Bakšys. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mantas Bakšys -/ import data.real.sqrt import tactic.interval_cases import tactic.linarith import tactic.norm_cast import tactic.norm_num import tactic.ring_exp /-! # IMO 2021 Q1 Let `n≥100` be an integer. Ivan writes the numbers `n, n+1,..., 2n` each on different cards. He then shuffles these `n+1` cards, and divides them into two piles. Prove that at least one of the piles contains two cards such that the sum of their numbers is a perfect square. # Solution We show there exists a triplet `a, b, c ∈ [n , 2n]` with `a < b < c` and each of the sums `(a + b)`, `(b + c)`, `(a + c)` being a perfect square. Specifically, we consider the linear system of equations a + b = (2 * l - 1) ^ 2 a + c = (2 * l) ^ 2 b + c = (2 * l + 1) ^ 2 which can be solved to give a = 2 * l * l - 4 * l b = 2 * l * l + 1 c = 2 * l * l + 4 * l Therefore, it is enough to show that there exists a natural number l such that `n ≤ 2 * l * l - 4 * l` and `2 * l * l + 4 * l ≤ 2 * n` for `n ≥ 100`. Then, by the Pigeonhole principle, at least two numbers in the triplet must lie in the same pile, which finishes the proof. -/ open real lemma lower_bound (n l : ℕ) (hl : 2 + sqrt (4 + 2 * n) ≤ 2 * l) : n + 4 * l ≤ 2 * l * l := begin suffices : 2 * ((n : ℝ) + 4 * l) - 8 * l + 4 ≤ 2 * (2 * l * l) - 8 * l + 4, { simp only [mul_le_mul_left, sub_le_sub_iff_right, add_le_add_iff_right, zero_lt_two] at this, exact_mod_cast this, }, rw [← le_sub_iff_add_le', sqrt_le_iff, pow_two] at hl, convert hl.2 using 1; ring, end lemma upper_bound (n l : ℕ) (hl : (l : ℝ) ≤ sqrt (1 + n) - 1) : 2 * l * l + 4 * l ≤ 2 * n := begin have h1 : ∀ n : ℕ, 0 ≤ 1 + (n : ℝ), by { intro n, exact_mod_cast nat.zero_le (1 + n) }, rw [le_sub_iff_add_le', le_sqrt (h1 l) (h1 n), pow_two] at hl, rw [← add_le_add_iff_right 2, ← @nat.cast_le ℝ], simp only [nat.cast_bit0, nat.cast_add, nat.cast_one, nat.cast_mul], convert (mul_le_mul_left zero_lt_two).mpr hl using 1; ring, end lemma radical_inequality {n : ℕ} (h : 107 ≤ n) : sqrt (4 + 2 * n) ≤ 2 * (sqrt (1 + n) - 3) := begin have h1n : 0 ≤ 1 + (n : ℝ), by { norm_cast, exact nat.zero_le _ }, rw sqrt_le_iff, split, { simp only [sub_nonneg, zero_le_mul_left, zero_lt_two, le_sqrt zero_lt_three.le h1n], norm_cast, linarith only [h] }, ring_exp, rw [pow_two, ← sqrt_mul h1n, sqrt_mul_self h1n], suffices : 24 * sqrt (1 + n) ≤ 2 * n + 36, by linarith, rw mul_self_le_mul_self_iff, swap, { norm_num, apply sqrt_nonneg }, swap, { norm_cast, linarith }, ring_exp, rw [pow_two, ← sqrt_mul h1n, sqrt_mul_self h1n], -- Not splitting into cases lead to a deterministic timeout on my machine obtain ⟨rfl, h'⟩ : 107 = n ∨ 107 < n := eq_or_lt_of_le h, { norm_num }, { norm_cast, nlinarith }, end -- We will later make use of the fact that there exists (l : ℕ) such that -- n ≤ 2 * l * l - 4 * l and 2 * l * l + 4 * l ≤ 2 * n for n ≥ 107. lemma exists_numbers_in_interval (n : ℕ) (hn : 107 ≤ n) : ∃ (l : ℕ), (n + 4 * l ≤ 2 * l * l ∧ 2 * l * l + 4 * l ≤ 2 * n) := begin rsuffices ⟨l, t⟩ : ∃ (l : ℕ), 2 + sqrt (4 + 2 * n) ≤ 2 * (l : ℝ) ∧ (l : ℝ) ≤ sqrt (1 + n) - 1, { exact ⟨l, lower_bound n l t.1, upper_bound n l t.2⟩ }, let x := sqrt (1 + n) - 1, refine ⟨⌊x⌋₊, _, _⟩, { transitivity 2 * (x - 1), { dsimp only [x], linarith only [radical_inequality hn] }, { simp only [mul_le_mul_left, zero_lt_two], linarith only [(nat.lt_floor_add_one x).le], } }, { apply nat.floor_le, rw [sub_nonneg, le_sqrt], all_goals { norm_cast, simp only [one_pow, le_add_iff_nonneg_right, zero_le'], } }, end lemma exists_triplet_summing_to_squares (n : ℕ) (hn : 100 ≤ n) : (∃ (a b c : ℕ), n ≤ a ∧ a < b ∧ b < c ∧ c ≤ 2 * n ∧ (∃ (k : ℕ), a + b = k * k) ∧ (∃ (l : ℕ), c + a = l * l) ∧ (∃ (m : ℕ), b + c = m * m)) := begin -- If n ≥ 107, we do not explicitly construct the triplet but use an existence -- argument from lemma above. obtain p|p : 107 ≤ n ∨ n < 107 := le_or_lt 107 n, { obtain ⟨l, hl1, hl2⟩ := exists_numbers_in_interval n p, have p : 1 < l, { contrapose! hl1, interval_cases l; linarith }, have h₁ : 4 * l ≤ 2 * l * l, { linarith }, have h₂ : 1 ≤ 2 * l, { linarith }, refine ⟨2 * l * l - 4 * l, 2 * l * l + 1, 2 * l * l + 4 * l, _, _, _, ⟨_, ⟨2 * l - 1, _⟩, ⟨2 * l, _⟩, 2 * l + 1, _⟩⟩, all_goals { zify [h₁, h₂], linarith } }, -- Otherwise, if 100 ≤ n < 107, then it suffices to consider explicit -- construction of a triplet {a, b, c}, which is constructed by setting l=9 -- in the argument at the start of the file. { refine ⟨126, 163, 198, p.le.trans _, _, _, _, ⟨17, _⟩, ⟨18, _⟩, 19, _⟩, swap 4, { linarith }, all_goals { norm_num } }, end -- Since it will be more convenient to work with sets later on, we will translate the above claim -- to state that there always exists a set B ⊆ [n, 2n] of cardinality at least 3, such that each -- pair of pairwise unequal elements of B sums to a perfect square. lemma exists_finset_3_le_card_with_pairs_summing_to_squares (n : ℕ) (hn : 100 ≤ n) : ∃ B : finset ℕ, (2 * 1 + 1 ≤ B.card) ∧ (∀ (a b ∈ B), a ≠ b → ∃ k, a + b = k * k) ∧ (∀ (c ∈ B), n ≤ c ∧ c ≤ 2 * n) := begin obtain ⟨a, b, c, hna, hab, hbc, hcn, h₁, h₂, h₃⟩ := exists_triplet_summing_to_squares n hn, refine ⟨{a, b, c}, _, _, _⟩, { suffices : ({a, b, c} : finset ℕ).card = 3, { rw this, exact le_rfl }, suffices : a ∉ {b, c} ∧ b ∉ {c}, { rw [finset.card_insert_of_not_mem this.1, finset.card_insert_of_not_mem this.2, finset.card_singleton], }, { rw [finset.mem_insert, finset.mem_singleton, finset.mem_singleton], push_neg, exact ⟨⟨hab.ne, (hab.trans hbc).ne⟩, hbc.ne⟩ } }, { intros x hx y hy hxy, simp only [finset.mem_insert, finset.mem_singleton] at hx hy, rcases hx with rfl|rfl|rfl; rcases hy with rfl|rfl|rfl, all_goals { contradiction <|> assumption <|> simpa only [add_comm x y], } }, { simp only [finset.mem_insert, finset.mem_singleton], rintros d (rfl|rfl|rfl); split; linarith only [hna, hab, hbc, hcn], }, end theorem IMO_2021_Q1 : ∀ (n : ℕ), 100 ≤ n → ∀ (A ⊆ finset.Icc n (2 * n)), (∃ (a b ∈ A), a ≠ b ∧ ∃ (k : ℕ), a + b = k * k) ∨ (∃ (a b ∈ finset.Icc n (2 * n) \ A), a ≠ b ∧ ∃ (k : ℕ), a + b = k * k) := begin intros n hn A hA, -- For each n ∈ ℕ such that 100 ≤ n, there exists a pairwise unequal triplet {a, b, c} ⊆ [n, 2n] -- such that all pairwise sums are perfect squares. In practice, it will be easier to use -- a finite set B ⊆ [n, 2n] such that all pairwise unequal pairs of B sum to a perfect square -- noting that B has cardinality greater or equal to 3, by the explicit construction of the -- triplet {a, b, c} before. obtain ⟨B, hB, h₁, h₂⟩ := exists_finset_3_le_card_with_pairs_summing_to_squares n hn, have hBsub : B ⊆ finset.Icc n (2 * n), { intros c hcB, simpa only [finset.mem_Icc] using h₂ c hcB }, have hB' : 2 * 1 < ((B ∩ (finset.Icc n (2 * n) \ A)) ∪ (B ∩ A)).card, { rw [← finset.inter_distrib_left, finset.sdiff_union_self_eq_union, finset.union_eq_left_iff_subset.mpr hA, (finset.inter_eq_left_iff_subset _ _).mpr hBsub], exact nat.succ_le_iff.mp hB }, -- Since B has cardinality greater or equal to 3, there must exist a subset C ⊆ B such that -- for any A ⊆ [n, 2n], either C ⊆ A or C ⊆ [n, 2n] \ A and C has cardinality greater -- or equal to 2. obtain ⟨C, hC, hCA⟩ := finset.exists_subset_or_subset_of_two_mul_lt_card hB', rw finset.one_lt_card at hC, rcases hC with ⟨a, ha, b, hb, hab⟩, simp only [finset.subset_iff, finset.mem_inter] at hCA, -- Now we split into the two cases C ⊆ [n, 2n] \ A and C ⊆ A, which can be dealt with identically. cases hCA; [right, left]; exact ⟨a, (hCA ha).2, b, (hCA hb).2, hab, h₁ a (hCA ha).1 b (hCA hb).1 hab⟩, end
022b9ebd56c9889029244cb81807e16b9d3803c7
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/data/vector2.lean
c76cde828a94d40ea766cc09f97a4f04d98d93f2
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
10,278
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 category.traversable.basic data.set.basic tactic.tauto universes u variables {n : ℕ} namespace vector variables {α : Type*} 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 @[simp] lemma to_list_map {β : Type*} (v : vector α n) (f : α → β) : (v.map f).to_list = v.to_list.map f := by cases v; refl 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] lemma nth_map {β : Type*} (v : vector α n) (f : α → β) (i : fin n) : (v.map f).nth i = f (v.nth i) := by simp [nth_eq_nth_le] @[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 lemma mem_iff_nth {a : α} {v : vector α n} : a ∈ v.to_list ↔ ∃ i, v.nth i = a := by simp only [list.mem_iff_nth_le, fin.exists_iff, vector.nth_eq_nth_le]; exact ⟨λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length at hi, h⟩, λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length, h⟩⟩ lemma nodup_iff_nth_inj {v : vector α n} : v.to_list.nodup ↔ function.injective v.nth := begin cases v with l hl, subst hl, simp only [list.nodup_iff_nth_le_inj], split, { intros h i j hij, cases i, cases j, simp [nth_eq_nth_le] at *, tauto }, { intros h i j hi hj hij, have := @h ⟨i, hi⟩ ⟨j, hj⟩, simp [nth_eq_nth_le] at *, tauto } end @[simp] lemma nth_mem (i : fin n) (v : vector α n) : v.nth i ∈ v.to_list := by rw [nth_eq_nth_le]; exact list.nth_le_mem _ _ _ 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 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 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 @[extensionality] theorem ext : ∀ {v w : vector α n} (h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w | ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw]) (λ m hm hn, h ⟨m, hv ▸ hm⟩)) instance zero_subsingleton : subsingleton (vector α 0) := ⟨λ _ _, vector.ext (λ m, fin.elim0 m)⟩ def to_array : vector α n → array n α | ⟨xs, h⟩ := cast (by rw h) xs.to_array section insert_nth variable {a : α} def insert_nth (a : α) (i : fin (n+1)) (v : vector α n) : vector α (n+1) := ⟨v.1.insert_nth i.1 a, begin rw [list.length_insert_nth, v.2], rw [v.2, ← nat.succ_le_succ_iff], exact i.2 end⟩ lemma insert_nth_val {i : fin (n+1)} {v : vector α n} : (v.insert_nth a i).val = v.val.insert_nth i.1 a := rfl @[simp] lemma remove_nth_val {i : fin n} : ∀{v : vector α n}, (remove_nth i v).val = v.val.remove_nth i.1 | ⟨l, hl⟩ := rfl lemma remove_nth_insert_nth {v : vector α n} {i : fin (n+1)} : remove_nth i (insert_nth a i v) = v := subtype.eq $ list.remove_nth_insert_nth i.1 v.1 lemma remove_nth_insert_nth_ne {v : vector α (n+1)} : ∀{i j : fin (n+2)} (h : i ≠ j), remove_nth i (insert_nth a j v) = insert_nth a (i.pred_above j h.symm) (remove_nth (j.pred_above i h) v) | ⟨i, hi⟩ ⟨j, hj⟩ ne := begin have : i ≠ j := fin.vne_of_ne ne, refine subtype.eq _, dsimp [insert_nth, remove_nth, fin.pred_above, fin.cast_lt], rcases lt_trichotomy i j with h | h | h, { have h_nji : ¬ j < i := lt_asymm h, have j_pos : 0 < j := lt_of_le_of_lt (zero_le i) h, simp [h, h_nji, fin.lt_iff_val_lt_val], rw [show j.pred = j - 1, from rfl, list.insert_nth_remove_nth_of_ge, nat.sub_add_cancel j_pos], { rw [v.2], exact lt_of_lt_of_le h (nat.le_of_succ_le_succ hj) }, { exact nat.le_sub_right_of_add_le h } }, { exact (this h).elim }, { have h_nij : ¬ i < j := lt_asymm h, have i_pos : 0 < i := lt_of_le_of_lt (zero_le j) h, simp [h, h_nij, fin.lt_iff_val_lt_val], rw [show i.pred = i - 1, from rfl, list.insert_nth_remove_nth_of_le, nat.sub_add_cancel i_pos], { show i - 1 + 1 ≤ v.val.length, rw [v.2, nat.sub_add_cancel i_pos], exact nat.le_of_lt_succ hi }, { exact nat.le_sub_right_of_add_le h } } end lemma insert_nth_comm (a b : α) (i j : fin (n+1)) (h : i ≤ j) : ∀(v : vector α n), (v.insert_nth a i).insert_nth b j.succ = (v.insert_nth b j).insert_nth a i.cast_succ | ⟨l, hl⟩ := begin refine subtype.eq _, simp [insert_nth_val, fin.succ_val, fin.cast_succ], apply list.insert_nth_comm, { assumption }, { rw hl, exact nat.le_of_succ_le_succ j.2 } end end insert_nth section update_nth /-- `update_nth v n a` replaces the `n`th element of `v` with `a` -/ def update_nth (v : vector α n) (i : fin n) (a : α) : vector α n := ⟨v.1.update_nth i.1 a, by rw [list.update_nth_length, v.2]⟩ @[simp] lemma nth_update_nth_same (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).nth i = a := by cases v; cases i; simp [vector.update_nth, vector.nth_eq_nth_le] lemma nth_update_nth_of_ne {v : vector α n} {i j : fin n} (h : i ≠ j) (a : α) : (v.update_nth i a).nth j = v.nth j := by cases v; cases i; cases j; simp [vector.update_nth, vector.nth_eq_nth_le, list.nth_le_update_nth_of_ne (fin.vne_of_ne h)] lemma nth_update_nth_eq_if {v : vector α n} {i j : fin n} (a : α) : (v.update_nth i a).nth j = if i = j then a else v.nth j := by split_ifs; try {simp *}; try {rw nth_update_nth_of_ne}; assumption end update_nth end vector namespace vector section traverse variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) nat private def traverse_aux {α β : Type u} (f : α → F β) : Π (x : list α), F (vector β x.length) | [] := pure vector.nil | (x::xs) := vector.cons <$> f x <*> traverse_aux xs protected def traverse {α β : Type u} (f : α → F β) : vector α n → F (vector β n) | ⟨v, Hv⟩ := cast (by rw Hv) $ traverse_aux f v variables [is_lawful_applicative F] [is_lawful_applicative G] variables {α β γ : Type u} @[simp] protected lemma traverse_def (f : α → F β) (x : α) : ∀ (xs : vector α n), (x :: xs).traverse f = cons <$> f x <*> xs.traverse f := by rintro ⟨xs, rfl⟩; refl protected lemma id_traverse : ∀ (x : vector α n), x.traverse id.mk = x := begin rintro ⟨x, rfl⟩, dsimp [vector.traverse, cast], induction x with x xs IH, {refl}, simp! [IH], refl end open function protected lemma comp_traverse (f : β → F γ) (g : α → G β) : ∀ (x : vector α n), vector.traverse (comp.mk ∘ functor.map f ∘ g) x = comp.mk (vector.traverse f <$> vector.traverse g x) := by rintro ⟨x, rfl⟩; dsimp [vector.traverse, cast]; induction x with x xs; simp! [cast, *] with functor_norm; [refl, simp [(∘)]] protected lemma traverse_eq_map_id {α β} (f : α → β) : ∀ (x : vector α n), x.traverse (id.mk ∘ f) = id.mk (map f x) := by rintro ⟨x, rfl⟩; simp!; induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β : Type*} (f : α → F β) : ∀ (x : vector α n), η (x.traverse f) = x.traverse (@η _ ∘ f) := by rintro ⟨x, rfl⟩; simp! [cast]; induction x with x xs IH; simp! * with functor_norm end traverse instance : traversable.{u} (flip vector n) := { traverse := @vector.traverse n, map := λ α β, @vector.map.{u u} α β n } instance : is_lawful_traversable.{u} (flip vector n) := { id_traverse := @vector.id_traverse n, comp_traverse := @vector.comp_traverse n, traverse_eq_map_id := @vector.traverse_eq_map_id n, naturality := @vector.naturality n, id_map := by intros; cases x; simp! [(<$>)], comp_map := by intros; cases x; simp! [(<$>)] } end vector
1d4cf498f6b49554dad62085002ac5d71fb908d9
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/polynomial/degree/lemmas.lean
1d8c9932ca23999f423577fc142db1eacefcd443
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
10,203
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.eval import tactic.interval_cases /-! # Theory of degrees of polynomials Some of the main results include - `nat_degree_comp_le` : The degree of the composition is at most the product of degrees -/ noncomputable theory open_locale classical polynomial open finsupp finset namespace polynomial universes u v w variables {R : Type u} {S : Type v} { ι : Type w} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : R[X]} section degree lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... = _ : congr_arg degree comp_eq_sum_left ... ≤ _ : degree_sum_le _ _ ... ≤ _ : sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + n • (degree q) : add_le_add degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + n • (nat_degree q) : add_le_add_left (nsmul_le_nsmul_of_le_right (@degree_le_nat_degree _ _ q) n) _ ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_nsmul, nsmul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_pos_of_root {p : R[X]} (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, simp only [h, ring_hom.map_zero] at this, exact hp this, end lemma nat_degree_le_iff_coeff_eq_zero : p.nat_degree ≤ n ↔ ∀ N : ℕ, n < N → p.coeff N = 0 := by simp_rw [nat_degree_le_iff_degree_le, degree_le_iff_coeff_zero, with_bot.coe_lt_coe] lemma nat_degree_add_le_iff_left {n : ℕ} (p q : R[X]) (qn : q.nat_degree ≤ n) : (p + q).nat_degree ≤ n ↔ p.nat_degree ≤ n := begin refine ⟨λ h, _, λ h, nat_degree_add_le_of_degree_le h qn⟩, refine nat_degree_le_iff_coeff_eq_zero.mpr (λ m hm, _), convert nat_degree_le_iff_coeff_eq_zero.mp h m hm using 1, rw [coeff_add, nat_degree_le_iff_coeff_eq_zero.mp qn _ hm, add_zero], end lemma nat_degree_add_le_iff_right {n : ℕ} (p q : R[X]) (pn : p.nat_degree ≤ n) : (p + q).nat_degree ≤ n ↔ q.nat_degree ≤ n := begin rw add_comm, exact nat_degree_add_le_iff_left _ _ pn, end lemma nat_degree_C_mul_le (a : R) (f : R[X]) : (C a * f).nat_degree ≤ f.nat_degree := calc (C a * f).nat_degree ≤ (C a).nat_degree + f.nat_degree : nat_degree_mul_le ... = 0 + f.nat_degree : by rw nat_degree_C a ... = f.nat_degree : zero_add _ lemma nat_degree_mul_C_le (f : R[X]) (a : R) : (f * C a).nat_degree ≤ f.nat_degree := calc (f * C a).nat_degree ≤ f.nat_degree + (C a).nat_degree : nat_degree_mul_le ... = f.nat_degree + 0 : by rw nat_degree_C a ... = f.nat_degree : add_zero _ lemma eq_nat_degree_of_le_mem_support (pn : p.nat_degree ≤ n) (ns : n ∈ p.support) : p.nat_degree = n := le_antisymm pn (le_nat_degree_of_mem_supp _ ns) lemma nat_degree_C_mul_eq_of_mul_eq_one {ai : R} (au : ai * a = 1) : (C a * p).nat_degree = p.nat_degree := le_antisymm (nat_degree_C_mul_le a p) (calc p.nat_degree = (1 * p).nat_degree : by nth_rewrite 0 [← one_mul p] ... = (C ai * (C a * p)).nat_degree : by rw [← C_1, ← au, ring_hom.map_mul, ← mul_assoc] ... ≤ (C a * p).nat_degree : nat_degree_C_mul_le ai (C a * p)) lemma nat_degree_mul_C_eq_of_mul_eq_one {ai : R} (au : a * ai = 1) : (p * C a).nat_degree = p.nat_degree := le_antisymm (nat_degree_mul_C_le p a) (calc p.nat_degree = (p * 1).nat_degree : by nth_rewrite 0 [← mul_one p] ... = ((p * C a) * C ai).nat_degree : by rw [← C_1, ← au, ring_hom.map_mul, ← mul_assoc] ... ≤ (p * C a).nat_degree : nat_degree_mul_C_le (p * C a) ai) /-- Although not explicitly stated, the assumptions of lemma `nat_degree_mul_C_eq_of_mul_ne_zero` force the polynomial `p` to be non-zero, via `p.leading_coeff ≠ 0`. -/ lemma nat_degree_mul_C_eq_of_mul_ne_zero (h : p.leading_coeff * a ≠ 0) : (p * C a).nat_degree = p.nat_degree := begin refine eq_nat_degree_of_le_mem_support (nat_degree_mul_C_le p a) _, refine mem_support_iff.mpr _, rwa coeff_mul_C, end /-- Although not explicitly stated, the assumptions of lemma `nat_degree_C_mul_eq_of_mul_ne_zero` force the polynomial `p` to be non-zero, via `p.leading_coeff ≠ 0`. -/ lemma nat_degree_C_mul_eq_of_mul_ne_zero (h : a * p.leading_coeff ≠ 0) : (C a * p).nat_degree = p.nat_degree := begin refine eq_nat_degree_of_le_mem_support (nat_degree_C_mul_le a p) _, refine mem_support_iff.mpr _, rwa coeff_C_mul, end lemma nat_degree_add_coeff_mul (f g : R[X]) : (f * g).coeff (f.nat_degree + g.nat_degree) = f.coeff f.nat_degree * g.coeff g.nat_degree := by simp only [coeff_nat_degree, coeff_mul_degree_add_degree] lemma nat_degree_lt_coeff_mul (h : p.nat_degree + q.nat_degree < m + n) : (p * q).coeff (m + n) = 0 := coeff_eq_zero_of_nat_degree_lt (nat_degree_mul_le.trans_lt h) lemma degree_sum_eq_of_disjoint (f : S → R[X]) (s : finset S) (h : set.pairwise { i | i ∈ s ∧ f i ≠ 0 } (ne on (degree ∘ f))) : degree (s.sum f) = s.sup (λ i, degree (f i)) := begin induction s using finset.induction_on with x s hx IH, { simp }, { simp only [hx, finset.sum_insert, not_false_iff, finset.sup_insert], specialize IH (h.mono (λ _, by simp {contextual := tt})), rcases lt_trichotomy (degree (f x)) (degree (s.sum f)) with H|H|H, { rw [←IH, sup_eq_right.mpr H.le, degree_add_eq_right_of_degree_lt H] }, { rcases s.eq_empty_or_nonempty with rfl|hs, { simp }, obtain ⟨y, hy, hy'⟩ := finset.exists_mem_eq_sup s hs (λ i, degree (f i)), rw [IH, hy'] at H, by_cases hx0 : f x = 0, { simp [hx0, IH] }, have hy0 : f y ≠ 0, { contrapose! H, simpa [H, degree_eq_bot] using hx0 }, refine absurd H (h _ _ (λ H, hx _)), { simp [hx0] }, { simp [hy, hy0] }, { exact H.symm ▸ hy } }, { rw [←IH, sup_eq_left.mpr H.le, degree_add_eq_left_of_degree_lt H] } } end lemma nat_degree_sum_eq_of_disjoint (f : S → R[X]) (s : finset S) (h : set.pairwise { i | i ∈ s ∧ f i ≠ 0 } (ne on (nat_degree ∘ f))) : nat_degree (s.sum f) = s.sup (λ i, nat_degree (f i)) := begin by_cases H : ∃ x ∈ s, f x ≠ 0, { obtain ⟨x, hx, hx'⟩ := H, have hs : s.nonempty := ⟨x, hx⟩, refine nat_degree_eq_of_degree_eq_some _, rw degree_sum_eq_of_disjoint, { rw [←finset.sup'_eq_sup hs, ←finset.sup'_eq_sup hs, finset.coe_sup', ←finset.sup'_eq_sup hs], refine le_antisymm _ _, { rw finset.sup'_le_iff, intros b hb, by_cases hb' : f b = 0, { simpa [hb'] using hs }, rw degree_eq_nat_degree hb', exact finset.le_sup' _ hb }, { rw finset.sup'_le_iff, intros b hb, simp only [finset.le_sup'_iff, exists_prop, function.comp_app], by_cases hb' : f b = 0, { refine ⟨x, hx, _⟩, contrapose! hx', simpa [hb', degree_eq_bot] using hx' }, exact ⟨b, hb, (degree_eq_nat_degree hb').ge⟩ } }, { exact h.imp (λ x y hxy hxy', hxy (nat_degree_eq_of_degree_eq hxy')) } }, { push_neg at H, rw [finset.sum_eq_zero H, nat_degree_zero, eq_comm, show 0 = ⊥, from rfl, finset.sup_eq_bot_iff], intros x hx, simp [H x hx] } end variables [semiring S] lemma nat_degree_pos_of_eval₂_root {p : R[X]} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < nat_degree p := lt_of_not_ge $ λ hlt, begin have A : p = C (p.coeff 0) := eq_C_of_nat_degree_le_zero hlt, rw [A, eval₂_C] at hz, simp only [inj (p.coeff 0) hz, ring_hom.map_zero] at A, exact hp A end lemma degree_pos_of_eval₂_root {p : R[X]} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < degree p := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_eval₂_root hp f hz inj) @[simp] lemma coe_lt_degree {p : R[X]} {n : ℕ} : ((n : with_bot ℕ) < degree p) ↔ n < nat_degree p := begin by_cases h : p = 0, { simp [h] }, rw [degree_eq_nat_degree h, with_bot.coe_lt_coe], end end degree end semiring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} lemma degree_mul_C (a0 : a ≠ 0) : (p * C a).degree = p.degree := by rw [degree_mul, degree_C a0, add_zero] lemma degree_C_mul (a0 : a ≠ 0) : (C a * p).degree = p.degree := by rw [degree_mul, degree_C a0, zero_add] lemma nat_degree_mul_C (a0 : a ≠ 0) : (p * C a).nat_degree = p.nat_degree := by simp only [nat_degree, degree_mul_C a0] lemma nat_degree_C_mul (a0 : a ≠ 0) : (C a * p).nat_degree = p.nat_degree := by simp only [nat_degree, degree_C_mul a0] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := begin by_cases q0 : q.nat_degree = 0, { rw [degree_le_zero_iff.mp (nat_degree_eq_zero_iff_degree_le_zero.mp q0), comp_C, nat_degree_C, nat_degree_C, mul_zero] }, { by_cases p0 : p = 0, { simp only [p0, zero_comp, nat_degree_zero, zero_mul] }, refine le_antisymm nat_degree_comp_le (le_nat_degree_of_ne_zero _), simp only [coeff_comp_degree_mul_degree q0, p0, mul_eq_zero, leading_coeff_eq_zero, or_self, ne_zero_of_nat_degree_gt (nat.pos_of_ne_zero q0), pow_ne_zero, ne.def, not_false_iff] } end lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp, coeff_nat_degree] end no_zero_divisors end polynomial
8c15129bd319a91f17a0fc22bbd89bd534fd9c88
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/order/field.lean
18f586ba07760e3afa699acdaaae16af313913f4
[ "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
16,568
lean
/- Copyright (c) 2022 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson, Devon Tuma, Eric Rodriguez, Oliver Nash -/ import tactic.positivity import tactic.linarith import topology.algebra.order.group import topology.algebra.field /-! # Topologies on linear ordered fields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open set filter topological_space open function open order_dual (to_dual of_dual) open_locale topology classical filter variables {α β : Type*} variables [linear_ordered_field α] [topological_space α] [order_topology α] variables {l : filter β} {f g : β → α} section continuous_mul lemma mul_tendsto_nhds_zero_right (x : α) : tendsto (uncurry ((*) : α → α → α)) (𝓝 0 ×ᶠ 𝓝 x) $ 𝓝 0 := begin have hx : 0 < 2 * (1 + |x|) := by positivity, rw ((nhds_basis_zero_abs_sub_lt α).prod $ nhds_basis_abs_sub_lt x).tendsto_iff (nhds_basis_zero_abs_sub_lt α), refine λ ε ε_pos, ⟨(ε/(2 * (1 + |x|)), 1), ⟨div_pos ε_pos hx, zero_lt_one⟩, _⟩, suffices : ∀ (a b : α), |a| < ε / (2 * (1 + |x|)) → |b - x| < 1 → |a| * |b| < ε, by simpa only [and_imp, prod.forall, mem_prod, ← abs_mul], intros a b h h', refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left _ (abs_nonneg a)) ((lt_div_iff hx).1 h), calc |b| = |(b - x) + x| : by rw sub_add_cancel b x ... ≤ |b - x| + |x| : abs_add (b - x) x ... ≤ 2 * (1 + |x|) : by linarith, end lemma mul_tendsto_nhds_zero_left (x : α) : tendsto (uncurry ((*) : α → α → α)) (𝓝 x ×ᶠ 𝓝 0) $ 𝓝 0 := begin intros s hs, have := mul_tendsto_nhds_zero_right x hs, rw [filter.mem_map, mem_prod_iff] at this ⊢, obtain ⟨U, hU, V, hV, h⟩ := this, exact ⟨V, hV, U, hU, λ y hy, ((mul_comm y.2 y.1) ▸ h (⟨hy.2, hy.1⟩ : (prod.mk y.2 y.1) ∈ U ×ˢ V) : y.1 * y.2 ∈ s)⟩, end lemma nhds_eq_map_mul_left_nhds_one {x₀ : α} (hx₀ : x₀ ≠ 0) : 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1) := begin have hx₀' : 0 < |x₀| := abs_pos.2 hx₀, refine filter.ext (λ t, _), simp only [exists_prop, set_of_subset_set_of, (nhds_basis_abs_sub_lt x₀).mem_iff, (nhds_basis_abs_sub_lt (1 : α)).mem_iff, filter.mem_map'], refine ⟨λ h, _, λ h, _⟩, { obtain ⟨i, hi, hit⟩ := h, refine ⟨i / (|x₀|), div_pos hi (abs_pos.2 hx₀), λ x hx, hit _⟩, calc |x₀ * x - x₀| = |x₀ * (x - 1)| : congr_arg abs (by ring_nf) ... = |x₀| * |x - 1| : abs_mul x₀ (x - 1) ... < |x₀| * (i / |x₀|) : mul_lt_mul' le_rfl hx (by positivity) (abs_pos.2 hx₀) ... = |x₀| * i / |x₀| : by ring ... = i : mul_div_cancel_left i (λ h, hx₀ (abs_eq_zero.1 h)) }, { obtain ⟨i, hi, hit⟩ := h, refine ⟨i * |x₀|, mul_pos hi (abs_pos.2 hx₀), λ x hx, _⟩, have : |x / x₀ - 1| < i, calc |x / x₀ - 1| = |x / x₀ - x₀ / x₀| : (by rw div_self hx₀) ... = |(x - x₀) / x₀| : congr_arg abs (sub_div x x₀ x₀).symm ... = |x - x₀| / |x₀| : abs_div (x - x₀) x₀ ... < i * |x₀| / |x₀| : div_lt_div_of_lt (abs_pos.2 hx₀) hx ... = i : by rw [← mul_div_assoc', div_self (ne_of_lt $ abs_pos.2 hx₀).symm, mul_one], specialize hit (x / x₀) this, rwa [mul_div_assoc', mul_div_cancel_left x hx₀] at hit } end lemma nhds_eq_map_mul_right_nhds_one {x₀ : α} (hx₀ : x₀ ≠ 0) : 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1) := by simp_rw [mul_comm _ x₀, nhds_eq_map_mul_left_nhds_one hx₀] lemma mul_tendsto_nhds_one_nhds_one : tendsto (uncurry ((*) : α → α → α)) (𝓝 1 ×ᶠ 𝓝 1) $ 𝓝 1 := begin rw ((nhds_basis_Ioo_pos (1 : α)).prod $ nhds_basis_Ioo_pos (1 : α)).tendsto_iff (nhds_basis_Ioo_pos_of_pos (zero_lt_one : (0 : α) < 1)), intros ε hε, have hε' : 0 ≤ 1 - ε / 4 := by linarith, have ε_pos : 0 < ε / 4 := by linarith, have ε_pos' : 0 < ε / 2 := by linarith, simp only [and_imp, prod.forall, mem_Ioo, function.uncurry_apply_pair, mem_prod, prod.exists], refine ⟨ε/4, ε/4, ⟨ε_pos, ε_pos⟩, λ a b ha ha' hb hb', _⟩, have ha0 : 0 ≤ a := le_trans hε' (le_of_lt ha), have hb0 : 0 ≤ b := le_trans hε' (le_of_lt hb), refine ⟨lt_of_le_of_lt _ (mul_lt_mul'' ha hb hε' hε'), lt_of_lt_of_le (mul_lt_mul'' ha' hb' ha0 hb0) _⟩, { calc 1 - ε = 1 - ε / 2 - ε/2 : by ring_nf ... ≤ 1 - ε/2 - ε/2 + (ε/2)*(ε/2) : le_add_of_nonneg_right (by positivity) ... = (1 - ε/2) * (1 - ε/2) : by ring_nf ... ≤ (1 - ε/4) * (1 - ε/4) : mul_le_mul (by linarith) (by linarith) (by linarith) hε' }, { calc (1 + ε/4) * (1 + ε/4) = 1 + ε/2 + (ε/4)*(ε/4) : by ring_nf ... = 1 + ε/2 + (ε * ε) / 16 : by ring_nf ... ≤ 1 + ε/2 + ε/2 : add_le_add_left (div_le_div (le_of_lt hε.1) (le_trans ((mul_le_mul_left hε.1).2 hε.2) (le_of_eq $ mul_one ε)) zero_lt_two (by linarith)) (1 + ε/2) ... ≤ 1 + ε : by ring_nf } end @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.has_continuous_mul : has_continuous_mul α := ⟨begin rw continuous_iff_continuous_at, rintro ⟨x₀, y₀⟩, by_cases hx₀ : x₀ = 0, { rw [hx₀, continuous_at, zero_mul, nhds_prod_eq], exact mul_tendsto_nhds_zero_right y₀ }, by_cases hy₀ : y₀ = 0, { rw [hy₀, continuous_at, mul_zero, nhds_prod_eq], exact mul_tendsto_nhds_zero_left x₀ }, have hxy : x₀ * y₀ ≠ 0 := mul_ne_zero hx₀ hy₀, have key : (λ p : α × α, x₀ * p.1 * (p.2 * y₀)) = ((λ x, x₀*x) ∘ (λ x, x*y₀)) ∘ (uncurry (*)), { ext p, simp [uncurry, mul_assoc] }, have key₂ : (λ x, x₀*x) ∘ (λ x, y₀*x) = λ x, (x₀ *y₀)*x, { ext x, simp }, calc map (uncurry (*)) (𝓝 (x₀, y₀)) = map (uncurry (*)) (𝓝 x₀ ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : α × α), x₀ * p.1 * (p.2 * y₀)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [uncurry, nhds_eq_map_mul_left_nhds_one hx₀, nhds_eq_map_mul_right_nhds_one hy₀, prod_map_map_eq, filter.map_map] ... = map ((λ x, x₀ * x) ∘ λ x, x * y₀) (map (uncurry (*)) (𝓝 1 ×ᶠ 𝓝 1)) : by rw [key, ← filter.map_map] ... ≤ map ((λ (x : α), x₀ * x) ∘ λ x, x * y₀) (𝓝 1) : map_mono (mul_tendsto_nhds_one_nhds_one) ... = 𝓝 (x₀*y₀) : by rw [← filter.map_map, ← nhds_eq_map_mul_right_nhds_one hy₀, nhds_eq_map_mul_left_nhds_one hy₀, filter.map_map, key₂, ← nhds_eq_map_mul_left_nhds_one hxy], end⟩ end continuous_mul /-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to a positive constant `C` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.at_top_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_top := begin refine tendsto_at_top_mono' _ _ (hf.at_top_mul_const (half_pos hC)), filter_upwards [hg.eventually (lt_mem_nhds (half_lt_self hC)), hf.eventually (eventually_ge_at_top 0)] with x hg hf using mul_le_mul_of_nonneg_left hg.le hf, end /-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and `g` tends to `at_top` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.mul_at_top {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, (f x * g x)) l at_top := by simpa only [mul_comm] using hg.at_top_mul hC hf /-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to a negative constant `C` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.at_top_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp (hf.at_top_mul (neg_pos.2 hC) hg.neg) /-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and `g` tends to `at_top` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.neg_mul_at_top {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [mul_comm] using hg.at_top_mul_neg hC hf /-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to a positive constant `C` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.at_bot_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_bot := by simpa [(∘)] using tendsto_neg_at_top_at_bot.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul hC hg) /-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to a negative constant `C` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.at_bot_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_top := by simpa [(∘)] using tendsto_neg_at_bot_at_top.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul_neg hC hg) /-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and `g` tends to `at_bot` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.mul_at_bot {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [mul_comm] using hg.at_bot_mul hC hf /-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and `g` tends to `at_bot` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.neg_mul_at_bot {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, (f x * g x)) l at_top := by simpa only [mul_comm] using hg.at_bot_mul_neg hC hf /-- The function `x ↦ x⁻¹` tends to `+∞` on the right of `0`. -/ lemma tendsto_inv_zero_at_top : tendsto (λx:α, x⁻¹) (𝓝[>] (0:α)) at_top := begin refine (at_top_basis' 1).tendsto_right_iff.2 (λ b hb, _), have hb' : 0 < b := by positivity, filter_upwards [Ioc_mem_nhds_within_Ioi ⟨le_rfl, inv_pos.2 hb'⟩] with x hx using (le_inv hx.1 hb').1 hx.2, end /-- The function `r ↦ r⁻¹` tends to `0` on the right as `r → +∞`. -/ lemma tendsto_inv_at_top_zero' : tendsto (λr:α, r⁻¹) at_top (𝓝[>] (0:α)) := begin refine (has_basis.tendsto_iff at_top_basis ⟨λ s, mem_nhds_within_Ioi_iff_exists_Ioc_subset⟩).2 _, refine λ b hb, ⟨b⁻¹, trivial, λ x hx, _⟩, have : 0 < x := lt_of_lt_of_le (inv_pos.2 hb) hx, exact ⟨inv_pos.2 this, (inv_le this hb).2 hx⟩ end lemma tendsto_inv_at_top_zero : tendsto (λr:α, r⁻¹) at_top (𝓝 0) := tendsto_inv_at_top_zero'.mono_right inf_le_left lemma filter.tendsto.div_at_top [has_continuous_mul α] {f g : β → α} {l : filter β} {a : α} (h : tendsto f l (𝓝 a)) (hg : tendsto g l at_top) : tendsto (λ x, f x / g x) l (𝓝 0) := by { simp only [div_eq_mul_inv], exact mul_zero a ▸ h.mul (tendsto_inv_at_top_zero.comp hg) } lemma filter.tendsto.inv_tendsto_at_top (h : tendsto f l at_top) : tendsto (f⁻¹) l (𝓝 0) := tendsto_inv_at_top_zero.comp h lemma filter.tendsto.inv_tendsto_zero (h : tendsto f l (𝓝[>] 0)) : tendsto (f⁻¹) l at_top := tendsto_inv_zero_at_top.comp h /-- The function `x^(-n)` tends to `0` at `+∞` for any positive natural `n`. A version for positive real powers exists as `tendsto_rpow_neg_at_top`. -/ lemma tendsto_pow_neg_at_top {n : ℕ} (hn : n ≠ 0) : tendsto (λ x : α, x ^ (-(n:ℤ))) at_top (𝓝 0) := by simpa only [zpow_neg, zpow_coe_nat] using (@tendsto_pow_at_top α _ _ hn).inv_tendsto_at_top lemma tendsto_zpow_at_top_zero {n : ℤ} (hn : n < 0) : tendsto (λ x : α, x^n) at_top (𝓝 0) := begin lift -n to ℕ using le_of_lt (neg_pos.mpr hn) with N, rw [← neg_pos, ← h, nat.cast_pos] at hn, simpa only [h, neg_neg] using tendsto_pow_neg_at_top hn.ne' end lemma tendsto_const_mul_zpow_at_top_zero {n : ℤ} {c : α} (hn : n < 0) : tendsto (λ x, c * x ^ n) at_top (𝓝 0) := (mul_zero c) ▸ (filter.tendsto.const_mul c (tendsto_zpow_at_top_zero hn)) lemma tendsto_const_mul_pow_nhds_iff' {n : ℕ} {c d : α} : tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ (c = 0 ∨ n = 0) ∧ c = d := begin rcases eq_or_ne n 0 with (rfl|hn), { simp [tendsto_const_nhds_iff] }, rcases lt_trichotomy c 0 with hc|rfl|hc, { have := tendsto_const_mul_pow_at_bot_iff.2 ⟨hn, hc⟩, simp [not_tendsto_nhds_of_tendsto_at_bot this, hc.ne, hn] }, { simp [tendsto_const_nhds_iff] }, { have := tendsto_const_mul_pow_at_top_iff.2 ⟨hn, hc⟩, simp [not_tendsto_nhds_of_tendsto_at_top this, hc.ne', hn] } end lemma tendsto_const_mul_pow_nhds_iff {n : ℕ} {c d : α} (hc : c ≠ 0) : tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ n = 0 ∧ c = d := by simp [tendsto_const_mul_pow_nhds_iff', hc] lemma tendsto_const_mul_zpow_at_top_nhds_iff {n : ℤ} {c d : α} (hc : c ≠ 0) : tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ (n = 0 ∧ c = d) ∨ (n < 0 ∧ d = 0) := begin refine ⟨λ h, _, λ h, _⟩, { by_cases hn : 0 ≤ n, { lift n to ℕ using hn, simp only [zpow_coe_nat] at h, rw [tendsto_const_mul_pow_nhds_iff hc, ← int.coe_nat_eq_zero] at h, exact or.inl h }, { rw not_le at hn, refine or.inr ⟨hn, tendsto_nhds_unique h (tendsto_const_mul_zpow_at_top_zero hn)⟩ } }, { cases h, { simp only [h.left, h.right, zpow_zero, mul_one], exact tendsto_const_nhds }, { exact h.2.symm ▸ tendsto_const_mul_zpow_at_top_zero h.1} } end -- TODO: With a different proof, this could be possibly generalised to only require a -- `linear_ordered_semifield` instance, which would also remove the need for the -- `nnreal` instance of `has_continuous_inv₀`. @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_topological_division_ring : topological_division_ring α := { continuous_at_inv₀ := begin suffices : ∀ {x : α}, 0 < x → continuous_at has_inv.inv x, { intros x hx, cases hx.symm.lt_or_lt, { exact this h }, convert (this $ neg_pos.mpr h).neg.comp continuous_neg.continuous_at, ext, simp [neg_inv] }, intros t ht, rw [continuous_at, (nhds_basis_Ioo_pos t).tendsto_iff $ nhds_basis_Ioo_pos_of_pos $ inv_pos.2 ht], rintros ε ⟨hε : ε > 0, hεt : ε ≤ t⁻¹⟩, refine ⟨min (t ^ 2 * ε / 2) (t / 2), by positivity, λ x h, _⟩, have hx : t / 2 < x, { rw [set.mem_Ioo, sub_lt_comm, lt_min_iff] at h, nlinarith }, have hx' : 0 < x := (half_pos ht).trans hx, have aux : 0 < 2 / t ^ 2 := by positivity, rw [set.mem_Ioo, ←sub_lt_iff_lt_add', sub_lt_comm, ←abs_sub_lt_iff] at h ⊢, rw [inv_sub_inv ht.ne' hx'.ne', abs_div, div_eq_mul_inv], suffices : |t * x|⁻¹ < 2 / t ^ 2, { rw [←abs_neg, neg_sub], refine (mul_lt_mul'' h this (by positivity) (by positivity)).trans_le _, rw [mul_comm, mul_min_of_nonneg _ _ aux.le], apply min_le_of_left_le, rw [←mul_div, ←mul_assoc, div_mul_cancel _ (sq_pos_of_pos ht).ne', mul_div_cancel' ε two_ne_zero] }, refine inv_lt_of_inv_lt aux _, rw [inv_div, abs_of_pos $ mul_pos ht hx', sq, ←mul_div_assoc'], exact mul_lt_mul_of_pos_left hx ht end } lemma nhds_within_pos_comap_mul_left {x : α} (hx : 0 < x) : comap (λ ε, x * ε) (𝓝[>] 0) = 𝓝[>] 0 := begin suffices : ∀ {x : α} (hx : 0 < x), 𝓝[>] 0 ≤ comap (λ ε, x * ε) (𝓝[>] 0), { refine le_antisymm _ (this hx), have hr : 𝓝[>] (0 : α) = ((𝓝[>] (0 : α)).comap (λ ε, x⁻¹ * ε)).comap (λ ε, x * ε), { simp [comap_comap, inv_mul_cancel hx.ne.symm, comap_id, one_mul_eq_id], }, conv_rhs { rw hr, }, rw comap_le_comap_iff (by convert univ_mem; exact (mul_left_surjective₀ hx.ne.symm).range_eq), exact this (inv_pos.mpr hx), }, intros x hx, convert nhds_within_le_comap (continuous_mul_left x).continuous_within_at, { exact (mul_zero _).symm, }, { rw image_const_mul_Ioi_zero hx, }, end lemma eventually_nhds_within_pos_mul_left {x : α} (hx : 0 < x) {p : α → Prop} (h : ∀ᶠ ε in 𝓝[>] 0, p ε) : ∀ᶠ ε in 𝓝[>] 0, p (x * ε) := begin convert h.comap (λ ε, x * ε), exact (nhds_within_pos_comap_mul_left hx).symm, end
00464d692e8130ab09584309cd9d41da0f3b3027
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/direct_sum/internal.lean
b02cc3edd749a61bda2e393b6955ee2b06fced1d
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
10,782
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Kevin Buzzard, Jujian Zhang -/ import algebra.algebra.operations import algebra.algebra.subalgebra.basic import algebra.direct_sum.algebra /-! # Internally graded rings and algebras This module provides `gsemiring` and `gcomm_semiring` instances for a collection of subobjects `A` when a `set_like.graded_monoid` instance is available: * on `add_submonoid R`s: `add_submonoid.gsemiring`, `add_submonoid.gcomm_semiring`. * on `add_subgroup R`s: `add_subgroup.gsemiring`, `add_subgroup.gcomm_semiring`. * on `submodule S R`s: `submodule.gsemiring`, `submodule.gcomm_semiring`. With these instances in place, it provides the bundled canonical maps out of a direct sum of subobjects into their carrier type: * `direct_sum.add_submonoid_coe_ring_hom` (a `ring_hom` version of `direct_sum.add_submonoid_coe`) * `direct_sum.add_subgroup_coe_ring_hom` (a `ring_hom` version of `direct_sum.add_subgroup_coe`) * `direct_sum.submodule_coe_alg_hom` (an `alg_hom` version of `direct_sum.submodule_coe`) Strictly the definitions in this file are not sufficient to fully define an "internal" direct sum; to represent this case, `(h : direct_sum.submodule_is_internal A) [set_like.graded_monoid A]` is needed. In the future there will likely be a data-carrying, constructive, typeclass version of `direct_sum.submodule_is_internal` for providing an explicit decomposition function. When `complete_lattice.independent (set.range A)` (a weaker condition than `direct_sum.submodule_is_internal A`), these provide a grading of `⨆ i, A i`, and the mapping `⨁ i, A i →+ ⨆ i, A i` can be obtained as `direct_sum.to_monoid (λ i, add_submonoid.inclusion $ le_supr A i)`. ## tags internally graded ring -/ open_locale direct_sum big_operators variables {ι : Type*} {S R : Type*} lemma set_like.has_graded_one.algebra_map_mem [has_zero ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [set_like.has_graded_one A] (s : S) : algebra_map S R s ∈ A 0 := begin rw algebra.algebra_map_eq_smul_one, exact ((A 0).smul_mem s set_like.has_graded_one.one_mem), end section direct_sum variables [decidable_eq ι] /-! #### From `add_submonoid`s -/ namespace add_submonoid /-- Build a `gsemiring` instance for a collection of `add_submonoid`s. -/ instance gsemiring [add_monoid ι] [semiring R] (A : ι → add_submonoid R) [set_like.graded_monoid A] : direct_sum.gsemiring (λ i, A i) := { mul_zero := λ i j _, subtype.ext (mul_zero _), zero_mul := λ i j _, subtype.ext (zero_mul _), mul_add := λ i j _ _ _, subtype.ext (mul_add _ _ _), add_mul := λ i j _ _ _, subtype.ext (add_mul _ _ _), ..set_like.gmonoid A } /-- Build a `gcomm_semiring` instance for a collection of `add_submonoid`s. -/ instance gcomm_semiring [add_comm_monoid ι] [comm_semiring R] (A : ι → add_submonoid R) [set_like.graded_monoid A] : direct_sum.gcomm_semiring (λ i, A i) := { ..set_like.gcomm_monoid A, ..add_submonoid.gsemiring A, } end add_submonoid /-- The canonical ring isomorphism between `⨁ i, A i` and `R`-/ def direct_sum.submonoid_coe_ring_hom [add_monoid ι] [semiring R] (A : ι → add_submonoid R) [h : set_like.graded_monoid A] : (⨁ i, A i) →+* R := direct_sum.to_semiring (λ i, (A i).subtype) rfl (λ _ _ _ _, rfl) /-- The canonical ring isomorphism between `⨁ i, A i` and `R`-/ @[simp] lemma direct_sum.submonoid_coe_ring_hom_of [add_monoid ι] [semiring R] (A : ι → add_submonoid R) [h : set_like.graded_monoid A] (i : ι) (x : A i) : direct_sum.submonoid_coe_ring_hom A (direct_sum.of (λ i, A i) i x) = x := direct_sum.to_semiring_of _ _ _ _ _ lemma direct_sum.coe_mul_apply_add_submonoid [add_monoid ι] [semiring R] (A : ι → add_submonoid R) [set_like.graded_monoid A] [Π (i : ι) (x : A i), decidable (x ≠ 0)] (r r' : ⨁ i, A i) (i : ι) : ((r * r') i : R) = ∑ ij in finset.filter (λ ij : ι × ι, ij.1 + ij.2 = i) (r.support.product r'.support), r ij.1 * r' ij.2 := begin rw [direct_sum.mul_eq_sum_support_ghas_mul, dfinsupp.finset_sum_apply, add_submonoid_class.coe_finset_sum], simp_rw [direct_sum.coe_of_add_submonoid_apply, ←finset.sum_filter, set_like.coe_ghas_mul], end /-! #### From `add_subgroup`s -/ namespace add_subgroup /-- Build a `gsemiring` instance for a collection of `add_subgroup`s. -/ instance gsemiring [add_monoid ι] [ring R] (A : ι → add_subgroup R) [h : set_like.graded_monoid A] : direct_sum.gsemiring (λ i, A i) := have i' : set_like.graded_monoid (λ i, (A i).to_add_submonoid) := {..h}, by exactI add_submonoid.gsemiring (λ i, (A i).to_add_submonoid) /-- Build a `gcomm_semiring` instance for a collection of `add_subgroup`s. -/ instance gcomm_semiring [add_comm_group ι] [comm_ring R] (A : ι → add_subgroup R) [h : set_like.graded_monoid A] : direct_sum.gsemiring (λ i, A i) := have i' : set_like.graded_monoid (λ i, (A i).to_add_submonoid) := {..h}, by exactI add_submonoid.gsemiring (λ i, (A i).to_add_submonoid) end add_subgroup /-- The canonical ring isomorphism between `⨁ i, A i` and `R`. -/ def direct_sum.subgroup_coe_ring_hom [add_monoid ι] [ring R] (A : ι → add_subgroup R) [set_like.graded_monoid A] : (⨁ i, A i) →+* R := direct_sum.to_semiring (λ i, (A i).subtype) rfl (λ _ _ _ _, rfl) @[simp] lemma direct_sum.subgroup_coe_ring_hom_of [add_monoid ι] [ring R] (A : ι → add_subgroup R) [set_like.graded_monoid A] (i : ι) (x : A i) : direct_sum.subgroup_coe_ring_hom A (direct_sum.of (λ i, A i) i x) = x := direct_sum.to_semiring_of _ _ _ _ _ lemma direct_sum.coe_mul_apply_add_subgroup [add_monoid ι] [ring R] (A : ι → add_subgroup R) [set_like.graded_monoid A] [Π (i : ι) (x : A i), decidable (x ≠ 0)] (r r' : ⨁ i, A i) (i : ι) : ((r * r') i : R) = ∑ ij in finset.filter (λ ij : ι × ι, ij.1 + ij.2 = i) (r.support.product r'.support), r ij.1 * r' ij.2 := begin rw [direct_sum.mul_eq_sum_support_ghas_mul, dfinsupp.finset_sum_apply, add_submonoid_class.coe_finset_sum], simp_rw [direct_sum.coe_of_add_subgroup_apply, ←finset.sum_filter, set_like.coe_ghas_mul], end /-! #### From `submodules`s -/ namespace submodule /-- Build a `gsemiring` instance for a collection of `submodule`s. -/ instance gsemiring [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [h : set_like.graded_monoid A] : direct_sum.gsemiring (λ i, A i) := have i' : set_like.graded_monoid (λ i, (A i).to_add_submonoid) := {..h}, by exactI add_submonoid.gsemiring (λ i, (A i).to_add_submonoid) /-- Build a `gsemiring` instance for a collection of `submodule`s. -/ instance gcomm_semiring [add_comm_monoid ι] [comm_semiring S] [comm_semiring R] [algebra S R] (A : ι → submodule S R) [h : set_like.graded_monoid A] : direct_sum.gcomm_semiring (λ i, A i) := have i' : set_like.graded_monoid (λ i, (A i).to_add_submonoid) := {..h}, by exactI add_submonoid.gcomm_semiring (λ i, (A i).to_add_submonoid) /-- Build a `galgebra` instance for a collection of `submodule`s. -/ instance galgebra [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [h : set_like.graded_monoid A] : direct_sum.galgebra S (λ i, A i) := { to_fun := ((algebra.linear_map S R).cod_restrict (A 0) $ set_like.has_graded_one.algebra_map_mem A).to_add_monoid_hom, map_one := subtype.ext $ by exact (algebra_map S R).map_one, map_mul := λ x y, sigma.subtype_ext (add_zero 0).symm $ (algebra_map S R).map_mul _ _, commutes := λ r ⟨i, xi⟩, sigma.subtype_ext ((zero_add i).trans (add_zero i).symm) $ algebra.commutes _ _, smul_def := λ r ⟨i, xi⟩, sigma.subtype_ext (zero_add i).symm $ algebra.smul_def _ _ } @[simp] lemma set_like.coe_galgebra_to_fun [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [h : set_like.graded_monoid A] (s : S) : ↑(@direct_sum.galgebra.to_fun _ S (λ i, A i) _ _ _ _ _ _ _ s) = (algebra_map S R s : R) := rfl /-- A direct sum of powers of a submodule of an algebra has a multiplicative structure. -/ instance nat_power_graded_monoid [comm_semiring S] [semiring R] [algebra S R] (p : submodule S R) : set_like.graded_monoid (λ i : ℕ, p ^ i) := { one_mem := by { rw [←one_le, pow_zero], exact le_rfl }, mul_mem := λ i j p q hp hq, by { rw pow_add, exact submodule.mul_mem_mul hp hq } } end submodule /-- The canonical algebra isomorphism between `⨁ i, A i` and `R`. -/ def direct_sum.submodule_coe_alg_hom [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [h : set_like.graded_monoid A] : (⨁ i, A i) →ₐ[S] R := direct_sum.to_algebra S _ (λ i, (A i).subtype) rfl (λ _ _ _ _, rfl) (λ _, rfl) /-- The supremum of submodules that form a graded monoid is a subalgebra, and equal to the range of `direct_sum.submodule_coe_alg_hom`. -/ lemma submodule.supr_eq_to_submodule_range [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [set_like.graded_monoid A] : (⨆ i, A i) = (direct_sum.submodule_coe_alg_hom A).range.to_submodule := (submodule.supr_eq_range_dfinsupp_lsum A).trans $ set_like.coe_injective rfl @[simp] lemma direct_sum.submodule_coe_alg_hom_of [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [h : set_like.graded_monoid A] (i : ι) (x : A i) : direct_sum.submodule_coe_alg_hom A (direct_sum.of (λ i, A i) i x) = x := direct_sum.to_semiring_of _ rfl (λ _ _ _ _, rfl) _ _ lemma direct_sum.coe_mul_apply_submodule [add_monoid ι] [comm_semiring S] [semiring R] [algebra S R] (A : ι → submodule S R) [Π (i : ι) (x : A i), decidable (x ≠ 0)] [set_like.graded_monoid A] (r r' : ⨁ i, A i) (i : ι) : ((r * r') i : R) = ∑ ij in finset.filter (λ ij : ι × ι, ij.1 + ij.2 = i) (r.support.product r'.support), r ij.1 * r' ij.2 := begin rw [direct_sum.mul_eq_sum_support_ghas_mul, dfinsupp.finset_sum_apply, submodule.coe_sum], simp_rw [direct_sum.coe_of_submodule_apply, ←finset.sum_filter, set_like.coe_ghas_mul], end end direct_sum section homogeneous_element lemma set_like.is_homogeneous_zero_submodule [has_zero ι] [semiring S] [add_comm_monoid R] [module S R] (A : ι → submodule S R) : set_like.is_homogeneous A (0 : R) := ⟨0, submodule.zero_mem _⟩ lemma set_like.is_homogeneous.smul [comm_semiring S] [semiring R] [algebra S R] {A : ι → submodule S R} {s : S} {r : R} (hr : set_like.is_homogeneous A r) : set_like.is_homogeneous A (s • r) := let ⟨i, hi⟩ := hr in ⟨i, submodule.smul_mem _ _ hi⟩ end homogeneous_element
5ee73da4681d985650e1007824fe9e9bd5eac312
59b654f4ee2fef898a3487dc03554a569051b63a
/src/combinatory.lean
f731365564a2269499a43a51d1f6ad93843897b7
[]
no_license
gunpinyo/twisted_cube_formalisation
180c9157478b66ec2b11ca47c8ff998a3e978a88
f78206ac495e84bd43a9b820fa10b6c94722e0ec
refs/heads/master
1,624,501,222,992
1,607,081,624,000
1,607,081,624,000
166,885,106
0
0
null
null
null
null
UTF-8
Lean
false
false
161
lean
-- inductive xbool : Type -- | const : bool → xbool -- | unknown : xbool -- structure xbool (n : ℕ) () -- inductive cube_hom : ℕ → ℕ → Type -- |
94ca6e2d3debf191f48c12e1aed73f989c1fc46c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/PreDefinition/WF/Ite.lean
c628ee583bd1219a2db6b7cd029f89593c0e5291
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,020
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Transform namespace Lean.Meta /-- Convert `ite` expressions in `e` to `dite`s. It is useful to make this conversion in the `WF` module because the condition is often used in termination proofs. -/ def iteToDIte (e : Expr) : MetaM Expr := do -- TODO: move this file to `Meta` if we decide to use it in other places. let post (e : Expr) : MetaM TransformStep := do if e.isAppOfArity ``ite 5 then let f := e.getAppFn let args := e.getAppArgs let c := args[1]! let h ← mkFreshUserName `h let args := args.set! 3 (Lean.mkLambda h BinderInfo.default c args[3]!) let args := args.set! 4 (Lean.mkLambda h BinderInfo.default (mkNot c) args[4]!) return .done <| mkAppN (mkConst ``dite f.constLevels!) args else return .done e transform e (post := post) end Lean.Meta
c63f01dd561539c5f990d68b76ce2e8492d1dd23
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/compiler/binomial.lean
2dc8a77d86e07a592a5cac184019424fede7e854
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
648
lean
import Std.Data.BinomialHeap open Std abbrev Heap := BinomialHeap Nat (fun a b => a < b) def mkHeap (n m : Nat) : Heap := let hs : List Heap := n.fold (fun i hs => let h : Heap := BinomialHeap.empty let h : Heap := m.fold (fun j h => let v := n*m - j*n - i h.insert v) h h :: hs) [] hs.foldl (fun h₁ h₂ => h₁.merge h₂) BinomialHeap.empty partial def display : Nat → Heap → IO Unit | prev, h => do if h.isEmpty then pure () else let m := h.head unless prev < m do IO.println s!"failed {prev} {m}" display m h.tail def main : IO Unit := do let h := mkHeap 20 20 display 0 h IO.println h.toList.length
676019735026273d287cc050680599fe83654869
79cc757e5e5b09c7a522f717a6c490d321d36469
/src/mywork/oct_15.lean
27e5903bd52d0ed938ab62af514888ea16f9c023
[]
no_license
LukeMathe/cs2120f21
534c3b8868dcfdea98a9d22513180c8a062794c6
d51940b174569a8782e62ae027b108b5f099a9aa
refs/heads/main
1,693,418,664,935
1,634,585,653,000
1,634,585,653,000
403,762,076
0
0
null
1,630,963,485,000
1,630,963,485,000
null
UTF-8
Lean
false
false
4,709
lean
import data.set /- We formally define two predicates on natural numbers. -/ def ev (n : ℕ) : Prop := n % 2 = 0 def od (n : ℕ) : Prop := ¬ ev n /- We now formally represent some sets. Bear in mind that we represent a set as a predicate, applicable to a value of the member type, and "reducing to" a proposition, possibly "about" that value. In the following example, among other things, we see that set ℕ and ℕ → Prop are (nearly) interchangeable as types. A set is its defined by its membership predicate. The "nearly" is because you get to use set notations when you use set T rather than T → Prop to specify the type of a set value. -/ def empte : set ℕ := { n : ℕ | false } def complete : set ℕ := { n : ℕ | true } def evens : set ℕ := { n : ℕ | ev n } def ods : set ℕ := { n : ℕ | od n } def evens_union_ods : set ℕ := { n : ℕ | ev n ∨ od n } def evens_intersect_ods : set ℕ := { n : ℕ | ev n ∧ od n } def evens_complement : set ℕ := { n : ℕ | ¬ (ev n) } def ods_complement : set ℕ := { n : ℕ | ¬ (od n) } def evens_intersect_empty : set ℕ := { n : ℕ | ev n ∧ n ∈ empte} def evens_intersect_complete : set ℕ := {n : ℕ | ev n ∧ n ∈ complete} def evens_union_empty : set ℕ := {n : ℕ | ev n ∨ n ∈ empte} def evens_union_complete : set ℕ := {n : ℕ | ev n ∨ n ∈ complete} -- fill in additional interesting combinations /- SET THEORY NOTATIONS -/ /- empty set Sometimes people use ∅ to represent the empty set -/ #check ( ∅ : set ℕ ) /- set membership A membership predicate applied to a value yields a proposition: one that is true for values in the set. The ∈ notation is just a shorthand for application of a membership predicate to a value, but it gives a sense of "inclusion" of a value in a collection of values. -/ #check evens 0 #check 0 ∈ evens #check 1 ∈ evens /- set difference The difference between sets s1 and s2, written s1 \ s2, is the set of values that are in s1 but not in s2. You can think of this as the set s1 with the elements in s2 "taken away." Sometimes people use subtraction notation for set difference: s1 - s2. -/ #check evens \ ods #check evens \ evens #check evens \ empte #check evens \ complete /- complement The complement of a set s is the set of all values in the "universe of discourse" (in Lean, a type) that are not in s. Lean doesn't provide a notation, so we have to define it ourselves. Here we define compl as the complement of a set of natural numbers. -/ def compl_nat (s : set ℕ ) : set ℕ := {a | a ∉ s} #check compl_nat evens /- union The union of two sets, s1 and s2, written as s1 ∪ s2, is the set of elements that are in s1 or s2. -/ #check ods ∪ complete #check ods ∪ empte #check ods ∪ evens /- intersection The intersection of two sets, s1 and s2, written as s1 ∩ s2, is the set of elements that are in s1 and in s2. -/ #check ods ∩ empte #check evens ∩ complete #check ods ∩ evens /- product The product of two sets, (s1 : set T) and (s2 : set V) is the set of all pairs (t, v), where t ∈ s1 and v ∈ t2. People sometimes use × to represent the set product operation. In Lean we have to define it ourselves. -/ def prodset {T V : Type} (s1 : set T) (s2 : set V) := { pr : T × V | pr.1 ∈ s1 ∧ pr.2 ∈ s2 } #check prodset evens empte #check prodset evens ods /- subset Given two sets, s1 and s2, of objects of some type T, we say that s1 is a subset of s2, written s1 ⊆ s2, if every element in s1 is in s2. We say that s1 is a proper subset of s2, written s1 ⊂ s2, if every value in s1 is in s2 and some value in s2 is not in s1. -/ #check evens ⊆ evens #check evens ⊂ evens #check evens ⊆ complete #check evens ⊂ complete #check evens ⊂ empte #check ∀ (s : set ℕ), empte ⊆ s /- powerset The powerset of a set, s, written 𝒫 s, is the set of all subsets of s. This makes the powerset a set of sets. -/ #check 𝒫 { 1, 2, 3} #check 𝒫 evens /- Now let's state and prove some theorems. -/ example : ∀ (n : ℕ), evens_union_ods n ↔ complete n := _ example : ∀ (n : ℕ), (n ∈ evens_union_ods) ↔ (n ∈ complete) := _ /- Now we are in a position to see formal definitions of all of the preceding set theory concepts. -/ axioms (P Q : ℕ → Prop) def pSet : set nat := { n : ℕ | P n} def qSet : set nat := { n : ℕ | Q n} #reduce 0 ∈ pSet #reduce pSet ∪ qSet #reduce pSet ∩ qSet #reduce pSet \ qSet #reduce pSet ⊆ qSet #reduce 𝒫 pSet -- harder to decipher /- Now that we understand these operations and their corresponding notations in set theory, we can start to state and prove theorems! -/
ef506a43728c54cdd4cedb63dbf0c70aae027939
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/topology/constructions.lean
3e704178f1688293b0c092a4ae7dddac642d0975
[ "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
29,789
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, Patrick Massot -/ import topology.maps /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable theory open topological_space set filter lattice open_locale classical topological_space universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} section constructions instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced subtype.val t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊓ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨆a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨅a, induced (λf, f a) (t₂ a) lemma quotient_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) : closure (quotient.mk '' s) = univ := eq_univ_of_forall $ λ x, begin rw mem_closure_iff, intros U U_op x_in_U, let V := quotient.mk ⁻¹' U, cases quotient.exists_rep x with y y_x, have y_in_V : y ∈ V, by simp only [mem_preimage, y_x, x_in_U], have V_op : is_open V := U_op, have : V ∩ s ≠ ∅ := mem_closure_iff.1 (H y) V V_op y_in_V, rcases exists_mem_of_ne_empty this with ⟨w, w_in_V, w_in_range⟩, exact ne_empty_of_mem ⟨w_in_V, mem_image_of_mem quotient.mk w_in_range⟩ end instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨bot_unique $ assume s hs, ⟨subtype.val '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.val_injective)⟩⟩ instance sum.discrete_topology [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := ⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩ instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)] [h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) := ⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩ section topα variable [topological_space α] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 a.val, (@subtype.val α s) ⁻¹' u ⊆ t := mem_nhds_induced subtype.val a t theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) : 𝓝 a = comap subtype.val (𝓝 a.val) := nhds_induced subtype.val a end topα end constructions section prod open topological_space variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, prod.mk (f x) (g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous.prod_mk continuous_snd continuous_fst lemma is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (continuous_fst s hs) (continuous_snd t ht) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = filter.prod (𝓝 a) (𝓝 b) := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) := by rw [nhds_prod_eq]; exact prod_mem_prod ha hb lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma tendsto_prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) : tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := tendsto_prod_mk_nhds hf hg lemma prod_generate_from_generate_from_eq {α : Type*} {β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open_prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ is_open_prod hs ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp [nhds_prod_eq, mem_prod_iff], simp [mem_nhds_sets_iff], exact forall_congr (assume a, ball_congr $ assume b h, ⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩, ⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩, assume ⟨u, uo, v, vo, au, bv, h⟩, ⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩) end /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := begin assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₁, refine ⟨o₁, _, o₁_open, yo₁⟩, assume z zs, rw mem_image_eq, exact ⟨(z, y₂), ho (by simp [zs, yo₂]), rfl⟩ end /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := begin /- This lemma could be proved by composing the fact that the first projection is open, and exchanging coordinates is a homeomorphism, hence open. As the `prod_comm` homeomorphism is defined later, we rather go for the direct proof, copy-pasting the proof for the first projection. -/ assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₂, refine ⟨o₂, _, o₂_open, yo₂⟩, assume z zs, rw mem_image_eq, exact ⟨(y₁, z), ho (by simp [zs, yo₁]), rfl⟩ end /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' {s : set α} {t : set β} : is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin by_cases h : set.prod s t = ∅, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s ≠ ∅ ∧ t ≠ ∅, by rwa [← ne.def, prod_ne_empty_iff] at h, split, { assume H : is_open (set.prod s t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp [st] at H, exact is_open_prod H.1 H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have filter.prod (𝓝 a) (𝓝 b) ⊓ principal (set.prod s t) = filter.prod (𝓝 a ⊓ principal s) (𝓝 b ⊓ principal t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_nhds, nhds_prod_eq, this]; exact prod_ne_bot lemma mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed_prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp [h₁, h₂, closure_prod_eq, closure_eq_of_is_closed] lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing (λx:α×γ, (f x.1, g x.2)) := ⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩, ..hf.to_inducing.prod_mk hg.to_inducing } protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id end prod section sum variables [topological_space α] [topological_space β] [topological_space γ] lemma continuous_inl : continuous (@sum.inl α β) := continuous_sup_rng_left continuous_coinduced_rng lemma continuous_inr : continuous (@sum.inr α β) := continuous_sup_rng_right continuous_coinduced_rng lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := continuous_sup_dom hf hg lemma embedding_inl : embedding (@sum.inl α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact lattice.le_sup_left }, { intros u hu, existsi (sum.inl '' u), change (is_open (sum.inl ⁻¹' (@sum.inl α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inl α β '' u))) ∧ sum.inl ⁻¹' (sum.inl '' u) = u, have : sum.inl ⁻¹' (@sum.inl α β '' u) = u := preimage_image_eq u (λ _ _, sum.inl.inj_iff.mp), rw this, have : sum.inr ⁻¹' (@sum.inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, sum.inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end, inj := λ _ _, sum.inl.inj_iff.mp } lemma embedding_inr : embedding (@sum.inr α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact lattice.le_sup_right }, { intros u hu, existsi (sum.inr '' u), change (is_open (sum.inl ⁻¹' (@sum.inr α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inr α β '' u))) ∧ sum.inr ⁻¹' (sum.inr '' u) = u, have : sum.inl ⁻¹' (@sum.inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, sum.inr_ne_inl h), rw this, have : sum.inr ⁻¹' (@sum.inr α β '' u) = u := preimage_image_eq u (λ _ _, sum.inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end, inj := λ _ _, sum.inr.inj_iff.mp } end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_subtype_val : embedding (@subtype.val α p) := ⟨⟨rfl⟩, subtype.val_injective⟩ lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma is_open.open_embedding_subtype_val {s : set α} (hs : is_open s) : open_embedding (subtype.val : s → α) := { induced := rfl, inj := subtype.val_injective, open_range := (subtype.val_range : range subtype.val = s).symm ▸ hs } lemma is_open.is_open_map_subtype_val {s : set α} (hs : is_open s) : is_open_map (subtype.val : s → α) := hs.open_embedding_subtype_val.is_open_map lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (function.restrict f s) := hf.comp hs.is_open_map_subtype_val lemma is_closed.closed_embedding_subtype_val {s : set α} (hs : is_closed s) : closed_embedding (subtype.val : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.val_injective, closed_range := (subtype.val_range : range subtype.val = s).symm ▸ hs } lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_val lemma continuous_at_subtype_val {p : α → Prop} {a : subtype p} : continuous_at subtype.val a := continuous_iff_continuous_at.mp continuous_subtype_val _ lemma map_nhds_subtype_val_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) : map (@subtype.val α p) (𝓝 ⟨a, ha⟩) = 𝓝 a := map_nhds_induced_eq (by simp [subtype.val_image, h]) lemma nhds_subtype_eq_comap {a : α} {h : p a} : 𝓝 (⟨a, h⟩ : subtype p) = comap subtype.val (𝓝 a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, subtype.val (f x)) b (𝓝 a.val) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in calc map f (𝓝 x) = map f (map subtype.val (𝓝 x')) : congr_arg (map f) (map_nhds_subtype_val_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x.val) (𝓝 x') : rfl ... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed (@subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from assume i, embedding_is_closed embedding_subtype_val (by simp [subtype.val_range]; exact h_is_closed i) (continuous_iff_is_closed.mp (f_cont i) _ hs), have is_closed (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from is_closed_Union_of_locally_finite (locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simp [and.comm, and.left_comm], simpa [(∘)], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ x.val ∈ closure (subtype.val '' s) := closure_induced $ assume x y, subtype.eq end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h end quotient section pi variables {ι : Type*} {π : ι → Type*} open topological_space lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : 𝓝 a = (⨅i, comap (λx, x i) (𝓝 (a i))) := calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced] lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha) lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * }, simpa [pi_if, hf] } } end end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] open lattice lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := is_open_sigma_iff lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ injective_sigma_mk }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ } lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ injective_sigma_mk }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk injective_sigma_mk is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk injective_sigma_mk is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 /-- A map out of a sum type is continuous if its restriction to each summand is. -/ lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) lemma is_open_map_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f := begin intros s hs, rw is_open_sigma_iff at hs, have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s), { rw Union_image_preimage_sigma_mk_eq_self }, rw this, rw [image_Union], apply is_open_Union, intro i, rw [image_image], exact h i _ (hs i) end /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨⟨_⟩, injective_sigma_map function.injective_id (λ i, (hf i).inj)⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).induced.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext p, rcases p with ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : ∀a∈s, f a ∈ closure t) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure (closure t) : closure_mono $ image_subset_iff.mpr $ h ... ⊆ closure t : begin rw [closure_eq_of_is_closed], exact subset.refl _, exact is_closed_closure end lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
b690b8745ad45caff9471dced86ccbaffb749320
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/algebra/big_operators/pi.lean
ffb4874072e04f94a995686cda3cbc3e1e26f2b7
[ "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
3,902
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import algebra.ring.pi import algebra.big_operators.basic import data.fintype.basic import algebra.group.prod /-! # Big operators for Pi Types This file contains theorems relevant to big operators in binary and arbitrary product of monoids and groups -/ open_locale big_operators namespace pi @[to_additive] lemma list_prod_apply {α : Type*} {β : α → Type*} [Πa, monoid (β a)] (a : α) (l : list (Πa, β a)) : l.prod a = (l.map (λf:Πa, β a, f a)).prod := (monoid_hom.apply β a).map_list_prod _ @[to_additive] lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α) (s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod := (monoid_hom.apply β a).map_multiset_prod _ end pi @[simp, to_additive] lemma finset.prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α) (s : finset γ) (g : γ → Πa, β a) : (∏ c in s, g c) a = ∏ c in s, g c a := (monoid_hom.apply β a).map_prod _ _ /-- An 'unapplied' analogue of `finset.prod_apply`. -/ @[to_additive "An 'unapplied' analogue of `finset.sum_apply`."] lemma finset.prod_fn {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (s : finset γ) (g : γ → Πa, β a) : (∏ c in s, g c) = (λ a, ∏ c in s, g c a) := funext (λ a, finset.prod_apply _ _ _) @[simp, to_additive] lemma fintype.prod_apply {α : Type*} {β : α → Type*} {γ : Type*} [fintype γ] [∀a, comm_monoid (β a)] (a : α) (g : γ → Πa, β a) : (∏ c, g c) a = ∏ c, g c a := finset.prod_apply a finset.univ g @[to_additive prod_mk_sum] lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ) (f : γ → α) (g : γ → β) : (∏ x in s, f x, ∏ x in s, g x) = ∏ x in s, (f x, g x) := by haveI := classical.dec_eq γ; exact finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt}) section single variables {I : Type*} [decidable_eq I] {Z : I → Type*} variables [Π i, add_comm_monoid (Z i)] -- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here. lemma finset.univ_sum_single [fintype I] (f : Π i, Z i) : ∑ i, pi.single i (f i) = f := by { ext a, simp } lemma add_monoid_hom.functions_ext [fintype I] (G : Type*) [add_comm_monoid G] (g h : (Π i, Z i) →+ G) (w : ∀ (i : I) (x : Z i), g (pi.single i x) = h (pi.single i x)) : g = h := begin ext k, rw [← finset.univ_sum_single k, g.map_sum, h.map_sum], simp only [w] end /-- This is used as the ext lemma instead of `add_monoid_hom.functions_ext` for reasons explained in note [partially-applied ext lemmas]. -/ @[ext] lemma add_monoid_hom.functions_ext' [fintype I] (M : Type*) [add_comm_monoid M] (g h : (Π i, Z i) →+ M) (H : ∀ i, g.comp (add_monoid_hom.single Z i) = h.comp (add_monoid_hom.single Z i)) : g = h := have _ := λ i, add_monoid_hom.congr_fun (H i), -- elab without an expected type g.functions_ext M h this end single section ring_hom open pi variables {I : Type*} [decidable_eq I] {f : I → Type*} variables [Π i, semiring (f i)] @[ext] lemma ring_hom.functions_ext [fintype I] (G : Type*) [semiring G] (g h : (Π i, f i) →+* G) (w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h := ring_hom.coe_add_monoid_hom_injective $ add_monoid_hom.functions_ext G (g : (Π i, f i) →+ G) h w end ring_hom namespace prod variables {α β γ : Type*} [comm_monoid α] [comm_monoid β] {s : finset γ} {f : γ → α × β} @[to_additive] lemma fst_prod : (∏ c in s, f c).1 = ∏ c in s, (f c).1 := (monoid_hom.fst α β).map_prod f s @[to_additive] lemma snd_prod : (∏ c in s, f c).2 = ∏ c in s, (f c).2 := (monoid_hom.snd α β).map_prod f s end prod
32cd535380d572e8e069dd6030fd632c37456629
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/tietze_extension.lean
def8be075ac0c4da29182385e387db9c19841b58
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
22,829
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import data.set.intervals.iso_Ioo import topology.algebra.order.monotone_continuity import topology.urysohns_bounded /-! # Tietze extension theorem In this file we prove a few version of the Tietze extension theorem. The theorem says that a continuous function `s → ℝ` defined on a closed set in a normal topological space `Y` can be extended to a continuous function on the whole space. Moreover, if all values of the original function belong to some (finite or infinite, open or closed) interval, then the extension can be chosen so that it takes values in the same interval. In particular, if the original function is a bounded function, then there exists a bounded extension of the same norm. The proof mostly follows <https://ncatlab.org/nlab/show/Tietze+extension+theorem>. We patch a small gap in the proof for unbounded functions, see `exists_extension_forall_exists_le_ge_of_closed_embedding`. ## Implementation notes We first prove the theorems for a closed embedding `e : X → Y` of a topological space into a normal topological space, then specialize them to the case `X = s : set Y`, `e = coe`. ## Tags Tietze extension theorem, Urysohn's lemma, normal topological space -/ variables {X Y : Type*} [topological_space X] [topological_space Y] [normal_space Y] open metric set filter open_locale bounded_continuous_function topological_space noncomputable theory namespace bounded_continuous_function /-- One step in the proof of the Tietze extension theorem. If `e : C(X, Y)` is a closed embedding of a topological space into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists a bounded continuous function `g : Y →ᵇ ℝ` of the norm `‖g‖ ≤ ‖f‖ / 3` such that the distance between `g ∘ e` and `f` is at most `(2 / 3) * ‖f‖`. -/ lemma tietze_extension_step (f : X →ᵇ ℝ) (e : C(X, Y)) (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, ‖g‖ ≤ ‖f‖ / 3 ∧ dist (g.comp_continuous e) f ≤ (2 / 3) * ‖f‖ := begin have h3 : (0 : ℝ) < 3 := by norm_num1, have h23 : 0 < (2 / 3 : ℝ) := by norm_num1, -- In the trivial case `f = 0`, we take `g = 0` rcases eq_or_ne f 0 with (rfl|hf), { use 0, simp }, replace hf : 0 < ‖f‖ := norm_pos_iff.2 hf, /- Otherwise, the closed sets `e '' (f ⁻¹' (Iic (-‖f‖ / 3)))` and `e '' (f ⁻¹' (Ici (‖f‖ / 3)))` are disjoint, hence by Urysohn's lemma there exists a function `g` that is equal to `-‖f‖ / 3` on the former set and is equal to `‖f‖ / 3` on the latter set. This function `g` satisfies the assertions of the lemma. -/ have hf3 : -‖f‖ / 3 < ‖f‖ / 3, from (div_lt_div_right h3).2 (left.neg_lt_self hf), have hc₁ : is_closed (e '' (f ⁻¹' (Iic (-‖f‖ / 3)))), from he.is_closed_map _ (is_closed_Iic.preimage f.continuous), have hc₂ : is_closed (e '' (f ⁻¹' (Ici (‖f‖ / 3)))), from he.is_closed_map _ (is_closed_Ici.preimage f.continuous), have hd : disjoint (e '' (f ⁻¹' (Iic (-‖f‖ / 3)))) (e '' (f ⁻¹' (Ici (‖f‖ / 3)))), { refine disjoint_image_of_injective he.inj (disjoint.preimage _ _), rwa [Iic_disjoint_Ici, not_le] }, rcases exists_bounded_mem_Icc_of_closed_of_le hc₁ hc₂ hd hf3.le with ⟨g, hg₁, hg₂, hgf⟩, refine ⟨g, _, _⟩, { refine (norm_le $ div_nonneg hf.le h3.le).mpr (λ y, _), simpa [abs_le, neg_div] using hgf y }, { refine (dist_le $ mul_nonneg h23.le hf.le).mpr (λ x, _), have hfx : -‖f‖ ≤ f x ∧ f x ≤ ‖f‖, by simpa only [real.norm_eq_abs, abs_le] using f.norm_coe_le_norm x, cases le_total (f x) (-‖f‖ / 3) with hle₁ hle₁, { calc |g (e x) - f x| = -‖f‖ / 3 - f x: by rw [hg₁ (mem_image_of_mem _ hle₁), abs_of_nonneg (sub_nonneg.2 hle₁)] ... ≤ (2 / 3) * ‖f‖ : by linarith }, { cases le_total (f x) (‖f‖ / 3) with hle₂ hle₂, { simp only [neg_div] at *, calc dist (g (e x)) (f x) ≤ |g (e x)| + |f x| : dist_le_norm_add_norm _ _ ... ≤ ‖f‖ / 3 + ‖f‖ / 3 : add_le_add (abs_le.2 $ hgf _) (abs_le.2 ⟨hle₁, hle₂⟩) ... = (2 / 3) * ‖f‖ : by linarith }, { calc |g (e x) - f x| = f x - ‖f‖ / 3 : by rw [hg₂ (mem_image_of_mem _ hle₂), abs_sub_comm, abs_of_nonneg (sub_nonneg.2 hle₂)] ... ≤ (2 / 3) * ‖f‖ : by linarith } } } end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version with a closed embedding and bundled composition. If `e : C(X, Y)` is a closed embedding of a topological space into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists a bounded continuous function `g : Y →ᵇ ℝ` of the same norm such that `g ∘ e = f`. -/ lemma exists_extension_norm_eq_of_closed_embedding' (f : X →ᵇ ℝ) (e : C(X, Y)) (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, ‖g‖ = ‖f‖ ∧ g.comp_continuous e = f := begin /- For the proof, we iterate `tietze_extension_step`. Each time we apply it to the difference between the previous approximation and `f`. -/ choose F hF_norm hF_dist using λ f : X →ᵇ ℝ, tietze_extension_step f e he, set g : ℕ → Y →ᵇ ℝ := λ n, (λ g, g + F (f - g.comp_continuous e))^[n] 0, have g0 : g 0 = 0 := rfl, have g_succ : ∀ n, g (n + 1) = g n + F (f - (g n).comp_continuous e), from λ n, function.iterate_succ_apply' _ _ _, have hgf : ∀ n, dist ((g n).comp_continuous e) f ≤ (2 / 3) ^ n * ‖f‖, { intro n, induction n with n ihn, { simp [g0] }, { rw [g_succ n, add_comp_continuous, ← dist_sub_right, add_sub_cancel', pow_succ, mul_assoc], refine (hF_dist _).trans (mul_le_mul_of_nonneg_left _ (by norm_num1)), rwa ← dist_eq_norm' } }, have hg_dist : ∀ n, dist (g n) (g (n + 1)) ≤ 1 / 3 * ‖f‖ * (2 / 3) ^ n, { intro n, calc dist (g n) (g (n + 1)) = ‖F (f - (g n).comp_continuous e)‖ : by rw [g_succ, dist_eq_norm', add_sub_cancel'] ... ≤ ‖f - (g n).comp_continuous e‖ / 3 : hF_norm _ ... = (1 / 3) * dist ((g n).comp_continuous e) f : by rw [dist_eq_norm', one_div, div_eq_inv_mul] ... ≤ (1 / 3) * ((2 / 3) ^ n * ‖f‖) : mul_le_mul_of_nonneg_left (hgf n) (by norm_num1) ... = 1 / 3 * ‖f‖ * (2 / 3) ^ n : by ac_refl }, have hg_cau : cauchy_seq g, from cauchy_seq_of_le_geometric _ _ (by norm_num1) hg_dist, have : tendsto (λ n, (g n).comp_continuous e) at_top (𝓝 $ (lim at_top g).comp_continuous e), from ((continuous_comp_continuous e).tendsto _).comp hg_cau.tendsto_lim, have hge : (lim at_top g).comp_continuous e = f, { refine tendsto_nhds_unique this (tendsto_iff_dist_tendsto_zero.2 _), refine squeeze_zero (λ _, dist_nonneg) hgf _, rw ← zero_mul (‖f‖), refine (tendsto_pow_at_top_nhds_0_of_lt_1 _ _).mul tendsto_const_nhds; norm_num1 }, refine ⟨lim at_top g, le_antisymm _ _, hge⟩, { rw [← dist_zero_left, ← g0], refine (dist_le_of_le_geometric_of_tendsto₀ _ _ (by norm_num1) hg_dist hg_cau.tendsto_lim).trans_eq _, field_simp [show (3 - 2 : ℝ) = 1, by norm_num1] }, { rw ← hge, exact norm_comp_continuous_le _ _ } end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version with a closed embedding and unbundled composition. If `e : C(X, Y)` is a closed embedding of a topological space into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists a bounded continuous function `g : Y →ᵇ ℝ` of the same norm such that `g ∘ e = f`. -/ lemma exists_extension_norm_eq_of_closed_embedding (f : X →ᵇ ℝ) {e : X → Y} (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, ‖g‖ = ‖f‖ ∧ g ∘ e = f := begin rcases exists_extension_norm_eq_of_closed_embedding' f ⟨e, he.continuous⟩ he with ⟨g, hg, rfl⟩, exact ⟨g, hg, rfl⟩ end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed set. If `f` is a bounded continuous real-valued function defined on a closed set in a normal topological space, then it can be extended to a bounded continuous function of the same norm defined on the whole space. -/ lemma exists_norm_eq_restrict_eq_of_closed {s : set Y} (f : s →ᵇ ℝ) (hs : is_closed s) : ∃ g : Y →ᵇ ℝ, ‖g‖ = ‖f‖ ∧ g.restrict s = f := exists_extension_norm_eq_of_closed_embedding' f ((continuous_map.id _).restrict s) (closed_embedding_subtype_coe hs) /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed embedding and a bounded continuous function that takes values in a non-trivial closed interval. See also `exists_extension_forall_mem_of_closed_embedding` for a more general statement that works for any interval (finite or infinite, open or closed). If `e : X → Y` is a closed embedding and `f : X →ᵇ ℝ` is a bounded continuous function such that `f x ∈ [a, b]` for all `x`, where `a ≤ b`, then there exists a bounded continuous function `g : Y →ᵇ ℝ` such that `g y ∈ [a, b]` for all `y` and `g ∘ e = f`. -/ lemma exists_extension_forall_mem_Icc_of_closed_embedding (f : X →ᵇ ℝ) {a b : ℝ} {e : X → Y} (hf : ∀ x, f x ∈ Icc a b) (hle : a ≤ b) (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ Icc a b) ∧ g ∘ e = f := begin rcases exists_extension_norm_eq_of_closed_embedding (f - const X ((a + b) / 2)) he with ⟨g, hgf, hge⟩, refine ⟨const Y ((a + b) / 2) + g, λ y, _, _⟩, { suffices : ‖f - const X ((a + b) / 2)‖ ≤ (b - a) / 2, by simpa [real.Icc_eq_closed_ball, add_mem_closed_ball_iff_norm] using (norm_coe_le_norm g y).trans (hgf.trans_le this), refine (norm_le $ div_nonneg (sub_nonneg.2 hle) zero_le_two).2 (λ x, _), simpa only [real.Icc_eq_closed_ball] using hf x }, { ext x, have : g (e x) = f x - (a + b) / 2 := congr_fun hge x, simp [this] } end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal topological space `Y`. Let `f` be a bounded continuous real-valued function on `X`. Then there exists a bounded continuous function `g : Y →ᵇ ℝ` such that `g ∘ e = f` and each value `g y` belongs to a closed interval `[f x₁, f x₂]` for some `x₁` and `x₂`. -/ lemma exists_extension_forall_exists_le_ge_of_closed_embedding [nonempty X] (f : X →ᵇ ℝ) {e : X → Y} (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, (∀ y, ∃ x₁ x₂, g y ∈ Icc (f x₁) (f x₂)) ∧ g ∘ e = f := begin inhabit X, -- Put `a = ⨅ x, f x` and `b = ⨆ x, f x` obtain ⟨a, ha⟩ : ∃ a, is_glb (range f) a, from ⟨_, is_glb_cinfi (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).1⟩, obtain ⟨b, hb⟩ : ∃ b, is_lub (range f) b, from ⟨_, is_lub_csupr (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).2⟩, -- Then `f x ∈ [a, b]` for all `x` have hmem : ∀ x, f x ∈ Icc a b, from λ x, ⟨ha.1 ⟨x, rfl⟩, hb.1 ⟨x, rfl⟩⟩, -- Rule out the trivial case `a = b` have hle : a ≤ b := (hmem default).1.trans (hmem default).2, rcases hle.eq_or_lt with (rfl|hlt), { have : ∀ x, f x = a, by simpa using hmem, use const Y a, simp [this, function.funext_iff] }, -- Put `c = (a + b) / 2`. Then `a < c < b` and `c - a = b - c`. set c := (a + b) / 2, have hac : a < c := left_lt_add_div_two.2 hlt, have hcb : c < b := add_div_two_lt_right.2 hlt, have hsub : c - a = b - c, by { simp only [c], field_simp, ring }, /- Due to `exists_extension_forall_mem_Icc_of_closed_embedding`, there exists an extension `g` such that `g y ∈ [a, b]` for all `y`. However, if `a` and/or `b` do not belong to the range of `f`, then we need to ensure that these points do not belong to the range of `g`. This is done in two almost identical steps. First we deal with the case `∀ x, f x ≠ a`. -/ obtain ⟨g, hg_mem, hgf⟩ : ∃ g : Y →ᵇ ℝ, (∀ y, ∃ x, g y ∈ Icc (f x) b) ∧ g ∘ e = f, { rcases exists_extension_forall_mem_Icc_of_closed_embedding f hmem hle he with ⟨g, hg_mem, hgf⟩, -- If `a ∈ range f`, then we are done. rcases em (∃ x, f x = a) with ⟨x, rfl⟩|ha', { exact ⟨g, λ y, ⟨x, hg_mem _⟩, hgf⟩ }, /- Otherwise, `g ⁻¹' {a}` is disjoint with `range e ∪ g ⁻¹' (Ici c)`, hence there exists a function `dg : Y → ℝ` such that `dg ∘ e = 0`, `dg y = 0` whenever `c ≤ g y`, `dg y = c - a` whenever `g y = a`, and `0 ≤ dg y ≤ c - a` for all `y`. -/ have hd : disjoint (range e ∪ g ⁻¹' (Ici c)) (g ⁻¹' {a}), { refine disjoint_union_left.2 ⟨_, disjoint.preimage _ _⟩, { rw set.disjoint_left, rintro _ ⟨x, rfl⟩ (rfl : g (e x) = a), exact ha' ⟨x, (congr_fun hgf x).symm⟩ }, { exact set.disjoint_singleton_right.2 hac.not_le } }, rcases exists_bounded_mem_Icc_of_closed_of_le (he.closed_range.union $ is_closed_Ici.preimage g.continuous) (is_closed_singleton.preimage g.continuous) hd (sub_nonneg.2 hac.le) with ⟨dg, dg0, dga, dgmem⟩, replace hgf : ∀ x, (g + dg) (e x) = f x, { intro x, simp [dg0 (or.inl $ mem_range_self _), ← hgf] }, refine ⟨g + dg, λ y, _, funext hgf⟩, { have hay : a < (g + dg) y, { rcases (hg_mem y).1.eq_or_lt with rfl|hlt, { refine (lt_add_iff_pos_right _).2 _, calc 0 < c - g y : sub_pos.2 hac ... = dg y : (dga rfl).symm }, { exact hlt.trans_le ((le_add_iff_nonneg_right _).2 $ (dgmem y).1) } }, rcases ha.exists_between hay with ⟨_, ⟨x, rfl⟩, hax, hxy⟩, refine ⟨x, hxy.le, _⟩, cases le_total c (g y) with hc hc, { simp [dg0 (or.inr hc), (hg_mem y).2] }, { calc g y + dg y ≤ c + (c - a) : add_le_add hc (dgmem _).2 ... = b : by rw [hsub, add_sub_cancel'_right] } } }, /- Now we deal with the case `∀ x, f x ≠ b`. The proof is the same as in the first case, with minor modifications that make it hard to deduplicate code. -/ choose xl hxl hgb using hg_mem, rcases em (∃ x, f x = b) with ⟨x, rfl⟩|hb', { exact ⟨g, λ y, ⟨xl y, x, hxl y, hgb y⟩, hgf⟩ }, have hd : disjoint (range e ∪ g ⁻¹' (Iic c)) (g ⁻¹' {b}), { refine disjoint_union_left.2 ⟨_, disjoint.preimage _ _⟩, { rw set.disjoint_left, rintro _ ⟨x, rfl⟩ (rfl : g (e x) = b), exact hb' ⟨x, (congr_fun hgf x).symm⟩ }, { exact set.disjoint_singleton_right.2 hcb.not_le } }, rcases exists_bounded_mem_Icc_of_closed_of_le (he.closed_range.union $ is_closed_Iic.preimage g.continuous) (is_closed_singleton.preimage g.continuous) hd (sub_nonneg.2 hcb.le) with ⟨dg, dg0, dgb, dgmem⟩, replace hgf : ∀ x, (g - dg) (e x) = f x, { intro x, simp [dg0 (or.inl $ mem_range_self _), ← hgf] }, refine ⟨g - dg, λ y, _, funext hgf⟩, { have hyb : (g - dg) y < b, { rcases (hgb y).eq_or_lt with rfl|hlt, { refine (sub_lt_self_iff _).2 _, calc 0 < g y - c : sub_pos.2 hcb ... = dg y : (dgb rfl).symm }, { exact ((sub_le_self_iff _).2 (dgmem _).1).trans_lt hlt } }, rcases hb.exists_between hyb with ⟨_, ⟨xu, rfl⟩, hyxu, hxub⟩, cases lt_or_le c (g y) with hc hc, { rcases em (a ∈ range f) with ⟨x, rfl⟩|ha', { refine ⟨x, xu, _, hyxu.le⟩, calc f x = c - (b - c) : by rw [← hsub, sub_sub_cancel] ... ≤ g y - dg y : sub_le_sub hc.le (dgmem _).2 }, { have hay : a < (g - dg) y, { calc a = c - (b - c) : by rw [← hsub, sub_sub_cancel] ... < g y - (b - c) : sub_lt_sub_right hc _ ... ≤ g y - dg y : sub_le_sub_left (dgmem _).2 _ }, rcases ha.exists_between hay with ⟨_, ⟨x, rfl⟩, ha, hxy⟩, exact ⟨x, xu, hxy.le, hyxu.le⟩ } }, { refine ⟨xl y, xu, _, hyxu.le⟩, simp [dg0 (or.inr hc), hxl] } }, end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal topological space `Y`. Let `f` be a bounded continuous real-valued function on `X`. Let `t` be a nonempty convex set of real numbers (we use `ord_connected` instead of `convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x`. Then there exists a bounded continuous real-valued function `g : Y →ᵇ ℝ` such that `g y ∈ t` for all `y` and `g ∘ e = f`. -/ lemma exists_extension_forall_mem_of_closed_embedding (f : X →ᵇ ℝ) {t : set ℝ} {e : X → Y} [hs : ord_connected t] (hf : ∀ x, f x ∈ t) (hne : t.nonempty) (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ t) ∧ g ∘ e = f := begin casesI is_empty_or_nonempty X, { rcases hne with ⟨c, hc⟩, refine ⟨const Y c, λ y, hc, funext $ λ x, is_empty_elim x⟩ }, rcases exists_extension_forall_exists_le_ge_of_closed_embedding f he with ⟨g, hg, hgf⟩, refine ⟨g, λ y, _, hgf⟩, rcases hg y with ⟨xl, xu, h⟩, exact hs.out (hf _) (hf _) h end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed set. Let `s` be a closed set in a normal topological space `Y`. Let `f` be a bounded continuous real-valued function on `s`. Let `t` be a nonempty convex set of real numbers (we use `ord_connected` instead of `convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x : s`. Then there exists a bounded continuous real-valued function `g : Y →ᵇ ℝ` such that `g y ∈ t` for all `y` and `g.restrict s = f`. -/ lemma exists_forall_mem_restrict_eq_of_closed {s : set Y} (f : s →ᵇ ℝ) (hs : is_closed s) {t : set ℝ} [ord_connected t] (hf : ∀ x, f x ∈ t) (hne : t.nonempty) : ∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ t) ∧ g.restrict s = f := begin rcases exists_extension_forall_mem_of_closed_embedding f hf hne (closed_embedding_subtype_coe hs) with ⟨g, hg, hgf⟩, exact ⟨g, hg, fun_like.coe_injective hgf⟩ end end bounded_continuous_function namespace continuous_map /-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal topological space `Y`. Let `f` be a continuous real-valued function on `X`. Let `t` be a nonempty convex set of real numbers (we use `ord_connected` instead of `convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x`. Then there exists a continuous real-valued function `g : C(Y, ℝ)` such that `g y ∈ t` for all `y` and `g ∘ e = f`. -/ lemma exists_extension_forall_mem_of_closed_embedding (f : C(X, ℝ)) {t : set ℝ} {e : X → Y} [hs : ord_connected t] (hf : ∀ x, f x ∈ t) (hne : t.nonempty) (he : closed_embedding e) : ∃ g : C(Y, ℝ), (∀ y, g y ∈ t) ∧ g ∘ e = f := begin have h : ℝ ≃o Ioo (-1 : ℝ) 1 := order_iso_Ioo_neg_one_one ℝ, set F : X →ᵇ ℝ := { to_fun := coe ∘ (h ∘ f), continuous_to_fun := continuous_subtype_coe.comp (h.continuous.comp f.continuous), map_bounded' := bounded_range_iff.1 ((bounded_Ioo (-1 : ℝ) 1).mono $ forall_range_iff.2 $ λ x, (h (f x)).2) }, set t' : set ℝ := (coe ∘ h) '' t, have ht_sub : t' ⊆ Ioo (-1 : ℝ) 1 := image_subset_iff.2 (λ x hx, (h x).2), haveI : ord_connected t', { constructor, rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ z hz, lift z to Ioo (-1 : ℝ) 1 using (Icc_subset_Ioo (h x).2.1 (h y).2.2 hz), change z ∈ Icc (h x) (h y) at hz, rw [← h.image_Icc] at hz, rcases hz with ⟨z, hz, rfl⟩, exact ⟨z, hs.out hx hy hz, rfl⟩ }, have hFt : ∀ x, F x ∈ t', from λ x, mem_image_of_mem _ (hf x), rcases F.exists_extension_forall_mem_of_closed_embedding hFt (hne.image _) he with ⟨G, hG, hGF⟩, set g : C(Y, ℝ) := ⟨h.symm ∘ cod_restrict G _ (λ y, ht_sub (hG y)), h.symm.continuous.comp $ G.continuous.subtype_mk _⟩, have hgG : ∀ {y a}, g y = a ↔ G y = h a, from λ y a, h.to_equiv.symm_apply_eq.trans subtype.ext_iff, refine ⟨g, λ y, _, _⟩, { rcases hG y with ⟨a, ha, hay⟩, convert ha, exact hgG.2 hay.symm }, { ext x, exact hgG.2 (congr_fun hGF _) } end /-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal topological space `Y`. Let `f` be a continuous real-valued function on `X`. Then there exists a continuous real-valued function `g : C(Y, ℝ)` such that `g ∘ e = f`. -/ lemma exists_extension_of_closed_embedding (f : C(X, ℝ)) (e : X → Y) (he : closed_embedding e) : ∃ g : C(Y, ℝ), g ∘ e = f := (exists_extension_forall_mem_of_closed_embedding f (λ x, mem_univ _) univ_nonempty he).imp $ λ g, and.right /-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed set. Let `s` be a closed set in a normal topological space `Y`. Let `f` be a continuous real-valued function on `s`. Let `t` be a nonempty convex set of real numbers (we use `ord_connected` instead of `convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x : s`. Then there exists a continuous real-valued function `g : C(Y, ℝ)` such that `g y ∈ t` for all `y` and `g.restrict s = f`. -/ lemma exists_restrict_eq_forall_mem_of_closed {s : set Y} (f : C(s, ℝ)) {t : set ℝ} [ord_connected t] (ht : ∀ x, f x ∈ t) (hne : t.nonempty) (hs : is_closed s) : ∃ g : C(Y, ℝ), (∀ y, g y ∈ t) ∧ g.restrict s = f := let ⟨g, hgt, hgf⟩ := exists_extension_forall_mem_of_closed_embedding f ht hne (closed_embedding_subtype_coe hs) in ⟨g, hgt, coe_injective hgf⟩ /-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed set. Let `s` be a closed set in a normal topological space `Y`. Let `f` be a continuous real-valued function on `s`. Then there exists a continuous real-valued function `g : C(Y, ℝ)` such that `g.restrict s = f`. -/ lemma exists_restrict_eq_of_closed {s : set Y} (f : C(s, ℝ)) (hs : is_closed s) : ∃ g : C(Y, ℝ), g.restrict s = f := let ⟨g, hg, hgf⟩ := exists_restrict_eq_forall_mem_of_closed f (λ _, mem_univ _) univ_nonempty hs in ⟨g, hgf⟩ end continuous_map
412b5c68f5ddad55858ca4924b565155ee62e139
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Init/Data/Nat/Control.lean
c5a1277be0d7f5712c41b69ace2398d6de3b5877
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
1,538
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Control.Basic import Init.Data.Nat.Basic namespace Nat universes u v @[inline] def forM {m} [Monad m] (n : Nat) (f : Nat → m Unit) : m Unit := let rec @[specialize] loop | 0 => pure () | i+1 => do f (n-i-1); loop i loop n @[inline] def forRevM {m} [Monad m] (n : Nat) (f : Nat → m Unit) : m Unit := let rec @[specialize] loop | 0 => pure () | i+1 => do f i; loop i loop n @[inline] def foldM {α : Type u} {m : Type u → Type v} [Monad m] (f : Nat → α → m α) (init : α) (n : Nat) : m α := let rec @[specialize] loop | 0, a => pure a | i+1, a => f (n-i-1) a >>= loop i loop n init @[inline] def foldRevM {α : Type u} {m : Type u → Type v} [Monad m] (f : Nat → α → m α) (init : α) (n : Nat) : m α := let rec @[specialize] loop | 0, a => pure a | i+1, a => f i a >>= loop i loop n init @[inline] def allM {m} [Monad m] (n : Nat) (p : Nat → m Bool) : m Bool := let rec @[specialize] loop | 0 => pure true | i+1 => do match (← p (n-i-1)) with | true => loop i | false => pure false loop n @[inline] def anyM {m} [Monad m] (n : Nat) (p : Nat → m Bool) : m Bool := let rec @[specialize] loop | 0 => pure false | i+1 => do match (← p (n-i-1)) with | true => pure true | false => loop i loop n end Nat
cd408deaf0f6312dbb77906907218143ee578fbb
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/shapes/products.lean
2f2f89bbb803b5f93b0c9e9295d99dd79094944d
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,936
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.has_limits import category_theory.discrete_category /-! # Categorical (co)products This file defines (co)products as special cases of (co)limits. A product is the categorical generalization of the object `Π i, f i` where `f : ι → C`. It is a limit cone over the diagram formed by `f`, implemented by converting `f` into a functor `discrete ι ⥤ C`. A coproduct is the dual concept. ## Main definitions * a `fan` is a cone over a discrete category * `fan.mk` constructs a fan from an indexed collection of maps * a `pi` is a `limit (discrete.functor f)` Each of these has a dual. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. -/ noncomputable theory universes w v u u₂ open category_theory namespace category_theory.limits variables {β : Type w} variables {C : Type u} [category.{v} C] -- We don't need an analogue of `pair` (for binary products), `parallel_pair` (for equalizers), -- or `(co)span`, since we already have `discrete.functor`. /-- A fan over `f : β → C` consists of a collection of maps from an object `P` to every `f b`. -/ abbreviation fan (f : β → C) := cone (discrete.functor f) /-- A cofan over `f : β → C` consists of a collection of maps from every `f b` to an object `P`. -/ abbreviation cofan (f : β → C) := cocone (discrete.functor f) /-- A fan over `f : β → C` consists of a collection of maps from an object `P` to every `f b`. -/ @[simps] def fan.mk {f : β → C} (P : C) (p : Π b, P ⟶ f b) : fan f := { X := P, π := { app := p } } /-- A cofan over `f : β → C` consists of a collection of maps from every `f b` to an object `P`. -/ @[simps] def cofan.mk {f : β → C} (P : C) (p : Π b, f b ⟶ P) : cofan f := { X := P, ι := { app := p } } /-- An abbreviation for `has_limit (discrete.functor f)`. -/ abbreviation has_product (f : β → C) := has_limit (discrete.functor f) /-- An abbreviation for `has_colimit (discrete.functor f)`. -/ abbreviation has_coproduct (f : β → C) := has_colimit (discrete.functor f) section variables (C) /-- An abbreviation for `has_limits_of_shape (discrete f)`. -/ abbreviation has_products_of_shape (β : Type v) := has_limits_of_shape.{v} (discrete β) /-- An abbreviation for `has_colimits_of_shape (discrete f)`. -/ abbreviation has_coproducts_of_shape (β : Type v) := has_colimits_of_shape.{v} (discrete β) end /-- `pi_obj f` computes the product of a family of elements `f`. (It is defined as an abbreviation for `limit (discrete.functor f)`, so for most facts about `pi_obj f`, you will just use general facts about limits.) -/ abbreviation pi_obj (f : β → C) [has_product f] := limit (discrete.functor f) /-- `sigma_obj f` computes the coproduct of a family of elements `f`. (It is defined as an abbreviation for `colimit (discrete.functor f)`, so for most facts about `sigma_obj f`, you will just use general facts about colimits.) -/ abbreviation sigma_obj (f : β → C) [has_coproduct f] := colimit (discrete.functor f) notation `∏ ` f:20 := pi_obj f notation `∐ ` f:20 := sigma_obj f /-- The `b`-th projection from the pi object over `f` has the form `∏ f ⟶ f b`. -/ abbreviation pi.π (f : β → C) [has_product f] (b : β) : ∏ f ⟶ f b := limit.π (discrete.functor f) b /-- The `b`-th inclusion into the sigma object over `f` has the form `f b ⟶ ∐ f`. -/ abbreviation sigma.ι (f : β → C) [has_coproduct f] (b : β) : f b ⟶ ∐ f := colimit.ι (discrete.functor f) b /-- The fan constructed of the projections from the product is limiting. -/ def product_is_product (f : β → C) [has_product f] : is_limit (fan.mk _ (pi.π f)) := is_limit.of_iso_limit (limit.is_limit (discrete.functor f)) (cones.ext (iso.refl _) (by tidy)) /-- The cofan constructed of the inclusions from the coproduct is colimiting. -/ def coproduct_is_coproduct (f : β → C) [has_coproduct f] : is_colimit (cofan.mk _ (sigma.ι f)) := is_colimit.of_iso_colimit (colimit.is_colimit (discrete.functor f)) (cocones.ext (iso.refl _) (by tidy)) /-- A collection of morphisms `P ⟶ f b` induces a morphism `P ⟶ ∏ f`. -/ abbreviation pi.lift {f : β → C} [has_product f] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ∏ f := limit.lift _ (fan.mk P p) /-- A collection of morphisms `f b ⟶ P` induces a morphism `∐ f ⟶ P`. -/ abbreviation sigma.desc {f : β → C} [has_coproduct f] {P : C} (p : Π b, f b ⟶ P) : ∐ f ⟶ P := colimit.desc _ (cofan.mk P p) /-- Construct a morphism between categorical products (indexed by the same type) from a family of morphisms between the factors. -/ abbreviation pi.map {f g : β → C} [has_product f] [has_product g] (p : Π b, f b ⟶ g b) : ∏ f ⟶ ∏ g := lim_map (discrete.nat_trans p) /-- Construct an isomorphism between categorical products (indexed by the same type) from a family of isomorphisms between the factors. -/ abbreviation pi.map_iso {f g : β → C} [has_products_of_shape β C] (p : Π b, f b ≅ g b) : ∏ f ≅ ∏ g := lim.map_iso (discrete.nat_iso p) /-- Construct a morphism between categorical coproducts (indexed by the same type) from a family of morphisms between the factors. -/ abbreviation sigma.map {f g : β → C} [has_coproduct f] [has_coproduct g] (p : Π b, f b ⟶ g b) : ∐ f ⟶ ∐ g := colim_map (discrete.nat_trans p) /-- Construct an isomorphism between categorical coproducts (indexed by the same type) from a family of isomorphisms between the factors. -/ abbreviation sigma.map_iso {f g : β → C} [has_coproducts_of_shape β C] (p : Π b, f b ≅ g b) : ∐ f ≅ ∐ g := colim.map_iso (discrete.nat_iso p) section comparison variables {D : Type u₂} [category.{v} D] (G : C ⥤ D) variables (f : β → C) /-- The comparison morphism for the product of `f`. This is an iso iff `G` preserves the product of `f`, see `preserves_product.of_iso_comparison`. -/ def pi_comparison [has_product f] [has_product (λ b, G.obj (f b))] : G.obj (∏ f) ⟶ ∏ (λ b, G.obj (f b)) := pi.lift (λ b, G.map (pi.π f b)) @[simp, reassoc] lemma pi_comparison_comp_π [has_product f] [has_product (λ b, G.obj (f b))] (b : β) : pi_comparison G f ≫ pi.π _ b = G.map (pi.π f b) := limit.lift_π _ b @[simp, reassoc] lemma map_lift_pi_comparison [has_product f] [has_product (λ b, G.obj (f b))] (P : C) (g : Π j, P ⟶ f j) : G.map (pi.lift g) ≫ pi_comparison G f = pi.lift (λ j, G.map (g j)) := by { ext, simp [← G.map_comp] } /-- The comparison morphism for the coproduct of `f`. This is an iso iff `G` preserves the coproduct of `f`, see `preserves_coproduct.of_iso_comparison`. -/ def sigma_comparison [has_coproduct f] [has_coproduct (λ b, G.obj (f b))] : ∐ (λ b, G.obj (f b)) ⟶ G.obj (∐ f) := sigma.desc (λ b, G.map (sigma.ι f b)) @[simp, reassoc] lemma ι_comp_sigma_comparison [has_coproduct f] [has_coproduct (λ b, G.obj (f b))] (b : β) : sigma.ι _ b ≫ sigma_comparison G f = G.map (sigma.ι f b) := colimit.ι_desc _ b @[simp, reassoc] lemma sigma_comparison_map_desc [has_coproduct f] [has_coproduct (λ b, G.obj (f b))] (P : C) (g : Π j, f j ⟶ P) : sigma_comparison G f ≫ G.map (sigma.desc g) = sigma.desc (λ j, G.map (g j)) := by { ext, simp [← G.map_comp] } end comparison variables (C) /-- An abbreviation for `Π J, has_limits_of_shape (discrete J) C` -/ abbreviation has_products := Π (J : Type v), has_limits_of_shape (discrete J) C /-- An abbreviation for `Π J, has_colimits_of_shape (discrete J) C` -/ abbreviation has_coproducts := Π (J : Type v), has_colimits_of_shape (discrete J) C end category_theory.limits
d1cb0435a1e23957a253c78b2dd793e8cf80ff79
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/tutorials/tutorial3.lean
525589c3624d00c4ea47da9e6f3500078a477dc8
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
3,262
lean
import data.real.basic import algebra.group.pi def even_fun (f : ℝ → ℝ) := ∀ x, f(-x) = f x def odd_fun (f : ℝ → ℝ) := ∀ x, f (-x) = - f x example : ∀ (f g : ℝ → ℝ), even_fun f → even_fun g → even_fun (f + g) := begin intros f g Hf Hg x, calc (f + g)(-x) = f (-x) + g (-x) : by refl ... = f (x) + g(x) : by rw [Hf,Hg] ... = (f + g)(x) : by refl end example : ∀ (f g : ℝ → ℝ), even_fun f → even_fun (g ∘ f) := begin intros f g H₁ x, calc (g ∘ f) (-x) = g (f (-x)) : by refl ... = g (f (x)) : by rw H₁ ... = (g ∘ f)(x) : by refl end example : ∀ (f g : ℝ → ℝ), odd_fun f → odd_fun g → odd_fun (g ∘ f) := begin intros f g Hf Hg x, calc (g ∘ f) (-x) = g (f (-x)) : by refl ... = g (- (f x)) : by rw Hf ... = - (g (f x)) : by rw Hg ... = - ((g ∘ f) x): by refl end def non_decreasing (f : ℝ → ℝ) := ∀ x y, x ≤ y → f x ≤ f y def non_increasing (f : ℝ → ℝ) := ∀ x y, x ≤ y → f y ≤ f x example : ∀ (f g : ℝ → ℝ), non_decreasing f → non_decreasing g → non_decreasing (g ∘ f) := begin intros f g Hf Hg x y H₁, calc (g ∘ f) (x) = g (f x) : by refl ... ≤ g (f y) : by { apply Hg, apply Hf, assumption } ... = (g ∘ f) (y) : by refl end example : ∀ (f g : ℝ → ℝ), non_decreasing f → non_increasing g → non_increasing (g ∘ f) := begin intros f g Hf Hg x y H₁, calc (g ∘ f) (y) = g (f y) : by refl ... ≤ g (f x) : by { apply Hg, apply Hf, assumption } ... = (g ∘ f) (x) : by refl end example : ∀ (a b : ℝ), a = a*b → a = 0 ∨ b = 1 := begin intros a b H₁, have H₂ : a*(b - 1) = 0, { calc a*(b - 1) = a*b - a : by ring ... = a - a : by rw ← H₁ ... = 0 : by ring }, rw mul_eq_zero at H₂, cases H₂ with H₂ H₂, { left, assumption }, { right, linarith } end example : ∀ (x y : ℝ), x^2 = y^2 → x = y ∨ x = -y := begin intros x y H₁, have H₂ : (x - y)*(x + y) = 0, { calc (x - y)*(x + y) = x^2 - y^2 : by ring ... = 0 : by linarith }, rw mul_eq_zero at H₂, cases H₂ with H₂ H₂, {left, linarith }, {right, linarith } end example : ∀ (f : ℝ → ℝ), non_decreasing f ↔ ∀ x y, x < y → f x ≤ f y := begin intros f, split; intros H₁, { intros x y H₂, apply H₁, linarith }, { intros x y H₂, have H₃ : x = y ∨ x < y, {apply eq_or_lt_of_le, assumption }, cases H₃ with H₃ H₃, { rw H₃ }, { apply H₁, assumption }} end example : ∀ (f : ℝ → ℝ), non_decreasing f → (∀ x, f (f x) = x) → ∀ x, f x = x := begin intros f H₁ H₂ x, have H₃ : f x ≤ x ∨ x ≤ f x, { apply le_total }, cases H₃ with H₃ H₃, { apply le_antisymm; try { assumption }, have H₄ : f (f x) ≤ f x, { apply H₁, assumption}, rw H₂ at H₄, assumption }, { apply le_antisymm; try { assumption }, have H₄ : f x ≤ f (f x), {apply H₁, assumption }, rw H₂ at H₄, assumption } end
75e663d7261fc212a6e8cf8d11e68ae22ee96239
534c92d7322a8676cfd1583e26f5946134561b54
/src/Exercises/01_Propositions/Q0107/S0007.lean
92d8bafc8c1825310245b7bd8b7cf514e676623b
[ "Apache-2.0" ]
permissive
kbuzzard/mathematics-in-lean
53f387174f04d6077f434e27c407aee9425837f7
3fad7bb7e888dabef94921101af8671b78a4304a
refs/heads/master
1,586,812,457,439
1,546,893,744,000
1,546,893,744,000
163,450,734
8
0
null
null
null
null
UTF-8
Lean
false
false
91
lean
theorem false_implies_false : false → false := begin intro Hfalse, exact Hfalse, end
c0d0f83502395a8abd8dd4a008beb6db304d9950
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/lean-scheme-submission/src/instances/empty_scheme.lean
1960cb00574944e13aac6b79c104118c8bacd9ed
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
1,070
lean
import scheme import spectrum_of_a_ring.properties import algebra.punit_instances universe u open topological_space local attribute [instance] classical.prop_decidable @[reducible] def empty_presheaf : presheaf_of_rings empty := { F := λ U, punit, res := λ U V HUV, id, Hid := λ U, rfl, Hcomp := λ U V W HWV HVU, rfl, Fring := by apply_instance, res_is_ring_hom := by apply_instance, } @[reducible] def empty_sheaf : sheaf_of_rings empty := { F := empty_presheaf, locality := λ U OC s t Hs, subsingleton.elim s t, gluing := λ U OC si Hsi, ⟨0, λ i, by apply subsingleton.elim⟩ } @[reducible] def empty_locally_ringed_space : locally_ringed_space empty := { O := empty_sheaf, Hstalks := λ x, empty.elim x, } def empty_scheme : scheme empty := { carrier := empty_locally_ringed_space, Haffinecov := begin existsi ({ γ := empty, Uis := λ x, empty.elim x, Hcov := opens.ext $ set.ext $ λ x, empty.elim x, } : covering.univ empty), intros i, eapply empty.elim i, end }
f32e89a59a57c1cf7021214cf9b32f9da08e6572
798dd332c1ad790518589a09bc82459fb12e5156
/data/list/basic.lean
12e02fd330aa2dce7625bc54d0c7121be9263580
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
160,305
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro Basic properties of lists. -/ import tactic.interactive tactic.mk_iff_of_inductive_prop tactic.split_ifs logic.basic logic.function logic.relation algebra.group order.basic data.nat.basic data.option data.bool data.prod data.sigma data.fin open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} @[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_inj {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe @[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_inj e, congr_arg _⟩ /- mem -/ theorem eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil | [] := assume h, rfl | (b :: l') := assume h, absurd (mem_cons_self b l') (h b) theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, by intro h; simp [h]⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih; simp at h; cases h with h h, { subst h, exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, e⟩, subst l, 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, {simp at h, contradiction }, {simp, simp at h, cases h with h h, {simp *}, {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, {simp at h, contradiction}, {cases (eq_or_mem_of_mem_cons h) with h h, {existsi c, simp [h]}, {rcases ih h with ⟨a, ha₁, ha₂⟩, existsi a, simp * }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp [join, @mem_join L, or_and_distrib_right, exists_or_distrib] 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 [bind_map l] /- list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp [mem_map]; exact λ a h e, ⟨a, H h, e⟩ /- append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t := by {induction s with b s H generalizing a, refl, simp [foldl], 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 [foldr], rw H _} @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp @[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 [and_assoc, @eq_comm _ c] 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 { simp [nil_eq_append_iff, iff_def, or_imp_distrib] {contextual := tt} }, case cons : a as ih { cases c, { simp, exact eq_comm }, { simp [ih, @eq_comm _ a, and_assoc, and_or_distrib_left] } } end /-- Split a list at an index. `split 2 [a, b, c] = ([a, b], [c])` -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) @[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 [split_at, split_at_eq_take_drop n xs] @[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) := by simp [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 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 le_add_right end /- join -/ attribute [simp] join theorem join_eq_nil {L : list (list α)} : join L = [] ↔ ∀ l ∈ L, l = [] := by induction L; simp [or_imp_distrib, forall_and_distrib, *] @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; simp * /- 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 := have b = a ∧ ∀ (x : α), x ∈ l → x = a, by simpa [or_imp_distrib, forall_and_distrib] using H, by dsimp; congr; [exact this.1, exact eq_repeat_of_mem this.2] 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 [*, repeat, nat.succ_add, -add_comm] 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; simp [repeat, -add_comm, *] 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; simp * @[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; simp * /- 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 := by simp [bind] /- concat -/ /-- Concatenate an element at the end of a list. `concat [a, b] c = [a, b, c]` -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a @[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₁ with b l₁ ih; [simp, simp [ih]] @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp [*, concat] @[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp [succ_eq_add_one] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by induction l₂ with b l₂ ih; simp /- 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₁; simp *, (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; simp * theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp @[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; simp * @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; simp * 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 @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; simp * @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; simp * theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp [reverse_core_eq] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; simp [*, or_comm] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp, λ 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 }, { simp, 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, simp *, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp *] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp * @[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 -/ @[simp] def head' : list α → option α | [] := none | (a :: l) := some a 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, simp} theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := by {induction l, contradiction, simp} /- map -/ lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := have f a = g a, from h _ (mem_cons_self _ _), have map f l = map g l, from map_congr $ assume a', h _ ∘ mem_cons_of_mem _, show f a :: map f l = g a :: map g l, by simp [*] theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; simp * theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; simp * @[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; simp * @[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; simp * theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α) (h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l := by revert a; induction l; intros; simp * theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α) (h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l := by revert a; induction l; intros; simp * theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero (begin rw [← length_map f l], simp [h] end) @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; simp * theorem bind_ret_eq_map {α β} (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by simp [list.bind]; induction l; simp [list.ret, join, *] @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl /- map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl /- sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_app_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_app_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h; simp * }, { 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; simp, { exact sublist_app_of_sublist_left ih }, { 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 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 at this; assumption, λ h, append_sublist_append_of_sublist_right h l⟩ theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (subset_of_sublist s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ subset_of_sublist s theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa using length_le_of_sublist h, λ h, by induction h; [apply sublist.refl, simp [*, 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; simp [-add_comm], by_cases h : a = b; simp [h, -add_comm], { intro, contradiction }, { rw ← ih, exact ⟨succ_inj, congr_arg _⟩ } 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; simp [-add_comm, index_of_cons], by_cases h : a = b; simp [h, -add_comm, zero_le], exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /- nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_ge_len : ∀ {l : list α} {n}, n ≥ length l → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_ge_len (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_ge_len hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ @[extensionality] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp [*, ext (λn, h (n+1))] theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by rw [nth_ge_len h₁, nth_ge_len (by rwa [← hl])] @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp * @[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, by simp); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ /-- Convert a list into an array (whose length is the length of `l`) -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ @[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget /- nth tail operation -/ /-- Apply a function to the nth tail of `l`. `modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c]`. Returns the input without using `f` if the index is larger than the length of the list. -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) 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 [h, mt succ_inj] 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 [update_nth_eq_modify_nth] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp [nth_modify_nth] @[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 [nth_modify_nth, h]; cases nth l n; refl theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp [update_nth_eq_modify_nth] 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 [update_nth_eq_modify_nth, h] /- take, drop -/ @[simp] theorem take_zero : ∀ (l : list α), take 0 l = [] := begin intros, reflexivity end @[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 theorem take_all : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_ge (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by simp | (succ n) (succ m) nil := by simp | (succ n) (succ m) (a::l) := by simp [min_succ_succ, take_take] @[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 _ _ 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 [update_nth] section take' variable [inhabited α] def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail @[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 [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' /- take_while -/ /-- Get the longest initial segment of the list whose members all satisfy `p`. `take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2]` -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /- foldl, foldr, scanl, scanr -/ 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 := by induction l generalizing a; simp * {contextual := tt} 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 := by induction l; simp * {contextual := tt} @[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 [foldl_append] @[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 [foldr_append] @[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 [foldl_join] @[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 [foldr_join] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; simp [*, 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 [foldr_eta l] /-- Fold a function `f` over the list from the left, returning the list of partial results. `scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6]` -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. `scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0]` -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' @[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 [scanr, scanr_aux] at t; simp [scanr, scanr_aux, t] @[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 [scanr] 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 [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; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; simp theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp [foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := by simp | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp [ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc]; simp lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := by simp | (a :: l) a₁ a₂ := by simp [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 /- sum -/ /-- Product of a list. `prod [a, b, c] = ((1 * a) * b) * c` -/ @[to_additive list.sum] def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 attribute [to_additive list.sum.equations._eqn_1] list.prod.equations._eqn_1 section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive list.sum_nil] theorem prod_nil : ([] : list α).prod = 1 := rfl @[simp, to_additive list.sum_cons] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp [list.prod] ... = _ : foldl_assoc @[simp, to_additive list.sum_append] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive list.sum_join] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; simp [list.join, *] at * end monoid @[simp, to_additive list.sum_erase] theorem prod_erase [decidable_eq α] [comm_monoid α] {a} : Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod | (b::l) h := begin rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩, { simp [list.erase] }, { simp [ne.symm, list.erase, 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; simp [*, nat.mul_succ] @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; simp * @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] /- lexicographic ordering -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {} {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { cases classical.em (a = b) with ab ab, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ instance [decidable_linear_order α] : decidable_linear_order (list α) := decidable_linear_order_of_STO' (lex (<)) /- all & any, bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x := by simp @[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 [or_imp_distrib, forall_and_distrib] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp 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 theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp [or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x := by simp theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (by simp) 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 (by simp [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, simp [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) @[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 := by induction l with a l; simp [forall_and_distrib, *] theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp [all_iff_forall] @[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 := by induction l with a l; simp [or_and_distrib_right, exists_or_distrib, *] 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₂⟩ 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; simp * 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; simp *; apply 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; simp * 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 [pmap_eq_map_attach] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; simp * /- find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat | [] n := [] | (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := find_indexes_aux p l 0 @[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, {simp}, by_cases p a; simp [h, IH] end @[simp] theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases p b; simp [h] at H, { subst b, assumption }, { 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 p b; simp [h] at H, { subst b, apply mem_cons_self }, { exact mem_cons_of_mem _ (IH H) } end end find /-- `indexes_of a l` is the list of all indexes of `a` in `l`. `indexes_of a [a, b, a, a] = [0, 2, 3]` -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) /- 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 [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 [filter_map, h] theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {simp}, simp [filter_map_cons_some (some ∘ f) _ _ rfl, IH] 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, {simp}, by_cases pa : p a; simp [filter_map, option.guard, pa, IH] 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 [h] }, 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 [h, h'] 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 p x; simp [h, option.guard] 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, {simp}, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp [filter_map_cons_none _ _ h, IH, or_and_distrib_right, exists_or_distrib, this] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp [filter_map_cons_some _ _ _ h, IH, or_and_distrib_right, exists_or_distrib, this] } 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 [map_filter_map, H] 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 [filter_map]; cases f a with b; simp [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 simp at h; by_cases pa : p a; [simp [pa, h.1.1 pa, filter_congr h.2], simp [pa, mt h.1.2 pa, filter_congr h.2]] @[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, begin simp [pb] at ain, assumption end, 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 [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 simp [pa] | (b::l) (or.inr ain) pa := by by_cases pb : p b; simp [pb, 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, {simp}, by_cases p a; simp [filter, *], show filter p l ≠ a :: l, 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 [-and.comm, eq_nil_iff_forall_not_mem, mem_filter] 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 p a; by_cases q a; simp * @[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) := by by_cases pa : p a; simp [span, take_while, drop_while, pa, span_eq_take_drop l] @[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) := by by_cases pa : p a; simp [take_while, drop_while, pa, take_while_append_drop l] /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs @[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; [refl, by_cases (p x)]; simp [*, -add_comm] 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 theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp [countp_eq_length_filter, length_pos_iff_exists_mem] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa 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 [countp_eq_length_filter] end filter /- count -/ section count variable [decidable_eq α] /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count (a : α) : list α → nat := countp (eq a) @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := by simp @[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 [count, countp_pos] @[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem 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 [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa 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 [count]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) end count /- prefix, suffix, infix -/ /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_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 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 [h]⟩ @[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₂, by simp⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, by simp⟩ @[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⟩ 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 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₂ := ⟨λ h, let ⟨r, e⟩ := h in begin rwa append_inj_left ((take_append_drop (length l₁) l₂).trans e.symm) _, simp [min_eq_left, length_le_of_sublist (sublist_of_prefix h)], end, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨λ ⟨r, e⟩, begin rwa append_inj_right ((take_append_drop (length l₂ - length l₁) l₂).trans e.symm) _, simp [min_eq_left, nat.sub_le, e.symm], apply nat.add_sub_cancel_left end, λ 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 /-- `inits l` is the list of initial segments of `l`. `inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]]` -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa, ⟨λ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⟩ /-- `tails l` is the list of terminal segments of `l`. `tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []]` -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp [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 -/ def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. `sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]` -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] @[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; simp! * 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; simp! * 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 [sublists'_aux_eq_sublists'] @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s; simp, { exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ (IH.1 h) }, { exact cons_sublist_cons _ (IH.1 h) }, { cases h with _ _ _ h s _ _ h, { exact or.inl (IH.2 h) }, { exact or.inr ⟨s, IH.2 h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp [-add_comm, *]; rw [← two_mul, mul_comm]; refl def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`. `sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]` -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) 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 * 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 [sublists_aux], rw [IH₂, IH₁], congr' 1, induction sublists_aux l cons with _ _ ih; simp * 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 [sublists_aux₁] | (a::l₁) l₂ f := by simp [sublists_aux₁]; rw [sublists_aux₁_append]; simp 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 [sublists_aux₁_append, sublists_aux₁] 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 := by simp [sublists_aux₁] | (a::l) f g := by simp [sublists_aux₁]; rw [sublists_aux₁_bind]; simp 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 [sublists, sublists_aux_cons_eq_sublists_aux₁], rw [sublists_aux₁_append, sublists_aux₁_bind], congr, funext x, simp, rw [← bind_ret_eq_map, sublists_aux₁_bind], simp [list.ret] end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp [sublists_aux_cons_append, sublists, map_id'] @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by simp [sublists_append]; rw [sublists, sublists_aux_cons_eq_sublists_aux₁]; simp [map_id', sublists_aux₁] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l; simp [(∘), *] 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 [sublists_eq_sublists', map_id'] 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; simp [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 [sublists_eq_sublists', length_sublists'] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp; exact ((append_sublist_append_left _).2 (singleton_sublist.2 $ mem_map.2 ⟨[], by simp [list.ret]⟩)).trans ((append_sublist_append_right _).2 IH) /- transpose -/ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. `transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]]` -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /- forall₂ -/ section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} open relator relation inductive forall₂ (R : α → β → Prop) : list α → list β → Prop | nil {} : forall₂ [] [] | cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂) run_cmd tactic.mk_iff_of_inductive_prop `list.forall₂ `list.forall₂_iff attribute [simp] forall₂.nil @[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₂; simp *, λ ⟨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; simp * 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₁ (forall₂_flip h₂) 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; simp * }, { assume h, subst h, exact forall₂_refl _ } end @[simp] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil := by rw [forall₂_iff]; simp @[simp] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil := by rw [forall₂_iff]; simp 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) @[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 | (a::l) _ := by simp [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 | _ (b::u) := by simp [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₂, { simp [length_eq_zero.1 h₁.symm] }, { 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⟩ lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈) | a b h [] [] forall₂.nil := by simp | 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 := by simp [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 := by simp [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 [h, this, h₁, rel_filter h₂], }, { have : ¬ q b, { rwa [← hpq h₁] }, simp [h, this, h₁, 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, { simp [filter_map_cons_none _ _ eq]}, { simp [filter_map_cons_some _ _ _ eq]}, end lemma rel_filter_map {f : α → option γ} {q : β → option δ} : ((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map | f g hfg _ _ forall₂.nil := forall₂.nil | f g hfg (a::as) (b::bs) (forall₂.cons h₁ h₂) := by rw [filter_map_cons, filter_map_cons]; from match f a, g b, hfg h₁ with | _, _, option.rel.none := rel_filter_map @hfg h₂ | _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂) end @[to_additive list.rel_sum] lemma rel_prod [monoid α] [monoid β] (h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod := assume a b, rel_foldl (assume a b, hf) h end forall₂ /- sections -/ /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ def sections : list (list α) → list (list α) | [] := [[]] | (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l theorem mem_sections {L : list (list α)} {f} : f ∈ sections L ↔ forall₂ (∈) f L := begin refine ⟨λ h, _, λ h, _⟩, { induction L generalizing f; simp [sections] at h; casesm* [Exists _, _ ∧ _, _ = _]; simp * }, { induction h with a l f L al fL fs; simp [sections], 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 def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ _ (lt_add_of_pos_left _ (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by simp [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 simp [permutations_aux, permutations_aux.rec, permutations] 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 [insert.def, h] @[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp [insert.def, h] @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l; simp [h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; simp * @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) @[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) : length (insert a l) = length l := by simp [h] @[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by simp [h] end insert /- 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 [erase_cons] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp [erase_cons, h] @[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by induction l with _ _ ih; [refl, simp [(ne_of_not_mem_cons h).symm, ih (not_mem_of_not_mem_cons 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 induction l with b l ih; [cases h, { simp at h, by_cases e : b = a, { subst b, exact ⟨[], l, not_mem_nil _, rfl, by simp⟩ }, { exact let ⟨l₁, l₂, h₁, h₂, h₃⟩ := ih (h.resolve_left (ne.symm e)) in ⟨b::l₁, l₂, not_mem_cons_of_ne_of_not_mem (ne.symm e) h₁, by rw h₂; refl, by simp [e, h₃]⟩ } }] @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := match l, l.erase a, exists_erase_eq h with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp [-add_comm]; refl end theorem erase_append_left {a : α} : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erase a = l₁.erase a ++ l₂ | (x::xs) l₂ h := begin by_cases h' : x = a; simp [h'], rw erase_append_left l₂ (mem_of_ne_of_mem (ne.symm h') h) end theorem erase_append_right {a : α} : ∀ {l₁ : list α} (l₂), a ∉ l₁ → (l₁++l₂).erase a = l₁ ++ l₂.erase a | [] l₂ h := rfl | (x::xs) l₂ h := by simp [*, (ne_of_not_mem_cons h).symm, (not_mem_of_not_mem_cons h)] theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := if h : a ∈ l then match l, l.erase a, exists_erase_eq h with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp end else by simp [h] 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 α}, l₁ <+ l₂ → l₁.erase a <+ l₂.erase a | ._ ._ sublist.slnil := sublist.slnil | ._ ._ (sublist.cons l₁ l₂ b s) := if h : b = a then by rw [h, erase_cons_head]; exact (erase_sublist _ _).trans s else by rw erase_cons_tail _ h; exact (erase_sublist_erase s).cons _ _ _ | ._ ._ (sublist.cons2 l₁ l₂ b s) := if h : b = a then by rw [h, erase_cons_head, erase_cons_head]; exact s else by rw [erase_cons_tail _ h, erase_cons_tail _ h]; exact (erase_sublist_erase s).cons2 _ _ _ 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 := ⟨mem_of_mem_erase, λ al, if h : b ∈ l then match l, l.erase b, exists_erase_eq h, al with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩, al := by simpa [ab] using al end else by simp [h, al]⟩ theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by simp [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 [hb, mt mem_of_mem_erase hb] else by simp [ha, 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 simp [list.erase] | (b::l) := if h : f b = f a then by simp [h, finj h] else by simp [h, mt (congr_arg f) h, map_erase l] 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₁; simp [map_erase finj, *] end erase /- diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := by by_cases a ∈ l₁; simp [list.diff, h] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; simp * 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 [diff_eq_foldl] @[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 [diff_eq_foldl, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := by simp | 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 [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 := by simp [erase_sublist] | (b::l₁) l₂ h := if heq : b = a then by simp [heq] else by simpa [heq, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (erase_sublist_erase b h) end diff /- zip & unzip -/ @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := by cases l; refl @[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β), (zip l₁ l₂).map prod.swap = zip l₂ l₁ | [] l₂ := by simp | l₁ [] := by simp | (a::l₁) (b::l₂) := by simp * @[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β), length (zip l₁ l₂) = min (length l₁) (length l₂) | [] l₂ := by simp | l₁ [] := by simp | (a::l₁) (b::l₂) := by simp [*, min_add_add_left] 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 [eq_nil_of_length_eq_zero h.symm] | l₁ [] r₁ r₂ h := by simp [eq_nil_of_length_eq_zero h] | (a::l₁) (b::l₂) r₁ r₂ h := by simp [zip_append (succ_inj h)] 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₂ := by simp | l₁ [] := by simp | (a::l₁) (b::l₂) := by simp [zip_map l₁ l₂] 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 [zip_map' l] 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 simp [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 [unzip_eq_map l] theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst := by simp [unzip_eq_map] theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd := by simp [unzip_eq_map] theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap := by simp [unzip_eq_map]; split; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp [zip_unzip l] 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 [unzip_zip_left (le_of_succ_le_succ h)] 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)] def revzip (l : list α) : list (α × α) := zip l l.reverse @[simp] theorem length_revzip (l : list α) : length (revzip l) = length l := by simp [revzip, length_zip] @[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) := by simp [revzip, unzip_zip] @[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 [enum] @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ /- product -/ /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a @[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 [product, and.left_comm] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; simp [*, right_distrib] /- sigma -/ section variable {σ : α → Type*} /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [5, 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ protected def sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a @[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 [list.sigma, and.left_comm] 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; simp * end /- of_fn -/ def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α | 0 h l := l | (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l) def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] 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 _ _) theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n := (length_of_fn_aux f _ _ _).trans (zero_add _) def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : _ then some (f ⟨i, h⟩) else none 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 [of_fn_nth_val, show m < n, from h], refl }, { simp [H, succ_add, -add_comm] } 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 [of_fn_nth_val, not_lt.2 (le_add_right n i)] 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 [of_fn_nth_val, i.2]; cases i; refl 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 [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; exact of_fn_nth_le l /- disjoint -/ section disjoint /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false 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 [disjoint_left, imp_not_comm] 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 [disjoint]; refl @[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp [disjoint, 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 [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 @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp [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 [*, 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 by simp [e.symm]; by_cases h : a ∈ t ++ l₂; [existsi t, existsi a::t]; simp [h]; [apply sublist_cons_of_sublist _ s, apply cons_sublist_cons _ s] 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 [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 [eq_nil_iff_forall_not_mem]; 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₂ := by cases l₂; simp [h, list.bag_inter] theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ | [] l₂ := by simp | (b::l₁) l₂ := by by_cases b ∈ l₂; simp [*, and_or_distrib_left]; by_cases ba : a = b; simp * theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁ | [] l₂ := by simp [nil_sublist] | (b::l₁) l₂ := begin by_cases b ∈ l₂; simp [h], { apply cons_sublist_cons, apply bag_inter_sublist_left }, { apply sublist_cons_of_sublist, apply bag_inter_sublist_left } end end bag_inter /- pairwise relation (generalized no duplicate) -/ section pairwise variable (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) attribute [simp] pairwise.nil run_cmd tactic.mk_iff_of_inductive_prop `list.pairwise `list.pairwise_iff variable {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ 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 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; simp * 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 {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 {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 pairwise_singleton (R) (a : α) : pairwise R [a] := by simp theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b := by simp 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 [*, or_imp_distrib, forall_and_distrib, and_assoc, and.left_comm] theorem pairwise_app_comm (s : symmetric R) {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) := have ∀ l₁ l₂ : list α, (∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) → (∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y), from λ l₁ l₂ a x xm y ym, s (a y ym x xm), by simp [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁) theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} : pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) := show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂), by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_app_comm s]; simp only [mem_append, or_comm] theorem pairwise_map (f : β → α) : ∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l | [] := by simp | (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, by simp *; rw this 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, induction l with a l IH; simp, cases e : f a with b; simp [e, IH], rw [filter_map_cons_some _ _ _ e], simp [IH], 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, simp 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}, 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 [pairwise_append, IH, this], simp [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; [simp, simpa [pairwise_append, IH] 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; 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, { apply H.1, simp [nth_le_mem] }, { 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 [pairwise_append, pairwise_map], 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 variable [decidable_rel R] instance decidable_pairwise (l : list α) : decidable (pairwise R l) := by induction l; simp; resetI; apply_instance /- pairwise reduct -/ /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function, and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 5, 6] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH @[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl @[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = a :: pw_filter R l := if_pos h @[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = pw_filter R l := if_neg h theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l | [] := nil_sublist _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { 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); dsimp at h, { 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, {simp}, 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; simp *, by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { simp [pw_filter_cons_of_pos h], 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 variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. `chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d` -/ inductive chain : α → list α → Prop | nil (a : α) : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) attribute [simp] chain.nil run_cmd tactic.mk_iff_of_inductive_prop `list.chain `list.chain_iff variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ 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 {S : α → α → Prop} {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 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 [*, 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 * 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; simp, simp at r, simp [r], show chain R b l, from 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, {simp}, apply IH.cons _, simp [r], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp; resetI; apply_instance end chain /- no duplicates predicate -/ /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) 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 [nodup] lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup | _ _ forall₂.nil := by simp | _ _ (forall₂.cons hab h) := by simpa 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, {simp}, 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 @[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 [nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ := (nodup_append.1 d).2.2 theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) := nodup_append.2 ⟨d₁, d₂, dj⟩ theorem nodup_app_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) := by simp [nodup_append, and.left_comm] theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) := by simp [nodup_append, not_or_distrib, and.left_comm, and_assoc] 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 [nodup, eq_comm] instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise 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; simp [list.erase, list.filter], by_cases b = a; simp *, subst b, show l = filter (λ a', ¬ a' = a) l, rw filter_eq_self.2, simpa only [eq_comm] using m end theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_sublist (erase_sublist _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L := by simp [nodup, pairwise_join, disjoint_left.symm] 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 [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm]; rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔ (∀ (x : α), x ∈ l₁ → nodup (f x)), from forall_swap.trans $ forall_congr $ λ_, by simp] 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, suffices ∀ (b₁ : β), b₁ ∈ l₂ → (a₁, b₁) = x → ∀ (b₂ : β), b₂ ∈ l₂ → (a₂, b₂) ≠ x, by simpa, λ b₁ mb₁ e b₂ mb₂ e', by subst e'; injection e; contradiction)⟩ 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, suffices ∀ (b₁ : σ a₁), sigma.mk a₁ b₁ = x → b₁ ∈ l₂ a₁ → ∀ (b₂ : σ a₂), sigma.mk a₂ b₂ = x → b₂ ∉ l₂ a₂, by simpa [and_comm], λ b₁ e mb₁ b₂ e' mb₂, by subst e'; injection e; contradiction)⟩ 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 simp; 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) := by by_cases h' : a ∈ l; simp [h', h]; apply nodup_cons h' h 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 }, simp, apply nodup_insert, exact ih h end theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup_filter _ @[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l := ⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h), λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩ @[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l := by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse] end nodup /- erase duplicates function -/ section erase_dup variable [decidable_eq α] /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). erase_dup [1, 2, 2, 0, 1] = [1, 2, 0] -/ def erase_dup : list α → list α := pw_filter (≠) @[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 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 using h @[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l := by simpa 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; simp, rw ← 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 -/ /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n @[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 := by simp | s (n+1) := 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 [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm, by simp [@mem_range' (s+1) n, or_and_distrib_left, or_iff_right_of_imp this, l] theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n | s 0 := rfl | s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n) theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n) | s 0 := chain.nil _ _ | s (n+1) := (chain_succ_range' (s+1) n).cons rfl theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) := (chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _) theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n) | s 0 := pairwise.nil _ | s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n) theorem nodup_range' (s n : ℕ) : nodup (range' s n) := (pairwise_lt_range' s n).imp (λ a b, ne_of_lt) theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m) | s 0 n := rfl | s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m), by rw [add_right_comm, range'_append] theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n := ⟨λ h, by simpa 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) _ := by simp | s (m+1) (n+1) h := by simp [nth_range' (s+1) (lt_of_add_lt_add_right h)] 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, by simp]; 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 [range_eq_range'] theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) := by simp [range_eq_range', pairwise_lt_range'] theorem nodup_range (n : ℕ) : nodup (range n) := by simp [range_eq_range', nodup_range'] theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n := by simp [range_eq_range', range'_sublist_right] theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := by simp [range_eq_range', range'_subset_right] @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := by simp [range_eq_range', zero_le] @[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 [range_eq_range', nth_range' _ h] theorem range_concat (n : ℕ) : range (n + 1) = range n ++ [n] := by simp [range_eq_range', range'_concat] theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n) | 0 := rfl | (n+1) := by simp [iota, range'_concat, iota_eq_reverse_range' n] @[simp] theorem length_iota (n : ℕ) : length (iota n) = n := by simp [iota_eq_reverse_range'] theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) := by simp [iota_eq_reverse_range', pairwise_lt_range'] theorem nodup_iota (n : ℕ) : nodup (iota n) := by simp [iota_eq_reverse_range', nodup_range'] theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n := by simp [iota_eq_reverse_range', 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 [show s + (n + 1) - 1 = s + n, from rfl, (∘), λ a i, show a - 1 - i = a - succ i, by rw [nat.sub_sub, add_comm]; refl] using reverse_range' s n @[simp] theorem enum_from_map_fst : ∀ n (l : list α), map prod.fst (enum_from n l) = range' n l.length | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _) @[simp] theorem enum_map_fst (l : list α) : map prod.fst (enum l) = range l.length := by simp [enum, range_eq_range'] def reduce_option {α} : list (option α) → list α := list.filter_map id def map_head {α} (f : α → α) : list α → list α | [] := [] | (x :: xs) := f x :: xs def map_last {α} (f : α → α) : list α → list α | [] := [] | [x] := [f x] | (x :: xs) := x :: map_last xs end list theorem option.to_list_nodup {α} (o : option α) : o.to_list.nodup := by cases o; simp [option.to_list]
767c5fe2a4524f50248a9fbaeab3a32f23b48772
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/rat/basic.lean
ff36d573cf8f8d8823d93cf8854c5611b1c2a401
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
27,722
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.equiv.encodable.basic import algebra.euclidean_domain /-! # Basics for the Rational Numbers ## Summary We define a rational number `q` as a structure `{ num, denom, pos, cop }`, where - `num` is the numerator of `q`, - `denom` is the denominator of `q`, - `pos` is a proof that `denom > 0`, and - `cop` is a proof `num` and `denom` are coprime. We then define the expected (discrete) field structure on `ℚ` and prove basic lemmas about it. Moreoever, we provide the expected casts from `ℕ` and `ℤ` into `ℚ`, i.e. `(↑n : ℚ) = n / 1`. ## Main Definitions - `rat` is the structure encoding `ℚ`. - `rat.mk n d` constructs a rational number `q = n / d` from `n d : ℤ`. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom -/ /-- `rat`, or `ℚ`, is the type of rational numbers. It is defined as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and `d` are coprime. This representation is preferred to the quotient because without periodic reduction, the numerator and denominator can grow exponentially (for example, adding 1/2 to itself repeatedly). -/ structure rat := mk' :: (num : ℤ) (denom : ℕ) (pos : 0 < denom) (cop : num.nat_abs.coprime denom) notation `ℚ` := rat namespace rat protected def repr : ℚ → string | ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else _root_.repr n ++ "/" ++ _root_.repr d instance : has_repr ℚ := ⟨rat.repr⟩ instance : has_to_string ℚ := ⟨rat.repr⟩ meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩ instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // 0 < d ∧ n.nat_abs.coprime d}) ⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩ /-- Embed an integer as a rational number -/ def of_int (n : ℤ) : ℚ := ⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩ instance : has_zero ℚ := ⟨of_int 0⟩ instance : has_one ℚ := ⟨of_int 1⟩ instance : inhabited ℚ := ⟨0⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/ def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ := let n' := n.nat_abs, g := n'.gcd d in ⟨n / g, d / g, begin apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2, simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _) end, begin have : int.nat_abs (n / ↑g) = n' / g, { cases int.nat_abs_eq n with e e; rw e, { refl }, rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl }, exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) }, rw this, exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos) end⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we define `n / 0 = 0` by convention. -/ def mk_nat (n : ℤ) (d : ℕ) : ℚ := if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩ /-- Form the quotient `n / d` where `n d : ℤ`. -/ def mk : ℤ → ℤ → ℚ | n (d : ℕ) := mk_nat n d | n -[1+ d] := mk_pnat (-n) d.succ_pnat localized "infix ` /. `:70 := rat.mk" in rat theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d := by change n /. d with dite _ _ _; simp [ne_of_gt h] theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl @[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl @[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 := by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl @[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 := by by_cases n = 0; simp [*, mk_nat] @[simp] theorem zero_mk (n) : 0 /. n = 0 := by cases n; simp [mk] private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a := int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b @[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 := begin constructor; intro h; [skip, {subst a, simp}], have : ∀ {a b}, mk_pnat a b = 0 → a = 0, { intros a b e, cases b with b h, injection e with e, apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e }, cases b with b; simp [mk, mk_nat] at h, { simp [mt (congr_arg int.of_nat) b0] at h, exact this h }, { apply neg_injective, simp [this h] } end theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0), a /. b = c /. d ↔ a * d = c * b := suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b, begin intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hb], all_goals { cases d with d d; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hd], all_goals { rw this, try {refl} } }, { change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b, constructor; intro h; apply neg_injective; simpa [left_distrib, neg_add_eq_iff_eq_add, eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h }, { change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ, constructor; intro h; apply neg_injective; simpa [left_distrib, eq_comm] using h }, { change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ, simp [left_distrib, sub_eq_add_neg], cc } end, begin intros, simp [mk_pnat], constructor; intro h, { cases h with ha hb, have ha, { have dv := @gcd_abs_dvd_left, have := int.eq_mul_of_div_eq_right dv ha, rw ← int.mul_div_assoc _ dv at this, exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have hb, { have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b, have := nat.eq_mul_of_div_eq_right dv hb, rw ← nat.mul_div_assoc _ dv at this, exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, { refine int.coe_nat_ne_zero.2 (ne_of_gt _), apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption }, apply mul_right_cancel' m0, simpa [mul_comm, mul_left_comm] using congr (congr_arg (*) ha.symm) (congr_arg coe hb) }, { suffices : ∀ a c, a * d = c * b → a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d, { cases this a.nat_abs c.nat_abs (by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂, have hs := congr_arg int.sign h, simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb), int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs, conv in a { rw ← int.sign_mul_nat_abs a }, conv in c { rw ← int.sign_mul_nat_abs c }, rw [int.mul_div_assoc, int.mul_div_assoc], exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩, all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } }, intros a c h, suffices bd : b / a.gcd b = d / c.gcd d, { refine ⟨_, bd⟩, apply nat.eq_of_mul_eq_mul_left hb, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd, ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] }, suffices : ∀ {a c : ℕ} (b>0) (d>0), a * d = c * b → b / a.gcd b ≤ d / c.gcd d, { exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) }, intros a c b hb d hd h, have gb0 := nat.gcd_pos_of_pos_right a hb, have gd0 := nat.gcd_pos_of_pos_right c hd, apply nat.le_of_dvd, apply (nat.le_div_iff_mul_le _ _ gd0).2, simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _), apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left, refine ⟨c / c.gcd d, _⟩, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)], apply congr_arg (/ c.gcd d), rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] } end @[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) : (a * c) /. (b * c) = a /. b := begin by_cases b0 : b = 0, { subst b0, simp }, apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc] end @[simp] theorem num_denom : ∀ {a : ℚ}, a.num /. a.denom = a | ⟨n, d, h, (c:_=1)⟩ := show mk_nat n d = _, by simp [mk_nat, ne_of_gt h, mk_pnat, c] theorem num_denom' {n d h c} : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom.symm theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom' @[elab_as_eliminator] def {u} num_denom_cases_on {C : ℚ → Sort u} : ∀ (a : ℚ) (H : ∀ n d, 0 < d → (int.nat_abs n).coprime d → C (n /. d)), C a | ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c @[elab_as_eliminator] def {u} num_denom_cases_on' {C : ℚ → Sort u} (a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a := num_denom_cases_on a $ λ n d h c, H n d $ ne_of_gt h theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a := begin cases e : a /. b with n d h c, rw [rat.num_denom', rat.mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.dvd_of_dvd_mul_right _), have := congr_arg int.nat_abs e, simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this] end theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b := begin by_cases b0 : b = 0, {simp [b0]}, cases e : a /. b with n d h c, rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _), rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp end protected def add : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_add ℚ := ⟨rat.add⟩ theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ) (fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂}, f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂) (f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0) (a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0) (H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d), f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) : f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc, rw fv, have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁), have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂), exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc)) end @[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b + c /. d = (a * d + c * b) /. (b * d) := begin apply lift_binop_eq rat.add; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, calc (n₁ * d₂ + n₂ * d₁) * (b * d) = (n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm] ... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂] ... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm] end protected def neg : ℚ → ℚ | ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩ instance : has_neg ℚ := ⟨rat.neg⟩ @[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b := begin by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, show rat.mk' _ _ _ _ = _, rw num_denom', have d0 := ne_of_gt (int.coe_nat_lt.2 h₁), apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha, simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁] end protected def mul : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_mul ℚ := ⟨rat.mul⟩ @[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : (a /. b) * (c /. d) = (a * c) /. (b * d) := begin apply lift_binop_eq rat.mul; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, cc end protected def inv : ℚ → ℚ | ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩ | ⟨0, d, h, c⟩ := 0 | ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩ instance : has_inv ℚ := ⟨rat.inv⟩ @[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a := begin by_cases a0 : a = 0, { subst a0, simp, refl }, by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha, refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _, { cases n with n; [cases n with n, skip], { refl }, { change int.of_nat n.succ with (n+1:ℕ), unfold rat.inv, rw num_denom' }, { unfold rat.inv, rw num_denom', refl } }, have n0 : n ≠ 0, { refine mt (λ (n0 : n = 0), _) a0, subst n0, simp at ha, exact (mk_eq_zero b0).1 ha }, have d0 := ne_of_gt (int.coe_nat_lt.2 h), have ha := (mk_eq b0 d0).1 ha, apply (mk_eq n0 a0).2, cc end variables (a b c : ℚ) protected theorem add_zero : a + 0 = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem zero_add : 0 + a = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem add_comm : a + b = b + a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂]; cc protected theorem add_assoc : a + b + c = a + (b + c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm, add_assoc] protected theorem add_left_neg : -a + a = 0 := num_denom_cases_on' a $ λ n d h, by simp [h] protected theorem mul_one : a * 1 = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem one_mul : 1 * a = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem mul_comm : a * b = b * a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂, mul_comm] protected theorem mul_assoc : a * b * c = a * (b * c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm] protected theorem add_mul : (a + b) * c = a * c + b * c := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero]; refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _; simp [mul_add, mul_comm, mul_assoc, mul_left_comm] protected theorem mul_add : a * (b + c) = a * b + a * c := by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a] protected theorem zero_ne_one : 0 ≠ (1:ℚ) := mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 := num_denom_cases_on' a $ λ n d h a0, have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0, by simp [h, n0, mul_comm]; exact eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0) protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 := eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h) instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance instance : field ℚ := { zero := 0, add := rat.add, neg := rat.neg, one := 1, mul := rat.mul, inv := rat.inv, zero_add := rat.zero_add, add_zero := rat.add_zero, add_comm := rat.add_comm, add_assoc := rat.add_assoc, add_left_neg := rat.add_left_neg, mul_one := rat.mul_one, one_mul := rat.one_mul, mul_comm := rat.mul_comm, mul_assoc := rat.mul_assoc, left_distrib := rat.mul_add, right_distrib := rat.add_mul, exists_pair_ne := ⟨0, 1, rat.zero_ne_one⟩, mul_inv_cancel := rat.mul_inv_cancel, inv_zero := rfl } /- Extra instances to short-circuit type class resolution -/ instance : division_ring ℚ := by apply_instance instance : integral_domain ℚ := by apply_instance -- TODO(Mario): this instance slows down data.real.basic --instance : domain ℚ := by apply_instance instance : nontrivial ℚ := by apply_instance instance : comm_ring ℚ := by apply_instance --instance : ring ℚ := by apply_instance instance : comm_semiring ℚ := by apply_instance instance : semiring ℚ := by apply_instance instance : add_comm_group ℚ := by apply_instance instance : add_group ℚ := by apply_instance instance : add_comm_monoid ℚ := by apply_instance instance : add_monoid ℚ := by apply_instance instance : add_left_cancel_semigroup ℚ := by apply_instance instance : add_right_cancel_semigroup ℚ := by apply_instance instance : add_comm_semigroup ℚ := by apply_instance instance : add_semigroup ℚ := by apply_instance instance : comm_monoid ℚ := by apply_instance instance : monoid ℚ := by apply_instance instance : comm_semigroup ℚ := by apply_instance instance : semigroup ℚ := by apply_instance theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b - c /. d = (a * d - c * b) /. (b * d) := by simp [b0, d0, sub_eq_add_neg] @[simp] lemma denom_neg_eq_denom : ∀ q : ℚ, (-q).denom = q.denom | ⟨_, d, _, _⟩ := rfl @[simp] lemma num_neg_eq_neg_num : ∀ q : ℚ, (-q).num = -(q.num) | ⟨n, _, _, _⟩ := rfl @[simp] lemma num_zero : rat.num 0 = 0 := rfl lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 := have q = q.num /. q.denom, from num_denom.symm, by simpa [hq] lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 := ⟨λ _, by simp *, zero_of_num_zero⟩ lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 := assume : q.num = 0, h $ zero_of_num_zero this @[simp] lemma num_one : (1 : ℚ).num = 1 := rfl @[simp] lemma denom_one : (1 : ℚ).denom = 1 := rfl lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 := ne_of_gt q.pos lemma eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.denom = q.num * p.denom := begin conv_lhs { rw [←(@num_denom p), ←(@num_denom q)] }, apply rat.mk_eq, { exact_mod_cast p.denom_ne_zero }, { exact_mod_cast q.denom_ne_zero } end lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 := assume : n = 0, hq $ by simpa [this] using hqnd lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 := assume : d = 0, hq $ by simpa [this] using hqnd lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 := assume : n /. d = 0, h $ (mk_eq_zero hd).1 this lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) := have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa, have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa, suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom), by simpa using this, by simp [mul_def hq' hr', -num_denom] lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) := if hr : r.num = 0 then have hr' : r = 0, from zero_of_num_zero hr, by simp * else calc q / r = q * r⁻¹ : div_eq_mul_inv ... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by simp ... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def ... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) : ∃ c : ℤ, n = c * q.num ∧ d = c * q.denom := have hq : q ≠ 0, from assume : q = 0, hn $ (rat.mk_eq_zero hd).1 (by cc), have q.num /. q.denom = n /. d, by rwa [num_denom], have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this, begin existsi n / q.num, have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end, split, { rw int.div_mul_cancel hqdn }, { apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left, { apply rat.num_ne_zero_of_ne_zero hq }, repeat { assumption } } end theorem mk_pnat_num (n : ℤ) (d : ℕ+) : (mk_pnat n d).num = n / nat.gcd n.nat_abs d := by cases d; refl theorem mk_pnat_denom (n : ℤ) (d : ℕ+) : (mk_pnat n d).denom = d / nat.gcd n.nat_abs d := by cases d; refl theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num = (q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom = (q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num := by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom := by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) lemma add_num_denom (q r : ℚ) : q + r = ((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) := have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3, have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3, by conv_lhs { rw [←@num_denom q, ←@num_denom r, rat.add_def hqd hrd] }; simp [mul_comm] section casts theorem coe_int_eq_mk : ∀ (z : ℤ), ↑z = z /. 1 | (n : ℕ) := show (n:ℚ) = n /. 1, by induction n with n IH n; simp [*, show (1:ℚ) = 1 /. 1, from rfl] | -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin induction n with n IH, {refl}, show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1, rw [neg_add, IH], simpa [show -1 = (-1) /. 1, from rfl] end theorem mk_eq_div (n d : ℤ) : n /. d = ((n : ℚ) / d) := begin by_cases d0 : d = 0, {simp [d0, div_zero]}, simp [division_def, coe_int_eq_mk, mul_def one_ne_zero d0] end theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z := (coe_int_eq_mk z).trans (of_int_eq_mk z).symm @[simp, norm_cast] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n := by rw coe_int_eq_of_int; refl @[simp, norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 := by rw coe_int_eq_of_int; refl lemma coe_int_num_of_denom_eq_one {q : ℚ} (hq : q.denom = 1) : ↑(q.num) = q := by { conv_rhs { rw [←(@num_denom q), hq] }, rw [coe_int_eq_mk], refl } instance : can_lift ℚ ℤ := ⟨coe, λ q, q.denom = 1, λ q hq, ⟨q.num, coe_int_num_of_denom_eq_one hq⟩⟩ theorem coe_nat_eq_mk (n : ℕ) : ↑n = n /. 1 := by rw [← int.cast_coe_nat, coe_int_eq_mk] @[simp, norm_cast] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n := by rw [← int.cast_coe_nat, coe_int_num] @[simp, norm_cast] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 := by rw [← int.cast_coe_nat, coe_int_denom] -- Will be subsumed by `int.coe_inj` after we have defined -- `discrete_linear_ordered_field ℚ` (which implies characteristic zero). lemma coe_int_inj (m n : ℤ) : (m : ℚ) = n ↔ m = n := ⟨λ h, by simpa using congr_arg num h, congr_arg _⟩ end casts lemma inv_def' {q : ℚ} : q⁻¹ = (q.denom : ℚ) / q.num := by { conv_lhs { rw ←(@num_denom q) }, cases q, simp [div_num_denom] } @[simp] lemma mul_denom_eq_num {q : ℚ} : q * q.denom = q.num := begin suffices : mk (q.num) ↑(q.denom) * mk ↑(q.denom) 1 = mk (q.num) 1, by { conv { for q [1] { rw ←(@num_denom q) }}, rwa [coe_int_eq_mk, coe_nat_eq_mk] }, have : (q.denom : ℤ) ≠ 0, from ne_of_gt (by exact_mod_cast q.pos), rw [(rat.mul_def this one_ne_zero), (mul_comm (q.denom : ℤ) 1), (div_mk_div_cancel_left this)] end lemma denom_div_cast_eq_one_iff (m n : ℤ) (hn : n ≠ 0) : ((m : ℚ) / n).denom = 1 ↔ n ∣ m := begin replace hn : (n:ℚ) ≠ 0, by rwa [ne.def, ← int.cast_zero, coe_int_inj], split, { intro h, lift ((m : ℚ) / n) to ℤ using h with k hk, use k, rwa [eq_div_iff_mul_eq hn, ← int.cast_mul, mul_comm, eq_comm, coe_int_inj] at hk }, { rintros ⟨d, rfl⟩, rw [int.cast_mul, mul_comm, mul_div_cancel _ hn, rat.coe_int_denom] } end lemma num_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) : (a / b : ℚ).num = a := begin lift b to ℕ using le_of_lt hb0, norm_cast at hb0 h, rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_num, pnat.mk_coe, h.gcd_eq_one, int.coe_nat_one, int.div_one] end lemma denom_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) : ((a / b : ℚ).denom : ℤ) = b := begin lift b to ℕ using le_of_lt hb0, norm_cast at hb0 h, rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_denom, pnat.mk_coe, h.gcd_eq_one, nat.div_one] end lemma div_int_inj {a b c d : ℤ} (hb0 : 0 < b) (hd0 : 0 < d) (h1 : nat.coprime a.nat_abs b.nat_abs) (h2 : nat.coprime c.nat_abs d.nat_abs) (h : (a : ℚ) / b = (c : ℚ) / d) : a = c ∧ b = d := begin apply and.intro, { rw [← (num_div_eq_of_coprime hb0 h1), h, num_div_eq_of_coprime hd0 h2] }, { rw [← (denom_div_eq_of_coprime hb0 h1), h, denom_div_eq_of_coprime hd0 h2] } end @[norm_cast] lemma coe_int_div_self (n : ℤ) : ((n / n : ℤ) : ℚ) = n / n := begin by_cases hn : n = 0, { subst hn, simp only [int.cast_zero, euclidean_domain.zero_div] }, { have : (n : ℚ) ≠ 0, { rwa ← coe_int_inj at hn }, simp only [int.div_self hn, int.cast_one, ne.def, not_false_iff, div_self this] } end @[norm_cast] lemma coe_nat_div_self (n : ℕ) : ((n / n : ℕ) : ℚ) = n / n := coe_int_div_self n lemma coe_int_div (a b : ℤ) (h : b ∣ a) : ((a / b : ℤ) : ℚ) = a / b := begin rcases h with ⟨c, rfl⟩, simp only [mul_comm b, int.mul_div_assoc c (dvd_refl b), int.cast_mul, mul_div_assoc, coe_int_div_self] end lemma coe_nat_div (a b : ℕ) (h : b ∣ a) : ((a / b : ℕ) : ℚ) = a / b := begin rcases h with ⟨c, rfl⟩, simp only [mul_comm b, nat.mul_div_assoc c (dvd_refl b), nat.cast_mul, mul_div_assoc, coe_nat_div_self] end protected lemma «forall» {p : ℚ → Prop} : (∀ r, p r) ↔ ∀ a b : ℤ, p (a / b) := ⟨λ h _ _, h _, λ h q, (show q = q.num / q.denom, from by simp [rat.div_num_denom]).symm ▸ (h q.1 q.2)⟩ protected lemma «exists» {p : ℚ → Prop} : (∃ r, p r) ↔ ∃ a b : ℤ, p (a / b) := ⟨λ ⟨r, hr⟩, ⟨r.num, r.denom, by rwa [← mk_eq_div, num_denom]⟩, λ ⟨a, b, h⟩, ⟨_, h⟩⟩ end rat
7e62e61e9a9e83859f76dd9040bdf94111e863ce
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/ideal/over.lean
ee5834597559e2dbc691ac556ebdace17813cc5c
[ "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
17,915
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 ring_theory.algebraic import ring_theory.localization.at_prime import ring_theory.localization.integral /-! # Ideals over/under ideals This file concerns ideals lying over other ideals. Let `f : R →+* S` be a ring homomorphism (typically a ring extension), `I` an ideal of `R` and `J` an ideal of `S`. We say `J` lies over `I` (and `I` under `J`) if `I` is the `f`-preimage of `J`. This is expressed here by writing `I = J.comap f`. ## Implementation notes The proofs of the `comap_ne_bot` and `comap_lt_comap` families use an approach specific for their situation: we construct an element in `I.comap f` from the coefficients of a minimal polynomial. Once mathlib has more material on the localization at a prime ideal, the results can be proven using more general going-up/going-down theory. -/ variables {R : Type*} [comm_ring R] namespace ideal open polynomial open_locale polynomial open submodule section comm_ring variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma coeff_zero_mem_comap_of_root_mem_of_eval_mem {r : S} (hr : r ∈ I) {p : R[X]} (hp : p.eval₂ f r ∈ I) : p.coeff 0 ∈ I.comap f := begin rw [←p.div_X_mul_X_add, eval₂_add, eval₂_C, eval₂_mul, eval₂_X] at hp, refine mem_comap.mpr ((I.add_mem_iff_right _).mp hp), exact I.mul_mem_left _ hr end lemma coeff_zero_mem_comap_of_root_mem {r : S} (hr : r ∈ I) {p : R[X]} (hp : p.eval₂ f r = 0) : p.coeff 0 ∈ I.comap f := coeff_zero_mem_comap_of_root_mem_of_eval_mem hr (hp.symm ▸ I.zero_mem) lemma exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem {r : S} (r_non_zero_divisor : ∀ {x}, x * r = 0 → x = 0) (hr : r ∈ I) {p : R[X]} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := begin refine p.rec_on_horner _ _ _, { intro h, contradiction }, { intros p a coeff_eq_zero a_ne_zero ih p_ne_zero hp, refine ⟨0, _, coeff_zero_mem_comap_of_root_mem hr hp⟩, simp [coeff_eq_zero, a_ne_zero] }, { intros p p_nonzero ih mul_nonzero hp, rw [eval₂_mul, eval₂_X] at hp, obtain ⟨i, hi, mem⟩ := ih p_nonzero (r_non_zero_divisor hp), refine ⟨i + 1, _, _⟩; simp [hi, mem] } end /-- Let `P` be an ideal in `R[x]`. The map `R[x]/P → (R / (P ∩ R))[x] / (P / (P ∩ R))` is injective. -/ lemma injective_quotient_le_comap_map (P : ideal R[X]) : function.injective ((map (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) P).quotient_map (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) le_comap_map) := begin refine quotient_map_injective' (le_of_eq _), rw comap_map_of_surjective (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) (map_surjective (quotient.mk (P.comap (C : R →+* R[X]))) quotient.mk_surjective), refine le_antisymm (sup_le le_rfl _) (le_sup_of_le_left le_rfl), refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _), simpa only [coeff_map, coe_map_ring_hom] using ext_iff.mp (ideal.mem_bot.mp (mem_comap.mp hp)) n, end /-- The identity in this lemma asserts that the "obvious" square ``` R → (R / (P ∩ R)) ↓ ↓ R[x] / P → (R / (P ∩ R))[x] / (P / (P ∩ R)) ``` commutes. It is used, for instance, in the proof of `quotient_mk_comp_C_is_integral_of_jacobson`, in the file `ring_theory/jacobson`. -/ lemma quotient_mk_maps_eq (P : ideal R[X]) : ((quotient.mk (map (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) P)).comp C).comp (quotient.mk (P.comap (C : R →+* R[X]))) = ((map (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) P).quotient_map (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) le_comap_map).comp ((quotient.mk P).comp C) := begin refine ring_hom.ext (λ x, _), repeat { rw [ring_hom.coe_comp, function.comp_app] }, rw [quotient_map_mk, coe_map_ring_hom, map_C], end /-- This technical lemma asserts the existence of a polynomial `p` in an ideal `P ⊂ R[x]` that is non-zero in the quotient `R / (P ∩ R) [x]`. The assumptions are equivalent to `P ≠ 0` and `P ∩ R = (0)`. -/ lemma exists_nonzero_mem_of_ne_bot {P : ideal R[X]} (Pb : P ≠ ⊥) (hP : ∀ (x : R), C x ∈ P → x = 0) : ∃ p : R[X], p ∈ P ∧ (polynomial.map (quotient.mk (P.comap (C : R →+* R[X]))) p) ≠ 0 := begin obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr Pb), refine ⟨m, submodule.coe_mem m, λ pp0, hm (submodule.coe_eq_zero.mp _)⟩, refine (injective_iff_map_eq_zero (polynomial.map_ring_hom (quotient.mk (P.comap (C : R →+* R[X]))))).mp _ _ pp0, refine map_injective _ ((quotient.mk (P.comap C)).injective_iff_ker_eq_bot.mpr _), rw [mk_ker], exact (submodule.eq_bot_iff _).mpr (λ x hx, hP x (mem_comap.mp hx)), end variables {p : ideal R} {P : ideal S} /-- If there is an injective map `R/p → S/P` such that following diagram commutes: ``` R → S ↓ ↓ R/p → S/P ``` then `P` lies over `p`. -/ lemma comap_eq_of_scalar_tower_quotient [algebra R S] [algebra (R ⧸ p) (S ⧸ P)] [is_scalar_tower R (R ⧸ p) (S ⧸ P)] (h : function.injective (algebra_map (R ⧸ p) (S ⧸ P))) : comap (algebra_map R S) P = p := begin ext x, split; rw [mem_comap, ← quotient.eq_zero_iff_mem, ← quotient.eq_zero_iff_mem, quotient.mk_algebra_map, is_scalar_tower.algebra_map_apply _ (R ⧸ p), quotient.algebra_map_eq], { intro hx, exact (injective_iff_map_eq_zero (algebra_map (R ⧸ p) (S ⧸ P))).mp h _ hx }, { intro hx, rw [hx, ring_hom.map_zero] }, end /-- If `P` lies over `p`, then `R / p` has a canonical map to `S / P`. -/ def quotient.algebra_quotient_of_le_comap (h : p ≤ comap f P) : algebra (R ⧸ p) (S ⧸ P) := ring_hom.to_algebra $ quotient_map _ f h /-- `R / p` has a canonical map to `S / pS`. -/ instance quotient.algebra_quotient_map_quotient : algebra (R ⧸ p) (S ⧸ map f p) := by exact quotient.algebra_quotient_of_le_comap le_comap_map @[simp] lemma quotient.algebra_map_quotient_map_quotient (x : R) : algebra_map (R ⧸ p) (S ⧸ map f p) (quotient.mk p x) = quotient.mk _ (f x) := rfl @[simp] lemma quotient.mk_smul_mk_quotient_map_quotient (x : R) (y : S) : quotient.mk p x • quotient.mk (map f p) y = quotient.mk _ (f x * y) := rfl instance quotient.tower_quotient_map_quotient [algebra R S] : is_scalar_tower R (R ⧸ p) (S ⧸ map (algebra_map R S) p) := is_scalar_tower.of_algebra_map_eq $ λ x, by rw [quotient.algebra_map_eq, quotient.algebra_map_quotient_map_quotient, quotient.mk_algebra_map] instance quotient_map_quotient.is_noetherian [algebra R S] [is_noetherian R S] (I : ideal R) : is_noetherian (R ⧸ I) (S ⧸ ideal.map (algebra_map R S) I) := is_noetherian_of_tower R $ is_noetherian_of_surjective S (ideal.quotient.mkₐ R _).to_linear_map $ linear_map.range_eq_top.mpr ideal.quotient.mk_surjective end comm_ring section is_domain variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma exists_coeff_ne_zero_mem_comap_of_root_mem [is_domain S] {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : R[X]} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem (λ _ h, or.resolve_right (mul_eq_zero.mp h) r_ne_zero) hr lemma exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff [is_prime I] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : R[X]} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hpI : p.eval₂ f r ∈ I) : ∃ i, p.coeff i ∈ (J.comap f : set R) \ (I.comap f) := begin obtain ⟨hrJ, hrI⟩ := hr, have rbar_ne_zero : quotient.mk I r ≠ 0 := mt (quotient.mk_eq_zero I).mp hrI, have rbar_mem_J : quotient.mk I r ∈ J.map (quotient.mk I) := mem_map_of_mem _ hrJ, have quotient_f : ∀ x ∈ I.comap f, (quotient.mk I).comp f x = 0, { simp [quotient.eq_zero_iff_mem] }, have rbar_root : (p.map (quotient.mk (I.comap f))).eval₂ (quotient.lift (I.comap f) _ quotient_f) (quotient.mk I r) = 0, { convert quotient.eq_zero_iff_mem.mpr hpI, exact trans (eval₂_map _ _ _) (hom_eval₂ p f (quotient.mk I) r).symm }, obtain ⟨i, ne_zero, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem rbar_ne_zero rbar_mem_J p_ne_zero rbar_root, rw coeff_map at ne_zero mem, refine ⟨i, (mem_quotient_iff_mem hIJ).mp _, mt _ ne_zero⟩, { simpa using mem }, simp [quotient.eq_zero_iff_mem], end lemma comap_lt_comap_of_root_mem_sdiff [I.is_prime] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : R[X]} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hp : p.eval₂ f r ∈ I) : I.comap f < J.comap f := let ⟨i, hJ, hI⟩ := exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff hIJ hr p_ne_zero hp in set_like.lt_iff_le_and_exists.mpr ⟨comap_mono hIJ, p.coeff i, hJ, hI⟩ lemma mem_of_one_mem (h : (1 : S) ∈ I) (x) : x ∈ I := (I.eq_top_iff_one.mpr h).symm ▸ mem_top lemma comap_lt_comap_of_integral_mem_sdiff [algebra R S] [hI : I.is_prime] (hIJ : I ≤ J) {x : S} (mem : x ∈ (J : set S) \ I) (integral : is_integral R x) : I.comap (algebra_map R S) < J.comap (algebra_map R S) := begin obtain ⟨p, p_monic, hpx⟩ := integral, refine comap_lt_comap_of_root_mem_sdiff hIJ mem _ _, swap, { apply map_monic_ne_zero p_monic, apply quotient.nontrivial, apply mt comap_eq_top_iff.mp, apply hI.1 }, convert I.zero_mem end lemma comap_ne_bot_of_root_mem [is_domain S] {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : R[X]} (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0) : I.comap f ≠ ⊥ := λ h, let ⟨i, hi, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem r_ne_zero hr p_ne_zero hp in absurd (mem_bot.mp (eq_bot_iff.mp h mem)) hi lemma is_maximal_of_is_integral_of_is_maximal_comap [algebra R S] (hRS : algebra.is_integral R S) (I : ideal S) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R S))) : is_maximal I := ⟨⟨mt comap_eq_top_iff.mpr hI.1.1, λ J I_lt_J, let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_eq_top_iff.1 $ hI.1.2 _ (comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (hRS x))⟩⟩ lemma is_maximal_of_is_integral_of_is_maximal_comap' (f : R →+* S) (hf : f.is_integral) (I : ideal S) [hI' : I.is_prime] (hI : is_maximal (I.comap f)) : is_maximal I := @is_maximal_of_is_integral_of_is_maximal_comap R _ S _ f.to_algebra hf I hI' hI variables [algebra R S] lemma comap_ne_bot_of_algebraic_mem [is_domain S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_algebraic R x) : I.comap (algebra_map R S) ≠ ⊥ := let ⟨p, p_ne_zero, hp⟩ := hx in comap_ne_bot_of_root_mem x_ne_zero x_mem p_ne_zero hp lemma comap_ne_bot_of_integral_mem [nontrivial R] [is_domain S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_integral R x) : I.comap (algebra_map R S) ≠ ⊥ := comap_ne_bot_of_algebraic_mem x_ne_zero x_mem (hx.is_algebraic R) lemma eq_bot_of_comap_eq_bot [nontrivial R] [is_domain S] (hRS : algebra.is_integral R S) (hI : I.comap (algebra_map R S) = ⊥) : I = ⊥ := begin refine eq_bot_iff.2 (λ x hx, _), by_cases hx0 : x = 0, { exact hx0.symm ▸ ideal.zero_mem ⊥ }, { exact absurd hI (comap_ne_bot_of_integral_mem hx0 hx (hRS x)) } end lemma is_maximal_comap_of_is_integral_of_is_maximal (hRS : algebra.is_integral R S) (I : ideal S) [hI : I.is_maximal] : is_maximal (I.comap (algebra_map R S)) := begin refine quotient.maximal_of_is_field _ _, haveI : is_prime (I.comap (algebra_map R S)) := comap_is_prime _ _, exact is_field_of_is_integral_of_is_field (is_integral_quotient_of_is_integral hRS) algebra_map_quotient_injective (by rwa ← quotient.maximal_ideal_iff_is_field_quotient), end lemma is_maximal_comap_of_is_integral_of_is_maximal' {R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) (hf : f.is_integral) (I : ideal S) (hI : I.is_maximal) : is_maximal (I.comap f) := @is_maximal_comap_of_is_integral_of_is_maximal R _ S _ f.to_algebra hf I hI section is_integral_closure variables (S) {A : Type*} [comm_ring A] variables [algebra R A] [algebra A S] [is_scalar_tower R A S] [is_integral_closure A R S] lemma is_integral_closure.comap_lt_comap {I J : ideal A} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R A) < J.comap (algebra_map R A) := let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (is_integral_closure.is_integral R S x) lemma is_integral_closure.is_maximal_of_is_maximal_comap (I : ideal A) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R A))) : is_maximal I := is_maximal_of_is_integral_of_is_maximal_comap (λ x, is_integral_closure.is_integral R S x) I hI variables [is_domain A] lemma is_integral_closure.comap_ne_bot [nontrivial R] {I : ideal A} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R A) ≠ ⊥ := let ⟨x, x_mem, x_ne_zero⟩ := I.ne_bot_iff.mp I_ne_bot in comap_ne_bot_of_integral_mem x_ne_zero x_mem (is_integral_closure.is_integral R S x) lemma is_integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal A} : I.comap (algebra_map R A) = ⊥ → I = ⊥ := imp_of_not_imp_not _ _ (is_integral_closure.comap_ne_bot S) end is_integral_closure lemma integral_closure.comap_lt_comap {I J : ideal (integral_closure R S)} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R (integral_closure R S)) < J.comap (algebra_map R (integral_closure R S)) := is_integral_closure.comap_lt_comap S I_lt_J lemma integral_closure.is_maximal_of_is_maximal_comap (I : ideal (integral_closure R S)) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R (integral_closure R S)))) : is_maximal I := is_integral_closure.is_maximal_of_is_maximal_comap S I hI section variables [is_domain S] lemma integral_closure.comap_ne_bot [nontrivial R] {I : ideal (integral_closure R S)} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R (integral_closure R S)) ≠ ⊥ := is_integral_closure.comap_ne_bot S I_ne_bot lemma integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal (integral_closure R S)} : I.comap (algebra_map R (integral_closure R S)) = ⊥ → I = ⊥ := is_integral_closure.eq_bot_of_comap_eq_bot S /-- `comap (algebra_map R S)` is a surjection from the prime spec of `R` to prime spec of `S`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_prime_of_is_integral' (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_prime Q ∧ Q.comap (algebra_map R S) = P := begin have hP0 : (0 : S) ∉ algebra.algebra_map_submonoid S P.prime_compl, { rintro ⟨x, ⟨hx, x0⟩⟩, exact absurd (hP x0) hx }, let Rₚ := localization P.prime_compl, let Sₚ := localization (algebra.algebra_map_submonoid S P.prime_compl), letI : is_domain (localization (algebra.algebra_map_submonoid S P.prime_compl)) := is_localization.is_domain_localization (le_non_zero_divisors_of_no_zero_divisors hP0), obtain ⟨Qₚ : ideal Sₚ, Qₚ_maximal⟩ := exists_maximal Sₚ, haveI Qₚ_max : is_maximal (comap _ Qₚ) := @is_maximal_comap_of_is_integral_of_is_maximal Rₚ _ Sₚ _ (localization_algebra P.prime_compl S) (is_integral_localization H) _ Qₚ_maximal, refine ⟨comap (algebra_map S Sₚ) Qₚ, ⟨comap_is_prime _ Qₚ, _⟩⟩, convert localization.at_prime.comap_maximal_ideal, rw [comap_comap, ← local_ring.eq_maximal_ideal Qₚ_max, ← is_localization.map_comp _], refl end end /-- More general going-up theorem than `exists_ideal_over_prime_of_is_integral'`. TODO: Version of going-up theorem with arbitrary length chains (by induction on this)? Not sure how best to write an ascending chain in Lean -/ theorem exists_ideal_over_prime_of_is_integral (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (I : ideal S) [is_prime I] (hIP : I.comap (algebra_map R S) ≤ P) : ∃ Q ≥ I, is_prime Q ∧ Q.comap (algebra_map R S) = P := begin let quot := (R ⧸ I.comap (algebra_map R S)), obtain ⟨Q' : ideal (S ⧸ I), ⟨Q'_prime, hQ'⟩⟩ := @exists_ideal_over_prime_of_is_integral' quot _ (S ⧸ I) _ ideal.quotient_algebra _ (is_integral_quotient_of_is_integral H) (map (quotient.mk (I.comap (algebra_map R S))) P) (map_is_prime_of_surjective quotient.mk_surjective (by simp [hIP])) (le_trans (le_of_eq ((ring_hom.injective_iff_ker_eq_bot _).1 algebra_map_quotient_injective)) bot_le), haveI := Q'_prime, refine ⟨Q'.comap _, le_trans (le_of_eq mk_ker.symm) (ker_le_comap _), ⟨comap_is_prime _ Q', _⟩⟩, rw comap_comap, refine trans _ (trans (congr_arg (comap (quotient.mk (comap (algebra_map R S) I))) hQ') _), { simpa [comap_comap] }, { refine trans (comap_map_of_surjective _ quotient.mk_surjective _) (sup_eq_left.2 _), simpa [← ring_hom.ker_eq_comap_bot] using hIP}, end /-- `comap (algebra_map R S)` is a surjection from the max spec of `S` to max spec of `R`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_maximal_of_is_integral [is_domain S] (H : algebra.is_integral R S) (P : ideal R) [P_max : is_maximal P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_maximal Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q, ⟨Q_prime, hQ⟩⟩ := exists_ideal_over_prime_of_is_integral' H P hP, haveI : Q.is_prime := Q_prime, exact ⟨Q, is_maximal_of_is_integral_of_is_maximal_comap H _ (hQ.symm ▸ P_max), hQ⟩, end end is_domain end ideal
e932b14fbe87ebc769c42191b0e849ea8553e764
586535ff9853f5b85dc5fdeb5b78f1ad2d573a6e
/src/ast.lean
1013885ea4c1890bbc2cc03bc7d768b6a1ee8135
[ "Apache-2.0" ]
permissive
Kha/rc-correctness
fede4ae228c5f04985cf332e718a5a433230b150
be5a521f1b0528ccbc685619b265cd11ea854edf
refs/heads/master
1,595,967,325,275
1,568,889,756,000
1,568,889,756,000
209,523,947
0
0
Apache-2.0
1,568,888,337,000
1,568,888,336,000
null
UTF-8
Lean
false
false
4,710
lean
import util namespace rc_correctness -- ast defs def var := ℕ def const := ℕ def cnstr := ℕ inductive expr : Type | const_app_full (c : const) (ys : list var) : expr | const_app_part (c : const) (ys : list var) : expr | var_app (x : var) (y : var) : expr | ctor (i : cnstr) (ys : list var) : expr | proj (i : cnstr) (x : var) : expr | reset (x : var) : expr | reuse (x : var) (i : cnstr) (ys : list var) : expr inductive fn_body : Type | ret (x : var) : fn_body | «let» (x : var) (e : expr) (F : fn_body) : fn_body | case (x : var) (Fs : list fn_body) : fn_body | inc (x : var) (F : fn_body) : fn_body | dec (x : var) (F : fn_body) : fn_body structure fn := (ys : list var) (F : fn_body) inductive rc : Type | var (x : var) : rc | const (c : const) : rc | expr (e : expr) : rc | fn_body (F : fn_body) : rc | fn (f : fn) : rc -- notation open rc_correctness.expr open rc_correctness.fn_body -- expr notation c `⟦` ys `…` `⟧` := expr.const_app_full c ys notation c `⟦` ys `…` `, ` `_` `⟧` := expr.const_app_part c ys notation x `⟦` y `⟧` := expr.var_app x y notation `⟪` ys `⟫` i := expr.ctor i ys notation x `[` i `]` := expr.proj i x notation `reuse ` x ` in ` `⟪` ys `⟫` i := expr.reuse x i ys -- fn_body notation x ` ≔ ` e `; ` F := fn_body.let x e F notation `case ` x ` of ` Fs := fn_body.case x Fs notation `inc ` x `; ` F := fn_body.inc x F notation `dec ` x `; ` F := fn_body.dec x F -- rc instance var_to_rc : has_coe var rc := ⟨rc.var⟩ instance const_to_rc : has_coe var rc := ⟨rc.const⟩ instance expr_to_rc : has_coe expr rc := ⟨rc.expr⟩ instance fn_body_to_rc : has_coe fn_body rc := ⟨rc.fn_body⟩ instance fn_to_rc : has_coe fn rc := ⟨rc.fn⟩ -- fn_body recursor, courtesy of Sebastian Ullrich def {l} fn_body.rec_wf (C : fn_body → Sort l) («ret» : Π (x : var), C (ret x)) («let» : Π (x : var) (e : expr) (F : fn_body) (F_ih : C F), C (x ≔ e; F)) («case» : Π (x : var) (Fs : list fn_body) (Fs_ih : ∀ F ∈ Fs, C F), C (case x of Fs)) («inc» : Π (x : var) (F : fn_body) (F_ih : C F), C (inc x; F)) («dec» : Π (x : var) (F : fn_body) (F_ih : C F), C (dec x; F)) : Π (x : fn_body), C x | (fn_body.ret a) := «ret» a | (x ≔ a; a_1) := «let» x a a_1 (fn_body.rec_wf a_1) | (case a of a_1) := «case» a a_1 (λ a h, have sizeof a < 1 + sizeof a_1, from nat.lt_add_left _ _ _ (list.sizeof_lt_sizeof_of_mem h), fn_body.rec_wf a) | (inc a; a_1) := «inc» a a_1 (fn_body.rec_wf a_1) | (dec a; a_1) := «dec» a a_1 (fn_body.rec_wf a_1) -- free variables def FV_expr : expr → finset var | (c⟦xs…⟧) := xs.to_finset | (c⟦xs…, _⟧) := xs.to_finset | (x⟦y⟧) := {x, y} | (⟪xs⟫i) := xs.to_finset | (x[i]) := {x} | (reset x) := {x} | (reuse x in ⟪xs⟫i) := insert x xs.to_finset def FV : fn_body → finset var | (ret x) := {x} | (x ≔ e; F) := FV_expr e ∪ ((FV F).erase x) | (case x of Fs) := insert x (finset.join (Fs.map_wf (λ F h, FV F))) | (inc x; F) := insert x (FV F) | (dec x; F) := insert x (FV F) -- var order local attribute [reducible] var abbreviation var_le : var → var → Prop := nat.le instance var_le_is_trans : is_trans var var_le := ⟨@nat.le_trans⟩ instance var_le_is_antisymm : is_antisymm var var_le := ⟨@nat.le_antisymm⟩ instance var_le_is_total : is_total var var_le := ⟨@nat.le_total⟩ local attribute [semireducible] var -- repr -- var local attribute [reducible] var instance var_has_repr : has_repr var := ⟨repr⟩ local attribute [semireducible] var -- const local attribute [reducible] const instance const_has_repr : has_repr const := ⟨repr⟩ local attribute [semireducible] const -- expr def expr_repr : expr → string | (c⟦ys…⟧) := c.repr ++ "⟦" ++ ys.repr ++ "…⟧" | (c⟦ys…, _⟧) := c.repr ++ "⟦" ++ ys.repr ++ "…, _⟧" | (x⟦y⟧) := x.repr ++ "⟦" ++ y.repr ++ "⟧" | (⟪ys⟫i) := "⟪" ++ ys.repr ++ "⟫" ++ i.repr | (x[i]) := x.repr ++ "[" ++ i.repr ++ "]" | (reset x) := "reset " ++ x.repr | (reuse x in ⟪ys⟫i) := "reuse " ++ x.repr ++ " in " ++ "⟪" ++ ys.repr ++ "⟫" ++ i.repr instance expr_has_repr : has_repr expr := ⟨expr_repr⟩ -- fn_body def fn_body_repr : fn_body → string | (ret x) := "ret " ++ x.repr | (x ≔ e; F) := x.repr ++ " ≔ " ++ repr e ++ "; " ++ fn_body_repr F | (case x of Fs) := "case " ++ x.repr ++ " of " ++ (Fs.map_wf (λ F h, fn_body_repr F)).repr | (inc x; F) := "inc " ++ x.repr ++ "; " ++ fn_body_repr F | (dec x; F) := "dec " ++ x.repr ++ "; " ++ fn_body_repr F instance fn_body_has_repr : has_repr fn_body := ⟨fn_body_repr⟩ end rc_correctness
f6b8aa0697c03e8a1badea8c982f1454648df7a7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/elabissues/typeclasses_with_preconditions.lean
1e06a7f75f8208cc654b168c5484930c7f76ebdc
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,217
lean
/- The current plan is to allow instances to have preconditions with registered tactics. Typeclass resolution will delay these proof obligations, effectively assuming that they will succeed. If typeclass resolution succeeds, it will return a list of (mvar, lctx) pairs to the elaborator, which will try to synthesize the proofs and throw a good error message if it fails. -/ class Foo (b : Bool) : Type class FooTrue (b : Bool) extends Foo b : Type := (H : b = true) /- This requires the tactic framework and auto_param. -/ -- @[instance] axiom CoeFooFooTrue (b : Bool) (H : b = true · refl) : HasCoe (Foo b) (FooTrue b) instance BoolToFoo (b : Bool) : Foo b := Foo.mk b def forceFooTrue (b : Bool) (fooTrue : FooTrue b) : Bool := b /- Should succeed (once CoeFooFooTrue can be written) -/ #check forceFooTrue true (Foo.mk true) /- Should fail (even after CoeFooFooTrue can be written -/ #check forceFooTrue false (Foo.mk false) /- This plan has one limitation, that has so far been deemed acceptable: it will not support classes with different instances depending on the provability of preconditions. The classic example is multiplying two elements of `ℤ/nℤ` where `n` is not prime. Here is a toy version of this problem: << @[class] axiom Prime (p : Nat) : Prop @[instance] axiom p2 : Prime 2 @[instance] axiom p3 : Prime 3 @[class] axiom Field : Type → Type @[class] axiom Ring : Type → Type @[instance] axiom FieldToDiv (α : Type) [Field α] : Div α @[instance] axiom FieldToMul (α : Type) [Field α] : Mul α @[instance] axiom RingToMul (α : Type) [Ring α] : Mul α axiom mkType : Nat → Type @[instance] axiom PrimeField (n : Nat) (Hp : Prime n · provePrimality) : Field (mkType n) @[instance] axiom NonPrimeRing (n : Nat) : Ring (mkType n) example (α β : mkType 4) : α * β = β * α >> The issue is that (depending on the order the instances are tried), the instance involving `FieldToMul` will succeed in typeclass resolution, but the proof will fail later on. I (@dselsam) still thinks this plan is a good compromise. For examples like this, the definition in question (i.e. `Prime`) can be made a class instead and taken as an inst-implicit argument to `PrimeField`. -/
d1a800fd92929d099d9767a79f9fc977e3cbe70a
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Util/CollectLevelParams.lean
667d80c92043f674dd9f7309523c80210db7c260
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
2,369
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.Expr namespace Lean namespace CollectLevelParams structure State where visitedLevel : LevelSet := {} visitedExpr : ExprSet := {} params : Array Name := #[] instance : Inhabited State := ⟨{}⟩ abbrev Visitor := State → State @[inline] def visitLevel (f : Level → Visitor) (u : Level) : Visitor := fun s => if !u.hasParam || s.visitedLevel.contains u then s else f u { s with visitedLevel := s.visitedLevel.insert u } partial def collect : Level → Visitor | Level.succ v _ => visitLevel collect v | Level.max u v _ => visitLevel collect v ∘ visitLevel collect u | Level.imax u v _ => visitLevel collect v ∘ visitLevel collect u | Level.param n _ => fun s => { s with params := s.params.push n } | _ => id @[inline] def visitExpr (f : Expr → Visitor) (e : Expr) : Visitor := fun s => if !e.hasLevelParam then s else if s.visitedExpr.contains e then s else f e { s with visitedExpr := s.visitedExpr.insert e } partial def main : Expr → Visitor | Expr.proj _ _ s _ => visitExpr main s | Expr.forallE _ d b _ => visitExpr main b ∘ visitExpr main d | Expr.lam _ d b _ => visitExpr main b ∘ visitExpr main d | Expr.letE _ t v b _ => visitExpr main b ∘ visitExpr main v ∘ visitExpr main t | Expr.app f a _ => visitExpr main a ∘ visitExpr main f | Expr.mdata _ b _ => visitExpr main b | Expr.const _ us _ => fun s => us.foldl (fun s u => visitLevel collect u s) s | Expr.sort u _ => visitLevel collect u | _ => id partial def State.getUnusedLevelParam (s : CollectLevelParams.State) (pre : Name := `v) : Level := let v := mkLevelParam pre; if s.visitedLevel.contains v then let rec loop (i : Nat) := let v := mkLevelParam (pre.appendIndexAfter i); if s.visitedLevel.contains v then loop (i+1) else v loop 1 else v end CollectLevelParams def collectLevelParams (s : CollectLevelParams.State) (e : Expr) : CollectLevelParams.State := CollectLevelParams.main e s def CollectLevelParams.State.collect (s : CollectLevelParams.State) (e : Expr) : CollectLevelParams.State := collectLevelParams s e end Lean
1241be4b0a723db8926b682e218e19d05febb7a3
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/meta7.lean
0d21f1c8ac08c714b1f925da5df53f20205c8e6a
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,181
lean
import Lean.Meta open Lean open Lean.Meta partial def fact : Nat → Nat | 0 => 1 | n+1 => (n+1)*fact n set_option trace.Meta.debug true set_option trace.Meta.check false def print (msg : MessageData) : MetaM Unit := trace! `Meta.debug msg def checkM (x : MetaM Bool) : MetaM Unit := unless (← x) do throwError "check failed" def ex (x_1 x_2 x_3 : Nat) : Nat × Nat := let x := fact (10 + x_1 + x_2 + x_3); let ty := Nat → Nat; let f : ty := fun x => x; let n := 20; let z := f 10; (let y : { v : Nat // v = n } := ⟨20, rfl⟩; y.1 + n + f x, z + 10) def tst1 : MetaM Unit := do print "----- tst1 -----"; let c ← getConstInfo `ex; lambdaTelescope c.value?.get! fun xs body => withTrackingZeta do check body; let ys ← getZetaFVarIds; let ys := ys.toList.map mkFVar; print ys; checkM $ pure $ ys.length == 2; let c ← mkAuxDefinitionFor `foo body; print c; check c; pure () #eval tst1 #print foo def tst2 : MetaM Unit := do print "----- tst2 -----"; let nat := mkConst `Nat; let t0 := mkApp (mkConst `IO) nat; let t := mkForall `_ BinderInfo.default nat t0; print t; check t; forallBoundedTelescope t (some 1) fun xs b => do print b; checkM $ pure $ xs.size == 1; checkM $ pure $ b == t0; pure () #eval tst2 def tst3 : MetaM Unit := do print "----- tst2 -----"; let nat := mkConst `Nat; let t0 := mkApp (mkConst `IO) nat; let t := t0; print t; check t; forallBoundedTelescope t (some 0) fun xs b => do print b; checkM $ pure $ xs.size == 0; checkM $ pure $ b == t0; pure () #eval tst3 def tst4 : MetaM Unit := do print "----- tst4 -----"; let nat := mkConst `Nat; withLocalDeclD `x nat fun x => withLocalDeclD `y nat fun y => do let m ← mkFreshExprMVar nat; print (← ppGoal m.mvarId!); let val ← mkAppM `Add.add #[mkNatLit 10, y]; let ⟨zId, nId, subst⟩ ← assertAfter m.mvarId! x.fvarId! `z nat val; print m; print (← ppGoal nId); withMVarContext nId do { print (subst.apply x ++ " " ++ subst.apply y ++ " " ++ mkFVar zId); assignExprMVar nId (← mkAppM `Add.add #[subst.apply x, mkFVar zId]); print (mkMVar nId) }; print m; let expected ← mkAppM `Add.add #[x, val]; checkM (isDefEq m expected); pure () #eval tst4 def tst5 : MetaM Unit := do print "----- tst5 -----"; let prop := mkSort levelZero; withLocalDeclD `p prop fun p => withLocalDeclD `q prop fun q => do withLocalDeclD `h₁ p fun h₁ => do let eq ← mkEq p q; withLocalDeclD `h₂ eq fun h₂ => do let m ← mkFreshExprMVar q; let r ← replaceLocalDecl m.mvarId! h₁.fvarId! q h₂; print (← ppGoal r.mvarId); assignExprMVar r.mvarId (mkFVar r.fvarId); print m; check m; pure () #eval tst5 def tst6 : MetaM Unit := do print "----- tst6 -----"; let nat := mkConst `Nat; withLocalDeclD `x nat fun x => withLocalDeclD `y nat fun y => do let m ← mkFreshExprMVar nat; print (← ppGoal m.mvarId!); let val ← mkAppM `Add.add #[mkNatLit 10, y]; let ⟨zId, nId, subst⟩ ← assertAfter m.mvarId! y.fvarId! `z nat val; print m; print (← ppGoal nId); withMVarContext nId do { print (subst.apply x ++ " " ++ subst.apply y ++ " " ++ mkFVar zId); assignExprMVar nId (← mkAppM `Add.add #[subst.apply x, mkFVar zId]); print (mkMVar nId) }; print m; let expected ← mkAppM `Add.add #[x, val]; checkM (isDefEq m expected); pure () #eval tst6 def tst7 : MetaM Unit := do print "----- tst7 -----"; let nat := mkConst `Nat; withLocalDeclD `x nat fun x => withLocalDeclD `y nat fun y => do let val ← mkAppM `Add.add #[x, y]; print val; let val := val.replaceFVars #[x, y] #[mkNatLit 0, mkNatLit 1]; print val; let expected ← mkAppM `Add.add #[mkNatLit 0, mkNatLit 1]; print expected; checkM (pure $ val == expected); pure () #eval tst7 def aux := [1, 2, 3].isEmpty def tst8 : MetaM Unit := do print "----- tst8 -----" let t := mkConst `aux let some t ← unfoldDefinition? t | throwError! "unexpected" let some t ← unfoldDefinition? t | throwError! "unexpected" print t let t ← whnfCore t print t pure () #eval tst8 def tst9 : MetaM Unit := do print "----- tst9 -----" let defInsts ← getDefaultInstances `OfNat print (toString defInsts) pure () #eval tst9
67f4be6e138886d4180bc5a800a6ddc45da6917c
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0908.lean
6446a48e580bc897cd88e9cf8a6b0a9517959dd3
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
44
lean
#check 2 #check (2 : ℕ) #check (2 : ℤ)
7f0ee9e98156b0cee46494610e233cd5c034f9ae
bdb33f8b7ea65f7705fc342a178508e2722eb851
/data/nat/pairing.lean
a96a256de8154d247113abf4ba562af7673123a9
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
2,500
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro Elegant pairing function. -/ import data.nat.sqrt open prod decidable namespace nat /-- Pairing function for the natural numbers. -/ def mkpair (a b : nat) : nat := if a < b then b*b + a else a*a + a + b /-- Unpairing function for the natural numbers. -/ def unpair (n : nat) : nat × nat := let s := sqrt n in if n - s*s < s then (n - s*s, s) else (s, n - s*s - s) theorem mkpair_unpair (n : nat) : mkpair (unpair n).1 (unpair n).2 = n := let s := sqrt n in begin dsimp [unpair], change sqrt n with s, have sm : s * s + (n - s * s) = n := nat.add_sub_cancel' (sqrt_le _), by_cases h : n - s * s < s; simp [h, mkpair], { exact sm }, { have hl : n - s*s - s ≤ s := nat.sub_le_left_of_le_add (nat.sub_le_left_of_le_add $ by rw ← add_assoc; apply sqrt_le_add), suffices : s * s + (s + (n - s * s - s)) = n, {simpa [not_lt_of_ge hl]}, rwa [nat.add_sub_cancel' (le_of_not_gt h)] } end theorem mkpair_unpair' {n a b} (H : unpair n = (a, b)) : mkpair a b = n := by simpa [H] using mkpair_unpair n theorem unpair_mkpair (a b : nat) : unpair (mkpair a b) = (a, b) := begin by_cases a < b; simp [h, mkpair], { show unpair (a + b * b) = (a, b), have be : sqrt (a + b * b) = b, { rw [add_comm, sqrt_add_eq], exact le_trans (le_of_lt h) (le_add_left _ _) }, simp [unpair, be, nat.add_sub_cancel, h] }, { show unpair (a + (b + a * a)) = (a, b), have ae : sqrt (a + (b + a * a)) = a, { rw [← add_assoc, add_comm, sqrt_add_eq], exact add_le_add_left (le_of_not_gt h) _ }, have : a ≤ a + (b + a * a) - a * a, { rw nat.add_sub_assoc (nat.le_add_left _ _), apply nat.le_add_right }, simp [unpair, ae, not_lt_of_ge this], show a + (b + a * a) - a * a - a = b, rw [nat.add_sub_assoc (nat.le_add_left _ _), nat.add_sub_cancel, nat.add_sub_cancel_left] } end theorem unpair_lt {n : nat} (n1 : n ≥ 1) : (unpair n).1 < n := let s := sqrt n in begin simp [unpair], change sqrt n with s, by_cases h : n - s * s < s; simp [h], { exact lt_of_lt_of_le h (sqrt_le_self _) }, { simp at h, have s0 : s > 0 := sqrt_pos.2 n1, exact lt_of_le_of_lt h (nat.sub_lt_self n1 (mul_pos s0 s0)) } end theorem unpair_le : ∀ (n : nat), (unpair n).1 ≤ n | 0 := dec_trivial | (n+1) := le_of_lt (unpair_lt (nat.succ_pos _)) end nat
9d129c6852e04d2e99d3a18abc10243ad2f5cbcc
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/casesUsing.lean
b7f2786e9c51b0e077f7af06c13278530307333c
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,248
lean
import Lean open Lean open Lean.Meta open Lean.Elab.Tactic universes u axiom elimEx (motive : Nat → Nat → Sort u) (x y : Nat) (diag : (a : Nat) → motive a a) (upper : (delta a : Nat) → motive a (a + delta.succ)) (lower : (delta a : Nat) → motive (a + delta.succ) a) : motive y x theorem ex1 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => apply Or.inl; apply Nat.leRefl | lower d => apply Or.inl; show p ≤ p + d.succ; admit | upper d => apply Or.inr; show q + d.succ > q; admit theorem ex2 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx case lower => admit case upper => admit case diag => apply Or.inl; apply Nat.leRefl axiom parityElim (motive : Nat → Sort u) (even : (n : Nat) → motive (2*n)) (odd : (n : Nat) → motive (2*n+1)) (n : Nat) : motive n theorem time2Eq (n : Nat) : 2*n = n + n := by rw Nat.mulComm show (0 + n) + n = n+n rw Nat.zeroAdd rfl theorem ex3 (n : Nat) : Exists (fun m => n = m + m ∨ n = m + m + 1) := by cases n using parityElim with | even i => apply Exists.intro i apply Or.inl rw time2Eq rfl | odd i => apply Exists.intro i apply Or.inr rw time2Eq rfl def ex4 {α} (xs : List α) (h : xs = [] → False) : α := by cases he:xs with | nil => apply False.elim; exact h he; done | cons x _ => exact x def ex5 {α} (xs : List α) (h : xs = [] → False) : α := by cases he:xs using List.casesOn with | nil => apply False.elim; exact h he; done | cons x _ => exact x theorem ex6 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false := match he:f xs with | true => False.elim (h₂ (h₁ he)) | false => rfl theorem ex7 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false := by cases he:f xs with | true => exact False.elim (h₂ (h₁ he)) | false => rfl theorem ex8 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false := by cases he:f xs using Bool.casesOn with | true => exact False.elim (h₂ (h₁ he)) | false => rfl theorem ex9 {α} (xs : List α) (h : xs = [] → False) : Nonempty α := by cases xs using List.rec with | nil => apply False.elim; apply h; rfl | cons x _ => apply Nonempty.intro; assumption theorem modLt (x : Nat) {y : Nat} (h : y > 0) : x % y < y := by induction x, y using Nat.mod.inductionOn generalizing h with | ind x y h₁ ih => rw [Nat.modEqSubMod h₁.2] exact ih h | base x y h₁ => match Iff.mp (Decidable.notAndIffOrNot ..) h₁ with | Or.inl h₁ => exact absurd h h₁ | Or.inr h₁ => have hgt := Nat.gtOfNotLe h₁ have heq := Nat.modEqOfLt hgt rw [← heq] at hgt assumption theorem ex11 {p q : Prop } (h : p ∨ q) : q ∨ p := by induction h using Or.casesOn with | inr h => ?myright | inl h => ?myleft case myleft => exact Or.inr h case myright => exact Or.inl h theorem ex12 {p q : Prop } (h : p ∨ q) : q ∨ p := by cases h using Or.casesOn with | inr h => ?myright | inl h => ?myleft case myleft => exact Or.inr h case myright => exact Or.inl h theorem ex13 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => ?hdiag | lower d => ?hlower | upper d => ?hupper case hdiag => apply Or.inl; apply Nat.leRefl case hlower => apply Or.inl; show p ≤ p + d.succ; admit case hupper => apply Or.inr; show q + d.succ > q; admit theorem ex14 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => ?hdiag | lower d => _ | upper d => ?hupper case hdiag => apply Or.inl; apply Nat.leRefl case lower => apply Or.inl; show p ≤ p + d.succ; admit case hupper => apply Or.inr; show q + d.succ > q; admit theorem ex15 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => ?hdiag | lower d => _ | upper d => ?hupper { apply Or.inl; apply Nat.leRefl } { apply Or.inr; show q + d.succ > q; admit } { apply Or.inl; show p ≤ p + d.succ; admit }
b44887cc096d292f89559d47390eeefc25c2b8db
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/IMO_2006_Pb_4.lean
8f3d05dc372c59f767fe0391f883c7c21f2c810a
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
322
lean
import data.pnat.basic import data.int.basic import data.real.basic import analysis.special_functions.exp_log import algebra.order.ring import algebra.ring.basic import tactic theorem IMO_2006_Pb_4 (a b: ℤ)(h:1+(2:ℝ)^a+(2:ℝ)^(2*a+1)=b^2): (a=0 ∧ (b= 2 ∨ b=-2))∨ (a=4∧ (b=23∨ b=-23)):= begin sorry end
a045772fea4d0f94c23326821a281f61a026db03
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/homotopy/cellcomplex.hlean
5ef55d2388bc4967635e8d8dbaa8a1814b609fde
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
1,700
hlean
/- Copyright (c) 2015 Ulrik Buchholtz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ulrik Buchholtz -/ import types.trunc homotopy.sphere hit.pushout open eq is_trunc is_equiv nat equiv trunc prod pushout sigma unit pointed -- where should this be? definition family : Type := ΣX, X → Type namespace cellcomplex /- define by recursion on ℕ both the type of fdccs of dimension n and the realization map fdcc n → Type in other words, we define a function fdcc : ℕ → family an alternative to the approach here (perhaps necessary) is to define relative cell complexes relative to a type A, and then use spherical indexing, so a -1-dimensional relative cell complex is just star : unit with realization A -/ definition fdcc_family [reducible] : ℕ → family := nat.rec -- a zero-dimensional cell complex is just an set -- with realization the identity map ⟨Set , λA, trunctype.carrier A⟩ (λn fdcc_family_n, -- sigma.rec (λ fdcc_n realize_n, /- a (succ n)-dimensional cell complex is a triple of an n-dimensional cell complex X, an set of (succ n)-cells A, and an attaching map f : A × sphere n → |X| -/ ⟨Σ X : pr1 fdcc_family_n , Σ A : Set, A × sphere n → pr2 fdcc_family_n X , /- the realization of such is the pushout of f with canonical map A × sphere n → unit -/ sigma.rec (λX , sigma.rec (λA f, pushout (λx , star) f)) ⟩) definition fdcc (n : ℕ) : Type := pr1 (fdcc_family n) definition cell : Πn, fdcc n → Set := nat.cases (λA, A) (λn T, pr1 (pr2 T)) end cellcomplex
40f2c5ab03d01390a764f63789ae4f95c851a409
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/ratfunc.lean
735db2340429fe862bee0b33bffe38a8b9510de1
[ "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
60,449
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.euclidean_domain import ring_theory.laurent_series import ring_theory.localization.fraction_ring import ring_theory.polynomial.content /-! # The field of rational functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the field `ratfunc K` of rational functions over a field `K`, and shows it is the field of fractions of `K[X]`. ## Main definitions Working with rational functions as polynomials: - `ratfunc.field` provides a field structure - `ratfunc.C` is the constant polynomial - `ratfunc.X` is the indeterminate - `ratfunc.eval` evaluates a rational function given a value for the indeterminate You can use `is_fraction_ring` API to treat `ratfunc` as the field of fractions of polynomials: * `algebra_map K[X] (ratfunc K)` maps polynomials to rational functions * `is_fraction_ring.alg_equiv` maps other fields of fractions of `K[X]` to `ratfunc K`, in particular: * `fraction_ring.alg_equiv K[X] (ratfunc K)` maps the generic field of fraction construction to `ratfunc K`. Combine this with `alg_equiv.restrict_scalars` to change the `fraction_ring K[X] ≃ₐ[K[X]] ratfunc K` to `fraction_ring K[X] ≃ₐ[K] ratfunc K`. Working with rational functions as fractions: - `ratfunc.num` and `ratfunc.denom` give the numerator and denominator. These values are chosen to be coprime and such that `ratfunc.denom` is monic. Embedding of rational functions into Laurent series, provided as a coercion, utilizing the underlying `ratfunc.coe_alg_hom`. Lifting homomorphisms of polynomials to other types, by mapping and dividing, as long as the homomorphism retains the non-zero-divisor property: - `ratfunc.lift_monoid_with_zero_hom` lifts a `K[X] →*₀ G₀` to a `ratfunc K →*₀ G₀`, where `[comm_ring K] [comm_group_with_zero G₀]` - `ratfunc.lift_ring_hom` lifts a `K[X] →+* L` to a `ratfunc K →+* L`, where `[comm_ring K] [field L]` - `ratfunc.lift_alg_hom` lifts a `K[X] →ₐ[S] L` to a `ratfunc K →ₐ[S] L`, where `[comm_ring K] [field L] [comm_semiring S] [algebra S K[X]] [algebra S L]` This is satisfied by injective homs. We also have lifting homomorphisms of polynomials to other polynomials, with the same condition on retaining the non-zero-divisor property across the map: - `ratfunc.map` lifts `K[X] →* R[X]` when `[comm_ring K] [comm_ring R]` - `ratfunc.map_ring_hom` lifts `K[X] →+* R[X]` when `[comm_ring K] [comm_ring R]` - `ratfunc.map_alg_hom` lifts `K[X] →ₐ[S] R[X]` when `[comm_ring K] [is_domain K] [comm_ring R] [is_domain R]` We also have a set of recursion and induction principles: - `ratfunc.lift_on`: define a function by mapping a fraction of polynomials `p/q` to `f p q`, if `f` is well-defined in the sense that `p/q = p'/q' → f p q = f p' q'`. - `ratfunc.lift_on'`: define a function by mapping a fraction of polynomials `p/q` to `f p q`, if `f` is well-defined in the sense that `f (a * p) (a * q) = f p' q'`. - `ratfunc.induction_on`: if `P` holds on `p / q` for all polynomials `p q`, then `P` holds on all rational functions We define the degree of a rational function, with values in `ℤ`: - `int_degree` is the degree of a rational function, defined as the difference between the `nat_degree` of its numerator and the `nat_degree` of its denominator. In particular, `int_degree 0 = 0`. ## Implementation notes To provide good API encapsulation and speed up unification problems, `ratfunc` is defined as a structure, and all operations are `@[irreducible] def`s We need a couple of maps to set up the `field` and `is_fraction_ring` structure, namely `ratfunc.of_fraction_ring`, `ratfunc.to_fraction_ring`, `ratfunc.mk` and `ratfunc.to_fraction_ring_ring_equiv`. All these maps get `simp`ed to bundled morphisms like `algebra_map K[X] (ratfunc K)` and `is_localization.alg_equiv`. There are separate lifts and maps of homomorphisms, to provide routes of lifting even when the codomain is not a field or even an integral domain. ## References * [Kleiman, *Misconceptions about $K_X$*][kleiman1979] * https://freedommathdance.blogspot.com/2012/11/misconceptions-about-kx.html * https://stacks.math.columbia.edu/tag/01X1 -/ noncomputable theory open_locale classical open_locale non_zero_divisors polynomial universes u v variable (K : Type u) /-- `ratfunc K` is `K(x)`, the field of rational functions over `K`. The inclusion of polynomials into `ratfunc` is `algebra_map K[X] (ratfunc K)`, the maps between `ratfunc K` and another field of fractions of `K[X]`, especially `fraction_ring K[X]`, are given by `is_localization.algebra_equiv`. -/ structure ratfunc [comm_ring K] : Type u := of_fraction_ring :: (to_fraction_ring : fraction_ring K[X]) namespace ratfunc section comm_ring variable {K} variable [comm_ring K] section rec /-! ### Constructing `ratfunc`s and their induction principles -/ lemma of_fraction_ring_injective : function.injective (of_fraction_ring : _ → ratfunc K) := λ x y, of_fraction_ring.inj lemma to_fraction_ring_injective : function.injective (to_fraction_ring : _ → fraction_ring K[X]) | ⟨x⟩ ⟨y⟩ rfl := rfl /-- Non-dependent recursion principle for `ratfunc K`: To construct a term of `P : Sort*` out of `x : ratfunc K`, it suffices to provide a constructor `f : Π (p q : K[X]), P` and a proof that `f p q = f p' q'` for all `p q p' q'` such that `q' * p = q * p'` where both `q` and `q'` are not zero divisors, stated as `q ∉ K[X]⁰`, `q' ∉ K[X]⁰`. If considering `K` as an integral domain, this is the same as saying that we construct a value of `P` for such elements of `ratfunc K` by setting `lift_on (p / q) f _ = f p q`. When `[is_domain K]`, one can use `ratfunc.lift_on'`, which has the stronger requirement of `∀ {p q a : K[X]} (hq : q ≠ 0) (ha : a ≠ 0), f (a * p) (a * q) = f p q)`. -/ @[irreducible] protected def lift_on {P : Sort v} (x : ratfunc K) (f : ∀ (p q : K[X]), P) (H : ∀ {p q p' q'} (hq : q ∈ K[X]⁰) (hq' : q' ∈ K[X]⁰), q' * p = q * p' → f p q = f p' q') : P := localization.lift_on (by exact to_fraction_ring x) -- Fix timeout by manipulating elaboration order (λ p q, f p q) (λ p p' q q' h, H q.2 q'.2 (let ⟨⟨c, hc⟩, mul_eq⟩ := (localization.r_iff_exists).mp h in mul_cancel_left_coe_non_zero_divisor.mp mul_eq)) lemma lift_on_of_fraction_ring_mk {P : Sort v} (n : K[X]) (d : K[X]⁰) (f : ∀ (p q : K[X]), P) (H : ∀ {p q p' q'} (hq : q ∈ K[X]⁰) (hq' : q' ∈ K[X]⁰), q' * p = q * p' → f p q = f p' q') : ratfunc.lift_on (by exact of_fraction_ring (localization.mk n d)) f @H = f n d := begin unfold ratfunc.lift_on, exact localization.lift_on_mk _ _ _ _ end lemma lift_on_condition_of_lift_on'_condition {P : Sort v} {f : ∀ (p q : K[X]), P} (H : ∀ {p q a} (hq : q ≠ 0) (ha : a ≠ 0), f (a * p) (a * q) = f p q) ⦃p q p' q' : K[X]⦄ (hq : q ≠ 0) (hq' : q' ≠ 0) (h : q' * p = q * p') : f p q = f p' q' := calc f p q = f (q' * p) (q' * q) : (H hq hq').symm ... = f (q * p') (q * q') : by rw [h, mul_comm q'] ... = f p' q' : H hq' hq section is_domain variable [is_domain K] /-- `ratfunc.mk (p q : K[X])` is `p / q` as a rational function. If `q = 0`, then `mk` returns 0. This is an auxiliary definition used to define an `algebra` structure on `ratfunc`; the `simp` normal form of `mk p q` is `algebra_map _ _ p / algebra_map _ _ q`. -/ @[irreducible] protected def mk (p q : K[X]) : ratfunc K := of_fraction_ring (algebra_map _ _ p / algebra_map _ _ q) lemma mk_eq_div' (p q : K[X]) : ratfunc.mk p q = of_fraction_ring (algebra_map _ _ p / algebra_map _ _ q) := by unfold ratfunc.mk lemma mk_zero (p : K[X]) : ratfunc.mk p 0 = of_fraction_ring 0 := by rw [mk_eq_div', ring_hom.map_zero, div_zero] lemma mk_coe_def (p : K[X]) (q : K[X]⁰) : ratfunc.mk p q = of_fraction_ring (is_localization.mk' _ p q) := by simp only [mk_eq_div', ← localization.mk_eq_mk', fraction_ring.mk_eq_div] lemma mk_def_of_mem (p : K[X]) {q} (hq : q ∈ K[X]⁰) : ratfunc.mk p q = of_fraction_ring (is_localization.mk' _ p ⟨q, hq⟩) := by simp only [← mk_coe_def, set_like.coe_mk] lemma mk_def_of_ne (p : K[X]) {q : K[X]} (hq : q ≠ 0) : ratfunc.mk p q = of_fraction_ring (is_localization.mk' _ p ⟨q, mem_non_zero_divisors_iff_ne_zero.mpr hq⟩) := mk_def_of_mem p _ lemma mk_eq_localization_mk (p : K[X]) {q : K[X]} (hq : q ≠ 0) : ratfunc.mk p q = of_fraction_ring (localization.mk p ⟨q, mem_non_zero_divisors_iff_ne_zero.mpr hq⟩) := by rw [mk_def_of_ne, localization.mk_eq_mk'] lemma mk_one' (p : K[X]) : ratfunc.mk p 1 = of_fraction_ring (algebra_map _ _ p) := by rw [← is_localization.mk'_one (fraction_ring K[X]) p, ← mk_coe_def, submonoid.coe_one] lemma mk_eq_mk {p q p' q' : K[X]} (hq : q ≠ 0) (hq' : q' ≠ 0) : ratfunc.mk p q = ratfunc.mk p' q' ↔ p * q' = p' * q := by rw [mk_def_of_ne _ hq, mk_def_of_ne _ hq', of_fraction_ring_injective.eq_iff, is_localization.mk'_eq_iff_eq', set_like.coe_mk, set_like.coe_mk, (is_fraction_ring.injective K[X] (fraction_ring K[X])).eq_iff] lemma lift_on_mk {P : Sort v} (p q : K[X]) (f : ∀ (p q : K[X]), P) (f0 : ∀ p, f p 0 = f 0 1) (H' : ∀ {p q p' q'} (hq : q ≠ 0) (hq' : q' ≠ 0), q' * p = q * p' → f p q = f p' q') (H : ∀ {p q p' q'} (hq : q ∈ K[X]⁰) (hq' : q' ∈ K[X]⁰), q' * p = q * p' → f p q = f p' q' := λ p q p' q' hq hq' h, H' (non_zero_divisors.ne_zero hq) (non_zero_divisors.ne_zero hq') h) : (ratfunc.mk p q).lift_on f @H = f p q := begin by_cases hq : q = 0, { subst hq, simp only [mk_zero, f0, ← localization.mk_zero 1, localization.lift_on_mk, lift_on_of_fraction_ring_mk, submonoid.coe_one], }, { simp only [mk_eq_localization_mk _ hq, localization.lift_on_mk, lift_on_of_fraction_ring_mk, set_like.coe_mk] } end /-- Non-dependent recursion principle for `ratfunc K`: if `f p q : P` for all `p q`, such that `f (a * p) (a * q) = f p q`, then we can find a value of `P` for all elements of `ratfunc K` by setting `lift_on' (p / q) f _ = f p q`. The value of `f p 0` for any `p` is never used and in principle this may be anything, although many usages of `lift_on'` assume `f p 0 = f 0 1`. -/ @[irreducible] protected def lift_on' {P : Sort v} (x : ratfunc K) (f : ∀ (p q : K[X]), P) (H : ∀ {p q a} (hq : q ≠ 0) (ha : a ≠ 0), f (a * p) (a * q) = f p q) : P := x.lift_on f (λ p q p' q' hq hq', lift_on_condition_of_lift_on'_condition @H (non_zero_divisors.ne_zero hq) (non_zero_divisors.ne_zero hq')) lemma lift_on'_mk {P : Sort v} (p q : K[X]) (f : ∀ (p q : K[X]), P) (f0 : ∀ p, f p 0 = f 0 1) (H : ∀ {p q a} (hq : q ≠ 0) (ha : a ≠ 0), f (a * p) (a * q) = f p q) : (ratfunc.mk p q).lift_on' f @H = f p q := begin rw [ratfunc.lift_on', ratfunc.lift_on_mk _ _ _ f0], exact lift_on_condition_of_lift_on'_condition @H end /-- Induction principle for `ratfunc K`: if `f p q : P (ratfunc.mk p q)` for all `p q`, then `P` holds on all elements of `ratfunc K`. See also `induction_on`, which is a recursion principle defined in terms of `algebra_map`. -/ @[irreducible] protected lemma induction_on' {P : ratfunc K → Prop} : Π (x : ratfunc K) (f : ∀ (p q : K[X]) (hq : q ≠ 0), P (ratfunc.mk p q)), P x | ⟨x⟩ f := localization.induction_on x (λ ⟨p, q⟩, by simpa only [mk_coe_def, localization.mk_eq_mk'] using f p q (mem_non_zero_divisors_iff_ne_zero.mp q.2)) end is_domain end rec section field /-! ### Defining the field structure -/ /-- The zero rational function. -/ @[irreducible] protected def zero : ratfunc K := ⟨0⟩ instance : has_zero (ratfunc K) := ⟨ratfunc.zero⟩ lemma of_fraction_ring_zero : (of_fraction_ring 0 : ratfunc K) = 0 := by unfold has_zero.zero ratfunc.zero /-- Addition of rational functions. -/ @[irreducible] protected def add : ratfunc K → ratfunc K → ratfunc K | ⟨p⟩ ⟨q⟩ := ⟨p + q⟩ instance : has_add (ratfunc K) := ⟨ratfunc.add⟩ lemma of_fraction_ring_add (p q : fraction_ring K[X]) : of_fraction_ring (p + q) = of_fraction_ring p + of_fraction_ring q := by unfold has_add.add ratfunc.add /-- Subtraction of rational functions. -/ @[irreducible] protected def sub : ratfunc K → ratfunc K → ratfunc K | ⟨p⟩ ⟨q⟩ := ⟨p - q⟩ instance : has_sub (ratfunc K) := ⟨ratfunc.sub⟩ lemma of_fraction_ring_sub (p q : fraction_ring K[X]) : of_fraction_ring (p - q) = of_fraction_ring p - of_fraction_ring q := by unfold has_sub.sub ratfunc.sub /-- Additive inverse of a rational function. -/ @[irreducible] protected def neg : ratfunc K → ratfunc K | ⟨p⟩ := ⟨-p⟩ instance : has_neg (ratfunc K) := ⟨ratfunc.neg⟩ lemma of_fraction_ring_neg (p : fraction_ring K[X]) : of_fraction_ring (-p) = - of_fraction_ring p := by unfold has_neg.neg ratfunc.neg /-- The multiplicative unit of rational functions. -/ @[irreducible] protected def one : ratfunc K := ⟨1⟩ instance : has_one (ratfunc K) := ⟨ratfunc.one⟩ lemma of_fraction_ring_one : (of_fraction_ring 1 : ratfunc K) = 1 := by unfold has_one.one ratfunc.one /-- Multiplication of rational functions. -/ @[irreducible] protected def mul : ratfunc K → ratfunc K → ratfunc K | ⟨p⟩ ⟨q⟩ := ⟨p * q⟩ instance : has_mul (ratfunc K) := ⟨ratfunc.mul⟩ lemma of_fraction_ring_mul (p q : fraction_ring K[X]) : of_fraction_ring (p * q) = of_fraction_ring p * of_fraction_ring q := by unfold has_mul.mul ratfunc.mul section is_domain variable [is_domain K] /-- Division of rational functions. -/ @[irreducible] protected def div : ratfunc K → ratfunc K → ratfunc K | ⟨p⟩ ⟨q⟩ := ⟨p / q⟩ instance : has_div (ratfunc K) := ⟨ratfunc.div⟩ lemma of_fraction_ring_div (p q : fraction_ring K[X]) : of_fraction_ring (p / q) = of_fraction_ring p / of_fraction_ring q := by unfold has_div.div ratfunc.div /-- Multiplicative inverse of a rational function. -/ @[irreducible] protected def inv : ratfunc K → ratfunc K | ⟨p⟩ := ⟨p⁻¹⟩ instance : has_inv (ratfunc K) := ⟨ratfunc.inv⟩ lemma of_fraction_ring_inv (p : fraction_ring K[X]) : of_fraction_ring (p⁻¹) = (of_fraction_ring p)⁻¹ := by unfold has_inv.inv ratfunc.inv -- Auxiliary lemma for the `field` instance lemma mul_inv_cancel : ∀ {p : ratfunc K} (hp : p ≠ 0), p * p⁻¹ = 1 | ⟨p⟩ h := have p ≠ 0 := λ hp, h $ by rw [hp, of_fraction_ring_zero], by simpa only [← of_fraction_ring_inv, ← of_fraction_ring_mul, ← of_fraction_ring_one] using _root_.mul_inv_cancel this end is_domain section has_smul variables {R : Type*} /-- Scalar multiplication of rational functions. -/ @[irreducible] protected def smul [has_smul R (fraction_ring K[X])] : R → ratfunc K → ratfunc K | r ⟨p⟩ := ⟨r • p⟩ @[nolint fails_quickly] -- cannot reproduce instance [has_smul R (fraction_ring K[X])] : has_smul R (ratfunc K) := ⟨ratfunc.smul⟩ lemma of_fraction_ring_smul [has_smul R (fraction_ring K[X])] (c : R) (p : fraction_ring K[X]) : of_fraction_ring (c • p) = c • of_fraction_ring p := by unfold has_smul.smul ratfunc.smul lemma to_fraction_ring_smul [has_smul R (fraction_ring K[X])] (c : R) (p : ratfunc K) : to_fraction_ring (c • p) = c • to_fraction_ring p := by { cases p, rw ←of_fraction_ring_smul } lemma smul_eq_C_smul (x : ratfunc K) (r : K) : r • x = polynomial.C r • x := begin cases x, induction x, { rw [←of_fraction_ring_smul, ←of_fraction_ring_smul, localization.smul_mk, localization.smul_mk, smul_eq_mul, polynomial.smul_eq_C_mul] }, { simp only } end section is_domain variable [is_domain K] variables [monoid R] [distrib_mul_action R K[X]] variables [is_scalar_tower R K[X] K[X]] lemma mk_smul (c : R) (p q : K[X]) : ratfunc.mk (c • p) q = c • ratfunc.mk p q := begin by_cases hq : q = 0, { rw [hq, mk_zero, mk_zero, ←of_fraction_ring_smul, smul_zero] }, { rw [mk_eq_localization_mk _ hq, mk_eq_localization_mk _ hq, ←localization.smul_mk, ←of_fraction_ring_smul] } end instance : is_scalar_tower R K[X] (ratfunc K) := ⟨λ c p q, q.induction_on' (λ q r _, by rw [← mk_smul, smul_assoc, mk_smul, mk_smul])⟩ end is_domain end has_smul variables (K) instance [subsingleton K] : subsingleton (ratfunc K) := to_fraction_ring_injective.subsingleton instance : inhabited (ratfunc K) := ⟨0⟩ instance [nontrivial K] : nontrivial (ratfunc K) := of_fraction_ring_injective.nontrivial /-- `ratfunc K` is isomorphic to the field of fractions of `K[X]`, as rings. This is an auxiliary definition; `simp`-normal form is `is_localization.alg_equiv`. -/ @[simps apply] def to_fraction_ring_ring_equiv : ratfunc K ≃+* fraction_ring K[X] := { to_fun := to_fraction_ring, inv_fun := of_fraction_ring, left_inv := λ ⟨_⟩, rfl, right_inv := λ _, rfl, map_add' := λ ⟨_⟩ ⟨_⟩, by simp [←of_fraction_ring_add], map_mul' := λ ⟨_⟩ ⟨_⟩, by simp [←of_fraction_ring_mul] } end field section tactic_interlude -- pre-porting note: should comm_ring be disabled here? /-- Solve equations for `ratfunc K` by working in `fraction_ring K[X]`. -/ meta def frac_tac : tactic unit := `[repeat { rintro (⟨⟩ : ratfunc _) }, simp only [← of_fraction_ring_zero, ← of_fraction_ring_add, ← of_fraction_ring_sub, ← of_fraction_ring_neg, ← of_fraction_ring_one, ← of_fraction_ring_mul, ← of_fraction_ring_div, ← of_fraction_ring_inv, add_assoc, zero_add, add_zero, mul_assoc, mul_zero, mul_one, mul_add, inv_zero, add_comm, add_left_comm, mul_comm, mul_left_comm, sub_eq_add_neg, div_eq_mul_inv, add_mul, zero_mul, one_mul, neg_mul, mul_neg, add_right_neg]] /-- Solve equations for `ratfunc K` by applying `ratfunc.induction_on`. -/ meta def smul_tac : tactic unit := `[repeat { rintro (⟨⟩ : ratfunc _) <|> intro }, simp_rw [←of_fraction_ring_smul], simp only [add_comm, mul_comm, zero_smul, succ_nsmul, zsmul_eq_mul, mul_add, mul_one, mul_zero, neg_add, mul_neg, int.of_nat_eq_coe, int.coe_nat_succ, int.cast_zero, int.cast_add, int.cast_one, int.cast_neg_succ_of_nat, int.cast_coe_nat, nat.cast_succ, localization.mk_zero, localization.add_mk_self, localization.neg_mk, of_fraction_ring_zero, ← of_fraction_ring_add, ← of_fraction_ring_neg]] end tactic_interlude variable (K) instance : comm_ring (ratfunc K) := { add := (+), add_assoc := by frac_tac, add_comm := by frac_tac, zero := 0, zero_add := by frac_tac, add_zero := by frac_tac, neg := has_neg.neg, add_left_neg := by frac_tac, sub := has_sub.sub, sub_eq_add_neg := by frac_tac, mul := (*), mul_assoc := by frac_tac, mul_comm := by frac_tac, left_distrib := by frac_tac, right_distrib := by frac_tac, one := 1, one_mul := by frac_tac, mul_one := by frac_tac, nsmul := (•), nsmul_zero' := by smul_tac, nsmul_succ' := λ _, by smul_tac, zsmul := (•), zsmul_zero' := by smul_tac, zsmul_succ' := λ _, by smul_tac, zsmul_neg' := λ _, by smul_tac, npow := npow_rec } variables {K} section lift_hom variables {G₀ L R S F : Type*} [comm_group_with_zero G₀] [field L] [comm_ring R] [comm_ring S] /-- Lift a monoid homomorphism that maps polynomials `φ : R[X] →* S[X]` to a `ratfunc R →* ratfunc S`, on the condition that `φ` maps non zero divisors to non zero divisors, by mapping both the numerator and denominator and quotienting them. -/ def map [monoid_hom_class F R[X] S[X]] (φ : F) (hφ : R[X]⁰ ≤ S[X]⁰.comap φ) : ratfunc R →* ratfunc S := { to_fun := λ f, ratfunc.lift_on f (λ n d, if h : φ d ∈ S[X]⁰ then of_fraction_ring (localization.mk (φ n) ⟨φ d, h⟩) else 0) $ λ p q p' q' hq hq' h, begin rw [dif_pos, dif_pos, of_fraction_ring.inj_eq, localization.mk_eq_mk_iff], rotate, { exact hφ hq' }, { exact hφ hq }, refine localization.r_of_eq _, simpa only [map_mul] using (congr_arg φ h), end, map_one' := begin rw [←of_fraction_ring_one, ←localization.mk_one, lift_on_of_fraction_ring_mk, dif_pos], { simpa using of_fraction_ring_one }, { simpa using submonoid.one_mem _} end, map_mul' := λ x y, begin cases x, cases y, induction x with p q, induction y with p' q', { have hq : φ q ∈ S[X]⁰ := hφ q.prop, have hq' : φ q' ∈ S[X]⁰ := hφ q'.prop, have hqq' : φ ↑(q * q') ∈ S[X]⁰, { simpa using submonoid.mul_mem _ hq hq' }, simp_rw [←of_fraction_ring_mul, localization.mk_mul, lift_on_of_fraction_ring_mk, dif_pos hq, dif_pos hq', dif_pos hqq', ←of_fraction_ring_mul, submonoid.coe_mul, map_mul, localization.mk_mul, submonoid.mk_mul_mk] }, { refl }, { refl } end } lemma map_apply_of_fraction_ring_mk [monoid_hom_class F R[X] S[X]] (φ : F) (hφ : R[X]⁰ ≤ S[X]⁰.comap φ) (n : R[X]) (d : R[X]⁰) : map φ hφ (of_fraction_ring (localization.mk n d)) = of_fraction_ring (localization.mk (φ n) ⟨φ d, hφ d.prop⟩) := begin convert lift_on_of_fraction_ring_mk _ _ _ _, rw dif_pos end lemma map_injective [monoid_hom_class F R[X] S[X]] (φ : F) (hφ : R[X]⁰ ≤ S[X]⁰.comap φ) (hf : function.injective φ) : function.injective (map φ hφ) := begin rintro ⟨x⟩ ⟨y⟩ h, induction x, induction y, { simpa only [map_apply_of_fraction_ring_mk, of_fraction_ring_injective.eq_iff, localization.mk_eq_mk_iff, localization.r_iff_exists, mul_cancel_left_coe_non_zero_divisor, exists_const, set_like.coe_mk, ←map_mul, hf.eq_iff] using h }, { refl }, { refl } end /-- Lift a ring homomorphism that maps polynomials `φ : R[X] →+* S[X]` to a `ratfunc R →+* ratfunc S`, on the condition that `φ` maps non zero divisors to non zero divisors, by mapping both the numerator and denominator and quotienting them. -/ def map_ring_hom [ring_hom_class F R[X] S[X]] (φ : F) (hφ : R[X]⁰ ≤ S[X]⁰.comap φ) : ratfunc R →+* ratfunc S := { map_zero' := begin simp_rw [monoid_hom.to_fun_eq_coe, ←of_fraction_ring_zero, ←localization.mk_zero (1 : R[X]⁰), ←localization.mk_zero (1 : S[X]⁰), map_apply_of_fraction_ring_mk, map_zero, localization.mk_eq_mk', is_localization.mk'_zero], end, map_add' := begin rintro ⟨x⟩ ⟨y⟩, induction x, induction y, { simp only [←of_fraction_ring_add, localization.add_mk, map_add, set_like.coe_mk, map_mul, monoid_hom.to_fun_eq_coe, map_apply_of_fraction_ring_mk, submonoid.mk_mul_mk, submonoid.coe_mul] }, { refl }, { refl } end, ..map φ hφ } lemma coe_map_ring_hom_eq_coe_map [ring_hom_class F R[X] S[X]] (φ : F) (hφ : R[X]⁰ ≤ S[X]⁰.comap φ) : (map_ring_hom φ hφ : ratfunc R → ratfunc S) = map φ hφ := rfl -- TODO: Generalize to `fun_like` classes, /-- Lift an monoid with zero homomorphism `R[X] →*₀ G₀` to a `ratfunc R →*₀ G₀` on the condition that `φ` maps non zero divisors to non zero divisors, by mapping both the numerator and denominator and quotienting them. -/ def lift_monoid_with_zero_hom (φ : R[X] →*₀ G₀) (hφ : R[X]⁰ ≤ G₀⁰.comap φ) : ratfunc R →*₀ G₀ := { to_fun := λ f, ratfunc.lift_on f (λ p q, φ p / (φ q)) $ λ p q p' q' hq hq' h, begin casesI subsingleton_or_nontrivial R, { rw [subsingleton.elim p q, subsingleton.elim p' q, subsingleton.elim q' q] }, rw [div_eq_div_iff, ←map_mul, mul_comm p, h, map_mul, mul_comm]; exact non_zero_divisors.ne_zero (hφ ‹_›), end, map_one' := by { rw [←of_fraction_ring_one, ←localization.mk_one, lift_on_of_fraction_ring_mk], simp only [map_one, submonoid.coe_one, div_one] }, map_mul' := λ x y, by { cases x, cases y, induction x with p q, induction y with p' q', { rw [←of_fraction_ring_mul, localization.mk_mul], simp only [lift_on_of_fraction_ring_mk, div_mul_div_comm, map_mul, submonoid.coe_mul] }, { refl }, { refl } }, map_zero' := by { rw [←of_fraction_ring_zero, ←localization.mk_zero (1 : R[X]⁰), lift_on_of_fraction_ring_mk], simp only [map_zero, zero_div] } } lemma lift_monoid_with_zero_hom_apply_of_fraction_ring_mk (φ : R[X] →*₀ G₀) (hφ : R[X]⁰ ≤ G₀⁰.comap φ) (n : R[X]) (d : R[X]⁰) : lift_monoid_with_zero_hom φ hφ (of_fraction_ring (localization.mk n d)) = φ n / φ d := lift_on_of_fraction_ring_mk _ _ _ _ lemma lift_monoid_with_zero_hom_injective [nontrivial R] (φ : R[X] →*₀ G₀) (hφ : function.injective φ) (hφ' : R[X]⁰ ≤ G₀⁰.comap φ := non_zero_divisors_le_comap_non_zero_divisors_of_injective _ hφ) : function.injective (lift_monoid_with_zero_hom φ hφ') := begin rintro ⟨x⟩ ⟨y⟩, induction x, induction y, { simp_rw [lift_monoid_with_zero_hom_apply_of_fraction_ring_mk, localization.mk_eq_mk_iff], intro h, refine localization.r_of_eq _, have := mul_eq_mul_of_div_eq_div _ _ _ _ h, rwa [←map_mul, ←map_mul, hφ.eq_iff, mul_comm, mul_comm y_a] at this, all_goals { exact (map_ne_zero_of_mem_non_zero_divisors _ hφ (set_like.coe_mem _)) } }, { exact λ _, rfl }, { exact λ _, rfl } end /-- Lift an injective ring homomorphism `R[X] →+* L` to a `ratfunc R →+* L` by mapping both the numerator and denominator and quotienting them. -/ def lift_ring_hom (φ : R[X] →+* L) (hφ : R[X]⁰ ≤ L⁰.comap φ) : ratfunc R →+* L := { map_add' := λ x y, by { simp only [monoid_with_zero_hom.to_fun_eq_coe], casesI subsingleton_or_nontrivial R, { rw [subsingleton.elim (x + y) y, subsingleton.elim x 0, map_zero, zero_add] }, cases x, cases y, induction x with p q, induction y with p' q', { rw [←of_fraction_ring_add, localization.add_mk], simp only [ring_hom.to_monoid_with_zero_hom_eq_coe, lift_monoid_with_zero_hom_apply_of_fraction_ring_mk], rw [div_add_div, div_eq_div_iff], { rw [mul_comm _ p, mul_comm _ p', mul_comm _ (φ p'), add_comm], simp only [map_add, map_mul, submonoid.coe_mul] }, all_goals { try { simp only [←map_mul, ←submonoid.coe_mul] }, exact non_zero_divisors.ne_zero (hφ (set_like.coe_mem _)) } }, { refl }, { refl } }, ..lift_monoid_with_zero_hom φ.to_monoid_with_zero_hom hφ } lemma lift_ring_hom_apply_of_fraction_ring_mk (φ : R[X] →+* L) (hφ : R[X]⁰ ≤ L⁰.comap φ) (n : R[X]) (d : R[X]⁰) : lift_ring_hom φ hφ (of_fraction_ring (localization.mk n d)) = φ n / φ d := lift_monoid_with_zero_hom_apply_of_fraction_ring_mk _ _ _ _ lemma lift_ring_hom_injective [nontrivial R] (φ : R[X] →+* L) (hφ : function.injective φ) (hφ' : R[X]⁰ ≤ L⁰.comap φ := non_zero_divisors_le_comap_non_zero_divisors_of_injective _ hφ) : function.injective (lift_ring_hom φ hφ') := lift_monoid_with_zero_hom_injective _ hφ end lift_hom variable (K) instance [is_domain K] : field (ratfunc K) := by exact { inv := has_inv.inv, inv_zero := by frac_tac, div := (/), div_eq_mul_inv := by frac_tac, mul_inv_cancel := λ _, mul_inv_cancel, zpow := zpow_rec, .. ratfunc.comm_ring K, .. ratfunc.nontrivial K } section is_fraction_ring /-! ### `ratfunc` as field of fractions of `polynomial` -/ section is_domain variable [is_domain K] instance (R : Type*) [comm_semiring R] [algebra R K[X]] : algebra R (ratfunc K) := { to_fun := λ x, ratfunc.mk (algebra_map _ _ x) 1, map_add' := λ x y, by simp only [mk_one', ring_hom.map_add, of_fraction_ring_add], map_mul' := λ x y, by simp only [mk_one', ring_hom.map_mul, of_fraction_ring_mul], map_one' := by simp only [mk_one', ring_hom.map_one, of_fraction_ring_one], map_zero' := by simp only [mk_one', ring_hom.map_zero, of_fraction_ring_zero], smul := (•), smul_def' := λ c x, x.induction_on' $ λ p q hq, by simp_rw [mk_one', ← mk_smul, mk_def_of_ne (c • p) hq, mk_def_of_ne p hq, ← of_fraction_ring_mul, is_localization.mul_mk'_eq_mk'_of_mul, algebra.smul_def], commutes' := λ c x, mul_comm _ _ } variables {K} lemma mk_one (x : K[X]) : ratfunc.mk x 1 = algebra_map _ _ x := rfl lemma of_fraction_ring_algebra_map (x : K[X]) : of_fraction_ring (algebra_map _ (fraction_ring K[X]) x) = algebra_map _ _ x := by rw [← mk_one, mk_one'] @[simp] lemma mk_eq_div (p q : K[X]) : ratfunc.mk p q = (algebra_map _ _ p / algebra_map _ _ q) := by simp only [mk_eq_div', of_fraction_ring_div, of_fraction_ring_algebra_map] @[simp] lemma div_smul {R} [monoid R] [distrib_mul_action R K[X]] [is_scalar_tower R K[X] K[X]] (c : R) (p q : K[X]) : algebra_map _ (ratfunc K) (c • p) / (algebra_map _ _ q) = c • (algebra_map _ _ p / algebra_map _ _ q) := by rw [←mk_eq_div, mk_smul, mk_eq_div] lemma algebra_map_apply {R : Type*} [comm_semiring R] [algebra R K[X]] (x : R) : algebra_map R (ratfunc K) x = (algebra_map _ _ (algebra_map R K[X] x)) / (algebra_map K[X] _ 1) := by { rw [←mk_eq_div], refl } lemma map_apply_div_ne_zero {R F : Type*} [comm_ring R] [is_domain R] [monoid_hom_class F K[X] R[X]] (φ : F) (hφ : K[X]⁰ ≤ R[X]⁰.comap φ) (p q : K[X]) (hq : q ≠ 0) : map φ hφ (algebra_map _ _ p / algebra_map _ _ q) = algebra_map _ _ (φ p) / algebra_map _ _ (φ q) := begin have hq' : φ q ≠ 0 := non_zero_divisors.ne_zero (hφ (mem_non_zero_divisors_iff_ne_zero.mpr hq)), simp only [←mk_eq_div, mk_eq_localization_mk _ hq, map_apply_of_fraction_ring_mk, mk_eq_localization_mk _ hq', set_like.coe_mk], end @[simp] lemma map_apply_div {R F : Type*} [comm_ring R] [is_domain R] [monoid_with_zero_hom_class F K[X] R[X]] (φ : F) (hφ : K[X]⁰ ≤ R[X]⁰.comap φ) (p q : K[X]) : map φ hφ (algebra_map _ _ p / algebra_map _ _ q) = algebra_map _ _ (φ p) / algebra_map _ _ (φ q) := begin rcases eq_or_ne q 0 with rfl|hq, { have : (0 : ratfunc K) = algebra_map K[X] _ 0 / algebra_map K[X] _ 1, { simp }, rw [map_zero, map_zero, map_zero, div_zero, div_zero, this, map_apply_div_ne_zero, map_one, map_one, div_one, map_zero, map_zero], exact one_ne_zero }, exact map_apply_div_ne_zero _ _ _ _ hq end @[simp] lemma lift_monoid_with_zero_hom_apply_div {L : Type*} [comm_group_with_zero L] (φ : monoid_with_zero_hom K[X] L) (hφ : K[X]⁰ ≤ L⁰.comap φ) (p q : K[X]) : lift_monoid_with_zero_hom φ hφ (algebra_map _ _ p / algebra_map _ _ q) = φ p / φ q := begin rcases eq_or_ne q 0 with rfl|hq, { simp only [div_zero, map_zero] }, simpa only [←mk_eq_div, mk_eq_localization_mk _ hq, lift_monoid_with_zero_hom_apply_of_fraction_ring_mk], end @[simp] lemma lift_ring_hom_apply_div {L : Type*} [field L] (φ : K[X] →+* L) (hφ : K[X]⁰ ≤ L⁰.comap φ) (p q : K[X]) : lift_ring_hom φ hφ (algebra_map _ _ p / algebra_map _ _ q) = φ p / φ q := lift_monoid_with_zero_hom_apply_div _ _ _ _ variables (K) lemma of_fraction_ring_comp_algebra_map : of_fraction_ring ∘ algebra_map K[X] (fraction_ring K[X]) = algebra_map _ _ := funext of_fraction_ring_algebra_map lemma algebra_map_injective : function.injective (algebra_map K[X] (ratfunc K)) := begin rw ← of_fraction_ring_comp_algebra_map, exact of_fraction_ring_injective.comp (is_fraction_ring.injective _ _), end @[simp] lemma algebra_map_eq_zero_iff {x : K[X]} : algebra_map K[X] (ratfunc K) x = 0 ↔ x = 0 := ⟨(injective_iff_map_eq_zero _).mp (algebra_map_injective K) _, λ hx, by rw [hx, ring_hom.map_zero]⟩ variables {K} lemma algebra_map_ne_zero {x : K[X]} (hx : x ≠ 0) : algebra_map K[X] (ratfunc K) x ≠ 0 := mt (algebra_map_eq_zero_iff K).mp hx section lift_alg_hom variables {L R S : Type*} [field L] [comm_ring R] [is_domain R] [comm_semiring S] [algebra S K[X]] [algebra S L] [algebra S R[X]] (φ : K[X] →ₐ[S] L) (hφ : K[X]⁰ ≤ L⁰.comap φ) /-- Lift an algebra homomorphism that maps polynomials `φ : K[X] →ₐ[S] R[X]` to a `ratfunc K →ₐ[S] ratfunc R`, on the condition that `φ` maps non zero divisors to non zero divisors, by mapping both the numerator and denominator and quotienting them. -/ def map_alg_hom (φ : K[X] →ₐ[S] R[X]) (hφ : K[X]⁰ ≤ R[X]⁰.comap φ) : ratfunc K →ₐ[S] ratfunc R := { commutes' := λ r, by simp_rw [ring_hom.to_fun_eq_coe, coe_map_ring_hom_eq_coe_map, algebra_map_apply r, map_apply_div, map_one, alg_hom.commutes], ..map_ring_hom φ hφ } lemma coe_map_alg_hom_eq_coe_map (φ : K[X] →ₐ[S] R[X]) (hφ : K[X]⁰ ≤ R[X]⁰.comap φ) : (map_alg_hom φ hφ : ratfunc K → ratfunc R) = map φ hφ := rfl /-- Lift an injective algebra homomorphism `K[X] →ₐ[S] L` to a `ratfunc K →ₐ[S] L` by mapping both the numerator and denominator and quotienting them. -/ def lift_alg_hom : ratfunc K →ₐ[S] L := { commutes' := λ r, by simp_rw [ring_hom.to_fun_eq_coe, alg_hom.to_ring_hom_eq_coe, algebra_map_apply r, lift_ring_hom_apply_div, alg_hom.coe_to_ring_hom, map_one, div_one, alg_hom.commutes], ..lift_ring_hom φ.to_ring_hom hφ } lemma lift_alg_hom_apply_of_fraction_ring_mk (n : K[X]) (d : K[X]⁰) : lift_alg_hom φ hφ (of_fraction_ring (localization.mk n d)) = φ n / φ d := lift_monoid_with_zero_hom_apply_of_fraction_ring_mk _ _ _ _ lemma lift_alg_hom_injective (φ : K[X] →ₐ[S] L) (hφ : function.injective φ) (hφ' : K[X]⁰ ≤ L⁰.comap φ := non_zero_divisors_le_comap_non_zero_divisors_of_injective _ hφ) : function.injective (lift_alg_hom φ hφ') := lift_monoid_with_zero_hom_injective _ hφ @[simp] lemma lift_alg_hom_apply_div (p q : K[X]) : lift_alg_hom φ hφ (algebra_map _ _ p / algebra_map _ _ q) = φ p / φ q := lift_monoid_with_zero_hom_apply_div _ _ _ _ end lift_alg_hom variables (K) /-- `ratfunc K` is the field of fractions of the polynomials over `K`. -/ instance : is_fraction_ring K[X] (ratfunc K) := { map_units := λ y, by rw ← of_fraction_ring_algebra_map; exact (to_fraction_ring_ring_equiv K).symm.to_ring_hom.is_unit_map (is_localization.map_units _ y), eq_iff_exists := λ x y, by rw [← of_fraction_ring_algebra_map, ← of_fraction_ring_algebra_map]; exact (to_fraction_ring_ring_equiv K).symm.injective.eq_iff.trans (is_localization.eq_iff_exists _ _), surj := by { rintro ⟨z⟩, convert is_localization.surj K[X]⁰ z, ext ⟨x, y⟩, simp only [← of_fraction_ring_algebra_map, function.comp_app, ← of_fraction_ring_mul] } } variables {K} @[simp] lemma lift_on_div {P : Sort v} (p q : K[X]) (f : ∀ (p q : K[X]), P) (f0 : ∀ p, f p 0 = f 0 1) (H' : ∀ {p q p' q'} (hq : q ≠ 0) (hq' : q' ≠ 0), q' * p = q * p' → f p q = f p' q') (H : ∀ {p q p' q'} (hq : q ∈ K[X]⁰) (hq' : q' ∈ K[X]⁰), q' * p = q * p' → f p q = f p' q' := λ p q p' q' hq hq' h, H' (non_zero_divisors.ne_zero hq) (non_zero_divisors.ne_zero hq') h) : (algebra_map _ (ratfunc K) p / algebra_map _ _ q).lift_on f @H = f p q := by rw [← mk_eq_div, lift_on_mk _ _ f f0 @H'] @[simp] lemma lift_on'_div {P : Sort v} (p q : K[X]) (f : ∀ (p q : K[X]), P) (f0 : ∀ p, f p 0 = f 0 1) (H) : (algebra_map _ (ratfunc K) p / algebra_map _ _ q).lift_on' f @H = f p q := begin rw [ratfunc.lift_on', lift_on_div _ _ _ f0], exact lift_on_condition_of_lift_on'_condition @H end /-- Induction principle for `ratfunc K`: if `f p q : P (p / q)` for all `p q : K[X]`, then `P` holds on all elements of `ratfunc K`. See also `induction_on'`, which is a recursion principle defined in terms of `ratfunc.mk`. -/ protected lemma induction_on {P : ratfunc K → Prop} (x : ratfunc K) (f : ∀ (p q : K[X]) (hq : q ≠ 0), P (algebra_map _ (ratfunc K) p / algebra_map _ _ q)) : P x := x.induction_on' (λ p q hq, by simpa using f p q hq) lemma of_fraction_ring_mk' (x : K[X]) (y : K[X]⁰) : of_fraction_ring (is_localization.mk' _ x y) = is_localization.mk' (ratfunc K) x y := by rw [is_fraction_ring.mk'_eq_div, is_fraction_ring.mk'_eq_div, ← mk_eq_div', ← mk_eq_div] @[simp] lemma of_fraction_ring_eq : (of_fraction_ring : fraction_ring K[X] → ratfunc K) = is_localization.alg_equiv K[X]⁰ _ _ := funext $ λ x, localization.induction_on x $ λ x, by simp only [is_localization.alg_equiv_apply, is_localization.ring_equiv_of_ring_equiv_apply, ring_equiv.to_fun_eq_coe, localization.mk_eq_mk'_apply, is_localization.map_mk', of_fraction_ring_mk', ring_equiv.coe_to_ring_hom, ring_equiv.refl_apply, set_like.eta] @[simp] lemma to_fraction_ring_eq : (to_fraction_ring : ratfunc K → fraction_ring K[X]) = is_localization.alg_equiv K[X]⁰ _ _ := funext $ λ ⟨x⟩, localization.induction_on x $ λ x, by simp only [localization.mk_eq_mk'_apply, of_fraction_ring_mk', is_localization.alg_equiv_apply, ring_equiv.to_fun_eq_coe, is_localization.ring_equiv_of_ring_equiv_apply, is_localization.map_mk', ring_equiv.coe_to_ring_hom, ring_equiv.refl_apply, set_like.eta] @[simp] lemma to_fraction_ring_ring_equiv_symm_eq : (to_fraction_ring_ring_equiv K).symm = (is_localization.alg_equiv K[X]⁰ _ _).to_ring_equiv := by { ext x, simp [to_fraction_ring_ring_equiv, of_fraction_ring_eq, alg_equiv.coe_ring_equiv'] } end is_domain end is_fraction_ring end comm_ring variable {K} section num_denom /-! ### Numerator and denominator -/ open gcd_monoid polynomial variables [field K] /-- `ratfunc.num_denom` are numerator and denominator of a rational function over a field, normalized such that the denominator is monic. -/ def num_denom (x : ratfunc K) : K[X] × K[X] := x.lift_on' (λ p q, if q = 0 then ⟨0, 1⟩ else let r := gcd p q in ⟨polynomial.C ((q / r).leading_coeff⁻¹) * (p / r), polynomial.C ((q / r).leading_coeff⁻¹) * (q / r)⟩) begin intros p q a hq ha, rw [if_neg hq, if_neg (mul_ne_zero ha hq)], have hpq : gcd p q ≠ 0 := mt (and.right ∘ (gcd_eq_zero_iff _ _).mp) hq, have ha' : a.leading_coeff ≠ 0 := polynomial.leading_coeff_ne_zero.mpr ha, have hainv : (a.leading_coeff)⁻¹ ≠ 0 := inv_ne_zero ha', simp only [prod.ext_iff, gcd_mul_left, normalize_apply, polynomial.coe_norm_unit, mul_assoc, comm_group_with_zero.coe_norm_unit _ ha'], have hdeg : (gcd p q).degree ≤ q.degree := degree_gcd_le_right _ hq, have hdeg' : (polynomial.C (a.leading_coeff⁻¹) * gcd p q).degree ≤ q.degree, { rw [polynomial.degree_mul, polynomial.degree_C hainv, zero_add], exact hdeg }, have hdivp : (polynomial.C a.leading_coeff⁻¹) * gcd p q ∣ p := (C_mul_dvd hainv).mpr (gcd_dvd_left p q), have hdivq : (polynomial.C a.leading_coeff⁻¹) * gcd p q ∣ q := (C_mul_dvd hainv).mpr (gcd_dvd_right p q), rw [euclidean_domain.mul_div_mul_cancel ha hdivp, euclidean_domain.mul_div_mul_cancel ha hdivq, leading_coeff_div hdeg, leading_coeff_div hdeg', polynomial.leading_coeff_mul, polynomial.leading_coeff_C, div_C_mul, div_C_mul, ← mul_assoc, ← polynomial.C_mul, ← mul_assoc, ← polynomial.C_mul], split; congr; rw [inv_div, mul_comm, mul_div_assoc, ← mul_assoc, inv_inv, _root_.mul_inv_cancel ha', one_mul, inv_div], end @[simp] lemma num_denom_div (p : K[X]) {q : K[X]} (hq : q ≠ 0) : num_denom (algebra_map _ _ p / algebra_map _ _ q) = (polynomial.C ((q / gcd p q).leading_coeff⁻¹) * (p / gcd p q), polynomial.C ((q / gcd p q).leading_coeff⁻¹) * (q / gcd p q)) := begin rw [num_denom, lift_on'_div, if_neg hq], intros p, rw [if_pos rfl, if_neg (one_ne_zero' K[X])], simp, end /-- `ratfunc.num` is the numerator of a rational function, normalized such that the denominator is monic. -/ def num (x : ratfunc K) : K[X] := x.num_denom.1 private lemma num_div' (p : K[X]) {q : K[X]} (hq : q ≠ 0) : num (algebra_map _ _ p / algebra_map _ _ q) = polynomial.C ((q / gcd p q).leading_coeff⁻¹) * (p / gcd p q) := by rw [num, num_denom_div _ hq] @[simp] lemma num_zero : num (0 : ratfunc K) = 0 := by { convert num_div' (0 : K[X]) one_ne_zero; simp } @[simp] lemma num_div (p q : K[X]) : num (algebra_map _ _ p / algebra_map _ _ q) = polynomial.C ((q / gcd p q).leading_coeff⁻¹) * (p / gcd p q) := begin by_cases hq : q = 0, { simp [hq] }, { exact num_div' p hq, }, end @[simp] lemma num_one : num (1 : ratfunc K) = 1 := by { convert num_div (1 : K[X]) 1; simp } @[simp] lemma num_algebra_map (p : K[X]) : num (algebra_map _ _ p) = p := by { convert num_div p 1; simp } lemma num_div_dvd (p : K[X]) {q : K[X]} (hq : q ≠ 0) : num (algebra_map _ _ p / algebra_map _ _ q) ∣ p := begin rw [num_div _ q, C_mul_dvd], { exact euclidean_domain.div_dvd_of_dvd (gcd_dvd_left p q) }, { simpa only [ne.def, inv_eq_zero, polynomial.leading_coeff_eq_zero] using right_div_gcd_ne_zero hq }, end /-- A version of `num_div_dvd` with the LHS in simp normal form -/ @[simp] lemma num_div_dvd' (p : K[X]) {q : K[X]} (hq : q ≠ 0) : C ((q / gcd p q).leading_coeff)⁻¹ * (p / gcd p q) ∣ p := by simpa using num_div_dvd p hq /-- `ratfunc.denom` is the denominator of a rational function, normalized such that it is monic. -/ def denom (x : ratfunc K) : K[X] := x.num_denom.2 @[simp] lemma denom_div (p : K[X]) {q : K[X]} (hq : q ≠ 0) : denom (algebra_map _ _ p / algebra_map _ _ q) = polynomial.C ((q / gcd p q).leading_coeff⁻¹) * (q / gcd p q) := by rw [denom, num_denom_div _ hq] lemma monic_denom (x : ratfunc K) : (denom x).monic := x.induction_on (λ p q hq, begin rw [denom_div p hq, mul_comm], exact polynomial.monic_mul_leading_coeff_inv (right_div_gcd_ne_zero hq) end) lemma denom_ne_zero (x : ratfunc K) : denom x ≠ 0 := (monic_denom x).ne_zero @[simp] lemma denom_zero : denom (0 : ratfunc K) = 1 := by { convert denom_div (0 : K[X]) one_ne_zero; simp } @[simp] lemma denom_one : denom (1 : ratfunc K) = 1 := by { convert denom_div (1 : K[X]) one_ne_zero; simp } @[simp] lemma denom_algebra_map (p : K[X]) : denom (algebra_map _ (ratfunc K) p) = 1 := by { convert denom_div p one_ne_zero; simp } @[simp] lemma denom_div_dvd (p q : K[X]) : denom (algebra_map _ _ p / algebra_map _ _ q) ∣ q := begin by_cases hq : q = 0, { simp [hq], }, rw [denom_div _ hq, C_mul_dvd], { exact euclidean_domain.div_dvd_of_dvd (gcd_dvd_right p q) }, { simpa only [ne.def, inv_eq_zero, polynomial.leading_coeff_eq_zero] using right_div_gcd_ne_zero hq }, end @[simp] lemma num_div_denom (x : ratfunc K) : algebra_map _ _ (num x) / algebra_map _ _ (denom x) = x := x.induction_on (λ p q hq, begin have q_div_ne_zero := right_div_gcd_ne_zero hq, rw [num_div p q, denom_div p hq, ring_hom.map_mul, ring_hom.map_mul, mul_div_mul_left, div_eq_div_iff, ← ring_hom.map_mul, ← ring_hom.map_mul, mul_comm _ q, ← euclidean_domain.mul_div_assoc, ← euclidean_domain.mul_div_assoc, mul_comm], { apply gcd_dvd_right }, { apply gcd_dvd_left }, { exact algebra_map_ne_zero q_div_ne_zero }, { exact algebra_map_ne_zero hq }, { refine algebra_map_ne_zero (mt polynomial.C_eq_zero.mp _), exact inv_ne_zero (polynomial.leading_coeff_ne_zero.mpr q_div_ne_zero) }, end) lemma is_coprime_num_denom (x : ratfunc K) : is_coprime x.num x.denom := begin induction x using ratfunc.induction_on with p q hq, rw [num_div, denom_div _ hq], exact (is_coprime_mul_unit_left ((leading_coeff_ne_zero.2 $ right_div_gcd_ne_zero hq).is_unit.inv.map C) _ _).2 (is_coprime_div_gcd_div_gcd hq), end @[simp] lemma num_eq_zero_iff {x : ratfunc K} : num x = 0 ↔ x = 0 := ⟨λ h, by rw [← num_div_denom x, h, ring_hom.map_zero, zero_div], λ h, h.symm ▸ num_zero⟩ lemma num_ne_zero {x : ratfunc K} (hx : x ≠ 0) : num x ≠ 0 := mt num_eq_zero_iff.mp hx lemma num_mul_eq_mul_denom_iff {x : ratfunc K} {p q : K[X]} (hq : q ≠ 0) : x.num * q = p * x.denom ↔ x = algebra_map _ _ p / algebra_map _ _ q := begin rw [← (algebra_map_injective K).eq_iff, eq_div_iff (algebra_map_ne_zero hq)], conv_rhs { rw ← num_div_denom x }, rw [ring_hom.map_mul, ring_hom.map_mul, div_eq_mul_inv, mul_assoc, mul_comm (has_inv.inv _), ← mul_assoc, ← div_eq_mul_inv, div_eq_iff], exact algebra_map_ne_zero (denom_ne_zero x) end lemma num_denom_add (x y : ratfunc K) : (x + y).num * (x.denom * y.denom) = (x.num * y.denom + x.denom * y.num) * (x + y).denom := (num_mul_eq_mul_denom_iff (mul_ne_zero (denom_ne_zero x) (denom_ne_zero y))).mpr $ begin conv_lhs { rw [← num_div_denom x, ← num_div_denom y] }, rw [div_add_div, ring_hom.map_mul, ring_hom.map_add, ring_hom.map_mul, ring_hom.map_mul], { exact algebra_map_ne_zero (denom_ne_zero x) }, { exact algebra_map_ne_zero (denom_ne_zero y) } end lemma num_denom_neg (x : ratfunc K) : (-x).num * x.denom = - x.num * (-x).denom := by rw [num_mul_eq_mul_denom_iff (denom_ne_zero x), _root_.map_neg, neg_div, num_div_denom] lemma num_denom_mul (x y : ratfunc K) : (x * y).num * (x.denom * y.denom) = x.num * y.num * (x * y).denom := (num_mul_eq_mul_denom_iff (mul_ne_zero (denom_ne_zero x) (denom_ne_zero y))).mpr $ by conv_lhs { rw [← num_div_denom x, ← num_div_denom y, div_mul_div_comm, ← ring_hom.map_mul, ← ring_hom.map_mul] } lemma num_dvd {x : ratfunc K} {p : K[X]} (hp : p ≠ 0) : num x ∣ p ↔ ∃ (q : K[X]) (hq : q ≠ 0), x = algebra_map _ _ p / algebra_map _ _ q := begin split, { rintro ⟨q, rfl⟩, obtain ⟨hx, hq⟩ := mul_ne_zero_iff.mp hp, use denom x * q, rw [ring_hom.map_mul, ring_hom.map_mul, ← div_mul_div_comm, div_self, mul_one, num_div_denom], { exact ⟨mul_ne_zero (denom_ne_zero x) hq, rfl⟩ }, { exact algebra_map_ne_zero hq } }, { rintro ⟨q, hq, rfl⟩, exact num_div_dvd p hq }, end lemma denom_dvd {x : ratfunc K} {q : K[X]} (hq : q ≠ 0) : denom x ∣ q ↔ ∃ (p : K[X]), x = algebra_map _ _ p / algebra_map _ _ q := begin split, { rintro ⟨p, rfl⟩, obtain ⟨hx, hp⟩ := mul_ne_zero_iff.mp hq, use num x * p, rw [ring_hom.map_mul, ring_hom.map_mul, ← div_mul_div_comm, div_self, mul_one, num_div_denom], { exact algebra_map_ne_zero hp } }, { rintro ⟨p, rfl⟩, exact denom_div_dvd p q }, end lemma num_mul_dvd (x y : ratfunc K) : num (x * y) ∣ num x * num y := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw num_dvd (mul_ne_zero (num_ne_zero hx) (num_ne_zero hy)), refine ⟨x.denom * y.denom, mul_ne_zero (denom_ne_zero x) (denom_ne_zero y), _⟩, rw [ring_hom.map_mul, ring_hom.map_mul, ← div_mul_div_comm, num_div_denom, num_div_denom] end lemma denom_mul_dvd (x y : ratfunc K) : denom (x * y) ∣ denom x * denom y := begin rw denom_dvd (mul_ne_zero (denom_ne_zero x) (denom_ne_zero y)), refine ⟨x.num * y.num, _⟩, rw [ring_hom.map_mul, ring_hom.map_mul, ← div_mul_div_comm, num_div_denom, num_div_denom] end lemma denom_add_dvd (x y : ratfunc K) : denom (x + y) ∣ denom x * denom y := begin rw denom_dvd (mul_ne_zero (denom_ne_zero x) (denom_ne_zero y)), refine ⟨x.num * y.denom + x.denom * y.num, _⟩, rw [ring_hom.map_mul, ring_hom.map_add, ring_hom.map_mul, ring_hom.map_mul, ← div_add_div, num_div_denom, num_div_denom], { exact algebra_map_ne_zero (denom_ne_zero x) }, { exact algebra_map_ne_zero (denom_ne_zero y) }, end lemma map_denom_ne_zero {L F : Type*} [has_zero L] [zero_hom_class F K[X] L] (φ : F) (hφ : function.injective φ) (f : ratfunc K) : φ f.denom ≠ 0 := λ H, (denom_ne_zero f) ((map_eq_zero_iff φ hφ).mp H) lemma map_apply {R F : Type*} [comm_ring R] [is_domain R] [monoid_hom_class F K[X] R[X]] (φ : F) (hφ : K[X]⁰ ≤ R[X]⁰.comap φ) (f : ratfunc K) : map φ hφ f = algebra_map _ _ (φ f.num) / algebra_map _ _ (φ f.denom) := begin rw [←num_div_denom f, map_apply_div_ne_zero, num_div_denom f], exact denom_ne_zero _ end lemma lift_monoid_with_zero_hom_apply {L : Type*} [comm_group_with_zero L] (φ : K[X] →*₀ L) (hφ : K[X]⁰ ≤ L⁰.comap φ) (f : ratfunc K) : lift_monoid_with_zero_hom φ hφ f = φ f.num / φ f.denom := by rw [←num_div_denom f, lift_monoid_with_zero_hom_apply_div, num_div_denom] lemma lift_ring_hom_apply {L : Type*} [field L] (φ : K[X] →+* L) (hφ : K[X]⁰ ≤ L⁰.comap φ) (f : ratfunc K) : lift_ring_hom φ hφ f = φ f.num / φ f.denom := lift_monoid_with_zero_hom_apply _ _ _ lemma lift_alg_hom_apply {L S : Type*} [field L] [comm_semiring S] [algebra S K[X]] [algebra S L] (φ : K[X] →ₐ[S] L) (hφ : K[X]⁰ ≤ L⁰.comap φ) (f : ratfunc K) : lift_alg_hom φ hφ f = φ f.num / φ f.denom := lift_monoid_with_zero_hom_apply _ _ _ lemma num_mul_denom_add_denom_mul_num_ne_zero {x y : ratfunc K} (hxy : x + y ≠ 0) : x.num * y.denom + x.denom * y.num ≠ 0 := begin intro h_zero, have h := num_denom_add x y, rw [h_zero, zero_mul] at h, exact (mul_ne_zero (num_ne_zero hxy) (mul_ne_zero x.denom_ne_zero y.denom_ne_zero)) h end end num_denom section eval /-! ### Polynomial structure: `C`, `X`, `eval` -/ section domain variables [comm_ring K] [is_domain K] /-- `ratfunc.C a` is the constant rational function `a`. -/ def C : K →+* ratfunc K := algebra_map _ _ @[simp] lemma algebra_map_eq_C : algebra_map K (ratfunc K) = C := rfl @[simp] lemma algebra_map_C (a : K) : algebra_map K[X] (ratfunc K) (polynomial.C a) = C a := rfl @[simp] lemma algebra_map_comp_C : (algebra_map K[X] (ratfunc K)).comp polynomial.C = C := rfl lemma smul_eq_C_mul (r : K) (x : ratfunc K) : r • x = C r * x := by rw [algebra.smul_def, algebra_map_eq_C] /-- `ratfunc.X` is the polynomial variable (aka indeterminate). -/ def X : ratfunc K := algebra_map K[X] (ratfunc K) polynomial.X @[simp] lemma algebra_map_X : algebra_map K[X] (ratfunc K) polynomial.X = X := rfl end domain section field variables [field K] @[simp] lemma num_C (c : K) : num (C c) = polynomial.C c := num_algebra_map _ @[simp] lemma denom_C (c : K) : denom (C c) = 1 := denom_algebra_map _ @[simp] lemma num_X : num (X : ratfunc K) = polynomial.X := num_algebra_map _ @[simp] lemma denom_X : denom (X : ratfunc K) = 1 := denom_algebra_map _ lemma X_ne_zero : (ratfunc.X : ratfunc K) ≠ 0 := ratfunc.algebra_map_ne_zero polynomial.X_ne_zero variables {L : Type*} [field L] /-- Evaluate a rational function `p` given a ring hom `f` from the scalar field to the target and a value `x` for the variable in the target. Fractions are reduced by clearing common denominators before evaluating: `eval id 1 ((X^2 - 1) / (X - 1)) = eval id 1 (X + 1) = 2`, not `0 / 0 = 0`. -/ def eval (f : K →+* L) (a : L) (p : ratfunc K) : L := (num p).eval₂ f a / (denom p).eval₂ f a variables {f : K →+* L} {a : L} lemma eval_eq_zero_of_eval₂_denom_eq_zero {x : ratfunc K} (h : polynomial.eval₂ f a (denom x) = 0) : eval f a x = 0 := by rw [eval, h, div_zero] lemma eval₂_denom_ne_zero {x : ratfunc K} (h : eval f a x ≠ 0) : polynomial.eval₂ f a (denom x) ≠ 0 := mt eval_eq_zero_of_eval₂_denom_eq_zero h variables (f a) @[simp] lemma eval_C {c : K} : eval f a (C c) = f c := by simp [eval] @[simp] lemma eval_X : eval f a X = a := by simp [eval] @[simp] lemma eval_zero : eval f a 0 = 0 := by simp [eval] @[simp] lemma eval_one : eval f a 1 = 1 := by simp [eval] @[simp] lemma eval_algebra_map {S : Type*} [comm_semiring S] [algebra S K[X]] (p : S) : eval f a (algebra_map _ _ p) = (algebra_map _ K[X] p).eval₂ f a := by simp [eval, is_scalar_tower.algebra_map_apply S K[X] (ratfunc K)] /-- `eval` is an additive homomorphism except when a denominator evaluates to `0`. Counterexample: `eval _ 1 (X / (X-1)) + eval _ 1 (-1 / (X-1)) = 0` `... ≠ 1 = eval _ 1 ((X-1) / (X-1))`. See also `ratfunc.eval₂_denom_ne_zero` to make the hypotheses simpler but less general. -/ lemma eval_add {x y : ratfunc K} (hx : polynomial.eval₂ f a (denom x) ≠ 0) (hy : polynomial.eval₂ f a (denom y) ≠ 0) : eval f a (x + y) = eval f a x + eval f a y := begin unfold eval, by_cases hxy : polynomial.eval₂ f a (denom (x + y)) = 0, { have := polynomial.eval₂_eq_zero_of_dvd_of_eval₂_eq_zero f a (denom_add_dvd x y) hxy, rw polynomial.eval₂_mul at this, cases mul_eq_zero.mp this; contradiction }, rw [div_add_div _ _ hx hy, eq_div_iff (mul_ne_zero hx hy), div_eq_mul_inv, mul_right_comm, ← div_eq_mul_inv, div_eq_iff hxy], simp only [← polynomial.eval₂_mul, ← polynomial.eval₂_add], congr' 1, apply num_denom_add end /-- `eval` is a multiplicative homomorphism except when a denominator evaluates to `0`. Counterexample: `eval _ 0 X * eval _ 0 (1/X) = 0 ≠ 1 = eval _ 0 1 = eval _ 0 (X * 1/X)`. See also `ratfunc.eval₂_denom_ne_zero` to make the hypotheses simpler but less general. -/ lemma eval_mul {x y : ratfunc K} (hx : polynomial.eval₂ f a (denom x) ≠ 0) (hy : polynomial.eval₂ f a (denom y) ≠ 0) : eval f a (x * y) = eval f a x * eval f a y := begin unfold eval, by_cases hxy : polynomial.eval₂ f a (denom (x * y)) = 0, { have := polynomial.eval₂_eq_zero_of_dvd_of_eval₂_eq_zero f a (denom_mul_dvd x y) hxy, rw polynomial.eval₂_mul at this, cases mul_eq_zero.mp this; contradiction }, rw [div_mul_div_comm, eq_div_iff (mul_ne_zero hx hy), div_eq_mul_inv, mul_right_comm, ← div_eq_mul_inv, div_eq_iff hxy], repeat { rw ← polynomial.eval₂_mul }, congr' 1, apply num_denom_mul, end end field end eval section int_degree open polynomial variables [field K] /-- `int_degree x` is the degree of the rational function `x`, defined as the difference between the `nat_degree` of its numerator and the `nat_degree` of its denominator. In particular, `int_degree 0 = 0`. -/ def int_degree (x : ratfunc K) : ℤ := nat_degree x.num - nat_degree x.denom @[simp] lemma int_degree_zero : int_degree (0 : ratfunc K) = 0 := by rw [int_degree, num_zero, nat_degree_zero, denom_zero, nat_degree_one, sub_self] @[simp] lemma int_degree_one : int_degree (1 : ratfunc K) = 0 := by rw [int_degree, num_one, denom_one, sub_self] @[simp] lemma int_degree_C (k : K): int_degree (ratfunc.C k) = 0 := by rw [int_degree, num_C, nat_degree_C, denom_C, nat_degree_one, sub_self] @[simp] lemma int_degree_X : int_degree (X : ratfunc K) = 1 := by rw [int_degree, ratfunc.num_X, polynomial.nat_degree_X, ratfunc.denom_X, polynomial.nat_degree_one, int.coe_nat_one, int.coe_nat_zero, sub_zero] @[simp] lemma int_degree_polynomial {p : K[X]} : int_degree (algebra_map K[X] (ratfunc K) p) = nat_degree p := by rw [int_degree, ratfunc.num_algebra_map, ratfunc.denom_algebra_map, polynomial.nat_degree_one, int.coe_nat_zero, sub_zero] lemma int_degree_mul {x y : ratfunc K} (hx : x ≠ 0) (hy : y ≠ 0) : int_degree (x * y) = int_degree x + int_degree y := begin simp only [int_degree, add_sub, sub_add, sub_sub_eq_add_sub, sub_sub, sub_eq_sub_iff_add_eq_add], norm_cast, rw [← polynomial.nat_degree_mul x.denom_ne_zero y.denom_ne_zero, ← polynomial.nat_degree_mul (ratfunc.num_ne_zero (mul_ne_zero hx hy)) (mul_ne_zero x.denom_ne_zero y.denom_ne_zero), ← polynomial.nat_degree_mul (ratfunc.num_ne_zero hx) (ratfunc.num_ne_zero hy), ← polynomial.nat_degree_mul (mul_ne_zero (ratfunc.num_ne_zero hx) (ratfunc.num_ne_zero hy)) (x * y).denom_ne_zero, ratfunc.num_denom_mul] end @[simp] lemma int_degree_neg (x : ratfunc K) : int_degree (-x) = int_degree x := begin by_cases hx : x = 0, { rw [hx, neg_zero] }, { rw [int_degree, int_degree, ← nat_degree_neg x.num], exact nat_degree_sub_eq_of_prod_eq (num_ne_zero (neg_ne_zero.mpr hx)) (denom_ne_zero (- x)) (neg_ne_zero.mpr (num_ne_zero hx)) (denom_ne_zero x) (num_denom_neg x) } end lemma int_degree_add {x y : ratfunc K} (hxy : x + y ≠ 0) : (x + y).int_degree = (x.num * y.denom + x.denom * y.num).nat_degree - (x.denom * y.denom).nat_degree := nat_degree_sub_eq_of_prod_eq (num_ne_zero hxy) ((x + y).denom_ne_zero) (num_mul_denom_add_denom_mul_num_ne_zero hxy) (mul_ne_zero x.denom_ne_zero y.denom_ne_zero) (num_denom_add x y) lemma nat_degree_num_mul_right_sub_nat_degree_denom_mul_left_eq_int_degree {x : ratfunc K} (hx : x ≠ 0) {s : K[X]} (hs : s ≠ 0) : ((x.num * s).nat_degree : ℤ) - (s * x.denom).nat_degree = x.int_degree := begin apply nat_degree_sub_eq_of_prod_eq (mul_ne_zero (num_ne_zero hx) hs) (mul_ne_zero hs x.denom_ne_zero) (num_ne_zero hx) x.denom_ne_zero, rw mul_assoc end lemma int_degree_add_le {x y : ratfunc K} (hy : y ≠ 0) (hxy : x + y ≠ 0) : int_degree (x + y) ≤ max (int_degree x) (int_degree y) := begin by_cases hx : x = 0, { simp [hx] at *, }, rw [int_degree_add hxy, ← nat_degree_num_mul_right_sub_nat_degree_denom_mul_left_eq_int_degree hx y.denom_ne_zero, mul_comm y.denom, ← nat_degree_num_mul_right_sub_nat_degree_denom_mul_left_eq_int_degree hy x.denom_ne_zero, le_max_iff,sub_le_sub_iff_right, int.coe_nat_le, sub_le_sub_iff_right, int.coe_nat_le, ← le_max_iff, mul_comm y.num], exact nat_degree_add_le _ _, end end int_degree section laurent_series open power_series laurent_series hahn_series variables {F : Type u} [field F] (p q : F[X]) (f g : ratfunc F) /-- The coercion `ratfunc F → laurent_series F` as bundled alg hom. -/ def coe_alg_hom (F : Type u) [field F] : ratfunc F →ₐ[F[X]] laurent_series F := lift_alg_hom (algebra.of_id _ _) $ non_zero_divisors_le_comap_non_zero_divisors_of_injective _ $ polynomial.algebra_map_hahn_series_injective _ instance coe_to_laurent_series : has_coe (ratfunc F) (laurent_series F) := ⟨coe_alg_hom F⟩ lemma coe_def : (f : laurent_series F) = coe_alg_hom F f := rfl lemma coe_num_denom : (f : laurent_series F) = f.num / f.denom := lift_alg_hom_apply _ _ f lemma coe_injective : function.injective (coe : ratfunc F → laurent_series F) := lift_alg_hom_injective _ (polynomial.algebra_map_hahn_series_injective _) @[simp, norm_cast] lemma coe_apply : coe_alg_hom F f = f := rfl @[simp, norm_cast] lemma coe_zero : ((0 : ratfunc F) : laurent_series F) = 0 := (coe_alg_hom F).map_zero @[simp, norm_cast] lemma coe_one : ((1 : ratfunc F) : laurent_series F) = 1 := (coe_alg_hom F).map_one @[simp, norm_cast] lemma coe_add : ((f + g : ratfunc F) : laurent_series F) = f + g := (coe_alg_hom F).map_add _ _ @[simp, norm_cast] lemma coe_sub : ((f - g : ratfunc F) : laurent_series F) = f - g := (coe_alg_hom F).map_sub _ _ @[simp, norm_cast] lemma coe_neg : ((-f : ratfunc F) : laurent_series F) = -f := (coe_alg_hom F).map_neg _ @[simp, norm_cast] lemma coe_mul : ((f * g : ratfunc F) : laurent_series F) = f * g := (coe_alg_hom F).map_mul _ _ @[simp, norm_cast] lemma coe_pow (n : ℕ) : ((f ^ n : ratfunc F) : laurent_series F) = f ^ n := (coe_alg_hom F).map_pow _ _ @[simp, norm_cast] lemma coe_div : ((f / g : ratfunc F) : laurent_series F) = (f : laurent_series F) / (g : laurent_series F) := map_div₀ (coe_alg_hom F) _ _ @[simp, norm_cast] lemma coe_C (r : F) : ((C r : ratfunc F) : laurent_series F) = hahn_series.C r := by rw [coe_num_denom, num_C, denom_C, coe_coe, polynomial.coe_C, coe_C, coe_coe, polynomial.coe_one, power_series.coe_one, div_one] -- TODO: generalize over other modules @[simp, norm_cast] lemma coe_smul (r : F) : ((r • f : ratfunc F) : laurent_series F) = r • f := by rw [smul_eq_C_mul, ←C_mul_eq_smul, coe_mul, coe_C] @[simp, norm_cast] lemma coe_X : ((X : ratfunc F) : laurent_series F) = single 1 1 := by rw [coe_num_denom, num_X, denom_X, coe_coe, polynomial.coe_X, coe_X, coe_coe, polynomial.coe_one, power_series.coe_one, div_one] instance : algebra (ratfunc F) (laurent_series F) := ring_hom.to_algebra (coe_alg_hom F).to_ring_hom lemma algebra_map_apply_div : algebra_map (ratfunc F) (laurent_series F) (algebra_map _ _ p / algebra_map _ _ q) = algebra_map F[X] (laurent_series F) p / algebra_map _ _ q := begin convert coe_div _ _; rw [←mk_one, coe_def, coe_alg_hom, mk_eq_div, lift_alg_hom_apply_div, map_one, div_one, algebra.of_id_apply] end instance : is_scalar_tower F[X] (ratfunc F) (laurent_series F) := ⟨λ x y z, by { ext, simp }⟩ end laurent_series end ratfunc
70f0f3116bb542dee8f3b782ba91d14253a28b91
037dba89703a79cd4a4aec5e959818147f97635d
/src/2021/sets/sheet6.lean
59861539d56038cbfca56fb42d1aedac6b8ef9d0
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
1,175
lean
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Kevin Buzzard -/ import tactic -- imports all the Lean tactics /-! # Sets in Lean, sheet 6 : equality of sets Sets are extensional objects to mathematicians, which means that if two sets have the same elements, then they are equal. ## Tactics Tactics you will need to know for this sheet: * `ext` ### The `ext` tactic If the goal is `⊢ A = B` where `A` and `B` are subsets of `X`, then the tactic `ext x,` will create a hypothesis `x : X` and change the goal to `x ∈ A ↔ x ∈ B`. -/ open set variables (X : Type) -- Everything will be a subset of `X` (A B C D E : set X) -- A,B,C,D,E are subsets of `X` (x y z : X) -- x,y,z are elements of `X` or, more precisely, terms of type `X` example : A ⊆ B → B ⊆ A → A = B := begin sorry end example : A ∪ A = A := begin sorry end example : A ∩ A = A := begin sorry end example : A ∩ B = B ∩ A := begin sorry end example : A ∩ (B ∩ C) = (A ∩ B) ∩ C := begin sorry end example : A ∪ (B ∪ C) = (A ∪ B) ∪ C := begin sorry end
3f95e3d7443b4ef7e4e0507457daad14b39d0602
42610cc2e5db9c90269470365e6056df0122eaa0
/hott/init/pathover.hlean
1b96d4ebcbd042cca9edf27e62ee93397524497d
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
13,118
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Basic theorems about pathovers -/ prelude import .path .equiv open equiv is_equiv function variables {A A' : Type} {B B' : A → Type} {B'' : A' → Type} {C : Π⦃a⦄, B a → Type} {a a₂ a₃ a₄ : A} {p p' : a = a₂} {p₂ : a₂ = a₃} {p₃ : a₃ = a₄} {p₁₃ : a = a₃} {b b' : B a} {b₂ b₂' : B a₂} {b₃ : B a₃} {b₄ : B a₄} {c : C b} {c₂ : C b₂} namespace eq inductive pathover.{l} (B : A → Type.{l}) (b : B a) : Π{a₂ : A}, a = a₂ → B a₂ → Type.{l} := idpatho : pathover B b (refl a) b notation b ` =[`:50 p:0 `] `:0 b₂:50 := pathover _ b p b₂ definition idpo [reducible] [constructor] : b =[refl a] b := pathover.idpatho b /- equivalences with equality using transport -/ definition pathover_of_tr_eq [unfold 5 8] (r : p ▸ b = b₂) : b =[p] b₂ := by cases p; cases r; constructor definition pathover_of_eq_tr [unfold 5 8] (r : b = p⁻¹ ▸ b₂) : b =[p] b₂ := by cases p; cases r; constructor definition tr_eq_of_pathover [unfold 8] (r : b =[p] b₂) : p ▸ b = b₂ := by cases r; reflexivity definition eq_tr_of_pathover [unfold 8] (r : b =[p] b₂) : b = p⁻¹ ▸ b₂ := by cases r; reflexivity definition pathover_equiv_tr_eq [constructor] (p : a = a₂) (b : B a) (b₂ : B a₂) : (b =[p] b₂) ≃ (p ▸ b = b₂) := begin fapply equiv.MK, { exact tr_eq_of_pathover}, { exact pathover_of_tr_eq}, { intro r, cases p, cases r, apply idp}, { intro r, cases r, apply idp}, end definition pathover_equiv_eq_tr [constructor] (p : a = a₂) (b : B a) (b₂ : B a₂) : (b =[p] b₂) ≃ (b = p⁻¹ ▸ b₂) := begin fapply equiv.MK, { exact eq_tr_of_pathover}, { exact pathover_of_eq_tr}, { intro r, cases p, cases r, apply idp}, { intro r, cases r, apply idp}, end definition pathover_tr [unfold 5] (p : a = a₂) (b : B a) : b =[p] p ▸ b := by cases p;constructor definition tr_pathover [unfold 5] (p : a = a₂) (b : B a₂) : p⁻¹ ▸ b =[p] b := by cases p;constructor definition concato [unfold 12] (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) : b =[p ⬝ p₂] b₃ := pathover.rec_on r₂ r definition inverseo [unfold 8] (r : b =[p] b₂) : b₂ =[p⁻¹] b := pathover.rec_on r idpo definition apd [unfold 6] (f : Πa, B a) (p : a = a₂) : f a =[p] f a₂ := eq.rec_on p idpo definition concato_eq [unfold 10] (r : b =[p] b₂) (q : b₂ = b₂') : b =[p] b₂' := eq.rec_on q r definition eq_concato [unfold 9] (q : b = b') (r : b' =[p] b₂) : b =[p] b₂ := by induction q;exact r definition change_path [unfold 9] (q : p = p') (r : b =[p] b₂) : b =[p'] b₂ := q ▸ r -- infix ` ⬝ ` := concato infix ` ⬝o `:72 := concato infix ` ⬝op `:73 := concato_eq infix ` ⬝po `:73 := eq_concato -- postfix `⁻¹` := inverseo postfix `⁻¹ᵒ`:(max+10) := inverseo definition pathover_cancel_right (q : b =[p ⬝ p₂] b₃) (r : b₃ =[p₂⁻¹] b₂) : b =[p] b₂ := change_path !con_inv_cancel_right (q ⬝o r) definition pathover_cancel_right' (q : b =[p₁₃ ⬝ p₂⁻¹] b₂) (r : b₂ =[p₂] b₃) : b =[p₁₃] b₃ := change_path !inv_con_cancel_right (q ⬝o r) definition pathover_cancel_left (q : b₂ =[p⁻¹] b) (r : b =[p ⬝ p₂] b₃) : b₂ =[p₂] b₃ := change_path !inv_con_cancel_left (q ⬝o r) definition pathover_cancel_left' (q : b =[p] b₂) (r : b₂ =[p⁻¹ ⬝ p₁₃] b₃) : b =[p₁₃] b₃ := change_path !con_inv_cancel_left (q ⬝o r) /- Some of the theorems analogous to theorems for = in init.path -/ definition cono_idpo (r : b =[p] b₂) : r ⬝o idpo =[con_idp p] r := pathover.rec_on r idpo definition idpo_cono (r : b =[p] b₂) : idpo ⬝o r =[idp_con p] r := pathover.rec_on r idpo definition cono.assoc' (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) : r ⬝o (r₂ ⬝o r₃) =[!con.assoc'] (r ⬝o r₂) ⬝o r₃ := pathover.rec_on r₃ (pathover.rec_on r₂ (pathover.rec_on r idpo)) definition cono.assoc (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) : (r ⬝o r₂) ⬝o r₃ =[!con.assoc] r ⬝o (r₂ ⬝o r₃) := pathover.rec_on r₃ (pathover.rec_on r₂ (pathover.rec_on r idpo)) definition cono.right_inv (r : b =[p] b₂) : r ⬝o r⁻¹ᵒ =[!con.right_inv] idpo := pathover.rec_on r idpo definition cono.left_inv (r : b =[p] b₂) : r⁻¹ᵒ ⬝o r =[!con.left_inv] idpo := pathover.rec_on r idpo definition eq_of_pathover {a' a₂' : A'} (q : a' =[p] a₂') : a' = a₂' := by cases q;reflexivity definition pathover_of_eq [unfold 5 8] {a' a₂' : A'} (q : a' = a₂') : a' =[p] a₂' := by cases p;cases q;constructor definition pathover_constant [constructor] (p : a = a₂) (a' a₂' : A') : a' =[p] a₂' ≃ a' = a₂' := begin fapply equiv.MK, { exact eq_of_pathover}, { exact pathover_of_eq}, { intro r, cases p, cases r, reflexivity}, { intro r, cases r, reflexivity}, end definition pathover_of_eq_tr_constant_inv (p : a = a₂) (a' : A') : pathover_of_eq (tr_constant p a')⁻¹ = pathover_tr p a' := by cases p; constructor definition eq_of_pathover_idp [unfold 6] {b' : B a} (q : b =[idpath a] b') : b = b' := tr_eq_of_pathover q --should B be explicit in the next two definitions? definition pathover_idp_of_eq [unfold 6] {b' : B a} (q : b = b') : b =[idpath a] b' := pathover_of_tr_eq q definition pathover_idp [constructor] (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' := equiv.MK eq_of_pathover_idp (pathover_idp_of_eq) (to_right_inv !pathover_equiv_tr_eq) (to_left_inv !pathover_equiv_tr_eq) -- definition pathover_idp (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' := -- pathover_equiv_tr_eq idp b b' -- definition eq_of_pathover_idp [reducible] {b' : B a} (q : b =[idpath a] b') : b = b' := -- to_fun !pathover_idp q -- definition pathover_idp_of_eq [reducible] {b' : B a} (q : b = b') : b =[idpath a] b' := -- to_inv !pathover_idp q definition idp_rec_on [recursor] {P : Π⦃b₂ : B a⦄, b =[idpath a] b₂ → Type} {b₂ : B a} (r : b =[idpath a] b₂) (H : P idpo) : P r := have H2 : P (pathover_idp_of_eq (eq_of_pathover_idp r)), from eq.rec_on (eq_of_pathover_idp r) H, proof left_inv !pathover_idp r ▸ H2 qed definition rec_on_right [recursor] {P : Π⦃b₂ : B a₂⦄, b =[p] b₂ → Type} {b₂ : B a₂} (r : b =[p] b₂) (H : P !pathover_tr) : P r := by cases r; exact H definition rec_on_left [recursor] {P : Π⦃b : B a⦄, b =[p] b₂ → Type} {b : B a} (r : b =[p] b₂) (H : P !tr_pathover) : P r := by cases r; exact H --pathover with fibration B' ∘ f definition pathover_ap [unfold 10] (B' : A' → Type) (f : A → A') {p : a = a₂} {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) : b =[ap f p] b₂ := by cases q; constructor definition pathover_of_pathover_ap (B' : A' → Type) (f : A → A') {p : a = a₂} {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[ap f p] b₂) : b =[p] b₂ := by cases p; apply (idp_rec_on q); apply idpo definition pathover_compose [constructor] (B' : A' → Type) (f : A → A') (p : a = a₂) (b : B' (f a)) (b₂ : B' (f a₂)) : b =[p] b₂ ≃ b =[ap f p] b₂ := begin fapply equiv.MK, { exact pathover_ap B' f}, { exact pathover_of_pathover_ap B' f}, { intro q, cases p, esimp, apply (idp_rec_on q), apply idp}, { intro q, cases q, reflexivity}, end definition apd_con (f : Πa, B a) (p : a = a₂) (q : a₂ = a₃) : apd f (p ⬝ q) = apd f p ⬝o apd f q := by cases p; cases q; reflexivity definition apd_inv (f : Πa, B a) (p : a = a₂) : apd f p⁻¹ = (apd f p)⁻¹ᵒ := by cases p; reflexivity definition apd_eq_pathover_of_eq_ap (f : A → A') (p : a = a₂) : apd f p = pathover_of_eq (ap f p) := eq.rec_on p idp definition pathover_of_pathover_tr (q : b =[p ⬝ p₂] p₂ ▸ b₂) : b =[p] b₂ := pathover_cancel_right q !pathover_tr⁻¹ᵒ definition pathover_tr_of_pathover (q : b =[p₁₃ ⬝ p₂⁻¹] b₂) : b =[p₁₃] p₂ ▸ b₂ := pathover_cancel_right' q !pathover_tr definition pathover_of_tr_pathover (q : p ▸ b =[p⁻¹ ⬝ p₁₃] b₃) : b =[p₁₃] b₃ := pathover_cancel_left' !pathover_tr q definition tr_pathover_of_pathover (q : b =[p ⬝ p₂] b₃) : p ▸ b =[p₂] b₃ := pathover_cancel_left !pathover_tr⁻¹ᵒ q definition pathover_tr_of_eq (q : b = b') : b =[p] p ▸ b' := by cases q;apply pathover_tr definition tr_pathover_of_eq (q : b₂ = b₂') : p⁻¹ ▸ b₂ =[p] b₂' := by cases q;apply tr_pathover variable (C) definition transporto (r : b =[p] b₂) (c : C b) : C b₂ := by induction r;exact c infix ` ▸o `:75 := transporto _ definition fn_tro_eq_tro_fn (C' : Π ⦃a : A⦄, B a → Type) (q : b =[p] b₂) (f : Π(b : B a), C b → C' b) (c : C b) : f b (q ▸o c) = (q ▸o (f b c)) := by induction q;reflexivity variable {C} definition apo {f : A → A'} (g : Πa, B a → B'' (f a)) (q : b =[p] b₂) : g a b =[p] g a₂ b₂ := by induction q; constructor definition apo011 [unfold 10] (f : Πa, B a → A') (Ha : a = a₂) (Hb : b =[Ha] b₂) : f a b = f a₂ b₂ := by cases Hb; reflexivity definition apo0111 (f : Πa b, C b → A') (Ha : a = a₂) (Hb : b =[Ha] b₂) (Hc : c =[apo011 C Ha Hb] c₂) : f a b c = f a₂ b₂ c₂ := by cases Hb; apply (idp_rec_on Hc); apply idp definition apod11 {f : Πb, C b} {g : Πb₂, C b₂} (r : f =[p] g) {b : B a} {b₂ : B a₂} (q : b =[p] b₂) : f b =[apo011 C p q] g b₂ := by cases r; apply (idp_rec_on q); constructor definition apdo10 {f : Πb, C b} {g : Πb₂, C b₂} (r : f =[p] g) (b : B a) : f b =[apo011 C p !pathover_tr] g (p ▸ b) := by cases r; constructor definition apo10 [unfold 9] {f : B a → B' a} {g : B a₂ → B' a₂} (r : f =[p] g) (b : B a) : f b =[p] g (p ▸ b) := by cases r; constructor definition apo10_constant_right [unfold 9] {f : B a → A'} {g : B a₂ → A'} (r : f =[p] g) (b : B a) : f b = g (p ▸ b) := by cases r; constructor definition apo10_constant_left [unfold 9] {f : A' → B a} {g : A' → B a₂} (r : f =[p] g) (a' : A') : f a' =[p] g a' := by cases r; constructor definition apo11 {f : B a → B' a} {g : B a₂ → B' a₂} (r : f =[p] g) (q : b =[p] b₂) : f b =[p] g b₂ := by induction q; exact apo10 r b definition apd_compose1 (g : Πa, B a → B' a) (f : Πa, B a) (p : a = a₂) : apd (g ∘' f) p = apo g (apd f p) := by induction p; reflexivity definition apd_compose2 (g : Πa', B'' a') (f : A → A') (p : a = a₂) : apd (λa, g (f a)) p = pathover_of_pathover_ap B'' f (apd g (ap f p)) := by induction p; reflexivity definition cono.right_inv_eq (q : b = b') : concato_eq (pathover_idp_of_eq q) q⁻¹ = (idpo : b =[refl a] b) := by induction q;constructor definition cono.right_inv_eq' (q : b = b') : eq_concato q (pathover_idp_of_eq q⁻¹) = (idpo : b =[refl a] b) := by induction q;constructor definition cono.left_inv_eq (q : b = b') : concato_eq (pathover_idp_of_eq q⁻¹) q = (idpo : b' =[refl a] b') := by induction q;constructor definition cono.left_inv_eq' (q : b = b') : eq_concato q⁻¹ (pathover_idp_of_eq q) = (idpo : b' =[refl a] b') := by induction q;constructor definition pathover_of_fn_pathover_fn (f : Π{a}, B a ≃ B' a) (r : f b =[p] f b₂) : b =[p] b₂ := (left_inv f b)⁻¹ ⬝po apo (λa, f⁻¹ᵉ) r ⬝op left_inv f b₂ definition change_path_of_pathover (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂) (q : r =[s] r') : change_path s r = r' := by induction s; eapply idp_rec_on q; reflexivity definition pathover_of_change_path (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂) (q : change_path s r = r') : r =[s] r' := by induction s; induction q; constructor definition pathover_pathover_path [constructor] (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂) : (r =[s] r') ≃ change_path s r = r' := begin fapply equiv.MK, { apply change_path_of_pathover}, { apply pathover_of_change_path}, { intro q, induction s, induction q, reflexivity}, { intro q, induction s, eapply idp_rec_on q, reflexivity}, end definition inverseo2 [unfold 10] {r r' : b =[p] b₂} (s : r = r') : r⁻¹ᵒ = r'⁻¹ᵒ := by induction s; reflexivity definition concato2 [unfold 15 16] {r r' : b =[p] b₂} {r₂ r₂' : b₂ =[p₂] b₃} (s : r = r') (s₂ : r₂ = r₂') : r ⬝o r₂ = r' ⬝o r₂' := by induction s; induction s₂; reflexivity infixl ` ◾o `:75 := concato2 postfix [parsing_only] `⁻²ᵒ`:(max+10) := inverseo2 --this notation is abusive, should we use it? end eq
3c1364d1f48555b0f57f3d0c8b6dda189f50336f
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Elab/BuiltinNotation.lean
bb6a163876dd9d7d109a01efa708837e32c95c22
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
16,636
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.BorrowedAnnotation import Lean.Meta.KAbstract import Lean.Meta.MatchUtil import Lean.Elab.SyntheticMVars namespace Lean.Elab.Term open Meta @[builtinTermElab coeNotation] def elabCoe : TermElab := fun stx expectedType? => do let stx := stx[1] tryPostponeIfNoneOrMVar expectedType? let e ← elabTerm stx none let type ← inferType e match expectedType? with | some expectedType => if (← isDefEq expectedType type) then return e else mkCoe expectedType type e | _ => throwError "invalid coercion notation, expected type is not known" @[builtinTermElab anonymousCtor] def elabAnonymousCtor : TermElab := fun stx expectedType? => match stx with | `(⟨$args,*⟩) => do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => let expectedType ← whnf expectedType matchConstInduct expectedType.getAppFn (fun _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type {indentExpr expectedType}") (fun ival _ => do match ival.ctors with | [ctor] => if isPrivateNameFromImportedModule (← getEnv) ctor then throwError "invalid ⟨...⟩ notation, constructor for `{ival.name}` is marked as private" let cinfo ← getConstInfoCtor ctor let numExplicitFields ← forallTelescopeReducing cinfo.type fun xs _ => do let mut n := 0 for i in [cinfo.numParams:xs.size] do if (← getFVarLocalDecl xs[i]!).binderInfo.isExplicit then n := n + 1 return n let args := args.getElems if args.size < numExplicitFields then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' has #{numExplicitFields} explicit fields, but only #{args.size} provided" let newStx ← if args.size == numExplicitFields then `($(mkCIdentFrom stx ctor (canonical := true)) $(args)*) else if numExplicitFields == 0 then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' does not have explicit fields, but #{args.size} provided" else let extra := args[numExplicitFields-1:args.size] let newLast ← `(⟨$[$extra],*⟩) let newArgs := args[0:numExplicitFields-1].toArray.push newLast `($(mkCIdentFrom stx ctor (canonical := true)) $(newArgs)*) withMacroExpansion stx newStx $ elabTerm newStx expectedType? | _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type with only one constructor {indentExpr expectedType}") | none => throwError "invalid constructor ⟨...⟩, expected type must be known" | _ => throwUnsupportedSyntax @[builtinTermElab borrowed] def elabBorrowed : TermElab := fun stx expectedType? => match stx with | `(@& $e) => return markBorrowed (← elabTerm e expectedType?) | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Term.show] def expandShow : Macro := fun stx => match stx with | `(show $type from $val) => let thisId := mkIdentFrom stx `this; `(let_fun $thisId : $type := $val; $thisId) | `(show $type by%$b $tac) => `(show $type from by%$b $tac) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.have] def expandHave : Macro := fun stx => match stx with | `(have $x $bs* $[: $type]? := $val; $body) => `(let_fun $x $bs* $[: $type]? := $val; $body) | `(have%$tk $[: $type]? := $val; $body) => `(have $(mkIdentFrom tk `this (canonical := true)) $[: $type]? := $val; $body) | `(have $x $bs* $[: $type]? $alts; $body) => `(let_fun $x $bs* $[: $type]? $alts; $body) | `(have%$tk $[: $type]? $alts:matchAlts; $body) => `(have $(mkIdentFrom tk `this (canonical := true)) $[: $type]? $alts:matchAlts; $body) | `(have $pattern:term $[: $type]? := $val:term; $body) => `(let_fun $pattern:term $[: $type]? := $val:term ; $body) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.suffices] def expandSuffices : Macro | `(suffices%$tk $[$x :]? $type from $val; $body) => `(have%$tk $[$x]? : $type := $body; $val) | `(suffices%$tk $[$x :]? $type by%$b $tac:tacticSeq; $body) => `(have%$tk $[$x]? : $type := $body; by%$b $tac) | _ => Macro.throwUnsupported open Lean.Parser in private def elabParserMacroAux (prec e : Term) (withAnonymousAntiquot : Bool) : TermElabM Syntax := do let (some declName) ← getDeclName? | throwError "invalid `leading_parser` macro, it must be used in definitions" match extractMacroScopes declName with | { name := .str _ s, .. } => let kind := quote declName let s := quote s ``(withAntiquot (mkAntiquot $s $kind $(quote withAnonymousAntiquot)) (leadingNode $kind $prec $e)) | _ => throwError "invalid `leading_parser` macro, unexpected declaration name" @[builtinTermElab «leading_parser»] def elabLeadingParserMacro : TermElab := adaptExpander fun stx => match stx with | `(leading_parser $[: $prec?]? $[(withAnonymousAntiquot := $anon?)]? $e) => elabParserMacroAux (prec?.getD (quote Parser.maxPrec)) e (anon?.all (·.raw.isOfKind ``Parser.Term.trueVal)) | _ => throwUnsupportedSyntax private def elabTParserMacroAux (prec lhsPrec e : Term) : TermElabM Syntax := do let declName? ← getDeclName? match declName? with | some declName => let kind := quote declName; ``(Lean.Parser.trailingNode $kind $prec $lhsPrec $e) | none => throwError "invalid `trailing_parser` macro, it must be used in definitions" @[builtinTermElab «trailing_parser»] def elabTrailingParserMacro : TermElab := adaptExpander fun stx => match stx with | `(trailing_parser$[:$prec?]?$[:$lhsPrec?]? $e) => elabTParserMacroAux (prec?.getD <| quote Parser.maxPrec) (lhsPrec?.getD <| quote 0) e | _ => throwUnsupportedSyntax @[builtinTermElab Lean.Parser.Term.panic] def elabPanic : TermElab := fun stx expectedType? => do match stx with | `(panic! $arg) => let pos ← getRefPosition let env ← getEnv let stxNew ← match (← getDeclName?) with | some declName => `(panicWithPosWithDecl $(quote (toString env.mainModule)) $(quote (toString declName)) $(quote pos.line) $(quote pos.column) $arg) | none => `(panicWithPos $(quote (toString env.mainModule)) $(quote pos.line) $(quote pos.column) $arg) withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Term.unreachable] def expandUnreachable : Macro := fun _ => `(panic! "unreachable code has been reached") @[builtinMacro Lean.Parser.Term.assert] def expandAssert : Macro | `(assert! $cond; $body) => -- TODO: support for disabling runtime assertions match cond.raw.reprint with | some code => `(if $cond then $body else panic! ("assertion violation: " ++ $(quote code))) | none => `(if $cond then $body else panic! ("assertion violation")) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.dbgTrace] def expandDbgTrace : Macro | `(dbg_trace $arg:interpolatedStr; $body) => `(dbgTrace (s! $arg) fun _ => $body) | `(dbg_trace $arg:term; $body) => `(dbgTrace (toString $arg) fun _ => $body) | _ => Macro.throwUnsupported @[builtinTermElab «sorry»] def elabSorry : TermElab := fun stx expectedType? => do let stxNew ← `(sorryAx _ false) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? /-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/ partial def mkPairs (elems : Array Term) : MacroM Term := let rec loop (i : Nat) (acc : Term) := do if i > 0 then let i := i - 1 let elem := elems[i]! let acc ← `(Prod.mk $elem $acc) loop i acc else pure acc loop (elems.size - 1) elems.back partial def hasCDot : Syntax → Bool | Syntax.node _ k args => if k == ``Lean.Parser.Term.paren then false else if k == ``Lean.Parser.Term.cdot then true else args.any hasCDot | _ => false /-- Return `some` if succeeded expanding `·` notation occurring in the given syntax. Otherwise, return `none`. Examples: - `· + 1` => `fun _a_1 => _a_1 + 1` - `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/ partial def expandCDot? (stx : Term) : MacroM (Option Term) := do if hasCDot stx then let (newStx, binders) ← (go stx).run #[] `(fun $binders* => $(⟨newStx⟩)) else pure none where /-- Auxiliary function for expanding the `·` notation. The extra state `Array Syntax` contains the new binder names. If `stx` is a `·`, we create a fresh identifier, store in the extra state, and return it. Otherwise, we just return `stx`. -/ go : Syntax → StateT (Array Ident) MacroM Syntax | stx@`(($(_))) => pure stx | `(·) => withFreshMacroScope do let id : Ident ← `(a) modify fun s => s.push id pure id | stx => match stx with | .node i k args => do let args ← args.mapM go pure $ Syntax.node i k args | _ => pure stx /-- Helper method for elaborating terms such as `(.+.)` where a constant name is expected. This method is usually used to implement tactics that function names as arguments (e.g., `simp`). -/ def elabCDotFunctionAlias? (stx : Term) : TermElabM (Option Expr) := do let some stx ← liftMacroM <| expandCDotArg? stx | pure none let stx ← liftMacroM <| expandMacros stx match stx with | `(fun $binders* => $f $args*) => if binders == args then try Term.resolveId? f catch _ => return none else return none | `(fun $binders* => binop% $f $a $b) => if binders == #[a, b] then try Term.resolveId? f catch _ => return none else return none | _ => return none where expandCDotArg? (stx : Term) : MacroM (Option Term) := match stx with | `(($e)) => Term.expandCDot? e | _ => Term.expandCDot? stx @[builtinMacro Lean.Parser.Term.paren] def expandParen : Macro | `(()) => `(Unit.unit) | `(($e : $type)) => do match (← expandCDot? e) with | some e => `(($e : $type)) | none => Macro.throwUnsupported | `(($e)) => return (← expandCDot? e).getD e | `(($e, $es,*)) => do let pairs ← mkPairs (#[e] ++ es) return (← expandCDot? pairs).getD pairs | stx => if !stx[1][0].isMissing && stx[1][1].isMissing then -- parsed `(` and `term`, assume it's a basic parenthesis to get any elaboration output at all `(($(⟨stx[1][0]⟩))) else throw <| Macro.Exception.error stx "unexpected parentheses notation" @[builtinTermElab paren] def elabParen : TermElab := fun stx _ => do match stx with | `(($e : $type)) => let type ← withSynthesize (mayPostpone := true) <| elabType type let e ← elabTerm e type ensureHasType type e | _ => throwUnsupportedSyntax /-- Return `true` if `lhs` is a free variable and `rhs` does not depend on it. -/ private def isSubstCandidate (lhs rhs : Expr) : MetaM Bool := if lhs.isFVar then return !(← dependsOn rhs lhs.fvarId!) else return false /-- Given an expression `e` that is the elaboration of `stx`, if `e` is a free variable, then return `k stx`. Otherwise, return `(fun x => k x) e` -/ private def withLocalIdentFor (stx : Term) (e : Expr) (k : Term → TermElabM Expr) : TermElabM Expr := do if e.isFVar then k stx else let id ← mkFreshUserName `h let aux ← withLocalDeclD id (← inferType e) fun x => do mkLambdaFVars #[x] (← k (mkIdentFrom stx id)) return mkApp aux e @[builtinTermElab subst] def elabSubst : TermElab := fun stx expectedType? => do let expectedType? ← tryPostponeIfHasMVars? expectedType? match stx with | `($heqStx ▸ $hStx) => do synthesizeSyntheticMVars let mut heq ← withSynthesize <| elabTerm heqStx none let heqType ← inferType heq let heqType ← instantiateMVars heqType match (← Meta.matchEq? heqType) with | none => throwError "invalid `▸` notation, argument{indentExpr heq}\nhas type{indentExpr heqType}\nequality expected" | some (α, lhs, rhs) => let mut lhs := lhs let mut rhs := rhs let mkMotive (lhs typeWithLooseBVar : Expr) := do withLocalDeclD (← mkFreshUserName `x) α fun x => do withLocalDeclD (← mkFreshUserName `h) (← mkEq lhs x) fun h => do mkLambdaFVars #[x, h] $ typeWithLooseBVar.instantiate1 x match expectedType? with | some expectedType => let mut expectedAbst ← kabstract expectedType rhs unless expectedAbst.hasLooseBVars do expectedAbst ← kabstract expectedType lhs unless expectedAbst.hasLooseBVars do throwError "invalid `▸` notation, expected result type of cast is {indentExpr expectedType}\nhowever, the equality {indentExpr heq}\nof type {indentExpr heqType}\ndoes not contain the expected result type on either the left or the right hand side" heq ← mkEqSymm heq (lhs, rhs) := (rhs, lhs) let hExpectedType := expectedAbst.instantiate1 lhs let (h, badMotive?) ← withRef hStx do let h ← elabTerm hStx hExpectedType try return (← ensureHasType hExpectedType h, none) catch ex => -- if `rhs` occurs in `hType`, we try to apply `heq` to `h` too let hType ← inferType h let hTypeAbst ← kabstract hType rhs unless hTypeAbst.hasLooseBVars do throw ex let hTypeNew := hTypeAbst.instantiate1 lhs unless (← isDefEq hExpectedType hTypeNew) do throw ex let motive ← mkMotive rhs hTypeAbst if !(← isTypeCorrect motive) then return (h, some motive) else return (← mkEqRec motive h (← mkEqSymm heq), none) let motive ← mkMotive lhs expectedAbst if badMotive?.isSome || !(← isTypeCorrect motive) then -- Before failing try tos use `subst` if ← (isSubstCandidate lhs rhs <||> isSubstCandidate rhs lhs) then withLocalIdentFor heqStx heq fun heqStx => do let h ← instantiateMVars h if h.hasMVar then -- If `h` has metavariables, we try to elaborate `hStx` again after we substitute `heqStx` -- Remark: re-elaborating `hStx` may be problematic if `hStx` contains the `lhs` of `heqStx` which will be eliminated by `subst` let stxNew ← `(by subst $heqStx; exact $hStx) withMacroExpansion stx stxNew (elabTerm stxNew expectedType) else withLocalIdentFor hStx h fun hStx => do let stxNew ← `(by subst $heqStx; exact $hStx) withMacroExpansion stx stxNew (elabTerm stxNew expectedType) else throwError "invalid `▸` notation, failed to compute motive for the substitution" else mkEqRec motive h heq | none => let h ← elabTerm hStx none let hType ← inferType h let hTypeAbst ← kabstract hType lhs let motive ← mkMotive lhs hTypeAbst unless (← isTypeCorrect motive) do throwError "invalid `▸` notation, failed to compute motive for the substitution" mkEqRec motive h heq | _ => throwUnsupportedSyntax @[builtinTermElab stateRefT] def elabStateRefT : TermElab := fun stx _ => do let σ ← elabType stx[1] let mut mStx := stx[2] if mStx.getKind == ``Lean.Parser.Term.macroDollarArg then mStx := mStx[1] let m ← elabTerm mStx (← mkArrow (mkSort levelOne) (mkSort levelOne)) let ω ← mkFreshExprMVar (mkSort levelOne) let stWorld ← mkAppM ``STWorld #[ω, m] discard <| mkInstMVar stWorld mkAppM ``StateRefT' #[ω, σ, m] @[builtinTermElab noindex] def elabNoindex : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return DiscrTree.mkNoindexAnnotation e end Lean.Elab.Term
748838acb0b6bc2e973bef987acfc203e03601fe
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/hprop_trunc.hlean
6112166c0661fae2d73fbb76663bb8b155b8599f
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
1,774
hlean
/- Copyright (c) 2015 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Floris van Doorn Proof of the theorem that (is_trunc n A) is a mere proposition We prove this here to avoid circular dependency of files We want to use this in .equiv; .equiv is imported by .function and .function is imported by .trunc -/ import types.pi open equiv sigma sigma.ops eq function pi namespace is_trunc definition is_contr.sigma_char (A : Type) : (Σ (center : A), Π (a : A), center = a) ≃ (is_contr A) := begin fapply equiv.MK, { intro S, exact (is_contr.mk S.1 S.2)}, { intro H, cases H with H', cases H' with ce co, exact ⟨ce, co⟩}, { intro H, cases H with H', cases H' with ce co, exact idp}, { intro S, cases S, apply idp} end definition is_trunc.pi_char (n : trunc_index) (A : Type) : (Π (x y : A), is_trunc n (x = y)) ≃ (is_trunc (n .+1) A) := begin fapply equiv.MK, { intro H, apply is_trunc_succ_intro}, { intro H x y, apply is_trunc_eq}, { intro H, cases H, apply idp}, { intro P, apply eq_of_homotopy, intro a, apply eq_of_homotopy, intro b, change is_trunc.mk (to_internal n (a = b)) = P a b, induction (P a b), apply idp}, end definition is_hprop_is_trunc [instance] (n : trunc_index) : Π (A : Type), is_hprop (is_trunc n A) := begin induction n, { intro A, apply is_trunc_is_equiv_closed, { apply equiv.to_is_equiv, apply is_contr.sigma_char}, apply is_hprop.mk, intros, fapply sigma_eq, apply x.2, apply is_hprop.elimo}, { intro A, apply is_trunc_is_equiv_closed, apply equiv.to_is_equiv, apply is_trunc.pi_char}, end end is_trunc
8185f85a97e87a9f6686af1db0e799cb99717f40
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/lattice_intervals.lean
5897c15e515d8e1db58a2631b598674bc3007dfc
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,185
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.bounds.basic /-! # Intervals in Lattices > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we provide instances of lattice structures on intervals within lattices. Some of them depend on the order of the endpoints of the interval, and thus are not made global instances. These are probably not all of the lattice instances that could be placed on these intervals, but more can be added easily along the same lines when needed. ## Main definitions In the following, `*` can represent either `c`, `o`, or `i`. * `set.Ic*.order_bot` * `set.Ii*.semillatice_inf` * `set.I*c.order_top` * `set.I*c.semillatice_inf` * `set.I**.lattice` * `set.Iic.bounded_order`, within an `order_bot` * `set.Ici.bounded_order`, within an `order_top` -/ variable {α : Type*} namespace set namespace Ico instance [semilattice_inf α] {a b : α} : semilattice_inf (Ico a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, lt_of_le_of_lt inf_le_left hx.2⟩) /-- `Ico a b` has a bottom element whenever `a < b`. -/ @[reducible] protected def order_bot [partial_order α] {a b : α} (h : a < b) : order_bot (Ico a b) := (is_least_Ico h).order_bot end Ico namespace Iio instance [semilattice_inf α] {a : α} : semilattice_inf (Iio a) := subtype.semilattice_inf (λ x y hx hy, lt_of_le_of_lt inf_le_left hx) end Iio namespace Ioc instance [semilattice_sup α] {a b : α} : semilattice_sup (Ioc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨lt_of_lt_of_le hx.1 le_sup_left, sup_le hx.2 hy.2⟩) /-- `Ioc a b` has a top element whenever `a < b`. -/ @[reducible] protected def order_top [partial_order α] {a b : α} (h : a < b) : order_top (Ioc a b) := (is_greatest_Ioc h).order_top end Ioc namespace Ioi instance [semilattice_sup α] {a : α} : semilattice_sup (Ioi a) := subtype.semilattice_sup (λ x y hx hy, lt_of_lt_of_le hx le_sup_left) end Ioi namespace Iic instance [semilattice_inf α] {a : α} : semilattice_inf (Iic a) := subtype.semilattice_inf (λ x y hx hy, le_trans inf_le_left hx) instance [semilattice_sup α] {a : α} : semilattice_sup (Iic a) := subtype.semilattice_sup (λ x y hx hy, sup_le hx hy) instance [lattice α] {a : α} : lattice (Iic a) := { .. Iic.semilattice_inf, .. Iic.semilattice_sup } instance [preorder α] {a : α} : order_top (Iic a) := { top := ⟨a, le_refl a⟩, le_top := λ x, x.prop } @[simp] lemma coe_top [preorder α] {a : α} : ↑(⊤ : Iic a) = a := rfl instance [preorder α] [order_bot α] {a : α} : order_bot (Iic a) := { bot := ⟨⊥, bot_le⟩, bot_le := λ ⟨_,_⟩, subtype.mk_le_mk.2 bot_le } @[simp] lemma coe_bot [preorder α] [order_bot α] {a : α} : ↑(⊥ : Iic a) = (⊥ : α) := rfl instance [preorder α] [order_bot α] {a : α} : bounded_order (Iic a) := { .. Iic.order_top, .. Iic.order_bot } end Iic namespace Ici instance [semilattice_inf α] {a : α}: semilattice_inf (Ici a) := subtype.semilattice_inf (λ x y hx hy, le_inf hx hy) instance [semilattice_sup α] {a : α} : semilattice_sup (Ici a) := subtype.semilattice_sup (λ x y hx hy, le_trans hx le_sup_left) instance [lattice α] {a : α} : lattice (Ici a) := { .. Ici.semilattice_inf, .. Ici.semilattice_sup } instance [distrib_lattice α] {a : α} : distrib_lattice (Ici a) := { le_sup_inf := λ a b c, le_sup_inf, .. Ici.lattice } instance [preorder α] {a : α} : order_bot (Ici a) := { bot := ⟨a, le_refl a⟩, bot_le := λ x, x.prop } @[simp] lemma coe_bot [preorder α] {a : α} : ↑(⊥ : Ici a) = a := rfl instance [preorder α] [order_top α] {a : α}: order_top (Ici a) := { top := ⟨⊤, le_top⟩, le_top := λ ⟨_,_⟩, subtype.mk_le_mk.2 le_top } @[simp] lemma coe_top [preorder α] [order_top α] {a : α} : ↑(⊤ : Ici a) = (⊤ : α) := rfl instance [preorder α] [order_top α] {a : α}: bounded_order (Ici a) := { .. Ici.order_top, .. Ici.order_bot } end Ici namespace Icc instance [semilattice_inf α] {a b : α} : semilattice_inf (Icc a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, le_trans inf_le_left hx.2⟩) instance [semilattice_sup α] {a b : α} : semilattice_sup (Icc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨le_trans hx.1 le_sup_left, sup_le hx.2 hy.2⟩) instance [lattice α] {a b : α} : lattice (Icc a b) := { .. Icc.semilattice_inf, .. Icc.semilattice_sup } /-- `Icc a b` has a bottom element whenever `a ≤ b`. -/ @[reducible] protected def order_bot [preorder α] {a b : α} (h : a ≤ b) : order_bot (Icc a b) := (is_least_Icc h).order_bot /-- `Icc a b` has a top element whenever `a ≤ b`. -/ @[reducible] protected def order_top [preorder α] {a b : α} (h : a ≤ b) : order_top (Icc a b) := (is_greatest_Icc h).order_top /-- `Icc a b` is a `bounded_order` whenever `a ≤ b`. -/ @[reducible] protected def bounded_order [preorder α] {a b : α} (h : a ≤ b) : bounded_order (Icc a b) := { .. Icc.order_top h, .. Icc.order_bot h } end Icc end set
aa5e286865dc7219e6f4acdbee870bd95d402db2
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/order/rel_iso.lean
17eb6b62f5a5d40e9b2e8c88e1f341a7fd2e1ce0
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
28,759
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 algebra.group.defs import data.fun_like.basic import logic.embedding import logic.equiv.set import order.rel_classes /-! # Relation homomorphisms, embeddings, isomorphisms This file defines relation homomorphisms, embeddings, isomorphisms and order embeddings and isomorphisms. ## Main declarations * `rel_hom`: Relation homomorphism. A `rel_hom r s` is a function `f : α → β` such that `r a b → s (f a) (f b)`. * `rel_embedding`: Relation embedding. A `rel_embedding r s` is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. * `rel_iso`: Relation isomorphism. A `rel_iso r s` is an equivalence `f : α ≃ β` such that `r a b ↔ s (f a) (f b)`. * `sum_lex_congr`, `prod_lex_congr`: Creates a relation homomorphism between two `sum_lex` or two `prod_lex` from relation homomorphisms between their arguments. ## Notation * `→r`: `rel_hom` * `↪r`: `rel_embedding` * `≃r`: `rel_iso` -/ open function universes u v w variables {α β γ δ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} {u : δ → δ → Prop} /-- A relation homomorphism with respect to a given pair of relations `r` and `s` is a function `f : α → β` such that `r a b → s (f a) (f b)`. -/ @[nolint has_nonempty_instance] structure rel_hom {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) := (to_fun : α → β) (map_rel' : ∀ {a b}, r a b → s (to_fun a) (to_fun b)) infix ` →r `:25 := rel_hom /-- `rel_hom_class F r s` asserts that `F` is a type of functions such that all `f : F` satisfy `r a b → s (f a) (f b)`. The relations `r` and `s` are `out_param`s since figuring them out from a goal is a higher-order matching problem that Lean usually can't do unaided. -/ class rel_hom_class (F : Type*) {α β : out_param $ Type*} (r : out_param $ α → α → Prop) (s : out_param $ β → β → Prop) extends fun_like F α (λ _, β) := (map_rel : ∀ (f : F) {a b}, r a b → s (f a) (f b)) export rel_hom_class (map_rel) -- The free parameters `r` and `s` are `out_param`s so this is not dangerous. attribute [nolint dangerous_instance] rel_hom_class.to_fun_like namespace rel_hom_class variables {F : Type*} lemma map_inf [semilattice_inf α] [linear_order β] [rel_hom_class F ((<) : β → β → Prop) ((<) : α → α → Prop)] (a : F) (m n : β) : a (m ⊓ n) = a m ⊓ a n := (strict_mono.monotone $ λ x y, map_rel a).map_inf m n lemma map_sup [semilattice_sup α] [linear_order β] [rel_hom_class F ((>) : β → β → Prop) ((>) : α → α → Prop)] (a : F) (m n : β) : a (m ⊔ n) = a m ⊔ a n := @map_inf αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ protected theorem is_irrefl [rel_hom_class F r s] (f : F) : ∀ [is_irrefl β s], is_irrefl α r | ⟨H⟩ := ⟨λ a h, H _ (map_rel f h)⟩ protected theorem is_asymm [rel_hom_class F r s] (f : F) : ∀ [is_asymm β s], is_asymm α r | ⟨H⟩ := ⟨λ a b h₁ h₂, H _ _ (map_rel f h₁) (map_rel f h₂)⟩ protected theorem acc [rel_hom_class F r s] (f : F) (a : α) : acc s (f a) → acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, λ a' h, IH (f a') (map_rel f h) _ rfl⟩ end protected theorem well_founded [rel_hom_class F r s] (f : F) : ∀ (h : well_founded s), well_founded r | ⟨H⟩ := ⟨λ a, rel_hom_class.acc f _ (H _)⟩ end rel_hom_class namespace rel_hom instance : rel_hom_class (r →r s) r s := { coe := λ o, o.to_fun, coe_injective' := λ f g h, by { cases f, cases g, congr' }, map_rel := map_rel' } /-- Auxiliary instance if `rel_hom_class.to_fun_like.to_has_coe_to_fun` isn't found -/ instance : has_coe_to_fun (r →r s) (λ _, α → β) := ⟨λ o, o.to_fun⟩ initialize_simps_projections rel_hom (to_fun → apply) protected theorem map_rel (f : r →r s) : ∀ {a b}, r a b → s (f a) (f b) := f.map_rel' @[simp] theorem coe_fn_mk (f : α → β) (o) : (@rel_hom.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_fun (f : r →r s) : (f.to_fun : α → β) = f := rfl /-- The map `coe_fn : (r →r s) → (α → β)` is injective. -/ theorem coe_fn_injective : @function.injective (r →r s) (α → β) coe_fn := fun_like.coe_injective @[ext] theorem ext ⦃f g : r →r s⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h theorem ext_iff {f g : r →r s} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff /-- Identity map is a relation homomorphism. -/ @[refl, simps] protected def id (r : α → α → Prop) : r →r r := ⟨λ x, x, λ a b x, x⟩ /-- Composition of two relation homomorphisms is a relation homomorphism. -/ @[trans, simps] protected def comp (g : s →r t) (f : r →r s) : r →r t := ⟨λ x, g (f x), λ a b h, g.2 (f.2 h)⟩ /-- A relation homomorphism is also a relation homomorphism between dual relations. -/ protected def swap (f : r →r s) : swap r →r swap s := ⟨f, λ a b, f.map_rel⟩ /-- A function is a relation homomorphism from the preimage relation of `s` to `s`. -/ def preimage (f : α → β) (s : β → β → Prop) : f ⁻¹'o s →r s := ⟨f, λ a b, id⟩ end rel_hom /-- An increasing function is injective -/ lemma injective_of_increasing (r : α → α → Prop) (s : β → β → Prop) [is_trichotomous α r] [is_irrefl β s] (f : α → β) (hf : ∀ {x y}, r x y → s (f x) (f y)) : injective f := begin intros x y hxy, rcases trichotomous_of r x y with h | h | h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this, exact h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this end /-- An increasing function is injective -/ lemma rel_hom.injective_of_increasing [is_trichotomous α r] [is_irrefl β s] (f : r →r s) : injective f := injective_of_increasing r s f (λ x y, f.map_rel) -- TODO: define a `rel_iff_class` so we don't have to do all the `convert` trickery? theorem surjective.well_founded_iff {f : α → β} (hf : surjective f) (o : ∀ {a b}, r a b ↔ s (f a) (f b)) : well_founded r ↔ well_founded s := iff.intro (begin refine rel_hom_class.well_founded (rel_hom.mk _ _ : s →r r), { exact classical.some hf.has_right_inverse }, intros a b h, apply o.2, convert h, iterate 2 { apply classical.some_spec hf.has_right_inverse }, end) (rel_hom_class.well_founded (⟨f, λ _ _, o.1⟩ : r →r s)) /-- A relation embedding with respect to a given pair of relations `r` and `s` is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. -/ structure rel_embedding {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ↪ β := (map_rel_iff' : ∀ {a b}, s (to_embedding a) (to_embedding b) ↔ r a b) infix ` ↪r `:25 := rel_embedding /-- The induced relation on a subtype is an embedding under the natural inclusion. -/ definition subtype.rel_embedding {X : Type*} (r : X → X → Prop) (p : X → Prop) : ((subtype.val : subtype p → X) ⁻¹'o r) ↪r r := ⟨embedding.subtype p, λ x y, iff.rfl⟩ theorem preimage_equivalence {α β} (f : α → β) {s : β → β → Prop} (hs : equivalence s) : equivalence (f ⁻¹'o s) := ⟨λ a, hs.1 _, λ a b h, hs.2.1 h, λ a b c h₁ h₂, hs.2.2 h₁ h₂⟩ namespace rel_embedding /-- A relation embedding is also a relation homomorphism -/ def to_rel_hom (f : r ↪r s) : (r →r s) := { to_fun := f.to_embedding.to_fun, map_rel' := λ x y, (map_rel_iff' f).mpr } instance : has_coe (r ↪r s) (r →r s) := ⟨to_rel_hom⟩ -- see Note [function coercion] instance : has_coe_to_fun (r ↪r s) (λ _, α → β) := ⟨λ o, o.to_embedding⟩ -- TODO: define and instantiate a `rel_embedding_class` when `embedding_like` is defined instance : rel_hom_class (r ↪r s) r s := { coe := coe_fn, coe_injective' := λ f g h, by { rcases f with ⟨⟨⟩⟩, rcases g with ⟨⟨⟩⟩, congr' }, map_rel := λ f a b, iff.mpr (map_rel_iff' f) } /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : r ↪r s) : α → β := h initialize_simps_projections rel_embedding (to_embedding_to_fun → apply, -to_embedding) @[simp] lemma to_rel_hom_eq_coe (f : r ↪r s) : f.to_rel_hom = f := rfl @[simp] lemma coe_coe_fn (f : r ↪r s) : ((f : r →r s) : α → β) = f := rfl theorem injective (f : r ↪r s) : injective f := f.inj' @[simp] theorem inj (f : r ↪r s) {a b} : f a = f b ↔ a = b := f.injective.eq_iff theorem map_rel_iff (f : r ↪r s) : ∀ {a b}, s (f a) (f b) ↔ r a b := f.map_rel_iff' @[simp] theorem coe_fn_mk (f : α ↪ β) (o) : (@rel_embedding.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_embedding (f : r ↪r s) : (f.to_embedding : α → β) = f := rfl /-- The map `coe_fn : (r ↪r s) → (α → β)` is injective. -/ theorem coe_fn_injective : @function.injective (r ↪r s) (α → β) coe_fn := fun_like.coe_injective @[ext] theorem ext ⦃f g : r ↪r s⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h theorem ext_iff {f g : r ↪r s} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff /-- Identity map is a relation embedding. -/ @[refl, simps] protected def refl (r : α → α → Prop) : r ↪r r := ⟨embedding.refl _, λ a b, iff.rfl⟩ /-- Composition of two relation embeddings is a relation embedding. -/ @[trans] protected def trans (f : r ↪r s) (g : s ↪r t) : r ↪r t := ⟨f.1.trans g.1, λ a b, by simp [f.map_rel_iff, g.map_rel_iff]⟩ instance (r : α → α → Prop) : inhabited (r ↪r r) := ⟨rel_embedding.refl _⟩ theorem trans_apply (f : r ↪r s) (g : s ↪r t) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem coe_trans (f : r ↪r s) (g : s ↪r t) : ⇑(f.trans g) = g ∘ f := rfl /-- A relation embedding is also a relation embedding between dual relations. -/ protected def swap (f : r ↪r s) : swap r ↪r swap s := ⟨f.to_embedding, λ a b, f.map_rel_iff⟩ /-- If `f` is injective, then it is a relation embedding from the preimage relation of `s` to `s`. -/ def preimage (f : α ↪ β) (s : β → β → Prop) : f ⁻¹'o s ↪r s := ⟨f, λ a b, iff.rfl⟩ theorem eq_preimage (f : r ↪r s) : r = f ⁻¹'o s := by { ext a b, exact f.map_rel_iff.symm } protected theorem is_irrefl (f : r ↪r s) [is_irrefl β s] : is_irrefl α r := ⟨λ a, mt f.map_rel_iff.2 (irrefl (f a))⟩ protected theorem is_refl (f : r ↪r s) [is_refl β s] : is_refl α r := ⟨λ a, f.map_rel_iff.1 $ refl _⟩ protected theorem is_symm (f : r ↪r s) [is_symm β s] : is_symm α r := ⟨λ a b, imp_imp_imp f.map_rel_iff.2 f.map_rel_iff.1 symm⟩ protected theorem is_asymm (f : r ↪r s) [is_asymm β s] : is_asymm α r := ⟨λ a b h₁ h₂, asymm (f.map_rel_iff.2 h₁) (f.map_rel_iff.2 h₂)⟩ protected theorem is_antisymm : ∀ (f : r ↪r s) [is_antisymm β s], is_antisymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, f.inj' (H _ _ (o.2 h₁) (o.2 h₂))⟩ protected theorem is_trans : ∀ (f : r ↪r s) [is_trans β s], is_trans α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b c h₁ h₂, o.1 (H _ _ _ (o.2 h₁) (o.2 h₂))⟩ protected theorem is_total : ∀ (f : r ↪r s) [is_total β s], is_total α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o o).1 (H _ _)⟩ protected theorem is_preorder : ∀ (f : r ↪r s) [is_preorder β s], is_preorder α r | f H := by exactI {..f.is_refl, ..f.is_trans} protected theorem is_partial_order : ∀ (f : r ↪r s) [is_partial_order β s], is_partial_order α r | f H := by exactI {..f.is_preorder, ..f.is_antisymm} protected theorem is_linear_order : ∀ (f : r ↪r s) [is_linear_order β s], is_linear_order α r | f H := by exactI {..f.is_partial_order, ..f.is_total} protected theorem is_strict_order : ∀ (f : r ↪r s) [is_strict_order β s], is_strict_order α r | f H := by exactI {..f.is_irrefl, ..f.is_trans} protected theorem is_trichotomous : ∀ (f : r ↪r s) [is_trichotomous β s], is_trichotomous α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o (or_congr f.inj'.eq_iff o)).1 (H _ _)⟩ protected theorem is_strict_total_order' : ∀ (f : r ↪r s) [is_strict_total_order' β s], is_strict_total_order' α r | f H := by exactI {..f.is_trichotomous, ..f.is_strict_order} protected theorem acc (f : r ↪r s) (a : α) : acc s (f a) → acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, λ a' h, IH (f a') (f.map_rel_iff.2 h) _ rfl⟩ end protected theorem well_founded : ∀ (f : r ↪r s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ protected theorem is_well_order : ∀ (f : r ↪r s) [is_well_order β s], is_well_order α r | f H := by exactI {wf := f.well_founded H.wf, ..f.is_strict_total_order'} /-- `quotient.out` as a relation embedding between the lift of a relation and the relation. -/ @[simps] noncomputable def _root_.quotient.out_rel_embedding [s : setoid α] {r : α → α → Prop} (H) : quotient.lift₂ r H ↪r r := ⟨embedding.quotient_out α, begin refine λ x y, quotient.induction_on₂ x y (λ a b, _), apply iff_iff_eq.2 (H _ _ _ _ _ _); apply quotient.mk_out end⟩ /-- A relation is well founded iff its lift to a quotient is. -/ @[simp] theorem _root_.well_founded_lift₂_iff [s : setoid α] {r : α → α → Prop} {H} : well_founded (quotient.lift₂ r H) ↔ well_founded r := ⟨λ hr, begin suffices : ∀ {x : quotient s} {a : α}, ⟦a⟧ = x → acc r a, { exact ⟨λ a, this rfl⟩ }, { refine λ x, hr.induction x _, rintros x IH a rfl, exact ⟨_, λ b hb, IH ⟦b⟧ hb rfl⟩ } end, (quotient.out_rel_embedding H).well_founded⟩ alias _root_.well_founded_lift₂_iff ↔ _root_.well_founded.of_quotient_lift₂ _root_.well_founded.quotient_lift₂ /-- To define an relation embedding from an antisymmetric relation `r` to a reflexive relation `s` it suffices to give a function together with a proof that it satisfies `s (f a) (f b) ↔ r a b`. -/ def of_map_rel_iff (f : α → β) [is_antisymm α r] [is_refl β s] (hf : ∀ a b, s (f a) (f b) ↔ r a b) : r ↪r s := { to_fun := f, inj' := λ x y h, antisymm ((hf _ _).1 (h ▸ refl _)) ((hf _ _).1 (h ▸ refl _)), map_rel_iff' := hf } @[simp] lemma of_map_rel_iff_coe (f : α → β) [is_antisymm α r] [is_refl β s] (hf : ∀ a b, s (f a) (f b) ↔ r a b) : ⇑(of_map_rel_iff f hf : r ↪r s) = f := rfl /-- It suffices to prove `f` is monotone between strict relations to show it is a relation embedding. -/ def of_monotone [is_trichotomous α r] [is_asymm β s] (f : α → β) (H : ∀ a b, r a b → s (f a) (f b)) : r ↪r s := begin haveI := @is_asymm.is_irrefl β s _, refine ⟨⟨f, λ a b e, _⟩, λ a b, ⟨λ h, _, H _ _⟩⟩, { refine ((@trichotomous _ r _ a b).resolve_left _).resolve_right _; exact λ h, @irrefl _ s _ _ (by simpa [e] using H _ _ h) }, { refine (@trichotomous _ r _ a b).resolve_right (or.rec (λ e, _) (λ h', _)), { subst e, exact irrefl _ h }, { exact asymm (H _ _ h') h } } end @[simp] theorem of_monotone_coe [is_trichotomous α r] [is_asymm β s] (f : α → β) (H) : (@of_monotone _ _ r s _ _ f H : α → β) = f := rfl /-- A relation embedding from an empty type. -/ def of_is_empty (r : α → α → Prop) (s : β → β → Prop) [is_empty α] : r ↪r s := ⟨embedding.of_is_empty, is_empty_elim⟩ /-- `sum.inl` as a relation embedding into `sum.lift_rel r s`. -/ @[simps] def sum_lift_rel_inl (r : α → α → Prop) (s : β → β → Prop) : r ↪r sum.lift_rel r s := { to_fun := sum.inl, inj' := sum.inl_injective, map_rel_iff' := λ a b, sum.lift_rel_inl_inl } /-- `sum.inr` as a relation embedding into `sum.lift_rel r s`. -/ @[simps] def sum_lift_rel_inr (r : α → α → Prop) (s : β → β → Prop) : s ↪r sum.lift_rel r s := { to_fun := sum.inr, inj' := sum.inr_injective, map_rel_iff' := λ a b, sum.lift_rel_inr_inr } /-- `sum.map` as a relation embedding between `sum.lift_rel` relations. -/ @[simps] def sum_lift_rel_map (f : r ↪r s) (g : t ↪r u) : sum.lift_rel r t ↪r sum.lift_rel s u := { to_fun := sum.map f g, inj' := f.injective.sum_map g.injective, map_rel_iff' := by { rintro (a | b) (c | d); simp [f.map_rel_iff, g.map_rel_iff] } } /-- `sum.inl` as a relation embedding into `sum.lex r s`. -/ @[simps] def sum_lex_inl (r : α → α → Prop) (s : β → β → Prop) : r ↪r sum.lex r s := { to_fun := sum.inl, inj' := sum.inl_injective, map_rel_iff' := λ a b, sum.lex_inl_inl } /-- `sum.inr` as a relation embedding into `sum.lex r s`. -/ @[simps] def sum_lex_inr (r : α → α → Prop) (s : β → β → Prop) : s ↪r sum.lex r s := { to_fun := sum.inr, inj' := sum.inr_injective, map_rel_iff' := λ a b, sum.lex_inr_inr } /-- `sum.map` as a relation embedding between `sum.lex` relations. -/ @[simps] def sum_lex_map (f : r ↪r s) (g : t ↪r u) : sum.lex r t ↪r sum.lex s u := { to_fun := sum.map f g, inj' := f.injective.sum_map g.injective, map_rel_iff' := by { rintro (a | b) (c | d); simp [f.map_rel_iff, g.map_rel_iff] } } /-- `λ b, prod.mk a b` as a relation embedding. -/ @[simps] def prod_lex_mk_left (s : β → β → Prop) {a : α} (h : ¬ r a a) : s ↪r prod.lex r s := { to_fun := prod.mk a, inj' := prod.mk.inj_left a, map_rel_iff' := λ b₁ b₂, by simp [prod.lex_def, h] } /-- `λ a, prod.mk a b` as a relation embedding. -/ @[simps] def prod_lex_mk_right (r : α → α → Prop) {b : β} (h : ¬ s b b) : r ↪r prod.lex r s := { to_fun := λ a, (a, b), inj' := prod.mk.inj_right b, map_rel_iff' := λ a₁ a₂, by simp [prod.lex_def, h] } /-- `prod.map` as a relation embedding. -/ @[simps] def prod_lex_map (f : r ↪r s) (g : t ↪r u) : prod.lex r t ↪r prod.lex s u := { to_fun := prod.map f g, inj' := f.injective.prod_map g.injective, map_rel_iff' := λ a b, by simp [prod.lex_def, f.map_rel_iff, g.map_rel_iff] } end rel_embedding /-- A relation isomorphism is an equivalence that is also a relation embedding. -/ structure rel_iso {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ≃ β := (map_rel_iff' : ∀ {a b}, s (to_equiv a) (to_equiv b) ↔ r a b) infix ` ≃r `:25 := rel_iso namespace rel_iso /-- Convert an `rel_iso` to an `rel_embedding`. This function is also available as a coercion but often it is easier to write `f.to_rel_embedding` than to write explicitly `r` and `s` in the target type. -/ def to_rel_embedding (f : r ≃r s) : r ↪r s := ⟨f.to_equiv.to_embedding, f.map_rel_iff'⟩ theorem to_equiv_injective : injective (to_equiv : (r ≃r s) → α ≃ β) | ⟨e₁, o₁⟩ ⟨e₂, o₂⟩ h := by { congr, exact h } instance : has_coe (r ≃r s) (r ↪r s) := ⟨to_rel_embedding⟩ -- see Note [function coercion] instance : has_coe_to_fun (r ≃r s) (λ _, α → β) := ⟨λ f, f⟩ -- TODO: define and instantiate a `rel_iso_class` when `equiv_like` is defined instance : rel_hom_class (r ≃r s) r s := { coe := coe_fn, coe_injective' := equiv.coe_fn_injective.comp to_equiv_injective, map_rel := λ f a b, iff.mpr (map_rel_iff' f) } @[simp] lemma to_rel_embedding_eq_coe (f : r ≃r s) : f.to_rel_embedding = f := rfl @[simp] lemma coe_coe_fn (f : r ≃r s) : ((f : r ↪r s) : α → β) = f := rfl theorem map_rel_iff (f : r ≃r s) : ∀ {a b}, s (f a) (f b) ↔ r a b := f.map_rel_iff' @[simp] theorem coe_fn_mk (f : α ≃ β) (o : ∀ ⦃a b⦄, s (f a) (f b) ↔ r a b) : (rel_iso.mk f o : α → β) = f := rfl @[simp] theorem coe_fn_to_equiv (f : r ≃r s) : (f.to_equiv : α → β) = f := rfl /-- The map `coe_fn : (r ≃r s) → (α → β)` is injective. Lean fails to parse `function.injective (λ e : r ≃r s, (e : α → β))`, so we use a trick to say the same. -/ theorem coe_fn_injective : @function.injective (r ≃r s) (α → β) coe_fn := fun_like.coe_injective @[ext] theorem ext ⦃f g : r ≃r s⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h theorem ext_iff {f g : r ≃r s} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff /-- Inverse map of a relation isomorphism is a relation isomorphism. -/ @[symm] protected def symm (f : r ≃r s) : s ≃r r := ⟨f.to_equiv.symm, λ a b, by erw [← f.map_rel_iff, f.1.apply_symm_apply, f.1.apply_symm_apply]⟩ /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : r ≃r s) : α → β := h /-- See Note [custom simps projection]. -/ def simps.symm_apply (h : r ≃r s) : β → α := h.symm initialize_simps_projections rel_iso (to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv) /-- Identity map is a relation isomorphism. -/ @[refl, simps apply] protected def refl (r : α → α → Prop) : r ≃r r := ⟨equiv.refl _, λ a b, iff.rfl⟩ /-- Composition of two relation isomorphisms is a relation isomorphism. -/ @[trans, simps apply] protected def trans (f₁ : r ≃r s) (f₂ : s ≃r t) : r ≃r t := ⟨f₁.to_equiv.trans f₂.to_equiv, λ a b, f₂.map_rel_iff.trans f₁.map_rel_iff⟩ instance (r : α → α → Prop) : inhabited (r ≃r r) := ⟨rel_iso.refl _⟩ @[simp] lemma default_def (r : α → α → Prop) : default = rel_iso.refl r := rfl /-- A relation isomorphism between equal relations on equal types. -/ @[simps to_equiv apply] protected def cast {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} (h₁ : α = β) (h₂ : r == s) : r ≃r s := ⟨equiv.cast h₁, λ a b, by { subst h₁, rw eq_of_heq h₂, refl }⟩ @[simp] protected theorem cast_symm {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} (h₁ : α = β) (h₂ : r == s) : (rel_iso.cast h₁ h₂).symm = rel_iso.cast h₁.symm h₂.symm := rfl @[simp] protected theorem cast_refl {α : Type u} {r : α → α → Prop} (h₁ : α = α := rfl) (h₂ : r == r := heq.rfl) : rel_iso.cast h₁ h₂ = rel_iso.refl r := rfl @[simp] protected theorem cast_trans {α β γ : Type u} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} (h₁ : α = β) (h₁' : β = γ) (h₂ : r == s) (h₂' : s == t): (rel_iso.cast h₁ h₂).trans (rel_iso.cast h₁' h₂') = rel_iso.cast (h₁.trans h₁') (h₂.trans h₂') := ext $ λ x, by { subst h₁, refl } /-- a relation isomorphism is also a relation isomorphism between dual relations. -/ protected def swap (f : r ≃r s) : (swap r) ≃r (swap s) := ⟨f.to_equiv, λ _ _, f.map_rel_iff⟩ @[simp] theorem coe_fn_symm_mk (f o) : ((@rel_iso.mk _ _ r s f o).symm : β → α) = f.symm := rfl @[simp] theorem apply_symm_apply (e : r ≃r s) (x : β) : e (e.symm x) = x := e.to_equiv.apply_symm_apply x @[simp] theorem symm_apply_apply (e : r ≃r s) (x : α) : e.symm (e x) = x := e.to_equiv.symm_apply_apply x theorem rel_symm_apply (e : r ≃r s) {x y} : r x (e.symm y) ↔ s (e x) y := by rw [← e.map_rel_iff, e.apply_symm_apply] theorem symm_apply_rel (e : r ≃r s) {x y} : r (e.symm x) y ↔ s x (e y) := by rw [← e.map_rel_iff, e.apply_symm_apply] protected lemma bijective (e : r ≃r s) : bijective e := e.to_equiv.bijective protected lemma injective (e : r ≃r s) : injective e := e.to_equiv.injective protected lemma surjective (e : r ≃r s) : surjective e := e.to_equiv.surjective @[simp] lemma range_eq (e : r ≃r s) : set.range e = set.univ := e.surjective.range_eq @[simp] lemma eq_iff_eq (f : r ≃r s) {a b} : f a = f b ↔ a = b := f.injective.eq_iff /-- Any equivalence lifts to a relation isomorphism between `s` and its preimage. -/ protected def preimage (f : α ≃ β) (s : β → β → Prop) : f ⁻¹'o s ≃r s := ⟨f, λ a b, iff.rfl⟩ instance is_well_order.preimage {α : Type u} (r : α → α → Prop) [is_well_order α r] (f : β ≃ α) : is_well_order β (f ⁻¹'o r) := @rel_embedding.is_well_order _ _ (f ⁻¹'o r) r (rel_iso.preimage f r) _ instance is_well_order.ulift {α : Type u} (r : α → α → Prop) [is_well_order α r] : is_well_order (ulift α) (ulift.down ⁻¹'o r) := is_well_order.preimage r equiv.ulift /-- A surjective relation embedding is a relation isomorphism. -/ @[simps apply] noncomputable def of_surjective (f : r ↪r s) (H : surjective f) : r ≃r s := ⟨equiv.of_bijective f ⟨f.injective, H⟩, λ a b, f.map_rel_iff⟩ /-- Given relation isomorphisms `r₁ ≃r s₁` and `r₂ ≃r s₂`, construct a relation isomorphism for the lexicographic orders on the sum. -/ def sum_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @rel_iso α₁ β₁ r₁ s₁) (e₂ : @rel_iso α₂ β₂ r₂ s₂) : sum.lex r₁ r₂ ≃r sum.lex s₁ s₂ := ⟨equiv.sum_congr e₁.to_equiv e₂.to_equiv, λ a b, by cases e₁ with f hf; cases e₂ with g hg; cases a; cases b; simp [hf, hg]⟩ /-- Given relation isomorphisms `r₁ ≃r s₁` and `r₂ ≃r s₂`, construct a relation isomorphism for the lexicographic orders on the product. -/ def prod_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @rel_iso α₁ β₁ r₁ s₁) (e₂ : @rel_iso α₂ β₂ r₂ s₂) : prod.lex r₁ r₂ ≃r prod.lex s₁ s₂ := ⟨equiv.prod_congr e₁.to_equiv e₂.to_equiv, λ a b, by simp [prod.lex_def, e₁.map_rel_iff, e₂.map_rel_iff]⟩ instance : group (r ≃r r) := { one := rel_iso.refl r, mul := λ f₁ f₂, f₂.trans f₁, inv := rel_iso.symm, mul_assoc := λ f₁ f₂ f₃, rfl, one_mul := λ f, ext $ λ _, rfl, mul_one := λ f, ext $ λ _, rfl, mul_left_inv := λ f, ext f.symm_apply_apply } @[simp] lemma coe_one : ⇑(1 : r ≃r r) = id := rfl @[simp] lemma coe_mul (e₁ e₂ : r ≃r r) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl lemma mul_apply (e₁ e₂ : r ≃r r) (x : α) : (e₁ * e₂) x = e₁ (e₂ x) := rfl @[simp] lemma inv_apply_self (e : r ≃r r) (x) : e⁻¹ (e x) = x := e.symm_apply_apply x @[simp] lemma apply_inv_self (e : r ≃r r) (x) : e (e⁻¹ x) = x := e.apply_symm_apply x /-- Two relations on empty types are isomorphic. -/ def rel_iso_of_is_empty (r : α → α → Prop) (s : β → β → Prop) [is_empty α] [is_empty β] : r ≃r s := ⟨equiv.equiv_of_is_empty α β, is_empty_elim⟩ /-- Two irreflexive relations on a unique type are isomorphic. -/ def rel_iso_of_unique_of_irrefl (r : α → α → Prop) (s : β → β → Prop) [is_irrefl α r] [is_irrefl β s] [unique α] [unique β] : r ≃r s := ⟨equiv.equiv_of_unique α β, λ x y, by simp [not_rel_of_subsingleton r, not_rel_of_subsingleton s]⟩ /-- Two reflexive relations on a unique type are isomorphic. -/ def rel_iso_of_unique_of_refl (r : α → α → Prop) (s : β → β → Prop) [is_refl α r] [is_refl β s] [unique α] [unique β] : r ≃r s := ⟨equiv.equiv_of_unique α β, λ x y, by simp [rel_of_subsingleton r, rel_of_subsingleton s]⟩ end rel_iso /-- `subrel r p` is the inherited relation on a subset. -/ def subrel (r : α → α → Prop) (p : set α) : p → p → Prop := (coe : p → α) ⁻¹'o r @[simp] theorem subrel_val (r : α → α → Prop) (p : set α) {a b} : subrel r p a b ↔ r a.1 b.1 := iff.rfl namespace subrel /-- The relation embedding from the inherited relation on a subset. -/ protected def rel_embedding (r : α → α → Prop) (p : set α) : subrel r p ↪r r := ⟨embedding.subtype _, λ a b, iff.rfl⟩ @[simp] theorem rel_embedding_apply (r : α → α → Prop) (p a) : subrel.rel_embedding r p a = a.1 := rfl instance (r : α → α → Prop) [is_well_order α r] (p : set α) : is_well_order p (subrel r p) := rel_embedding.is_well_order (subrel.rel_embedding r p) instance (r : α → α → Prop) [is_refl α r] (p : set α) : is_refl p (subrel r p) := ⟨λ x, @is_refl.refl α r _ x⟩ instance (r : α → α → Prop) [is_symm α r] (p : set α) : is_symm p (subrel r p) := ⟨λ x y, @is_symm.symm α r _ x y⟩ instance (r : α → α → Prop) [is_trans α r] (p : set α) : is_trans p (subrel r p) := ⟨λ x y z, @is_trans.trans α r _ x y z⟩ instance (r : α → α → Prop) [is_irrefl α r] (p : set α) : is_irrefl p (subrel r p) := ⟨λ x, @is_irrefl.irrefl α r _ x⟩ end subrel /-- Restrict the codomain of a relation embedding. -/ def rel_embedding.cod_restrict (p : set β) (f : r ↪r s) (H : ∀ a, f a ∈ p) : r ↪r subrel s p := ⟨f.to_embedding.cod_restrict p H, f.map_rel_iff'⟩ @[simp] theorem rel_embedding.cod_restrict_apply (p) (f : r ↪r s) (H a) : rel_embedding.cod_restrict p f H a = ⟨f a, H a⟩ := rfl
ba234f73c9fe91131ba1435b617ac3a736eaf09c
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/tactic/basic.lean
99fa3ca4dd87e3e84fe1eab8fd815d5022b7ca2e
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
478
lean
import tactic.alias tactic.cache tactic.converter.interactive tactic.core tactic.doc_blame tactic.ext tactic.generalize_proofs tactic.interactive tactic.library_search tactic.lift tactic.localized tactic.mk_iff_of_inductive_prop tactic.push_neg tactic.rcases tactic.replacer tactic.restate_axiom tactic.rewrite tactic.sanity_check tactic.simpa tactic.simps tactic.split_ifs tactic.squeeze tactic.well_founded_tactics tactic.where
20b9b0d62286dd9ff214e83f22e985b3ac873954
5df84495ec6c281df6d26411cc20aac5c941e745
/src/formal_ml/vcd.lean
614979390fdc3770437a7aaf33da5612051babc7
[ "Apache-2.0" ]
permissive
eric-wieser/formal-ml
e278df5a8df78aa3947bc8376650419e1b2b0a14
630011d19fdd9539c8d6493a69fe70af5d193590
refs/heads/master
1,681,491,589,256
1,612,642,743,000
1,612,642,743,000
360,114,136
0
0
Apache-2.0
1,618,998,189,000
1,618,998,188,000
null
UTF-8
Lean
false
false
29,357
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import measure_theory.borel_space import data.set.countable import data.complex.exponential import formal_ml.ennreal import formal_ml.nnreal import formal_ml.sum import formal_ml.exp_bound /- The Vapnik-Chevronenkis Dimension and its connection to learning is one of the most remarkable and fundamental results in machine learning. In particular, it allows us to understand simple, infinite hypothesis spaces, like the separating hyperplane, and begin to understand the complexity of neural networks. This analysis is also a precursor to understanding support vector machines and structural risk. -/ lemma filter_union {α:Type*} [decidable_eq α] {S:finset α} {P:α → Prop} [decidable_pred P]: finset.filter P S ∪ finset.filter (λ a, ¬P a) S = S := begin ext a;split;intro A1, { simp at A1, cases A1 with A1 A1;apply A1.left, }, { simp, simp [A1], apply em, }, end lemma filter_disjoint {α:Type*} [decidable_eq α] {S T:finset α} {P:α → Prop} [decidable_pred P]: disjoint (finset.filter P S) (finset.filter (λ a, ¬P a) T) := begin rw finset.disjoint_left, intros a B1 B2, simp at B1, simp at B2, apply B2.right, apply B1.right, end lemma filter_disjoint' {α:Type*} [DE:decidable_eq α] {S:finset α} {P:α → Prop} [DP:decidable_pred P]: disjoint (finset.filter P S) (finset.filter (λ a, ¬P a) S) := @filter_disjoint α DE S S P DP lemma filter_card {α:Type*} [decidable_eq α] {S:finset α} {P:α → Prop} [decidable_pred P]: (finset.filter P S).card + (finset.filter (λ a, ¬P a) S).card = S.card := begin have A1:(finset.filter P S ∪ finset.filter (λ a, ¬P a) S).card = S.card, { rw filter_union, }, rw ← A1, rw finset.card_union_eq, apply filter_disjoint, end namespace VC_PAC_problem def Φ:ℕ → ℕ → ℕ | 0 m := 1 | d 0 := 1 | (nat.succ d) (nat.succ m) := Φ (d.succ) m + Φ d m @[simp] lemma phi_d_zero_eq_one {d:ℕ}:Φ d 0 = 1 := begin cases d;unfold Φ, end @[simp] lemma phi_zero_m_eq_one {m:ℕ}:Φ 0 m = 1 := begin cases m;unfold Φ, end lemma phi_succ_succ {d m:ℕ}:Φ d.succ m.succ = Φ d.succ m + Φ d m := rfl end VC_PAC_problem /- It is important to be able to talk about the VC dimension of a set of sets without referring to a particular problem. For that reason, I have placed it outside of the VC_PAC_problem. -/ namespace VC_PAC_problem section VC_PAC_problem universe u variable {α:Type u} open_locale classical --The set of restrictions of concepts onto S, conventionally written as Πc(S) and represented as vectors. noncomputable def restrict_set (C:set (set α)) (S:finset α):finset (finset α) := S.powerset.filter (λ x, ∃ c∈ C, c ∩ (↑S) = (↑x)) --Does there exist a concept that agrees with any subset of S on S? def shatters (C:set (set α)) (S:finset α):Prop := (restrict_set C S) = S.powerset --What is the largest extended natural number n such that all finite sets of size ≤ n can be shattered? --Note that if the VC dimension is infinity, then that means that any finite set can be shattered, --but it does not say anything about infinite sets. See Kearns and Vazirani, page 51. --For example, the Borel algebra on the reals shatters every finite set, but does not shatter --all infinite sets (e.g. it does not shatter the reals themselves), so it has a VC dimension of --infinity. --Note: an empty hypothesis space, by this definition, has a VCD of infinity. This may cause problems. /-noncomputable def VCD (C:set (set α)):enat := Sup {n:enat|∃ (X':finset α), ((X'.card:enat) = n) ∧ shatters C (X')}-/ /- Consider all sets that can be shattered. What is the supremum of their sizes (in enat)? -/ noncomputable def VCD (C:set (set α)):enat := Sup ((λ X':finset α, (↑(X'.card):enat)) '' {X':finset α|shatters C (X')}) /- Normally, this restriction is defined for sets of exactly size m. However, this runs into problems if there do not exist sets of a certain size. -/ noncomputable def restrict_set_bound (C:set (set α)) (m:ℕ):nat := Sup ((λ X', (restrict_set C X').card) '' {X':finset α|X'.card ≤ m}) lemma restrict_set_subset {C:set (set α)} (S:finset α):restrict_set C S⊆ S.powerset := begin unfold restrict_set, simp, end lemma mem_restrict_set_subset {C:set (set α)} {S:finset α} {c:finset α}:c ∈ restrict_set C S → c⊆ S := begin intros A1, rw ← finset.mem_powerset, have A2:= @restrict_set_subset α C S, apply A2, apply A1, end -- filter (λ x, true) --{S':set P.X|∃ c ∈ P.C, (S')= c ∩ (S)} lemma mem_restrict_set {C:set (set α)} (S:finset α) (T:finset α): T ∈ restrict_set C S ↔ (∃ c∈ C, c ∩ (↑S) = (↑T)) := begin unfold restrict_set, rw finset.mem_filter, split;intros B1, { apply B1.right, }, { split, rw finset.mem_powerset, cases B1 with c B1, cases B1 with B1 B2, rw finset.subset_iff, intros x A1, have B3:= set.inter_subset_right c (↑S), rw B2 at B3, apply B3, simp, apply A1, apply B1, }, end lemma shatters_iff {C:set (set α)} (S:finset α): (shatters C S) ↔ (∀ S'⊆ S, ∃ c∈ C, c ∩(↑S) = (↑S')) := begin unfold shatters, split;intros A1, { intros S' B1, rw finset.ext_iff at A1, have B2 := A1 S', rw finset.mem_powerset at B2, rw ← B2 at B1, rw mem_restrict_set at B1, apply B1, }, { apply finset.subset.antisymm, apply restrict_set_subset, rw finset.subset_iff, intros S' C1, rw finset.mem_powerset at C1, have C2 := A1 S' C1, rw mem_restrict_set, apply C2, }, end lemma shatters_def (C:set (set α)) (S:finset α): shatters C S = ((restrict_set C S) = S.powerset) := rfl /-Introducing a trivial upper bound establishes that Sup exists meaningfully (instead of a default value of zero).-/ lemma restrict_set_trivial_upper_bound {C:set (set α)} (X':finset α): (restrict_set C X').card ≤ 2^(X'.card) := begin have B1:(restrict_set C X').card ≤ X'.powerset.card, { apply finset.card_le_of_subset, apply restrict_set_subset, }, apply le_trans B1, rw finset.card_powerset, end lemma restrict_set_le_upper_bound {C:set (set α)} (X':finset α): (restrict_set C X').card ≤ restrict_set_bound C (X'.card) := begin apply le_cSup, rw bdd_above_def, unfold upper_bounds, apply exists.intro (2^(X'.card)), simp, intros X'' A1, have A3:2^(X''.card) ≤ 2^(X'.card), { apply linear_ordered_semiring.pow_monotone one_le_two A1, repeat {apply nat.nontrivial}, }, apply le_trans _ A3, apply restrict_set_trivial_upper_bound, simp, apply exists.intro X', split, refl, refl, end lemma shatters_card_le_VCD {C:set (set α)} {S:finset α}:shatters C S → (S.card:enat) ≤ VCD C := begin unfold VCD, intros A1, apply le_Sup, simp, apply exists.intro S, simp [A1], end lemma VCD_le {C:set (set α)} {d:enat}:(∀ S:finset α, shatters C S → (↑S.card) ≤ d) → VCD C ≤ d := begin intros A1, unfold VCD, apply Sup_le, intros b B1, simp at B1, cases B1 with X' B1, cases B1 with B1 B2, subst b, apply A1 X' B1, end lemma restrict_set_elements_subset_of_VCD_zero {C:set (set α)} {S T U:finset α}:(VCD C = 0) → T ∈ (restrict_set C S) → U ∈ (restrict_set C S) → T ⊆ U := begin intros A1 A2 A3, rw finset.subset_iff, intros x B1, apply by_contradiction, intros B2, have B3 := (mem_restrict_set _ _).mp A2, have B4 := (mem_restrict_set _ _).mp A3, cases B3 with c_yes B3, cases B4 with c_no B4, cases B3 with B3 B5, cases B4 with B4 B6, have C1:↑T ⊆ c_yes, {rw ← B5,apply set.inter_subset_left}, have C2:x∈ c_yes,{apply C1,simp,apply B1}, have C3:c_yes ∩ {x} = {x}, {ext,split;intros B8A;simp;simp at B8A,apply B8A.right,subst x_1,simp [C2]}, have C4:↑U ⊆ c_no, {rw ← B6,apply set.inter_subset_left}, have C5:T ⊆ S, { rw ← finset.coe_subset,rw ← B5, apply set.inter_subset_right, }, have C6:x ∈ S, { apply C5, apply B1, }, have C7:x∉ c_no, { intros C5A,apply B2,rw ← finset.mem_coe,rw ← B6, simp, apply and.intro C5A C6, }, have C8:c_no ∩ ↑({x}:finset α) = ↑(∅:finset α), { simp, apply C7, }, have C9:shatters C {x}, { unfold shatters, rw finset.powerset_singleton, apply finset.subset.antisymm, apply restrict_set_subset, rw finset.subset_iff, intros X' C9A, simp at C9A,cases C9A;subst X';rw mem_restrict_set, {apply exists.intro c_no, apply exists.intro B4, exact C8}, {apply exists.intro c_yes, apply exists.intro B3,simp,apply C3}, }, have C10:1 ≤ VCD C, { apply shatters_card_le_VCD C9, }, rw A1 at C10, have C11:(0:enat) < (1:enat) := enat.zero_lt_one, rw lt_iff_not_ge at C11, apply C11, apply C10, end lemma restrict_set_elements_eq_of_VCD_zero {C:set (set α)} {S T U:finset α}:(VCD C = 0) → T ∈ (restrict_set C S) → U ∈ (restrict_set C S) → T = U := begin intros A1 A2 A3, apply finset.subset.antisymm, apply restrict_set_elements_subset_of_VCD_zero A1 A2 A3, apply restrict_set_elements_subset_of_VCD_zero A1 A3 A2, end lemma mem_restrict_set_of_mem_restrict_set {C:set (set α)} {S₁ S₂ T:finset α}: T ∈ restrict_set C S₂ → S₁ ⊆ S₂ → (T ∩ S₁) ∈ restrict_set C S₁ := begin repeat {rw mem_restrict_set}, intros A1 A2, cases A1 with c A1, apply exists.intro c, cases A1 with A1 A3, apply exists.intro A1, simp, rw ← A3, rw set.inter_assoc, rw ← finset.coe_subset at A2, rw set.inter_eq_self_of_subset_right A2, end lemma mem_restrict_set_insert {C:set (set α)} {S c:finset α} {x:α}:x∉ S → (x∉ c) → ((c ∈ restrict_set C S) ↔ (insert x c ∈ restrict_set C (insert x S)) ∨ c∈ restrict_set C (insert x S)) := begin repeat {rw mem_restrict_set}, intros A1 AX,split;intros A2, { cases A2 with c' A2, cases A2 with A2 A3, cases (em (x∈ c')) with B1 B1, { left, apply exists.intro c', apply exists.intro A2, simp, have B2:insert x c' = c' := set.insert_eq_of_mem B1, rw ← B2, rw ← set.insert_inter, rw A3, }, { right, apply exists.intro c', apply exists.intro A2, simp, rw set.inter_insert_of_not_mem B1, apply A3, }, }, { cases A2 with A2 A2;cases A2 with c' A2;cases A2 with A2 A3; apply exists.intro c';apply exists.intro A2, { simp at A3, have C1:=set.mem_of_inter_insert A3, rw set.inter_insert_of_mem C1 at A3, apply set.eq_of_insert_of_not_mem _ _ A3, simp, intro C2, apply A1, apply AX, }, { ext a;split;intros D1, { rw ← A3, simp at D1, simp [D1], }, { have D2:a ≠ x, { intros D2A, subst a, apply AX D1, }, rw ← A3 at D1, simp [D2] at D1, simp [D1], }, }, }, end lemma mem_restrict_set_erase {C:set (set α)} {S c:finset α} {x:α}:x∉ S → (x∈ c) → (c ∈ restrict_set C (insert x S)) → (c.erase x ∈ restrict_set C S) := begin intros A1 A2 A3, rw mem_restrict_set_insert A1, left, rw finset.insert_erase, apply A3, apply A2, apply finset.not_mem_erase, end lemma restrict_card_le_one_of_VCD_zero {C:set (set α)} {S:finset α}:(VCD C = 0) → (restrict_set C S).card ≤ 1 := begin intros A1, apply finset.card_identical_elements, intros T U B1 B2, apply restrict_set_elements_eq_of_VCD_zero A1 B1 B2, end lemma restrict_set_empty_of_empty {S:finset α}:restrict_set ∅ S = ∅ := begin ext c, rw mem_restrict_set, split;intros B1, { cases B1 with c2 B1, cases B1 with B1 B2, simp at B1, exfalso, apply B1, }, { exfalso, simp at B1, apply B1, }, end lemma restrict_set_nonempty_empty {C:set (set α)}: set.nonempty C → restrict_set C ∅ = {∅} := begin intros A1, ext c, rw mem_restrict_set,split;intros B1, { simp, cases B1 with c' B1, cases B1 with B1 B2, rw ← finset.coe_inj, rw ← B2, simp, }, { simp at B1, subst c, rw set.nonempty_def at A1, cases A1 with c' A1, apply exists.intro c', apply exists.intro A1, simp, }, end lemma restrict_set_empty_card_le_1 {C:set (set α)}: (restrict_set C ∅).card ≤ 1 := begin cases (set.eq_empty_or_nonempty C) with B1 B1, { subst C, rw restrict_set_empty_of_empty, simp, }, { rw restrict_set_nonempty_empty B1, simp, }, end lemma filter_union {α:Type*} {S:finset α} {P:α → Prop}: finset.filter P S ∪ finset.filter (λ a, ¬P a) S = S := begin ext a;split;intro A1, { simp at A1, cases A1 with A1 A1;apply A1.left, }, { simp, simp [A1], apply em, }, end lemma recursive_restrict_set_card {C:set (set α)} {x:α} {S:finset α}:x∉ S → ((restrict_set C (insert x S)).filter (λ c,(x∉c ∧ (insert x c) ∈ (restrict_set C (insert x S))))).card + (restrict_set C S).card = (restrict_set C (insert x S)).card := begin intro A1, let Ex := restrict_set C (insert x S), let E := restrict_set C S, begin have B1:Ex = restrict_set C (insert x S) := rfl, have B2:E = restrict_set C S := rfl, repeat {rw ← B1}, repeat {rw ← B2}, rw add_comm, rw ← @filter_card _ _ Ex (λ c, x ∈ c), simp, simp, rw ← @filter_card _ _ (finset.filter (λ c, x∉ c) Ex) (λ c, (insert x c) ∈ Ex), simp, repeat {rw finset.filter_filter}, rw add_comm _ (finset.filter (λ (a : finset α), x ∉ a ∧ insert x a ∉ Ex) Ex).card, rw ← add_assoc, simp, have C1:(finset.filter (λ (a : finset α), x ∉ a ∧ insert x a ∉ Ex) Ex) = (finset.filter (λ (a : finset α), insert x a ∉ Ex) E), { ext c,split;repeat {rw B1};repeat {rw B2};intros C1A;simp at C1A;simp [C1A], { rw mem_restrict_set_insert A1 C1A.right.left, apply or.inr C1A.left}, { have C1B:x ∉ c, { have C1B1:c ⊆ S := mem_restrict_set_subset C1A.left, intro C1B2, apply A1, apply C1B1, apply C1B2, }, have C1C := (mem_restrict_set_insert A1 C1B).mp C1A.left, simp [C1A.right] at C1C, apply and.intro C1C C1B, }, }, rw C1, clear C1, have C2:(finset.filter (has_mem.mem x) Ex).card = (finset.filter (λ a, insert x a ∈ Ex) E).card , { have C2A:(finset.filter (has_mem.mem x) Ex) = (finset.filter (λ a, insert x a ∈ Ex) E).image (insert x), { ext a,split;repeat {rw B1};repeat {rw B2};intros C2A1;simp at C2A1;simp, { apply exists.intro (a.erase x), cases C2A1 with C2A1 C2A2, have C2A3:insert x (a.erase x) = a := finset.insert_erase C2A2, have C2A4:x ∉ a.erase x := finset.not_mem_erase x a, split, split, apply mem_restrict_set_erase A1 C2A2 C2A1, rw C2A3, apply C2A1, apply C2A3, }, { cases C2A1 with c C2A1, cases C2A1 with C2A1 C2A2, cases C2A1 with C2A1 C2A3, subst a, simp [C2A3], }, }, rw C2A, clear C2A, repeat {rw B1}, repeat {rw B2}, apply finset.card_image_of_inj_on, intros c C2B c' C2C, simp at C2B, simp at C2C, have C2D:∀ {c'':finset α}, c'' ∈ restrict_set C S → x ∉ c'', { intros c'' C2D1 C2D3, apply A1, have C2D2 := mem_restrict_set_subset C2D1, apply C2D2, apply C2D3, }, apply finset.eq_of_insert_of_not_mem, apply C2D C2B.left, apply C2D C2C.left, }, rw C2, rw ← @filter_card _ _ E (λ a, insert x a ∈ Ex), end end lemma enat.le_coe_eq_coe {v:enat} {d:nat}:v ≤ d → ∃ d':ℕ, v = d' ∧ d' ≤ d := begin --intros A1, apply enat.cases_on v, { intros A1, simp at A1, exfalso, apply A1, }, { intros n A1, apply exists.intro n, simp at A1, simp [A1], }, end lemma phi_monotone_m {d m₁ m₂:ℕ}:m₁ ≤ m₂ → Φ d m₁ ≤ Φ d m₂ := begin intros A1, rw le_iff_exists_add at A1, cases A1 with c A1, subst m₂, induction c, simp, have A2:(m₁ + c_n.succ) = (m₁ + c_n).succ := rfl, rw A2, cases d, simp, rw phi_succ_succ, apply le_trans c_ih, simp, end lemma phi_le_d_succ {d m:ℕ}:Φ d m ≤ Φ d.succ m := begin revert d, induction m, intro d, simp, intro d, rw phi_succ_succ, cases d, simp, rw phi_succ_succ, rw add_comm, simp, apply le_trans m_ih, apply m_ih, end lemma phi_monotone_d {d₁ d₂ m:ℕ}:d₁ ≤ d₂ → Φ d₁ m ≤ Φ d₂ m := begin intros A1, rw le_iff_exists_add at A1, cases A1 with c A1, subst d₂, induction c, simp, have A2:(d₁ + c_n.succ) = (d₁ + c_n).succ := rfl, rw A2, apply le_trans c_ih, apply phi_le_d_succ, end lemma eq_restrict_set {C:finset (finset α)} {S:finset α}:(∀ c∈ C , c⊆ S)→ C = restrict_set (C.to_set_of_sets) S := begin intros A1, ext c,split;intros B1, { rw mem_restrict_set, apply exists.intro (↑c), split, rw finset.mem_to_set_of_sets, apply B1, have B2 := A1 c B1, apply set.inter_eq_self_of_subset_left, simp, apply B2, }, { rw mem_restrict_set at B1, cases B1 with c' B1, cases B1 with B1 B2, rw finset.mem_to_set_of_sets' at B1, cases B1 with c'' B1, cases B1 with B1 B2, subst c', rw set.inter_eq_self_of_subset_left at B2, simp at B2, subst c'', apply B1, simp, apply A1 c'' B1, }, end lemma finite_restrict_set_eq_image {C:finset (finset α)} {S:finset α}: (restrict_set C.to_set_of_sets S) = C.image (λ S', S'∩ S) := begin ext,split;intros A1A, { simp, rw mem_restrict_set at A1A, cases A1A with c A1A, cases A1A with A1A A1B, rw finset.mem_to_set_of_sets' at A1A, cases A1A with c' A1A, apply exists.intro c', cases A1A with A1A A1C, rw A1C at A1B, rw ← finset.coe_inter at A1B, rw finset.coe_inj at A1B, apply and.intro A1A A1B, }, { simp at A1A, cases A1A with c A1A, cases A1A with A1A A1B, subst a, rw mem_restrict_set, apply exists.intro (↑c), split, rw finset.mem_to_set_of_sets, apply A1A, rw finset.coe_inter, }, end lemma finite_restrict_set_le {C:finset (finset α)} {S:finset α}: (restrict_set C.to_set_of_sets S).card ≤ C.card := begin rw finite_restrict_set_eq_image, apply finset.card_image_le, end lemma shatters_subset {S:finset α} {x:α} {C:set (set α)} {S':finset α}:x∉S → shatters ( ( (restrict_set C (insert x S)).filter (λ (c:finset α),(x∉c ∧ ((insert x c) ∈ (restrict_set C (insert x S))))) ).to_set_of_sets ) S' → S' ⊆ S := begin intros A1 A2, rw shatters_iff at A2, have D1A:S' ⊆ S' := finset.subset.refl S', have D1B := A2 S' D1A, cases D1B with c D1B, cases D1B with D1B D1C, rw finset.mem_to_set_of_sets' at D1B, cases D1B with c' D1B, cases D1B with D1B D1D, subst c, simp at D1B, cases D1B with D1B D1E, cases D1E with D1E D1F, have D1G:= mem_restrict_set_subset D1B, rw ← finset.coe_inter at D1C, rw finset.coe_inj at D1C, have D1H:S'⊆ c', { rw ← D1C, apply finset.inter_subset_left, }, apply finset.subset.trans D1H, apply finset.subset_of_not_mem_of_subset_insert D1E D1G, end lemma shatters_succ {S:finset α} {x:α} {C:set (set α)} {S':finset α}:x∉S → shatters ( ( (restrict_set C (insert x S)).filter (λ (c:finset α),(x∉c ∧ ((insert x c) ∈ (restrict_set C (insert x S))))) ).to_set_of_sets ) S' → shatters C (insert x S') := begin intros A1 A2, rw shatters_iff, intros c B1, have D1:S' ⊆ S := shatters_subset A1 A2, have D2:(insert x (↑S':set α)) ⊆ (insert x ↑S), { apply set.insert_subset_insert, simp, apply D1, }, rw shatters_iff at A2, cases (em (x ∈ c)) with A3 A3, { have C1:c.erase x ⊆ S', { rw ← finset.subset_insert_iff, apply B1, }, have B2 := A2 (c.erase x) C1, cases B2 with c' B2, cases B2 with B2 B3, simp, rw finset.mem_to_set_of_sets' at B2, cases B2 with c'' B2, cases B2 with B2 B4, simp at B2, cases B2 with B2 B5, cases B5 with B5 B6, rw mem_restrict_set at B6, cases B6 with c''' B6, cases B6 with B6 B7, subst c', apply exists.intro c''', apply and.intro B6, simp at B7, rw ← finset.coe_inter at B3, rw finset.coe_inj at B3, have B8:insert x (c'' ∩ S') = insert x (c.erase x), { rw B3, }, rw finset.insert_erase A3 at B8, have B9 := set.mem_of_inter_insert B7, rw ← finset.insert_inter_eq_insert_inter_insert at B8, rw ← B8, rw finset.coe_inter, repeat {rw finset.coe_insert}, rw ← B7, rw set.inter_assoc, rw set.inter_comm (insert x ↑S), rw ← set.inter_assoc, symmetry, apply set.inter_eq_self_of_subset_left, have B10:=set.inter_subset_right c''' (insert x ↑S'), apply set.subset.trans B10 D2, }, { have E1:c ⊆ S', { rw finset.subset_iff, intros a E1A, have E1B := B1 E1A, rw finset.mem_insert at E1B, cases E1B with E1B E1B, { subst a, exfalso, apply A3 E1A, }, apply E1B, }, have E2 := A2 c E1, cases E2 with c' E2, cases E2 with E2 E3, rw finset.mem_to_set_of_sets' at E2, cases E2 with c'' E2, cases E2 with E2 E3, simp at E2, subst c', cases E2 with E2 E4, cases E4 with E4 E5, rw mem_restrict_set at E2, cases E2 with c''' E2, cases E2 with E2 E6, apply exists.intro c''', apply exists.intro E2, have E7:x ∉ (↑c'':set α), {simp [E4]}, rw ← set.inter_insert_of_not_mem E7 at E3, simp at E6, rw ← E3, simp, rw ← E6, rw set.inter_assoc, rw set.inter_comm (insert x ↑S), rw ← set.inter_assoc, symmetry, apply set.inter_eq_self_of_subset_left, have E8:=set.inter_subset_right c''' (insert x ↑S'), apply set.subset.trans E8 D2, }, end lemma VCD_succ {S:finset α} {x:α} {C:set (set α)} {d:ℕ}:x∉S → VCD C = d.succ → VCD ( ( (restrict_set C (insert x S)).filter (λ (c:finset α),(x∉c ∧ ((insert x c) ∈ (restrict_set C (insert x S))))) ).to_set_of_sets ) ≤ d := begin intros A1 A2, apply VCD_le, intros T B1, have B2:T ⊆ S := shatters_subset A1 B1, have B3:x ∉ T, { intro B3A, apply A1, apply B2, apply B3A, }, have B4:shatters C (insert x T), { apply shatters_succ, apply A1, apply B1, }, have B5:((insert x T).card:enat) ≤ VCD C, { apply shatters_card_le_VCD B4, }, rw A2 at B5, simp at B5, rw finset.card_insert_of_not_mem B3 at B5, have B6:T.card + 1 = (T.card).succ := rfl, rw B6 at B5, rw nat.succ_le_succ_iff at B5, simp, apply B5 end --This is known as Sauer's Lemma, or Sauer-Saleh Lemma. --This connects VC-dimension to the complexity of the hypothesis space restricted to a finite set --of certain size. lemma restrict_set_le_phi {C:set (set α)} {S:finset α} (d:ℕ): (VCD C = d) → (restrict_set C S).card ≤ Φ d S.card := begin revert d, revert C, apply finset.induction_on S, { intros C d A1, simp, apply restrict_set_empty_card_le_1, }, { intros x S B1 B2 C d B3, cases d, { rw phi_zero_m_eq_one, apply restrict_card_le_one_of_VCD_zero, simp at B3, apply B3, }, let C':finset (finset α) := (restrict_set C (insert x S)).filter (λ c,(x∉c ∧ (insert x c) ∈ (restrict_set C (insert x S)))), begin have C0:C' = (restrict_set C (insert x S)).filter (λ c,(x∉c ∧ (insert x c) ∈ (restrict_set C (insert x S)))) := rfl, rw ← recursive_restrict_set_card B1, rw ← C0, have D1:C'.card + (restrict_set C S).card ≤ C'.card + Φ d.succ S.card, { simp [B2,B3], }, apply le_trans D1, have C5:C' = restrict_set (C'.to_set_of_sets) S, { apply eq_restrict_set, intros c C3A, rw C0 at C3A, simp at C3A, have C3C := mem_restrict_set_subset C3A.left, apply finset.subset_of_not_mem_of_subset_insert C3A.right.left C3C, }, rw C5, have C6:VCD (C'.to_set_of_sets) ≤ (d:enat), { rw C0, apply VCD_succ, apply B1, apply B3 }, have C7:∃d':ℕ, VCD (C'.to_set_of_sets) = d' ∧ d' ≤ d, { apply enat.le_coe_eq_coe C6, }, cases C7 with d' C7, have C8:(restrict_set C'.to_set_of_sets S).card + Φ d.succ S.card ≤ Φ d S.card + Φ d.succ S.card, { simp, have C8A:(restrict_set C'.to_set_of_sets S).card ≤ Φ d' S.card, { apply B2, apply C7.left, }, apply le_trans C8A, apply phi_monotone_d, apply C7.right, }, apply le_trans C8, rw finset.card_insert_of_not_mem B1, rw phi_succ_succ, rw add_comm, end, }, end /- Lemma 3.2 in K+V. -/ lemma phi_sum {d m : ℕ} : Φ d m = (finset.range (d.succ)).sum (λ i, nat.choose m i) := begin revert d, induction m, { intros d, simp, rw finset.sum_eq_single 0, { refl }, { intros b h h2, cases b, { exfalso, apply h2, refl }, { rw nat.choose_zero_succ } }, { intros h, exfalso, apply h, simp } }, { intros d, cases d, { rw phi_zero_m_eq_one, simp }, { rw phi_succ_succ, rw m_ih, rw m_ih, rw choose_sum_rec } }, end /- A key question will be how to handle product measures. Eventually, we need to think about either: 1. How to create a product measure, as a technical detail that is factored out of the theorem. 2. How to create a stochastic process of IID instances. 3. Assume the existence of a stochastic process. #2 or #3 is closer to our standard approach. Either way, we need to extend independence to infinite sets of random variables/events. -/ lemma shatters_subset' {C:set (set α)} {S:finset α} {T:finset α}:shatters C T → S ⊆ T → shatters C S := begin haveI:decidable_eq α := classical.decidable_eq α, intros h h5, rw shatters_iff, intros S' h_subset, rw shatters_iff at h, have h2 := h S' _, cases h2 with c h2, cases h2 with h2 h3, apply exists.intro c, apply exists.intro h2, apply set.subset.antisymm, { rw ← h3, apply set.inter_subset_inter, apply set.subset.refl, simp, apply h5 }, { apply set.subset_inter, rw ← h3, apply set.inter_subset_left, simp, apply h_subset }, apply finset.subset.trans, apply h_subset, apply h5, end lemma VCD_le' {C:set (set α)} {d:nat}:(∀ S:finset α, (S.card = (nat.succ d)) → ¬(shatters C S)) → VCD C ≤ ↑d := begin intros A1, apply VCD_le, intros S A2, apply classical.by_contradiction, intros A3, rw ← lt_iff_not_ge at A3, simp at A3, have A4:= nat.succ_le_of_lt A3, have A5:∃ (T:finset α), T.card = (d.succ) ∧ T ⊆ S, { apply finset.exists_subset_card A4 }, cases A5 with T A5, have A6 := A1 T A5.left, apply A6, apply @shatters_subset' α C T S, apply A2, apply A5.right, end /- The standard way to prove an exact VC dimension. For a particular size, show that there exists a set that can be shattered, and any set one larger can't be shattered. -/ lemma VCD_eq {C:set (set α)} {d:nat} {T:finset α}:T.card = d → (shatters C T) → (∀ S:finset α, (S.card = (nat.succ d)) → ¬(shatters C S)) → (VCD C = ↑d) := begin intros h1 h2 h3, apply le_antisymm, apply VCD_le', apply h3, rw ← h1, apply shatters_card_le_VCD, apply h2 end --def process {Ω:Type*}:Type := probability_space (ℕ → Ω) -- TODO: introduce ε-nets, and show that the VC dimension of C is a bound on -- the VC-dimension of the ε-net. -- TODO: show that if the training examples cover the ε-net, then any consistent -- algorithm will get a hypothesis with low error. -- TODO: Introduce the proof from 3.5.2 proving a bound on the probability of -- hitting the ε-net. end VC_PAC_problem end VC_PAC_problem
0818311c4bc8198c572144b254fc9617bcb22710
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/shapes/types_auto.lean
4580c29c2913d2eebd27afdc856d37afbacbc675
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,772
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.types import Mathlib.category_theory.limits.shapes.products import Mathlib.category_theory.limits.shapes.binary_products import Mathlib.category_theory.limits.shapes.terminal import Mathlib.PostPort universes u namespace Mathlib /-! # Special shapes for limits in `Type`. The general shape (co)limits defined in `category_theory.limits.types` are intended for use through the limits API, and the actual implementation should mostly be considered "sealed". In this file, we provide definitions of the "standard" special shapes of limits in `Type`, giving the expected definitional implementation: * the terminal object is `punit` * the binary product of `X` and `Y` is `X × Y` * the product of a family `f : J → Type` is `Π j, f j`. Because these are not intended for use with the `has_limit` API, we instead construct terms of `limit_data`. As an example, when setting up the monoidal category structure on `Type` we use the `types_has_terminal` and `types_has_binary_products` instances. -/ namespace category_theory.limits.types /-- A restatement of `types.lift_π_apply` that uses `pi.π` and `pi.lift`. -/ @[simp] theorem pi_lift_π_apply {β : Type u} (f : β → Type u) {P : Type u} (s : (b : β) → P ⟶ f b) (b : β) (x : P) : pi.π f b (pi.lift s x) = s b x := congr_fun (limit.lift_π (fan.mk P s) b) x /-- A restatement of `types.map_π_apply` that uses `pi.π` and `pi.map`. -/ @[simp] theorem pi_map_π_apply {β : Type u} {f : β → Type u} {g : β → Type u} (α : (j : β) → f j ⟶ g j) (b : β) (x : ∏ fun (j : β) => f j) : pi.π g b (pi.map α x) = α b (pi.π f b x) := limit.map_π_apply (discrete.nat_trans α) b x /-- The category of types has `punit` as a terminal object. -/ def terminal_limit_cone : limit_cone (functor.empty (Type u)) := limit_cone.mk (cone.mk PUnit (nat_trans.mk sorry)) (id (is_limit.mk sorry)) /-- The category of types has `pempty` as an initial object. -/ def initial_limit_cone : colimit_cocone (functor.empty (Type u)) := colimit_cocone.mk (cocone.mk pempty (nat_trans.mk sorry)) (id (is_colimit.mk sorry)) /-- The product type `X × Y` forms a cone for the binary product of `X` and `Y`. -/ -- We manually generate the other projection lemmas since the simp-normal form for the legs is -- otherwise not created correctly. @[simp] theorem binary_product_cone_X (X : Type u) (Y : Type u) : cone.X (binary_product_cone X Y) = (X × Y) := Eq.refl (X × Y) @[simp] theorem binary_product_cone_fst (X : Type u) (Y : Type u) : binary_fan.fst (binary_product_cone X Y) = prod.fst := rfl @[simp] theorem binary_product_cone_snd (X : Type u) (Y : Type u) : binary_fan.snd (binary_product_cone X Y) = prod.snd := rfl /-- The product type `X × Y` is a binary product for `X` and `Y`. -/ @[simp] theorem binary_product_limit_lift (X : Type u) (Y : Type u) (s : binary_fan X Y) (x : cone.X s) : is_limit.lift (binary_product_limit X Y) s x = (binary_fan.fst s x, binary_fan.snd s x) := Eq.refl (is_limit.lift (binary_product_limit X Y) s x) /-- The category of types has `X × Y`, the usual cartesian product, as the binary product of `X` and `Y`. -/ @[simp] theorem binary_product_limit_cone_is_limit (X : Type u) (Y : Type u) : limit_cone.is_limit (binary_product_limit_cone X Y) = binary_product_limit X Y := Eq.refl (limit_cone.is_limit (binary_product_limit_cone X Y)) /-- The functor which sends `X, Y` to the product type `X × Y`. -/ -- We add the option `type_md` to tell `@[simps]` to not treat homomorphisms `X ⟶ Y` in `Type*` as -- a function type @[simp] theorem binary_product_functor_obj_map (X : Type u) (Y₁ : Type u) (Y₂ : Type u) (f : Y₁ ⟶ Y₂) : functor.map (functor.obj binary_product_functor X) f = is_limit.lift (binary_product_limit X Y₂) (binary_fan.mk prod.fst (prod.snd ≫ f)) := Eq.refl (functor.map (functor.obj binary_product_functor X) f) /-- The product functor given by the instance `has_binary_products (Type u)` is isomorphic to the explicit binary product functor given by the product type. -/ def binary_product_iso_prod : binary_product_functor ≅ prod.functor := nat_iso.of_components (fun (X : Type u) => nat_iso.of_components (fun (Y : Type u) => iso.symm (is_limit.cone_point_unique_up_to_iso (limit.is_limit (pair X Y)) (binary_product_limit X Y))) sorry) sorry /-- The sum type `X ⊕ Y` forms a cocone for the binary coproduct of `X` and `Y`. -/ @[simp] theorem binary_coproduct_cocone_ι_app (X : Type u) (Y : Type u) (j : discrete walking_pair) : ∀ (ᾰ : functor.obj (pair X Y) j), nat_trans.app (cocone.ι (binary_coproduct_cocone X Y)) j ᾰ = walking_pair.rec sum.inl sum.inr j ᾰ := fun (ᾰ : functor.obj (pair X Y) j) => Eq.refl (walking_pair.rec sum.inl sum.inr j ᾰ) /-- The sum type `X ⊕ Y` is a binary coproduct for `X` and `Y`. -/ def binary_coproduct_colimit (X : Type u) (Y : Type u) : is_colimit (binary_coproduct_cocone X Y) := is_colimit.mk fun (s : binary_cofan X Y) => sum.elim (binary_cofan.inl s) (binary_cofan.inr s) /-- The category of types has `X ⊕ Y`, as the binary coproduct of `X` and `Y`. -/ def binary_coproduct_colimit_cocone (X : Type u) (Y : Type u) : colimit_cocone (pair X Y) := colimit_cocone.mk (binary_coproduct_cocone X Y) (binary_coproduct_colimit X Y) /-- The category of types has `Π j, f j` as the product of a type family `f : J → Type`. -/ def product_limit_cone {J : Type u} (F : J → Type u) : limit_cone (discrete.functor F) := limit_cone.mk (cone.mk ((j : J) → F j) (nat_trans.mk fun (j : discrete J) (f : functor.obj (functor.obj (functor.const (discrete J)) ((j : J) → F j)) j) => f j)) (is_limit.mk fun (s : cone (discrete.functor F)) (x : cone.X s) (j : J) => nat_trans.app (cone.π s) j x) /-- The category of types has `Σ j, f j` as the coproduct of a type family `f : J → Type`. -/ def coproduct_colimit_cocone {J : Type u} (F : J → Type u) : colimit_cocone (discrete.functor F) := colimit_cocone.mk (cocone.mk (sigma fun (j : J) => F j) (nat_trans.mk fun (j : discrete J) (x : functor.obj (discrete.functor F) j) => sigma.mk j x)) (is_colimit.mk fun (s : cocone (discrete.functor F)) (x : cocone.X (cocone.mk (sigma fun (j : J) => F j) (nat_trans.mk fun (j : discrete J) (x : functor.obj (discrete.functor F) j) => sigma.mk j x))) => nat_trans.app (cocone.ι s) (sigma.fst x) (sigma.snd x)) /-- Show the given fork in `Type u` is an equalizer given that any element in the "difference kernel" comes from `X`. The converse of `unique_of_type_equalizer`. -/ def type_equalizer_of_unique {X : Type u} {Y : Type u} {Z : Type u} (f : X ⟶ Y) {g : Y ⟶ Z} {h : Y ⟶ Z} (w : f ≫ g = f ≫ h) (t : ∀ (y : Y), g y = h y → exists_unique fun (x : X) => f x = y) : is_limit (fork.of_ι f w) := fork.is_limit.mk' (fork.of_ι f w) fun (s : fork g h) => { val := fun (i : functor.obj (functor.obj (functor.const walking_parallel_pair) (cone.X s)) walking_parallel_pair.zero) => classical.some sorry, property := sorry } /-- The converse of `type_equalizer_of_unique`. -/ theorem unique_of_type_equalizer {X : Type u} {Y : Type u} {Z : Type u} (f : X ⟶ Y) {g : Y ⟶ Z} {h : Y ⟶ Z} (w : f ≫ g = f ≫ h) (t : is_limit (fork.of_ι f w)) (y : Y) (hy : g y = h y) : exists_unique fun (x : X) => f x = y := sorry theorem type_equalizer_iff_unique {X : Type u} {Y : Type u} {Z : Type u} (f : X ⟶ Y) {g : Y ⟶ Z} {h : Y ⟶ Z} (w : f ≫ g = f ≫ h) : Nonempty (is_limit (fork.of_ι f w)) ↔ ∀ (y : Y), g y = h y → exists_unique fun (x : X) => f x = y := sorry /-- Show that the subtype `{x : Y // g x = h x}` is an equalizer for the pair `(g,h)`. -/ def equalizer_limit {Y : Type u} {Z : Type u} {g : Y ⟶ Z} {h : Y ⟶ Z} : limit_cone (parallel_pair g h) := limit_cone.mk (fork.of_ι subtype.val sorry) (fork.is_limit.mk' (fork.of_ι subtype.val sorry) fun (s : fork g h) => { val := fun (i : functor.obj (functor.obj (functor.const walking_parallel_pair) (cone.X s)) walking_parallel_pair.zero) => { val := fork.ι s i, property := sorry }, property := sorry }) end Mathlib
76f533f1096d81141b5cb336fe5eb77a2b9a59d7
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/server/edits.lean
e3d84fe4947fcbd94f49b2d477f395d97ba8ead1
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,306
lean
import Lean.Data.Lsp open IO Lean Lsp def main : IO Unit := do Ipc.runWith (←IO.appPath) #["--server"] do let hIn ← Ipc.stdin hIn.write (←FS.readBinFile "init_vscode_1_47_2.log") hIn.flush discard $ Ipc.readResponseAs 0 InitializeResult Ipc.writeNotification ⟨"initialized", InitializedParams.mk⟩ hIn.write (←FS.readBinFile "open_content.log") hIn.flush discard <| Ipc.collectDiagnostics 1 "file:///test.lean" 1 hIn.write (←FS.readBinFile "content_changes.log") hIn.flush let diags ← Ipc.collectDiagnostics 2 "file:///test.lean" 7 if diags.isEmpty then throw $ userError "Test failed, no diagnostics received." else let diag := diags.getLast! FS.writeFile "edits_diag.json.produced" (toString <| toJson (diag : JsonRpc.Message)) if let some (refDiag : JsonRpc.Notification PublishDiagnosticsParams) := (Json.parse $ ←FS.readFile "edits_diag.json") >>= fromJson? then assert! (diag == refDiag) else throw $ userError "Failed parsing test file." Ipc.writeRequest ⟨3, "shutdown", Json.null⟩ let shutResp ← Ipc.readResponseAs 3 Json assert! shutResp.result.isNull Ipc.writeNotification ⟨"exit", Json.null⟩ discard $ Ipc.waitForExit
5abdebd12f1fb0d600804dc0fcdf2fd138f23e67
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/category/FinBddDistLat.lean
02344d9e5de7480b20e27cce4224480ad7c0b053
[ "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,341
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.fintype.order import order.category.BddDistLat import order.category.FinPartOrd /-! # The category of finite bounded distributive lattices > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `FinBddDistLat`, the category of finite distributive lattices with bounded lattice homomorphisms. -/ universes u open category_theory /-- The category of finite distributive lattices with bounded lattice morphisms. -/ structure FinBddDistLat := (to_BddDistLat : BddDistLat) [is_fintype : fintype to_BddDistLat] namespace FinBddDistLat instance : has_coe_to_sort FinBddDistLat Type* := ⟨λ X, X.to_BddDistLat⟩ instance (X : FinBddDistLat) : distrib_lattice X := X.to_BddDistLat.to_DistLat.str instance (X : FinBddDistLat) : bounded_order X := X.to_BddDistLat.is_bounded_order attribute [instance] FinBddDistLat.is_fintype /-- Construct a bundled `FinBddDistLat` from a `nonempty` `bounded_order` `distrib_lattice`. -/ def of (α : Type*) [distrib_lattice α] [bounded_order α] [fintype α] : FinBddDistLat := ⟨⟨⟨α⟩⟩⟩ /-- Construct a bundled `FinBddDistLat` from a `nonempty` `bounded_order` `distrib_lattice`. -/ def of' (α : Type*) [distrib_lattice α] [fintype α] [nonempty α] : FinBddDistLat := by { haveI := fintype.to_bounded_order α, exact ⟨⟨⟨α⟩⟩⟩ } instance : inhabited FinBddDistLat := ⟨of punit⟩ instance large_category : large_category FinBddDistLat := induced_category.category to_BddDistLat instance concrete_category : concrete_category FinBddDistLat := induced_category.concrete_category to_BddDistLat instance has_forget_to_BddDistLat : has_forget₂ FinBddDistLat BddDistLat := induced_category.has_forget₂ FinBddDistLat.to_BddDistLat instance has_forget_to_FinPartOrd : has_forget₂ FinBddDistLat FinPartOrd := { forget₂ := { obj := λ X, FinPartOrd.of X, map := λ X Y f, (show bounded_lattice_hom X Y, from f : X →o Y) } } /-- Constructs an equivalence between finite distributive lattices from an order isomorphism between them. -/ @[simps] def iso.mk {α β : FinBddDistLat.{u}} (e : α ≃o β) : α ≅ β := { hom := (e : bounded_lattice_hom α β), inv := (e.symm : bounded_lattice_hom β α), hom_inv_id' := by { ext, exact e.symm_apply_apply _ }, inv_hom_id' := by { ext, exact e.apply_symm_apply _ } } example {X Y : FinBddDistLat} : (X ⟶ Y) = bounded_lattice_hom X Y := rfl /-- `order_dual` as a functor. -/ @[simps] def dual : FinBddDistLat ⥤ FinBddDistLat := { obj := λ X, of Xᵒᵈ, map := λ X Y, bounded_lattice_hom.dual } /-- The equivalence between `FinBddDistLat` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : FinBddDistLat ≌ FinBddDistLat := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end FinBddDistLat lemma FinBddDistLat_dual_comp_forget_to_BddDistLat : FinBddDistLat.dual ⋙ forget₂ FinBddDistLat BddDistLat = forget₂ FinBddDistLat BddDistLat ⋙ BddDistLat.dual := rfl
2621563928a3809efdb487a7d07610190a1eafae
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/bench/qsort.lean
f1c22f0670dbef02c7e1ae9326a4cf42fa1b0138
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
2,407
lean
abbrev Elem := UInt32 def badRand (seed : Elem) : Elem := seed * 1664525 + 1013904223 def mkRandomArray : Nat → Elem → Array Elem → Array Elem | 0, seed, as => as | i+1, seed, as => mkRandomArray i (badRand seed) (as.push seed) partial def checkSortedAux (a : Array Elem) : Nat → IO Unit | i => if i < a.size - 1 then do unless (a.get! i <= a.get! (i+1)) $ throw (IO.userError "array is not sorted"); checkSortedAux (i+1) else pure () -- copied from stdlib, but with `UInt32` indices instead of `Nat` (which is more comparable to the other versions) abbrev Idx := UInt32 instance : HasLift UInt32 Nat := ⟨UInt32.toNat⟩ prefix `↑`:max := oldCoe @[specialize] private partial def partitionAux {α : Type} [Inhabited α] (lt : α → α → Bool) (hi : Idx) (pivot : α) : Array α → Idx → Idx → Idx × Array α | as, i, j => if j < hi then if lt (as.get! ↑j) pivot then let as := as.swap! ↑i ↑j; partitionAux as (i+1) (j+1) else partitionAux as i (j+1) else let as := as.swap! ↑i ↑hi; (i, as) @[inline] def partition {α : Type} [Inhabited α] (as : Array α) (lt : α → α → Bool) (lo hi : Idx) : Idx × Array α := let mid := (lo + hi) / 2; let as := if lt (as.get! ↑mid) (as.get! ↑lo) then as.swap! ↑lo ↑mid else as; let as := if lt (as.get! ↑hi) (as.get! ↑lo) then as.swap! ↑lo ↑hi else as; let as := if lt (as.get! ↑mid) (as.get! ↑hi) then as.swap! ↑mid ↑hi else as; let pivot := as.get! ↑hi; partitionAux lt hi pivot as lo lo @[specialize] partial def qsortAux {α : Type} [Inhabited α] (lt : α → α → Bool) : Array α → Idx → Idx → Array α | as, low, high => if low < high then let p := partition as lt low high; -- TODO: fix `partial` support in the equation compiler, it breaks if we use `let (mid, as) := partition as lt low high` let mid := p.1; let as := p.2; let as := qsortAux as low mid; qsortAux as (mid+1) high else as @[inline] def qsort {α : Type} [Inhabited α] (as : Array α) (lt : α → α → Bool) : Array α := qsortAux lt as 0 (UInt32.ofNat (as.size - 1)) def main (xs : List String) : IO Unit := do let n := xs.head!.toNat!; n.forM $ fun _ => n.forM $ fun i => do let xs := mkRandomArray i (UInt32.ofNat i) Array.empty; let xs := qsort xs (fun a b => a < b); --IO.println xs; checkSortedAux xs 0
2181a9977be924e541e8305dd032af248d6707dc
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/empty_eq.lean
d805901f34d73ca9a8752408bdaa2baf0baf5b4d
[ "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
217
lean
open nat inductive fin : nat → Type := | fz : Π n, fin (succ n) | fs : Π {n}, fin n → fin (succ n) open fin definition case0 {C : fin zero → Type} : Π (f : fin zero), C f | [none] print definition case0
7562174380809cc2cdd828846d4ce51072f0a921
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Std/Data/HashMap.lean
8c40ac307a39eb8a7844c59e709ba6aefe2ff7a0
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,232
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Std.Data.AssocList namespace Std universes u v w def HashMapBucket (α : Type u) (β : Type v) := { b : Array (AssocList α β) // b.size > 0 } def HashMapBucket.update {α : Type u} {β : Type v} (data : HashMapBucket α β) (i : USize) (d : AssocList α β) (h : i.toNat < data.val.size) : HashMapBucket α β := ⟨ data.val.uset i d h, by erw [Array.sizeSetEq]; exact data.property ⟩ structure HashMapImp (α : Type u) (β : Type v) where size : Nat buckets : HashMapBucket α β def mkHashMapImp {α : Type u} {β : Type v} (nbuckets := 8) : HashMapImp α β := let n := if nbuckets = 0 then 8 else nbuckets; { size := 0, buckets := ⟨ mkArray n AssocList.nil, by rw [Array.sizeMkArrayEq]; cases nbuckets; decide!; apply Nat.zeroLtSucc; done ⟩ } namespace HashMapImp variable {α : Type u} {β : Type v} def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } := ⟨u % n, USize.modnLt _ h⟩ @[inline] def reinsertAux (hashFn : α → USize) (data : HashMapBucket α β) (a : α) (b : β) : HashMapBucket α β := let ⟨i, h⟩ := mkIdx data.property (hashFn a) data.update i (AssocList.cons a b (data.val.uget i h)) h @[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (d : δ) (f : δ → α → β → m δ) : m δ := data.val.foldlM (init := d) fun d b => b.foldlM f d @[inline] def foldBuckets {δ : Type w} (data : HashMapBucket α β) (d : δ) (f : δ → α → β → δ) : δ := Id.run $ foldBucketsM data d f @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (d : δ) (h : HashMapImp α β) : m δ := foldBucketsM h.buckets d f @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (d : δ) (m : HashMapImp α β) : δ := foldBuckets m.buckets d f def findEntry? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option (α × β) := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).findEntry? a def find? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option β := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).find? a def contains [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Bool := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).contains a -- TODO: remove `partial` by using well-founded recursion partial def moveEntries [Hashable α] (i : Nat) (source : Array (AssocList α β)) (target : HashMapBucket α β) : HashMapBucket α β := if h : i < source.size then let idx : Fin source.size := ⟨i, h⟩ let es : AssocList α β := source.get idx -- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl let source := source.set idx AssocList.nil let target := es.foldl (reinsertAux hash) target moveEntries (i+1) source target else target def expand [Hashable α] (size : Nat) (buckets : HashMapBucket α β) : HashMapImp α β := let nbuckets := buckets.val.size * 2 have nbuckets > 0 from Nat.mulPos buckets.property (decide! : 2 > 0) let new_buckets : HashMapBucket α β := ⟨mkArray nbuckets AssocList.nil, by rw [Array.sizeMkArrayEq]; assumption⟩ { size := size, buckets := moveEntries 0 buckets.val new_buckets } def insert [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) (b : β) : HashMapImp α β := match m with | ⟨size, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size, buckets.update i (bkt.replace a b) h⟩ else let size' := size + 1 let buckets' := buckets.update i (AssocList.cons a b bkt) h if size' ≤ buckets.val.size then { size := size', buckets := buckets' } else expand size' buckets' def erase [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : HashMapImp α β := match m with | ⟨ size, buckets ⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩ else m inductive WellFormed [BEq α] [Hashable α] : HashMapImp α β → Prop where | mkWff : ∀ n, WellFormed (mkHashMapImp n) | insertWff : ∀ m a b, WellFormed m → WellFormed (insert m a b) | eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a) end HashMapImp def HashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := { m : HashMapImp α β // m.WellFormed } open Std.HashMapImp def mkHashMap {α : Type u} {β : Type v} [BEq α] [Hashable α] (nbuckets := 8) : HashMap α β := ⟨ mkHashMapImp nbuckets, WellFormed.mkWff nbuckets ⟩ namespace HashMap variable {α : Type u} {β : Type v} [BEq α] [Hashable α] instance : Inhabited (HashMap α β) where default := mkHashMap instance : EmptyCollection (HashMap α β) := ⟨mkHashMap⟩ @[inline] def insert (m : HashMap α β) (a : α) (b : β) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.insert a b, WellFormed.insertWff m a b hw ⟩ @[inline] def erase (m : HashMap α β) (a : α) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩ @[inline] def findEntry? (m : HashMap α β) (a : α) : Option (α × β) := match m with | ⟨ m, _ ⟩ => m.findEntry? a @[inline] def find? (m : HashMap α β) (a : α) : Option β := match m with | ⟨ m, _ ⟩ => m.find? a @[inline] def findD (m : HashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [Inhabited β] (m : HashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" @[inline] def getOp (self : HashMap α β) (idx : α) : Option β := self.find? idx @[inline] def contains (m : HashMap α β) (a : α) : Bool := match m with | ⟨ m, _ ⟩ => m.contains a @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (init : δ) (h : HashMap α β) : m δ := match h with | ⟨ h, _ ⟩ => h.foldM f init @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (init : δ) (m : HashMap α β) : δ := match m with | ⟨ m, _ ⟩ => m.fold f init @[inline] def size (m : HashMap α β) : Nat := match m with | ⟨ {size := sz, ..}, _ ⟩ => sz @[inline] def isEmpty (m : HashMap α β) : Bool := m.size = 0 @[inline] def empty : HashMap α β := mkHashMap def toList (m : HashMap α β) : List (α × β) := m.fold (init := []) fun r k v => (k, v)::r def toArray (m : HashMap α β) : Array (α × β) := m.fold (init := #[]) fun r k v => r.push (k, v) def numBuckets (m : HashMap α β) : Nat := m.val.buckets.val.size end HashMap end Std
85be07730e8b5247556aa7bcf6ecd245793f41ac
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/FixedParams.lean
34ab6677b68e3ff03d75146a369dfd0af20e9cf4
[ "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
6,597
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.LCNF.Basic import Lean.Compiler.LCNF.Types namespace Lean.Compiler.LCNF namespace FixedParams /-! # Fixed Parameter Static Analyzer -/ /- If function is partially applied, we assume missing parameters are not fixed. Note that, since LCNF is in A-normal form, if function is used as an argument, none of its parameters will be considered fixed. We assume functions that are not in mutual block do not invoke the function being analyzed. We track fixed arguments using "abstract values". They are just a "token" or ⊤. We can view it as a form of constant propagation. When analyzing a function call to another function in the same mutual block, we visit its body after binding its parameters to "abstract values". We keep a cache of the already visited pairs ("declName", "abstract values"). Whenever, we find a recursive call to the function being analyzed, we check whether the arguments match the initial "abstract values". We interrupt the analysis if all parameters of the function being analyzed have been marked as not fixed. -/ /-- Abstract value for the "fixed parameter" analysis. -/ inductive AbsValue where | top | erased | val (i : Nat) deriving Inhabited, BEq, Hashable structure Context where /-- Declaration in the same mutual block. -/ decls : Array Decl /-- Function being analyzed. We check every recursive call to this function. Remark: `main` is in `decls`. -/ main : Decl /-- The assignment maps free variable ids in the current code being analyzed to abstract values. We only track the abstract value assigned to parameters. -/ assignment : FVarIdMap AbsValue structure State where /-- Set of calls that have been already analyzed. Recall that we assume that only functions in `decls` may have recursive calls to the function being analyzed (i.e., `main`). Whenever there is function application `f a₁ ... aₙ`, where `f` is in `decls`, `f` is not `main`, and we visit with the abstract values assigned to `aᵢ`, but first we record the visit here. -/ visited : HashSet (Name × Array AbsValue) := {} /-- Bitmask containing the result, i.e., which parameters of `main` are fixed. We initialize it with `true` everywhere. -/ fixed : Array Bool /-- Monad for the fixed parameter static analyzer. We use the unit-exception to interrupt the analysis. -/ abbrev FixParamM := ReaderT Context <| EStateM Unit State /-- Stop the analysis and mark all parameters as non-fixed. -/ abbrev abort : FixParamM α := do modify fun s => { s with fixed := s.fixed.map fun _ => false } throw () def evalFVar (fvarId : FVarId) : FixParamM AbsValue := do let some val := (← read).assignment.find? fvarId | return .top return val def evalArg (arg : Arg) : FixParamM AbsValue := do match arg with | .erased => return .erased | .type (.fvar fvarId) => evalFVar fvarId | .type _ => return .top | .fvar fvarId => evalFVar fvarId def inMutualBlock (declName : Name) : FixParamM Bool := return (← read).decls.any (·.name == declName) def mkAssignment (decl : Decl) (values : Array AbsValue) : FVarIdMap AbsValue := Id.run do let mut assignment := {} for param in decl.params, value in values do assignment := assignment.insert param.fvarId value return assignment mutual partial def evalLetValue (e : LetValue) : FixParamM Unit := do match e with | .const declName _ args => evalApp declName args | _ => return () partial def evalCode (code : Code) : FixParamM Unit := do match code with | .let decl k => evalLetValue decl.value; evalCode k | .fun decl k | .jp decl k => evalCode decl.value; evalCode k | .cases c => c.alts.forM fun alt => evalCode alt.getCode | .unreach .. | .jmp .. | .return .. => return () partial def evalApp (declName : Name) (args : Array Arg) : FixParamM Unit := do let main := (← read).main if declName == main.name then -- Recursive call to the function being analyzed for h : i in [:main.params.size] do if _h : i < args.size then have : i < main.params.size := h.upper let param := main.params[i] let val ← evalArg args[i] unless val == .val i || (val == .erased && param.type.isErased) do -- Found non fixed argument -- Remark: if the argument is erased and the type of the parameter is erased we assume it is a fixed "propositonal" parameter. modify fun s => { s with fixed := s.fixed.set! i false } else -- Partial application mark argument as not fixed modify fun s => { s with fixed := s.fixed.set! i false } unless (← get).fixed.contains true do throw () -- stop analysis, none of the arguments are fixed. for decl in (← read).decls do if declName == decl.name then -- Call to another function in the same mutual block. let mut values := #[] for i in [:decl.params.size] do if h : i < args.size then values := values.push (← evalArg args[i]) else values := values.push .top let key := (declName, values) unless (← get).visited.contains key do modify fun s => { s with visited := s.visited.insert key } let assignment := mkAssignment decl values withReader (fun ctx => { ctx with assignment }) <| evalCode decl.value end def mkInitialValues (numParams : Nat) : Array AbsValue := Id.run do let mut values := #[] for i in [:numParams] do values := values.push <| .val i return values end FixedParams open FixedParams /-- Given the (potentially mutually) recursive declarations `decls`, return a map from declaration name `decl.name` to a bit-mask `m` where `m[i]` is true iff the `decl.params[i]` is a fixed argument. That is, it does not change in recursive applications. The function assumes that if a function `f` was declared in a mutual block, then `decls` contains all (computationally relevant) functions in the mutual block. -/ def mkFixedParamsMap (decls : Array Decl) : NameMap (Array Bool) := Id.run do let mut result := {} for decl in decls do let values := mkInitialValues decl.params.size let assignment := mkAssignment decl values let fixed := Array.mkArray decl.params.size true match evalCode decl.value |>.run { main := decl, decls, assignment } |>.run { fixed } with | .ok _ s | .error _ s => result := result.insert decl.name s.fixed return result end Lean.Compiler.LCNF
0ff726e9dc1beeb54974abfe20b6fe924702ecf3
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0411.lean
2540b187c6f62b8fb2fa2c80287f03e6a219ec4d
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
91
lean
example : ∃ x, x + 2 = 8 := begin let a : ℕ := 3 * 2, existsi a, reflexivity end
fb424363f6efc1daa2a6d6ce7159f84d21b54d23
f1b175e38ffc5cc1c7c5551a72d0dbaf70786f83
/data/set/basic.lean
f305d946aa43757387cca9efbd3767b56e2353c0
[ "Apache-2.0" ]
permissive
mjendrusch/mathlib
df3ae884dd5ce38c7edf452bcbfd3baf4e3a6214
5c209edb7eb616a26f64efe3500f2b1ba95b8d55
refs/heads/master
1,585,663,284,800
1,539,062,055,000
1,539,062,055,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
42,567
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import tactic.ext tactic.finish data.subtype tactic.interactive open function /- set coercion to a type -/ namespace set instance {α : Type*} : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩ end set section set_coe universe u variables {α : Type u} @[simp] theorem set.set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.property namespace set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[extensionality] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff (s t : set α) : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨begin intros h x, rw h end, ext⟩ @[trans] theorem mem_of_mem_of_subset {α : Type u} {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /- mem and set_of -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl @[simp] theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl @[simp] lemma sep_set_of {α} {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl @[simp] lemma set_of_mem {α} {s : set α} : {a | a ∈ s} = s := rfl /- subset -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {α : Type u} {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, e ▸ ⟨subset.refl _, subset.refl _⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alterantive name theorem eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ theorem not_subset : (¬ s ⊆ t) ↔ ∃a, a ∈ s ∧ a ∉ t := by simp [subset_def, classical.not_forall] /- strict subset -/ /-- `s ⊂ t` means that `s` is a strict subset of `t`, that is, `s ⊆ t` but `s ≠ t`. -/ def strict_subset (s t : set α) := s ⊆ t ∧ s ≠ t instance : has_ssubset (set α) := ⟨strict_subset⟩ theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ s ≠ t) := rfl lemma exists_of_ssubset {α : Type u} {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := classical.by_contradiction $ assume hn, have t ⊆ s, from assume a hat, classical.by_contradiction $ assume has, hn ⟨a, hat, has⟩, h.2 $ subset.antisymm h.1 this lemma ssubset_iff_subset_not_subset {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h @[simp] theorem not_not_mem [decidable (a ∈ s)] : ¬ (a ∉ s) ↔ a ∈ s := not_not /- empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := by simp [ext_iff] theorem ne_empty_of_mem {s : set α} {x : α} (h : x ∈ s) : s ≠ ∅ := by { intro hs, rw hs at h, apply not_mem_empty _ h } @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s := assume x, assume h, false.elim h theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := by simp [subset.antisymm_iff] theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem ne_empty_iff_exists_mem {s : set α} : s ≠ ∅ ↔ ∃ x, x ∈ s := by haveI := classical.prop_decidable; simp [eq_empty_iff_forall_not_mem] theorem exists_mem_of_ne_empty {s : set α} : s ≠ ∅ → ∃ x, x ∈ s := ne_empty_iff_exists_mem.1 -- TODO: remove when simplifier stops rewriting `a ≠ b` to `¬ a = b` theorem not_eq_empty_iff_exists {s : set α} : ¬ (s = ∅) ↔ ∃ x, x ∈ s := ne_empty_iff_exists_mem theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem subset_ne_empty {s t : set α} (h : t ⊆ s) : t ≠ ∅ → s ≠ ∅ := mt (subset_eq_empty h) theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := by simp [iff_def] /- universal set -/ theorem univ_def : @univ α = {x | true} := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial theorem empty_ne_univ [h : inhabited α] : (∅ : set α) ≠ univ := by simp [ext_iff] @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := by simp [subset.antisymm_iff] theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 lemma nonempty_iff_univ_ne_empty {α : Type*} : nonempty α ↔ (univ : set α) ≠ ∅ := begin split, { rintro ⟨a⟩ H2, show a ∈ (∅ : set α), by rw ←H2 ; trivial }, { intro H, cases exists_mem_of_ne_empty H with a _, exact ⟨a⟩ } end instance univ_decidable : decidable_pred (@set.univ α) := λ x, is_true trivial /- union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext (assume x, or_self _) @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext (assume x, or_false _) @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext (assume x, false_or _) theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext (assume x, or.comm) theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (assume x, or.assoc) instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := by finish theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := by finish theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := by finish [subset_def, ext_iff, iff_def] @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := by finish [subset_def, union_def] @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := by finish [iff_def, subset_def] theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := by finish [subset_def] theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h (by refl) theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union (by refl) h @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := ⟨by finish [ext_iff], by finish [ext_iff]⟩ /- intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext (assume x, and_self _) @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (assume x, and_false _) @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (assume x, false_and _) theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (assume x, and.comm) theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (assume x, and.assoc) instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by finish theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := by finish @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x H, and.left H @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := by finish [subset_def, inter_def] @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := ⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩, λ ⟨h₁, h₂⟩, subset_inter h₁ h₂⟩ @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := ext (assume x, and_true _) @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := ext (assume x, true_and _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := by finish [subset_def] theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := by finish [subset_def] theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := by finish [subset_def] theorem inter_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∩ t = s := by finish [subset_def, ext_iff, iff_def] theorem inter_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∩ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_inter_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) ∩ s = s := by finish [ext_iff, iff_def] theorem union_inter_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) ∩ t = t := by finish [ext_iff, iff_def] -- TODO(Mario): remove? theorem nonempty_of_inter_nonempty_right {s t : set α} (h : s ∩ t ≠ ∅) : t ≠ ∅ := by finish [ext_iff, iff_def] theorem nonempty_of_inter_nonempty_left {s t : set α} (h : s ∩ t ≠ ∅) : s ≠ ∅ := by finish [ext_iff, iff_def] /- distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (assume x, and_or_distrib_left) theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (assume x, or_and_distrib_right) theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (assume x, or_and_distrib_left) theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (assume x, and_or_distrib_right) /- insert -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem insert_of_has_insert (x : α) (s : set α) : has_insert.insert x s = insert x s := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := assume y ys, or.inr ys theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := by finish [insert_def] @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := by finish [ext_iff, iff_def] theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := assume a', or.imp_right (@h a') theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := by finish [ssubset_def, ext_iff] theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ by simp [or.left_comm] theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] -- TODO(Jeremy): make this automatic theorem insert_ne_empty (a : α) (s : set α) : insert a s ≠ ∅ := by safe [ext_iff, iff_def]; have h' := a_1 a; finish -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := by finish theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ s → P x) (ha : P a) : ∀ x, x ∈ insert a s → P x := by finish theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := by finish [iff_def] /- singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := rfl @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := by finish [singleton_def] -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := by finish @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := by finish [ext_iff, iff_def] theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := by finish theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := by finish [ext_iff, or_comm] @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := by finish @[simp] theorem singleton_ne_empty (a : α) : ({a} : set α) ≠ ∅ := insert_ne_empty _ _ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := ⟨λh, h (by simp), λh b e, by simp at e; simp [*]⟩ theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := ext $ by simp @[simp] theorem union_singleton : s ∪ {a} = insert a s := by simp [singleton_def] @[simp] theorem singleton_union : {a} ∪ s = insert a s := by rw [union_comm, union_singleton] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := by simp [eq_empty_iff_forall_not_mem] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] /- separation -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := by finish [ext_iff, iff_def, subset_def] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := assume x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (h : {x ∈ s | p x} = ∅) : ∀ x ∈ s, ¬ p x := by finish [ext_iff] @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := set.ext $ by simp /- complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ -s := h theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ -s) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ -s = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ -s ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ -s = ∅ := by finish [ext_iff] @[simp] theorem compl_inter_self (s : set α) : -s ∩ s = ∅ := by finish [ext_iff] @[simp] theorem compl_empty : -(∅ : set α) = univ := by finish [ext_iff] @[simp] theorem compl_union (s t : set α) : -(s ∪ t) = -s ∩ -t := by finish [ext_iff] @[simp] theorem compl_compl (s : set α) : -(-s) = s := by finish [ext_iff] -- ditto theorem compl_inter (s t : set α) : -(s ∩ t) = -s ∪ -t := by finish [ext_iff] @[simp] theorem compl_univ : -(univ : set α) = ∅ := by finish [ext_iff] theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = -(-s ∩ -t) := by simp [compl_inter, compl_compl] theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = -(-s ∪ -t) := by simp [compl_compl] @[simp] theorem union_compl_self (s : set α) : s ∪ -s = univ := by finish [ext_iff] @[simp] theorem compl_union_self (s : set α) : -s ∪ s = univ := by finish [ext_iff] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : -s ⊆ t ↔ -t ⊆ s := by haveI := classical.prop_decidable; exact forall_congr (λ a, not_imp_comm) lemma compl_subset_compl {s t : set α} : -s ⊆ -t ↔ t ⊆ s := by rw [compl_subset_comm, compl_compl] theorem compl_subset_iff_union {s t : set α} : -s ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, by haveI := classical.prop_decidable; exact or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ -t ↔ t ⊆ -s := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ -t ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff /- set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ -t := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := by finish [ext_iff, iff_def, subset_def] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := by finish [ext_iff, iff_def] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := by finish [ext_iff, iff_def] theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := inter_distrib_right _ _ _ theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inter_assoc _ _ _ theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := by finish [ext_iff] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := by finish [ext_iff, iff_def] theorem diff_subset (s t : set α) : s \ t ⊆ s := by finish [subset_def] theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := by finish [subset_def] theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := diff_subset_diff h (by refl) theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := diff_subset_diff (subset.refl s) h theorem compl_eq_univ_diff (s : set α) : -s = univ \ s := by finish [ext_iff] theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := ⟨assume h x hx, classical.by_contradiction $ assume : x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩, assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := ext $ by simp [not_or_distrib, and.comm, and.left_comm] lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := ⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)), assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩ lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := by rw [diff_subset_iff, diff_subset_iff, union_comm] @[simp] theorem insert_diff (h : a ∈ t) : insert a s \ t = s \ t := ext $ by intro; constructor; simp [or_imp_distrib, h] {contextual := tt} theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := by finish [ext_iff, iff_def] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_diff_self, union_comm] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := ext $ by simp [iff_def] {contextual:=tt} theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := by finish [ext_iff, iff_def, subset_def] @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := ext $ by simp /- powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl /- inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage_eq {s : set β} {a : α} : (a ∈ f ⁻¹' s) = (f a ∈ s) := rfl theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' (- s) = - (f ⁻¹' s) := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by rw [s_eq]; simp, assume h, ext $ assume ⟨x, hx⟩, by simp [h]⟩ end preimage /- function image -/ section image infix ` '' `:80 := image /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f1 f2 : α → β) (a : set α) : Prop := ∀ x ∈ a, f1 x = f2 x -- TODO(Jeremy): use bounded exists in image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) ▸ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := by finish [mem_image_eq] @[simp] theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := iff.intro (assume h a ha, h _ $ mem_image_of_mem _ ha) (assume h b ⟨a, ha, eq⟩, eq ▸ h a ha) theorem mono_image {f : α → β} {s t : set α} (h : s ⊆ t) : f '' s ⊆ f '' t := assume x ⟨y, hy, y_eq⟩, y_eq ▸ mem_image_of_mem _ $ h hy theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] theorem image_eq_image_of_eq_on {f₁ f₂ : α → β} {s : set α} (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /- Proof is removed as it uses generated names TODO(Jeremy): make automatic, begin safe [ext_iff, iff_def, mem_image, (∘)], have h' := h_2 (g a_2), finish end -/ theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := by finish [ext_iff, iff_def, mem_image_eq] @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := ext $ by simp theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (subset_inter (mono_image $ inter_subset_left _ _) (mono_image $ inter_subset_right _ _)) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by simp [image]; exact H @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := ext $ λ x, by simp [image]; rw eq_comm lemma inter_singleton_ne_empty {α : Type*} {s : set α} {a : α} : s ∩ {a} ≠ ∅ ↔ a ∈ s := by finish [set.inter_singleton_eq_empty] theorem fix_set_compl (t : set α) : compl t = - t := rfl -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ -t ∈ S := begin suffices : ∀ x, -x = t ↔ -t = x, {simp [fix_set_compl, this]}, intro x, split; { intro e, subst e, simp } end @[simp] theorem image_id (s : set α) : id '' s = s := ext $ by simp theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := ext $ by simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' -s ⊆ -(f '' s) := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : -(f '' s) ⊆ f '' -s := compl_subset_iff_union.2 $ by rw ← image_union; simp [image_univ_of_surjective H] theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' -s = -(f '' s) := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) /- image and preimage are a Galois connection -/ theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} {s : set β} (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = preimage f t ↔ s = t := iff.intro (assume eq, by rw [← @image_preimage_eq β α f s hf, ← @image_preimage_eq β α f t hf, eq]) (assume eq, eq ▸ rfl) lemma surjective_preimage {f : β → α} (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 theorem compl_image : image (@compl α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {α : Type u} {p : set α → Prop} : compl '' {x | p x} = {x | p (- x)} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma subtype_val_image {p : α → Prop} {s : set (subtype p)} : subtype.val '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma injective_image {f : α → β} (hf : injective f) : injective (('') f) := assume s t, (image_eq_image hf).1 end image theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := ⟨assume h i, h (f i) (mem_range_self _), assume h a ⟨i, (hi : f i = a)⟩, hi ▸ h i⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id @[simp] theorem image_univ {ι : Type*} {f : ι → β} : f '' univ = range f := ext $ by simp [image, range] theorem range_comp {g : α → β} : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff {ι : Type*} {f : ι → β} {s : set β} : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff lemma nonempty_of_nonempty_range {α : Type*} {β : Type*} {f : α → β} (H : ¬range f = ∅) : nonempty α := begin cases exists_mem_of_ne_empty H with x h, cases mem_range.1 h with y _, exact ⟨y⟩ end theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' preimage f t = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ preimage f t, by simp [preimage, h_eq, hx]⟩ @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep end range lemma subtype_val_range {p : α → Prop} : range (@subtype.val _ p) = {x | p x} := by rw ← image_univ; simp [-image_univ, subtype_val_image] /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y end set namespace set section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} theorem mem_prod_eq {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ set.prod s t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ set.prod s t := ⟨a_in, b_in⟩ @[simp] theorem prod_empty {s : set α} : set.prod s ∅ = (∅ : set (α × β)) := ext $ by simp [set.prod] @[simp] theorem empty_prod {t : set β} : set.prod ∅ t = (∅ : set (α × β)) := ext $ by simp [set.prod] theorem insert_prod {a : α} {s : set α} {t : set β} : set.prod (insert a s) t = (prod.mk a '' t) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_insert {b : β} {s : set α} {t : set β} : set.prod s (insert b t) = ((λa, (a, b)) '' s) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_preimage_eq {f : γ → α} {g : δ → β} : set.prod (preimage f s) (preimage g t) = preimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : set.prod s₁ t₁ ⊆ set.prod s₂ t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ theorem prod_inter_prod : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) theorem image_swap_prod : (λp:β×α, (p.2, p.1)) '' set.prod t s = set.prod s t := ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod, and_comm]; exact ⟨ assume ⟨b', a', ⟨h_a, h_b⟩, h⟩, by subst a'; subst b'; assumption, assume h, ⟨b, a, ⟨rfl, rfl⟩, h⟩⟩ theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : set.prod (image m₁ s) (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (set.prod s t) := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : set.prod (range m₁) (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] @[simp] theorem prod_singleton_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α×β)) := ext $ by simp [set.prod] theorem prod_neq_empty_iff {s : set α} {t : set β} : set.prod s t ≠ ∅ ↔ (s ≠ ∅ ∧ t ≠ ∅) := by simp [not_eq_empty_iff_exists] @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl @[simp] theorem univ_prod_univ : set.prod (@univ α) (@univ β) = univ := ext $ assume ⟨a, b⟩, by simp lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : set.prod s t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] end prod section pi variables {α : Type*} {π : α → Type*} def pi (i : set α) (s : Πa, set (π a)) : set (Πa, π a) := { f | ∀a∈i, f a ∈ s a } @[simp] lemma pi_empty_index (s : Πa, set (π a)) : pi ∅ s = univ := by ext; simp [pi] @[simp] lemma pi_insert_index (a : α) (i : set α) (s : Πa, set (π a)) : pi (insert a i) s = ((λf, f a) ⁻¹' s a) ∩ pi i s := by ext; simp [pi, or_imp_distrib, forall_and_distrib] @[simp] lemma pi_singleton_index (a : α) (s : Πa, set (π a)) : pi {a} s = ((λf:(Πa, π a), f a) ⁻¹' s a) := by ext; simp [pi] lemma pi_if {p : α → Prop} [h : decidable_pred p] (i : set α) (s t : Πa, set (π a)) : pi i (λa, if p a then s a else t a) = pi {a ∈ i | p a} s ∩ pi {a ∈ i | ¬ p a} t := begin ext f, split, { assume h, split; { rintros a ⟨hai, hpa⟩, simpa [*] using h a } }, { rintros ⟨hs, ht⟩ a hai, by_cases p a; simp [*, pi] at * } end end pi end set
47f753d1383cd7623289ea563765136ad37b5473
4f065978c49388d188224610d9984673079f7d91
/group_products.lean
2271245b4b32583843ea0a7b1071b66d7d50fd73
[]
no_license
kckennylau/Lean
b323103f52706304907adcfaee6f5cb8095d4a33
907d0a4d2bd8f23785abd6142ad53d308c54fdcb
refs/heads/master
1,624,623,720,653
1,563,901,820,000
1,563,901,820,000
109,506,702
3
1
null
null
null
null
UTF-8
Lean
false
false
3,861
lean
import data.equiv universes u v w variables {α : Type u} {β : Type v} {γ : Type w} [group α] [group β] [group γ] variables (α β) structure isomorphism extends equiv α β := (map_mul : is_group_hom to_fun) namespace isomorphism variables {α β} (f : isomorphism α β) (g : isomorphism β γ) {x y : α} def comp : isomorphism α γ := { equiv.trans f.to_equiv g.to_equiv with map_mul := λ x y, calc g.to_fun (f.to_fun (x * y)) = g.to_fun (f.to_fun x * f.to_fun y) : congr_arg g.to_fun $ @isomorphism.map_mul _ _ _ _ f x y ... = g.to_fun (f.to_fun x) * g.to_fun (f.to_fun y) : @isomorphism.map_mul _ _ _ _ g _ _ } def inv : isomorphism β α := { equiv.symm f.to_equiv with map_mul := λ x y, calc f.inv_fun (x * y) = f.inv_fun (f.to_fun (f.inv_fun x) * y) : congr_arg f.inv_fun $ congr_arg (λ z, z * y) $ eq.symm $ f.right_inv x ... = f.inv_fun (f.to_fun (f.inv_fun x) * f.to_fun (f.inv_fun y)) : congr_arg f.inv_fun $ congr_arg (λ z, f.to_fun (f.inv_fun x) * z) $ eq.symm $ f.right_inv y ... = f.inv_fun (f.to_fun (f.inv_fun x * f.inv_fun y)) : congr_arg f.inv_fun $ eq.symm $ @isomorphism.map_mul _ _ _ _ f _ _ ... = f.inv_fun x * f.inv_fun y : f.left_inv (f.inv_fun x * f.inv_fun y) } def id : isomorphism α α := { equiv.refl α with map_mul := λ x y, rfl } end isomorphism structure automorphism extends isomorphism α α theorem automorphism.ext (f g : automorphism α) (H : ∀ x, f.to_isomorphism.to_equiv.to_fun x = g.to_isomorphism.to_equiv.to_fun x) : f = g := by cases f; cases f; cases g; cases g; congr; apply equiv.ext; exact H namespace automorphism instance : has_coe (automorphism α) (α → α) := ⟨λ f, f.to_isomorphism.to_equiv⟩ theorem map_mul (f : automorphism α) (x y : α) : (f : α → α) (x * y) = (f : α → α) x * (f : α → α) y := @isomorphism.map_mul _ _ _ _ f.to_isomorphism _ _ variable {α} theorem is_group_hom (f : automorphism α) : is_group_hom (f : α → α) := map_mul α f variable α instance : group (automorphism α) := { mul := λ f g, automorphism.mk $ g.to_isomorphism.comp f.to_isomorphism, mul_assoc := λ f g h, by unfold has_mul.mul; congr, one := automorphism.mk $ isomorphism.id, one_mul := λ f, by apply automorphism.ext; intro x; refl, mul_one := λ f, by apply automorphism.ext; intro x; refl, inv := λ f, automorphism.mk $ f.to_isomorphism.inv, mul_left_inv := λ f, by apply automorphism.ext; intro x; exact ((f.to_isomorphism).to_equiv).left_inv x} @[simp] lemma mul_apply (f g : automorphism α) (x : α) : (((f * g) : automorphism α) : α → α) x = (f:α → α) ((g:α → α) x) := rfl end automorphism variables (α β) def group_direct_product : group (α × β) := { mul := λ x y, (x.fst * y.fst, x.snd * y.snd), mul_assoc := λ x y z, by simp [mul_assoc], one := (1, 1), one_mul := λ x, by simp, mul_one := λ x, by rw prod.ext; split; apply mul_one, inv := λ x, (x.fst⁻¹, x.snd⁻¹), mul_left_inv := λ x, by rw prod.ext; split; apply mul_left_inv } def group_semidirect_product (f : β → automorphism α) (H : is_group_hom f) : group (α × β) := { mul := λ x y, (x.fst * (f x.snd : α → α) y.fst, x.snd * y.snd), mul_assoc := λ x y z, by rw prod.ext; split; simp [H, H x.snd, automorphism.map_mul α (f x.snd), mul_assoc], one := (1, 1), one_mul := λ x, by rw prod.ext; split; simp [H.one]; refl, mul_one := λ x, by rw prod.ext; split; simp [(*), semigroup.mul, monoid.mul, group.mul, (f x.snd).is_group_hom.one]; apply mul_one, inv := λ x, ((f x.snd⁻¹ : α → α) (x.fst⁻¹), x.snd⁻¹), mul_left_inv := λ x, calc ((f x.snd⁻¹ : α → α) (x.fst⁻¹) * (f x.snd⁻¹ : α → α) x.fst, x.snd⁻¹ * x.snd) = (1, 1) : by rw ← (f x.snd⁻¹).is_group_hom; simp [(f x.snd⁻¹).is_group_hom.one] }
a3a2c2b2e6f29bdc5bdb8ad71f8f010dfcd78e3e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1943.lean
7ad8c3dcb3105fc4f16193ccf668f6f56e6a8935
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
123
lean
open tactic meta def c := abstract `[assumption] structure B (U : Type) := (f : U → U) (w : ∀ u : U, f u = u . c)
c4aa6f0de0584c952ae83464a6d42ecec2ce34d4
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/meta/smt/interactive.lean
2b10a5cb1300b175f502a743cb418747c46313e0
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
10,261
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.smt.smt_tactic init.meta.interactive import init.meta.smt.rsimp namespace smt_tactic meta def save_info (p : pos) : smt_tactic unit := do (ss, ts) ← smt_tactic.read, tactic.save_info_thunk p (λ _, smt_state.to_format ss ts) meta def skip : smt_tactic unit := return () meta def solve_goals : smt_tactic unit := repeat close meta def step {α : Type} (tac : smt_tactic α) : smt_tactic unit := tac >> solve_goals meta def istep {α : Type} (line : nat) (col : nat) (tac : smt_tactic α) : smt_tactic unit := λ ss ts, (@scope_trace _ line col ((tac >> solve_goals) ss ts)).clamp_pos line col meta def execute (tac : smt_tactic unit) : tactic unit := using_smt tac meta def execute_with (cfg : smt_config) (tac : smt_tactic unit) : tactic unit := using_smt tac cfg namespace interactive open lean.parser open interactive open interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many meta def itactic : Type := smt_tactic unit meta def intros : parse ident* → smt_tactic unit | [] := smt_tactic.intros | hs := smt_tactic.intro_lst hs /-- Try to close main goal by using equalities implied by the congruence closure module. -/ meta def close : smt_tactic unit := smt_tactic.close /-- Produce new facts using heuristic lemma instantiation based on E-matching. This tactic tries to match patterns from lemmas in the main goal with terms in the main goal. The set of lemmas is populated with theorems tagged with the attribute specified at smt_config.em_attr, and lemmas added using tactics such as `smt_tactic.add_lemmas`. The current set of lemmas can be retrieved using the tactic `smt_tactic.get_lemmas`. -/ meta def ematch : smt_tactic unit := smt_tactic.ematch meta def apply (q : parse texpr) : smt_tactic unit := tactic.interactive.apply q meta def fapply (q : parse texpr) : smt_tactic unit := tactic.interactive.fapply q meta def apply_instance : smt_tactic unit := tactic.apply_instance meta def change (q : parse texpr) : smt_tactic unit := tactic.interactive.change q meta def exact (q : parse texpr) : smt_tactic unit := tactic.interactive.exact q meta def assert (h : parse ident) (q : parse $ tk ":" *> texpr) : smt_tactic unit := do e ← tactic.to_expr_strict q, smt_tactic.assert h e meta def define (h : parse ident) (q : parse $ tk ":" *> texpr) : smt_tactic unit := do e ← tactic.to_expr_strict q, smt_tactic.define h e meta def assertv (h : parse ident) (q₁ : parse $ tk ":" *> texpr) (q₂ : parse $ tk ":=" *> texpr) : smt_tactic unit := do t ← tactic.to_expr_strict q₁, v ← tactic.to_expr_strict ``(%%q₂ : %%t), smt_tactic.assertv h t v meta def definev (h : parse ident) (q₁ : parse $ tk ":" *> texpr) (q₂ : parse $ tk ":=" *> texpr) : smt_tactic unit := do t ← tactic.to_expr_strict q₁, v ← tactic.to_expr_strict ``(%%q₂ : %%t), smt_tactic.definev h t v meta def note (h : parse ident) (q : parse $ tk ":=" *> texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.note h p meta def pose (h : parse ident) (q : parse $ tk ":=" *> texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.pose h p meta def add_fact (q : parse texpr) : smt_tactic unit := do h ← tactic.get_unused_name `h none, p ← tactic.to_expr_strict q, smt_tactic.note h p meta def trace_state : smt_tactic unit := smt_tactic.trace_state meta def trace {α : Type} [has_to_tactic_format α] (a : α) : smt_tactic unit := tactic.trace a meta def destruct (q : parse texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.destruct p meta def by_cases (q : parse texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.by_cases p meta def by_contradiction : smt_tactic unit := smt_tactic.by_contradiction meta def by_contra : smt_tactic unit := smt_tactic.by_contradiction open tactic (resolve_name transparency to_expr) private meta def report_invalid_em_lemma {α : Type} (n : name) : smt_tactic α := fail ("invalid ematch lemma '" ++ to_string n ++ "'") private meta def add_lemma_name (md : transparency) (lhs_lemma : bool) (n : name) (ref : expr) : smt_tactic unit := do p ← resolve_name n, match p.to_raw_expr with | expr.const n _ := (add_ematch_lemma_from_decl_core md lhs_lemma n >> tactic.save_const_type_info n ref) <|> report_invalid_em_lemma n | _ := (do e ← to_expr p, add_ematch_lemma_core md lhs_lemma e >> try (tactic.save_type_info e ref)) <|> report_invalid_em_lemma n end private meta def add_lemma_pexpr (md : transparency) (lhs_lemma : bool) (p : pexpr) : smt_tactic unit := let e := pexpr.to_raw_expr p in match e with | (expr.const c []) := add_lemma_name md lhs_lemma c e | (expr.local_const c _ _ _) := add_lemma_name md lhs_lemma c e | _ := do new_e ← to_expr p, add_ematch_lemma_core md lhs_lemma new_e end private meta def add_lemma_pexprs (md : transparency) (lhs_lemma : bool) : list pexpr → smt_tactic unit | [] := return () | (p::ps) := add_lemma_pexpr md lhs_lemma p >> add_lemma_pexprs ps meta def add_lemma (l : parse qexpr_list_or_texpr) : smt_tactic unit := add_lemma_pexprs reducible ff l meta def add_lhs_lemma (l : parse qexpr_list_or_texpr) : smt_tactic unit := add_lemma_pexprs reducible tt l private meta def add_eqn_lemmas_for_core (md : transparency) : list name → smt_tactic unit | [] := return () | (c::cs) := do p ← resolve_name c, match p.to_raw_expr with | expr.const n _ := add_ematch_eqn_lemmas_for_core md n >> add_eqn_lemmas_for_core cs | _ := fail $ "'" ++ to_string c ++ "' is not a constant" end meta def add_eqn_lemmas_for (ids : parse ident*) : smt_tactic unit := add_eqn_lemmas_for_core reducible ids meta def add_eqn_lemmas (ids : parse ident*) : smt_tactic unit := add_eqn_lemmas_for ids private meta def add_hinst_lemma_from_name (md : transparency) (lhs_lemma : bool) (n : name) (hs : hinst_lemmas) (ref : expr) : smt_tactic hinst_lemmas := do p ← resolve_name n, match p.to_raw_expr with | expr.const n _ := (do h ← hinst_lemma.mk_from_decl_core md n lhs_lemma, tactic.save_const_type_info n ref, return $ hs.add h) <|> (do hs₁ ← mk_ematch_eqn_lemmas_for_core md n, tactic.save_const_type_info n ref, return $ hs.merge hs₁) <|> report_invalid_em_lemma n | _ := (do e ← to_expr p, h ← hinst_lemma.mk_core md e lhs_lemma, try (tactic.save_type_info e ref), return $ hs.add h) <|> report_invalid_em_lemma n end private meta def add_hinst_lemma_from_pexpr (md : transparency) (lhs_lemma : bool) (p : pexpr) (hs : hinst_lemmas) : smt_tactic hinst_lemmas := let e := pexpr.to_raw_expr p in match e with | (expr.const c []) := add_hinst_lemma_from_name md lhs_lemma c hs e | (expr.local_const c _ _ _) := add_hinst_lemma_from_name md lhs_lemma c hs e | _ := do new_e ← to_expr p, h ← hinst_lemma.mk_core md new_e lhs_lemma, return $ hs.add h end private meta def add_hinst_lemmas_from_pexprs (md : transparency) (lhs_lemma : bool) : list pexpr → hinst_lemmas → smt_tactic hinst_lemmas | [] hs := return hs | (p::ps) hs := do hs₁ ← add_hinst_lemma_from_pexpr md lhs_lemma p hs, add_hinst_lemmas_from_pexprs ps hs₁ meta def ematch_using (l : parse qexpr_list_or_texpr) : smt_tactic unit := do hs ← add_hinst_lemmas_from_pexprs reducible ff l hinst_lemmas.mk, smt_tactic.ematch_using hs /-- Try the given tactic, and do nothing if it fails. -/ meta def try (t : itactic) : smt_tactic unit := smt_tactic.try t /-- Keep applying the given tactic until it fails. -/ meta def repeat (t : itactic) : smt_tactic unit := smt_tactic.repeat t /-- Apply the given tactic to all remaining goals. -/ meta def all_goals (t : itactic) : smt_tactic unit := smt_tactic.all_goals t meta def induction (p : parse texpr) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : smt_tactic unit := slift (tactic.interactive.induction p rec_name ids revert) open tactic /-- Simplify the target type of the main goal. -/ meta def simp (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (cfg : simp_config := {}) : smt_tactic unit := tactic.interactive.simp hs attr_names ids [] cfg /-- Simplify the target type of the main goal using simplification lemmas and the current set of hypotheses. -/ meta def simp_using_hs (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (cfg : simp_config := {}) : smt_tactic unit := tactic.interactive.simp_using_hs hs attr_names ids cfg meta def simph (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (cfg : simp_config := {}) : smt_tactic unit := simp_using_hs hs attr_names ids cfg meta def dsimp (es : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) : smt_tactic unit := tactic.interactive.dsimp es attr_names ids [] meta def rsimp : smt_tactic unit := do ccs ← to_cc_state, _root_.rsimp.rsimplify_goal ccs meta def add_simp_lemmas : smt_tactic unit := get_hinst_lemmas_for_attr `rsimp_attr >>= add_lemmas /-- Keep applying heuristic instantiation until the current goal is solved, or it fails. -/ meta def eblast : smt_tactic unit := smt_tactic.eblast /-- Keep applying heuristic instantiation using the given lemmas until the current goal is solved, or it fails. -/ meta def eblast_using (l : parse qexpr_list_or_texpr) : smt_tactic unit := do hs ← add_hinst_lemmas_from_pexprs reducible ff l hinst_lemmas.mk, smt_tactic.repeat (smt_tactic.ematch_using hs >> smt_tactic.try smt_tactic.close) meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : smt_tactic unit := do e ← to_expr p, guard (expr.alpha_eqv t e) meta def guard_target (p : parse texpr) : smt_tactic unit := do t ← target, guard_expr_eq t p end interactive end smt_tactic
fdd8c3e7f6614bcc00f29f301a147a1b225dc477
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/expr.lean
e6f5896e926d20946440a642356b8d3a5fbe9c5c
[ "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
180
lean
import Lean open Lean def main : IO UInt32 := do let e := mkAppN (mkConst `f) #[mkConst `a, mkConst `b] IO.println e IO.println s!"hash: {e.hash}" IO.println e.getAppArgs pure 0
9747aaa5538c7d34445e2376000e93772a6ab7ea
5ae26df177f810c5006841e9c73dc56e01b978d7
/test/library_search/ring_theory.lean
fe39c9bdeca0cce703dabbc5eb81a32cc4764c8d
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
762
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.library_search import ring_theory.principal_ideal_domain import ring_theory.polynomial /- Turn off trace messages so they don't pollute the test build: -/ set_option trace.silence_library_search true example {α : Type} [euclidean_domain α] {S : ideal α} {x y : α} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := by library_search -- exact mod_mem_iff hy variables {R : Type} [comm_ring R] [decidable_eq R] variables {I : ideal (polynomial R)} example {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := by library_search -- exact ideal.leading_coeff_nth_mono I H
e92ff300b9d33fc44cf314e7bea6b3c391fcfcb8
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/rat/basic.lean
ff8516cd5fee30bdf1f8c3a34140b4df616ec6c1
[ "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
29,988
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.equiv.encodable.basic import algebra.euclidean_domain import data.nat.gcd import data.int.cast /-! # Basics for the Rational Numbers ## Summary We define a rational number `q` as a structure `{ num, denom, pos, cop }`, where - `num` is the numerator of `q`, - `denom` is the denominator of `q`, - `pos` is a proof that `denom > 0`, and - `cop` is a proof `num` and `denom` are coprime. We then define the expected (discrete) field structure on `ℚ` and prove basic lemmas about it. Moreoever, we provide the expected casts from `ℕ` and `ℤ` into `ℚ`, i.e. `(↑n : ℚ) = n / 1`. ## Main Definitions - `rat` is the structure encoding `ℚ`. - `rat.mk n d` constructs a rational number `q = n / d` from `n d : ℤ`. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom -/ /-- `rat`, or `ℚ`, is the type of rational numbers. It is defined as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and `d` are coprime. This representation is preferred to the quotient because without periodic reduction, the numerator and denominator can grow exponentially (for example, adding 1/2 to itself repeatedly). -/ structure rat := mk' :: (num : ℤ) (denom : ℕ) (pos : 0 < denom) (cop : num.nat_abs.coprime denom) notation `ℚ` := rat namespace rat /-- String representation of a rational numbers, used in `has_repr`, `has_to_string`, and `has_to_format` instances. -/ protected def repr : ℚ → string | ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else _root_.repr n ++ "/" ++ _root_.repr d instance : has_repr ℚ := ⟨rat.repr⟩ instance : has_to_string ℚ := ⟨rat.repr⟩ meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩ instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // 0 < d ∧ n.nat_abs.coprime d}) ⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩ /-- Embed an integer as a rational number -/ def of_int (n : ℤ) : ℚ := ⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩ instance : has_zero ℚ := ⟨of_int 0⟩ instance : has_one ℚ := ⟨of_int 1⟩ instance : inhabited ℚ := ⟨0⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/ def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ := let n' := n.nat_abs, g := n'.gcd d in ⟨n / g, d / g, begin apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2, simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _) end, begin have : int.nat_abs (n / ↑g) = n' / g, { cases int.nat_abs_eq n with e e; rw e, { refl }, rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl }, exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) }, rw this, exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos) end⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we define `n / 0 = 0` by convention. -/ def mk_nat (n : ℤ) (d : ℕ) : ℚ := if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩ /-- Form the quotient `n / d` where `n d : ℤ`. -/ def mk : ℤ → ℤ → ℚ | n (d : ℕ) := mk_nat n d | n -[1+ d] := mk_pnat (-n) d.succ_pnat localized "infix ` /. `:70 := rat.mk" in rat theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d := by change n /. d with dite _ _ _; simp [ne_of_gt h] theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl @[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl @[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 := by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl @[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 := by by_cases n = 0; simp [*, mk_nat] @[simp] theorem zero_mk (n) : 0 /. n = 0 := by cases n; simp [mk] private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a := int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b @[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 := begin constructor; intro h; [skip, {subst a, simp}], have : ∀ {a b}, mk_pnat a b = 0 → a = 0, { intros a b e, cases b with b h, injection e with e, apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e }, cases b with b; simp [mk, mk_nat] at h, { simp [mt (congr_arg int.of_nat) b0] at h, exact this h }, { apply neg_injective, simp [this h] } end theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0), a /. b = c /. d ↔ a * d = c * b := suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b, begin intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hb], all_goals { cases d with d d; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hd], all_goals { rw this, try {refl} } }, { change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b, constructor; intro h; apply neg_injective; simpa [left_distrib, neg_add_eq_iff_eq_add, eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h }, { change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ, constructor; intro h; apply neg_injective; simpa [left_distrib, eq_comm] using h }, { change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ, simp [left_distrib, sub_eq_add_neg], cc } end, begin intros, simp [mk_pnat], constructor; intro h, { cases h with ha hb, have ha, { have dv := @gcd_abs_dvd_left, have := int.eq_mul_of_div_eq_right dv ha, rw ← int.mul_div_assoc _ dv at this, exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have hb, { have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b, have := nat.eq_mul_of_div_eq_right dv hb, rw ← nat.mul_div_assoc _ dv at this, exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, { refine int.coe_nat_ne_zero.2 (ne_of_gt _), apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption }, apply mul_right_cancel' m0, simpa [mul_comm, mul_left_comm] using congr (congr_arg (*) ha.symm) (congr_arg coe hb) }, { suffices : ∀ a c, a * d = c * b → a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d, { cases this a.nat_abs c.nat_abs (by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂, have hs := congr_arg int.sign h, simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb), int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs, conv in a { rw ← int.sign_mul_nat_abs a }, conv in c { rw ← int.sign_mul_nat_abs c }, rw [int.mul_div_assoc, int.mul_div_assoc], exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩, all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } }, intros a c h, suffices bd : b / a.gcd b = d / c.gcd d, { refine ⟨_, bd⟩, apply nat.eq_of_mul_eq_mul_left hb, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd, ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] }, suffices : ∀ {a c : ℕ} (b>0) (d>0), a * d = c * b → b / a.gcd b ≤ d / c.gcd d, { exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) }, intros a c b hb d hd h, have gb0 := nat.gcd_pos_of_pos_right a hb, have gd0 := nat.gcd_pos_of_pos_right c hd, apply nat.le_of_dvd, apply (nat.le_div_iff_mul_le _ _ gd0).2, simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _), apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left, refine ⟨c / c.gcd d, _⟩, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)], apply congr_arg (/ c.gcd d), rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] } end @[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) : (a * c) /. (b * c) = a /. b := begin by_cases b0 : b = 0, { subst b0, simp }, apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc] end @[simp] theorem num_denom : ∀ {a : ℚ}, a.num /. a.denom = a | ⟨n, d, h, (c:_=1)⟩ := show mk_nat n d = _, by simp [mk_nat, ne_of_gt h, mk_pnat, c] theorem num_denom' {n d h c} : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom.symm theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom' /-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational numbers of the form `n /. d` with `0 < d` and coprime `n`, `d`. -/ @[elab_as_eliminator] def {u} num_denom_cases_on {C : ℚ → Sort u} : ∀ (a : ℚ) (H : ∀ n d, 0 < d → (int.nat_abs n).coprime d → C (n /. d)), C a | ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c /-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational numbers of the form `n /. d` with `d ≠ 0`. -/ @[elab_as_eliminator] def {u} num_denom_cases_on' {C : ℚ → Sort u} (a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a := num_denom_cases_on a $ λ n d h c, H n d h.ne' theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a := begin cases e : a /. b with n d h c, rw [rat.num_denom', rat.mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.dvd_of_dvd_mul_right _), have := congr_arg int.nat_abs e, simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this] end theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b := begin by_cases b0 : b = 0, {simp [b0]}, cases e : a /. b with n d h c, rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _), rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp end /-- Addition of rational numbers. Use `(+)` instead. -/ protected def add : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_add ℚ := ⟨rat.add⟩ theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ) (fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂}, f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂) (f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0) (a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0) (H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d), f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) : f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc, rw fv, have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁), have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂), exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc)) end @[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b + c /. d = (a * d + c * b) /. (b * d) := begin apply lift_binop_eq rat.add; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, calc (n₁ * d₂ + n₂ * d₁) * (b * d) = (n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm] ... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂] ... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm] end /-- Negation of rational numbers. Use `-r` instead. -/ protected def neg (r : ℚ) : ℚ := ⟨-r.num, r.denom, r.pos, by simp [r.cop]⟩ instance : has_neg ℚ := ⟨rat.neg⟩ @[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b := begin by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, show rat.mk' _ _ _ _ = _, rw num_denom', have d0 := ne_of_gt (int.coe_nat_lt.2 h₁), apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha, simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁] end /-- Multiplication of rational numbers. Use `(*)` instead. -/ protected def mul : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_mul ℚ := ⟨rat.mul⟩ @[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : (a /. b) * (c /. d) = (a * c) /. (b * d) := begin apply lift_binop_eq rat.mul; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, cc end /-- Inverse rational number. Use `r⁻¹` instead. -/ protected def inv : ℚ → ℚ | ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩ | ⟨0, d, h, c⟩ := 0 | ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩ instance : has_inv ℚ := ⟨rat.inv⟩ @[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a := begin by_cases a0 : a = 0, { subst a0, simp, refl }, by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha, refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _, { cases n with n; [cases n with n, skip], { refl }, { change int.of_nat n.succ with (n+1:ℕ), unfold rat.inv, rw num_denom' }, { unfold rat.inv, rw num_denom', refl } }, have n0 : n ≠ 0, { refine mt (λ (n0 : n = 0), _) a0, subst n0, simp at ha, exact (mk_eq_zero b0).1 ha }, have d0 := ne_of_gt (int.coe_nat_lt.2 h), have ha := (mk_eq b0 d0).1 ha, apply (mk_eq n0 a0).2, cc end variables (a b c : ℚ) protected theorem add_zero : a + 0 = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem zero_add : 0 + a = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem add_comm : a + b = b + a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂]; cc protected theorem add_assoc : a + b + c = a + (b + c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm, add_assoc] protected theorem add_left_neg : -a + a = 0 := num_denom_cases_on' a $ λ n d h, by simp [h] @[simp] lemma mk_zero_one : 0 /. 1 = 0 := show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl } @[simp] lemma mk_one_one : 1 /. 1 = 1 := show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl } @[simp] lemma mk_neg_one_one : (-1) /. 1 = -1 := show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl } protected theorem mul_one : a * 1 = a := num_denom_cases_on' a $ λ n d h, by { rw ← mk_one_one, simp [h, -mk_one_one] } protected theorem one_mul : 1 * a = a := num_denom_cases_on' a $ λ n d h, by { rw ← mk_one_one, simp [h, -mk_one_one] } protected theorem mul_comm : a * b = b * a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂, mul_comm] protected theorem mul_assoc : a * b * c = a * (b * c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm] protected theorem add_mul : (a + b) * c = a * c + b * c := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero]; refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _; simp [mul_add, mul_comm, mul_assoc, mul_left_comm] protected theorem mul_add : a * (b + c) = a * b + a * c := by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a] protected theorem zero_ne_one : 0 ≠ (1:ℚ) := suffices (1:ℚ) = 0 → false, by cc, by { rw [← mk_one_one, mk_eq_zero one_ne_zero], exact one_ne_zero } protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 := num_denom_cases_on' a $ λ n d h a0, have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0, by simpa [h, n0, mul_comm] using @div_mk_div_cancel_left 1 1 _ n0 protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 := eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h) instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance instance : field ℚ := { zero := 0, add := rat.add, neg := rat.neg, one := 1, mul := rat.mul, inv := rat.inv, zero_add := rat.zero_add, add_zero := rat.add_zero, add_comm := rat.add_comm, add_assoc := rat.add_assoc, add_left_neg := rat.add_left_neg, mul_one := rat.mul_one, one_mul := rat.one_mul, mul_comm := rat.mul_comm, mul_assoc := rat.mul_assoc, left_distrib := rat.mul_add, right_distrib := rat.add_mul, exists_pair_ne := ⟨0, 1, rat.zero_ne_one⟩, mul_inv_cancel := rat.mul_inv_cancel, inv_zero := rfl } /- Extra instances to short-circuit type class resolution -/ instance : division_ring ℚ := by apply_instance instance : integral_domain ℚ := by apply_instance -- TODO(Mario): this instance slows down data.real.basic --instance : domain ℚ := by apply_instance instance : nontrivial ℚ := by apply_instance instance : comm_ring ℚ := by apply_instance --instance : ring ℚ := by apply_instance instance : comm_semiring ℚ := by apply_instance instance : semiring ℚ := by apply_instance instance : add_comm_group ℚ := by apply_instance instance : add_group ℚ := by apply_instance instance : add_comm_monoid ℚ := by apply_instance instance : add_monoid ℚ := by apply_instance instance : add_left_cancel_semigroup ℚ := by apply_instance instance : add_right_cancel_semigroup ℚ := by apply_instance instance : add_comm_semigroup ℚ := by apply_instance instance : add_semigroup ℚ := by apply_instance instance : comm_monoid ℚ := by apply_instance instance : monoid ℚ := by apply_instance instance : comm_semigroup ℚ := by apply_instance instance : semigroup ℚ := by apply_instance theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b - c /. d = (a * d - c * b) /. (b * d) := by simp [b0, d0, sub_eq_add_neg] @[simp] lemma denom_neg_eq_denom (q : ℚ) : (-q).denom = q.denom := rfl @[simp] lemma num_neg_eq_neg_num (q : ℚ) : (-q).num = -(q.num) := rfl @[simp] lemma num_zero : rat.num 0 = 0 := rfl @[simp] lemma denom_zero : rat.denom 0 = 1 := rfl lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 := have q = q.num /. q.denom, from num_denom.symm, by simpa [hq] lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 := ⟨λ _, by simp *, zero_of_num_zero⟩ lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 := assume : q.num = 0, h $ zero_of_num_zero this @[simp] lemma num_one : (1 : ℚ).num = 1 := rfl @[simp] lemma denom_one : (1 : ℚ).denom = 1 := rfl lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 := ne_of_gt q.pos lemma eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.denom = q.num * p.denom := begin conv_lhs { rw [←(@num_denom p), ←(@num_denom q)] }, apply rat.mk_eq, { exact_mod_cast p.denom_ne_zero }, { exact_mod_cast q.denom_ne_zero } end lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 := assume : n = 0, hq $ by simpa [this] using hqnd lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 := assume : d = 0, hq $ by simpa [this] using hqnd lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 := assume : n /. d = 0, h $ (mk_eq_zero hd).1 this lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) := have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa, have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa, suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom), by simpa using this, by simp [mul_def hq' hr', -num_denom] lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) := if hr : r.num = 0 then have hr' : r = 0, from zero_of_num_zero hr, by simp * else calc q / r = q * r⁻¹ : div_eq_mul_inv q r ... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by simp ... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def ... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) : ∃ c : ℤ, n = c * q.num ∧ d = c * q.denom := have hq : q ≠ 0, from assume : q = 0, hn $ (rat.mk_eq_zero hd).1 (by cc), have q.num /. q.denom = n /. d, by rwa [num_denom], have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this, begin existsi n / q.num, have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end, split, { rw int.div_mul_cancel hqdn }, { apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left, { apply rat.num_ne_zero_of_ne_zero hq }, repeat { assumption } } end theorem mk_pnat_num (n : ℤ) (d : ℕ+) : (mk_pnat n d).num = n / nat.gcd n.nat_abs d := by cases d; refl theorem mk_pnat_denom (n : ℤ) (d : ℕ+) : (mk_pnat n d).denom = d / nat.gcd n.nat_abs d := by cases d; refl theorem mk_pnat_denom_dvd (n : ℤ) (d : ℕ+) : (mk_pnat n d).denom ∣ d.1 := begin rw mk_pnat_denom, apply nat.div_dvd_of_dvd, apply nat.gcd_dvd_right end theorem add_denom_dvd (q₁ q₂ : ℚ) : (q₁ + q₂).denom ∣ q₁.denom * q₂.denom := by { cases q₁, cases q₂, apply mk_pnat_denom_dvd } theorem mul_denom_dvd (q₁ q₂ : ℚ) : (q₁ * q₂).denom ∣ q₁.denom * q₂.denom := by { cases q₁, cases q₂, apply mk_pnat_denom_dvd } theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num = (q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom = (q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num := by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom := by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) lemma add_num_denom (q r : ℚ) : q + r = ((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) := have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3, have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3, by conv_lhs { rw [←@num_denom q, ←@num_denom r, rat.add_def hqd hrd] }; simp [mul_comm] section casts protected lemma add_mk (a b c : ℤ) : (a + b) /. c = a /. c + b /. c := if h : c = 0 then by simp [h] else by { rw [add_def h h, mk_eq h (mul_ne_zero h h)], simp [add_mul, mul_assoc] } theorem coe_int_eq_mk : ∀ (z : ℤ), ↑z = z /. 1 | (n : ℕ) := show (n:ℚ) = n /. 1, by induction n with n IH n; simp [*, rat.add_mk] | -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin induction n with n IH, { rw ← of_int_eq_mk, simp, refl }, show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1, rw [neg_add, IH, ← mk_neg_one_one], simp [-mk_neg_one_one] end theorem mk_eq_div (n d : ℤ) : n /. d = ((n : ℚ) / d) := begin by_cases d0 : d = 0, {simp [d0, div_zero]}, simp [division_def, coe_int_eq_mk, mul_def one_ne_zero d0] end @[simp] theorem num_div_denom (r : ℚ) : (r.num / r.denom : ℚ) = r := by rw [← int.cast_coe_nat, ← mk_eq_div, num_denom] lemma exists_eq_mul_div_num_and_eq_mul_div_denom {n d : ℤ} (n_ne_zero : n ≠ 0) (d_ne_zero : d ≠ 0) : ∃ (c : ℤ), n = c * ((n : ℚ) / d).num ∧ (d : ℤ) = c * ((n : ℚ) / d).denom := begin have : ((n : ℚ) / d) = rat.mk n d, by rw [←rat.mk_eq_div], exact rat.num_denom_mk n_ne_zero d_ne_zero this end theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z := (coe_int_eq_mk z).trans (of_int_eq_mk z).symm @[simp, norm_cast] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n := by rw coe_int_eq_of_int; refl @[simp, norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 := by rw coe_int_eq_of_int; refl lemma coe_int_num_of_denom_eq_one {q : ℚ} (hq : q.denom = 1) : ↑(q.num) = q := by { conv_rhs { rw [←(@num_denom q), hq] }, rw [coe_int_eq_mk], refl } lemma denom_eq_one_iff (r : ℚ) : r.denom = 1 ↔ ↑r.num = r := ⟨rat.coe_int_num_of_denom_eq_one, λ h, h ▸ rat.coe_int_denom r.num⟩ instance : can_lift ℚ ℤ := ⟨coe, λ q, q.denom = 1, λ q hq, ⟨q.num, coe_int_num_of_denom_eq_one hq⟩⟩ theorem coe_nat_eq_mk (n : ℕ) : ↑n = n /. 1 := by rw [← int.cast_coe_nat, coe_int_eq_mk] @[simp, norm_cast] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n := by rw [← int.cast_coe_nat, coe_int_num] @[simp, norm_cast] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 := by rw [← int.cast_coe_nat, coe_int_denom] -- Will be subsumed by `int.coe_inj` after we have defined -- `linear_ordered_field ℚ` (which implies characteristic zero). lemma coe_int_inj (m n : ℤ) : (m : ℚ) = n ↔ m = n := ⟨λ h, by simpa using congr_arg num h, congr_arg _⟩ end casts lemma inv_def' {q : ℚ} : q⁻¹ = (q.denom : ℚ) / q.num := by { conv_lhs { rw ←(@num_denom q) }, cases q, simp [div_num_denom] } @[simp] lemma mul_denom_eq_num {q : ℚ} : q * q.denom = q.num := begin suffices : mk (q.num) ↑(q.denom) * mk ↑(q.denom) 1 = mk (q.num) 1, by { conv { for q [1] { rw ←(@num_denom q) }}, rwa [coe_int_eq_mk, coe_nat_eq_mk] }, have : (q.denom : ℤ) ≠ 0, from ne_of_gt (by exact_mod_cast q.pos), rw [(rat.mul_def this one_ne_zero), (mul_comm (q.denom : ℤ) 1), (div_mk_div_cancel_left this)] end lemma denom_div_cast_eq_one_iff (m n : ℤ) (hn : n ≠ 0) : ((m : ℚ) / n).denom = 1 ↔ n ∣ m := begin replace hn : (n:ℚ) ≠ 0, by rwa [ne.def, ← int.cast_zero, coe_int_inj], split, { intro h, lift ((m : ℚ) / n) to ℤ using h with k hk, use k, rwa [eq_div_iff_mul_eq hn, ← int.cast_mul, mul_comm, eq_comm, coe_int_inj] at hk }, { rintros ⟨d, rfl⟩, rw [int.cast_mul, mul_comm, mul_div_cancel _ hn, rat.coe_int_denom] } end lemma num_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) : (a / b : ℚ).num = a := begin lift b to ℕ using le_of_lt hb0, norm_cast at hb0 h, rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_num, pnat.mk_coe, h.gcd_eq_one, int.coe_nat_one, int.div_one] end lemma denom_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) : ((a / b : ℚ).denom : ℤ) = b := begin lift b to ℕ using le_of_lt hb0, norm_cast at hb0 h, rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_denom, pnat.mk_coe, h.gcd_eq_one, nat.div_one] end lemma div_int_inj {a b c d : ℤ} (hb0 : 0 < b) (hd0 : 0 < d) (h1 : nat.coprime a.nat_abs b.nat_abs) (h2 : nat.coprime c.nat_abs d.nat_abs) (h : (a : ℚ) / b = (c : ℚ) / d) : a = c ∧ b = d := begin apply and.intro, { rw [← (num_div_eq_of_coprime hb0 h1), h, num_div_eq_of_coprime hd0 h2] }, { rw [← (denom_div_eq_of_coprime hb0 h1), h, denom_div_eq_of_coprime hd0 h2] } end @[norm_cast] lemma coe_int_div_self (n : ℤ) : ((n / n : ℤ) : ℚ) = n / n := begin by_cases hn : n = 0, { subst hn, simp only [int.cast_zero, euclidean_domain.zero_div] }, { have : (n : ℚ) ≠ 0, { rwa ← coe_int_inj at hn }, simp only [int.div_self hn, int.cast_one, ne.def, not_false_iff, div_self this] } end @[norm_cast] lemma coe_nat_div_self (n : ℕ) : ((n / n : ℕ) : ℚ) = n / n := coe_int_div_self n lemma coe_int_div (a b : ℤ) (h : b ∣ a) : ((a / b : ℤ) : ℚ) = a / b := begin rcases h with ⟨c, rfl⟩, simp only [mul_comm b, int.mul_div_assoc c (dvd_refl b), int.cast_mul, mul_div_assoc, coe_int_div_self] end lemma coe_nat_div (a b : ℕ) (h : b ∣ a) : ((a / b : ℕ) : ℚ) = a / b := begin rcases h with ⟨c, rfl⟩, simp only [mul_comm b, nat.mul_div_assoc c (dvd_refl b), nat.cast_mul, mul_div_assoc, coe_nat_div_self] end protected lemma «forall» {p : ℚ → Prop} : (∀ r, p r) ↔ ∀ a b : ℤ, p (a / b) := ⟨λ h _ _, h _, λ h q, (show q = q.num / q.denom, from by simp [rat.div_num_denom]).symm ▸ (h q.1 q.2)⟩ protected lemma «exists» {p : ℚ → Prop} : (∃ r, p r) ↔ ∃ a b : ℤ, p (a / b) := ⟨λ ⟨r, hr⟩, ⟨r.num, r.denom, by rwa [← mk_eq_div, num_denom]⟩, λ ⟨a, b, h⟩, ⟨_, h⟩⟩ end rat
70845a799f348abff33fdc93a48eca43f25f6a13
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/real.lean
d01323b77f70cf8272f8bf3b47641b1cb3733755
[ "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
680
lean
import data.real.basic meta def test_repr (r : ℝ) (s : string) : tactic unit := guard (repr r = s) <|> fail!"got {repr r}" run_cmd test_repr 0 "real.of_cauchy (sorry /- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... -/)" run_cmd test_repr 1 "real.of_cauchy (sorry /- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ... -/)" run_cmd test_repr (37 : ℕ) "real.of_cauchy (sorry /- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, ... -/)" run_cmd test_repr (2 + 3) "real.of_cauchy (sorry /- 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, ... -/)" run_cmd test_repr ⟨cau_seq.completion.mk $ ⟨λ n, 2^(-n:ℤ), sorry⟩⟩ "real.of_cauchy (sorry /- 1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64, 1/128, 1/256, 1/512, ... -/)"
7b7b39f1e6609aed9aadc78db242ef3b1842eed9
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/category_theory/instances/rings.lean
7aa88c971f02993d644f24a4fac14f6f535640b8
[ "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
5,217
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl Introduce CommRing -- the category of commutative rings. Currently only the basic setup. -/ import category_theory.instances.monoids import category_theory.fully_faithful import category_theory.adjunction import data.multivariate_polynomial import algebra.ring universes u v open category_theory namespace category_theory.instances /-- The category of rings. -/ @[reducible] def Ring : Type (u+1) := bundled ring instance (x : Ring) : ring x := x.str instance concrete_is_ring_hom : concrete_category @is_ring_hom := ⟨by introsI α ia; apply_instance, by introsI α β γ ia ib ic f g hf hg; apply_instance⟩ instance Ring_hom_is_ring_hom {R S : Ring} (f : R ⟶ S) : is_ring_hom (f : R → S) := f.2 /-- The category of commutative rings. -/ @[reducible] def CommRing : Type (u+1) := bundled comm_ring instance (x : CommRing) : comm_ring x := x.str -- Here we don't use the `concrete` machinery, -- because it would require introducing a useless synonym for `is_ring_hom`. instance : category CommRing := { hom := λ R S, { f : R → S // is_ring_hom f }, id := λ R, ⟨ id, by resetI; apply_instance ⟩, comp := λ R S T g h, ⟨ h.1 ∘ g.1, begin haveI := g.2, haveI := h.2, apply_instance end ⟩ } namespace CommRing variables {R S T : CommRing.{u}} @[simp] lemma id_val : subtype.val (𝟙 R) = id := rfl @[simp] lemma comp_val (f : R ⟶ S) (g : S ⟶ T) : (f ≫ g).val = g.val ∘ f.val := rfl instance hom_coe : has_coe_to_fun (R ⟶ S) := { F := λ f, R → S, coe := λ f, f.1 } @[simp] lemma hom_coe_app (f : R ⟶ S) (r : R) : f r = f.val r := rfl instance hom_is_ring_hom (f : R ⟶ S) : is_ring_hom (f : R → S) := f.2 def Int : CommRing := ⟨ℤ, infer_instance⟩ def Int.cast {R : CommRing} : Int ⟶ R := { val := int.cast, property := by apply_instance } def int.eq_cast' {R : Type u} [ring R] (f : int → R) [is_ring_hom f] : f = int.cast := funext $ int.eq_cast f (is_ring_hom.map_one f) (λ _ _, is_ring_hom.map_add f) def Int.hom_unique {R : CommRing} : unique (Int ⟶ R) := { default := Int.cast, uniq := λ f, subtype.ext.mpr $ funext $ int.eq_cast f f.2.map_one f.2.map_add } /-- The forgetful functor commutative rings to Type. -/ def forget : CommRing.{u} ⥤ Type u := { obj := λ R, R, map := λ _ _ f, f } instance forget.faithful : faithful (forget) := {} /-- The functor from commutative rings to rings. -/ def to_Ring : CommRing.{u} ⥤ Ring.{u} := { obj := λ X, { α := X.1, str := by apply_instance }, map := λ X Y f, ⟨ f, by apply_instance ⟩ } instance to_Ring.faithful : faithful (to_Ring) := {} /-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/ def forget_to_CommMon : CommRing.{u} ⥤ CommMon.{u} := { obj := λ X, { α := X.1, str := by apply_instance }, map := λ X Y f, ⟨ f, by apply_instance ⟩ } instance forget_to_CommMon.faithful : faithful (forget_to_CommMon) := {} example : faithful (forget_to_CommMon ⋙ CommMon.forget_to_Mon) := by apply_instance section open mv_polynomial local attribute [instance, priority 0] subtype.fintype set_fintype classical.prop_decidable noncomputable def polynomial : Type u ⥤ CommRing.{u} := { obj := λ α, ⟨mv_polynomial α ℤ, by apply_instance⟩, map := λ α β f, ⟨eval₂ C (X ∘ f), by apply_instance⟩, map_id' := λ α, subtype.ext.mpr $ funext $ eval₂_eta, map_comp' := λ α β γ f g, subtype.ext.mpr $ funext $ λ p, by apply mv_polynomial.induction_on p; intros; simp only [*, eval₂_add, eval₂_mul, eval₂_C, eval₂_X, comp_val, eq_self_iff_true, function.comp_app, types_comp] at * } @[simp] lemma polynomial_obj_α {α : Type u} : (polynomial.obj α).α = mv_polynomial α ℤ := rfl @[simp] lemma polynomial_map_val {α β : Type u} {f : α → β} : (CommRing.polynomial.map f).val = eval₂ C (X ∘ f) := rfl noncomputable def adj : adjunction polynomial (forget : CommRing ⥤ Type u) := adjunction.mk_of_hom_equiv _ _ { hom_equiv := λ α R, { to_fun := λ f, f ∘ X, inv_fun := λ f, ⟨eval₂ int.cast f, by apply_instance⟩, left_inv := λ f, subtype.ext.mpr $ funext $ λ p, begin have H0 := λ n, (congr (int.eq_cast' (f.val ∘ C)) (rfl : n = n)).symm, have H1 := λ p₁ p₂, (@is_ring_hom.map_add _ _ _ _ f.val f.2 p₁ p₂).symm, have H2 := λ p₁ p₂, (@is_ring_hom.map_mul _ _ _ _ f.val f.2 p₁ p₂).symm, apply mv_polynomial.induction_on p; intros; simp only [*, eval₂_add, eval₂_mul, eval₂_C, eval₂_X, eq_self_iff_true, function.comp_app, hom_coe_app] at * end, right_inv := by tidy }, hom_equiv_naturality_left_symm' := λ X' X Y f g, subtype.ext.mpr $ funext $ λ p, begin apply mv_polynomial.induction_on p; intros; simp only [*, eval₂_mul, eval₂_add, eval₂_C, eval₂_X, comp_val, equiv.coe_fn_symm_mk, hom_coe_app, polynomial_map_val, eq_self_iff_true, function.comp_app, add_right_inj, types_comp] at * end } end end CommRing end category_theory.instances
e73b7e4ae3f3b5508d3f158417c688986326f299
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/interactive/do_info.lean
668710cd7a9127e5874baa14d7fe09ed9932306c
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
284
lean
open tactic example (a b c : nat) : a = b → c = b → a = c := by do h ← intro `h, --^ "command": "info" intros, transitivity, --^ "command": "info" trace_state, assumption, --^ "command": "info" symmetry, --^ "command": "info" assumption --^ "command": "info"
7d8638635c0a128891db5c9337448d605928ae37
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/var.lean
99677e33102148a06f82f56649bb1cf514975ea9
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
105
lean
-- section variable A : Type parameter a : A end section variable A : Type variable a : A end
6a9ca49d7a0b1d5a1e6d128889a894274d158618
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/634d.lean
2723066ee713f7b773722130fc83cc9e123d218a
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
428
lean
section universe l definition A {n : ℕ} (t : Sort l) := t #check A #check _root_.A.{1} set_option pp.universes true #check A #check _root_.A.{1} end section universe l parameters {B : Sort l} definition P {n : ℕ} (b : B) := b #check P #check @_root_.P.{1} nat set_option pp.universes true #check P #check _root_.P.{1} set_option pp.implicit true #check @P 2 #check @_root_.P.{1} nat end
37c2c507393d203bf0ddf52aeb48dd45cc0a5a1b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/endomorphism.lean
47c1aa2b5eff0e67ee5b065bdb02f99a4ed990e6
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,232
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Scott Morrison, Simon Hudon -/ import algebra.hom.equiv.basic import category_theory.groupoid import category_theory.opposites import group_theory.group_action.defs /-! # Endomorphisms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Definition and basic properties of endomorphisms and automorphisms of an object in a category. For each `X : C`, we provide `End X := X ⟶ X` with a monoid structure, and `Aut X := X ≅ X ` with a group structure. -/ universes v v' u u' namespace category_theory /-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with `function.comp`, not with `category.comp`. -/ def End {C : Type u} [category_struct.{v} C] (X : C) := X ⟶ X namespace End section struct variables {C : Type u} [category_struct.{v} C] (X : C) instance has_one : has_one (End X) := ⟨𝟙 X⟩ instance inhabited : inhabited (End X) := ⟨𝟙 X⟩ /-- Multiplication of endomorphisms agrees with `function.comp`, not `category_struct.comp`. -/ instance has_mul : has_mul (End X) := ⟨λ x y, y ≫ x⟩ variable {X} /-- Assist the typechecker by expressing a morphism `X ⟶ X` as a term of `End X`. -/ def of (f : X ⟶ X) : End X := f /-- Assist the typechecker by expressing an endomorphism `f : End X` as a term of `X ⟶ X`. -/ def as_hom (f : End X) : X ⟶ X := f @[simp] lemma one_def : (1 : End X) = 𝟙 X := rfl @[simp] lemma mul_def (xs ys : End X) : xs * ys = ys ≫ xs := rfl end struct /-- Endomorphisms of an object form a monoid -/ instance monoid {C : Type u} [category.{v} C] {X : C} : monoid (End X) := { mul_one := category.id_comp, one_mul := category.comp_id, mul_assoc := λ x y z, (category.assoc z y x).symm, ..End.has_mul X, ..End.has_one X } section mul_action variables {C : Type u} [category.{v} C] open opposite instance mul_action_right {X Y : C} : mul_action (End Y) (X ⟶ Y) := { smul := λ r f, f ≫ r, one_smul := category.comp_id, mul_smul := λ r s f, eq.symm $ category.assoc _ _ _ } instance mul_action_left {X : Cᵒᵖ} {Y : C} : mul_action (End X) (unop X ⟶ Y) := { smul := λ r f, r.unop ≫ f, one_smul := category.id_comp, mul_smul := λ r s f, category.assoc _ _ _ } lemma smul_right {X Y : C} {r : End Y} {f : X ⟶ Y} : r • f = f ≫ r := rfl lemma smul_left {X : Cᵒᵖ} {Y : C} {r : (End X)} {f : unop X ⟶ Y} : r • f = r.unop ≫ f := rfl end mul_action /-- In a groupoid, endomorphisms form a group -/ instance group {C : Type u} [groupoid.{v} C] (X : C) : group (End X) := { mul_left_inv := groupoid.comp_inv, inv := groupoid.inv, ..End.monoid } end End lemma is_unit_iff_is_iso {C : Type u} [category.{v} C] {X : C} (f : End X) : is_unit (f : End X) ↔ is_iso f := ⟨λ h, { out := ⟨h.unit.inv, ⟨h.unit.inv_val, h.unit.val_inv⟩⟩ }, λ h, by exactI ⟨⟨f, inv f, by simp, by simp⟩, rfl⟩⟩ variables {C : Type u} [category.{v} C] (X : C) /-- Automorphisms of an object in a category. The order of arguments in multiplication agrees with `function.comp`, not with `category.comp`. -/ def Aut (X : C) := X ≅ X namespace Aut instance inhabited : inhabited (Aut X) := ⟨iso.refl X⟩ instance : group (Aut X) := by refine_struct { one := iso.refl X, inv := iso.symm, mul := flip iso.trans, div := _, npow := @npow_rec (Aut X) ⟨iso.refl X⟩ ⟨flip iso.trans⟩, zpow := @zpow_rec (Aut X) ⟨iso.refl X⟩ ⟨flip iso.trans⟩ ⟨iso.symm⟩ }; intros; try { refl }; ext; simp [flip, (*), monoid.mul, mul_one_class.mul, mul_one_class.one, has_one.one, monoid.one, has_inv.inv] lemma Aut_mul_def (f g : Aut X) : f * g = g.trans f := rfl lemma Aut_inv_def (f : Aut X) : f ⁻¹ = f.symm := rfl /-- Units in the monoid of endomorphisms of an object are (multiplicatively) equivalent to automorphisms of that object. -/ def units_End_equiv_Aut : (End X)ˣ ≃* Aut X := { to_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩, inv_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩, left_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl, right_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl, map_mul' := λ f g, by rcases f; rcases g; refl } /-- Isomorphisms induce isomorphisms of the automorphism group -/ def Aut_mul_equiv_of_iso {X Y : C} (h : X ≅ Y) : Aut X ≃* Aut Y := { to_fun := λ x, ⟨h.inv ≫ x.hom ≫ h.hom, h.inv ≫ x.inv ≫ h.hom⟩, inv_fun := λ y, ⟨h.hom ≫ y.hom ≫ h.inv, h.hom ≫ y.inv ≫ h.inv⟩, left_inv := by tidy, right_inv := by tidy, map_mul' := by simp [Aut_mul_def] } end Aut namespace functor variables {D : Type u'} [category.{v'} D] (f : C ⥤ D) (X) /-- `f.map` as a monoid hom between endomorphism monoids. -/ @[simps] def map_End : End X →* End (f.obj X) := { to_fun := functor.map f, map_mul' := λ x y, f.map_comp y x, map_one' := f.map_id X } /-- `f.map_iso` as a group hom between automorphism groups. -/ def map_Aut : Aut X →* Aut (f.obj X) := { to_fun := f.map_iso, map_mul' := λ x y, f.map_iso_trans y x, map_one' := f.map_iso_refl X } end functor end category_theory
ffaf0a6582e71a4b14321c2caf0a5c4a74ecd450
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/calculus/mean_value.lean
f64fd61e91c7183d3517f74e0db94909629a52d4
[ "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
74,763
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, Yury Kudryashov -/ import analysis.calculus.local_extr import analysis.convex.slope import analysis.convex.topology import data.complex.is_R_or_C /-! # The mean value inequality and equalities In this file we prove the following facts: * `convex.norm_image_sub_le_of_norm_deriv_le` : if `f` is differentiable on a convex set `s` and the norm of its derivative is bounded by `C`, then `f` is Lipschitz continuous on `s` with constant `C`; also a variant in which what is bounded by `C` is the norm of the difference of the derivative from a fixed linear map. This lemma and its versions are formulated using `is_R_or_C`, so they work both for real and complex derivatives. * `image_le_of*`, `image_norm_le_of_*` : several similar lemmas deducing `f x ≤ B x` or `‖f x‖ ≤ B x` from upper estimates on `f'` or `‖f'‖`, respectively. These lemmas differ by their assumptions: * `of_liminf_*` lemmas assume that limit inferior of some ratio is less than `B' x`; * `of_deriv_right_*`, `of_norm_deriv_right_*` lemmas assume that the right derivative or its norm is less than `B' x`; * `of_*_lt_*` lemmas assume a strict inequality whenever `f x = B x` or `‖f x‖ = B x`; * `of_*_le_*` lemmas assume a non-strict inequality everywhere on `[a, b)`; * name of a lemma ends with `'` if (1) it assumes that `B` is continuous on `[a, b]` and has a right derivative at every point of `[a, b)`, and (2) the lemma has a counterpart assuming that `B` is differentiable everywhere on `ℝ` * `norm_image_sub_le_*_segment` : if derivative of `f` on `[a, b]` is bounded above by a constant `C`, then `‖f x - f a‖ ≤ C * ‖x - a‖`; several versions deal with right derivative and derivative within `[a, b]` (`has_deriv_within_at` or `deriv_within`). * `convex.is_const_of_fderiv_within_eq_zero` : if a function has derivative `0` on a convex set `s`, then it is a constant on `s`. * `exists_ratio_has_deriv_at_eq_ratio_slope` and `exists_ratio_deriv_eq_ratio_slope` : Cauchy's Mean Value Theorem. * `exists_has_deriv_at_eq_slope` and `exists_deriv_eq_slope` : Lagrange's Mean Value Theorem. * `domain_mvt` : Lagrange's Mean Value Theorem, applied to a segment in a convex domain. * `convex.image_sub_lt_mul_sub_of_deriv_lt`, `convex.mul_sub_lt_image_sub_of_lt_deriv`, `convex.image_sub_le_mul_sub_of_deriv_le`, `convex.mul_sub_le_image_sub_of_le_deriv`, if `∀ x, C (</≤/>/≥) (f' x)`, then `C * (y - x) (</≤/>/≥) (f y - f x)` whenever `x < y`. * `convex.monotone_on_of_deriv_nonneg`, `convex.antitone_on_of_deriv_nonpos`, `convex.strict_mono_of_deriv_pos`, `convex.strict_anti_of_deriv_neg` : if the derivative of a function is non-negative/non-positive/positive/negative, then the function is monotone/antitone/strictly monotone/strictly monotonically decreasing. * `convex_on_of_deriv_monotone_on`, `convex_on_of_deriv2_nonneg` : if the derivative of a function is increasing or its second derivative is nonnegative, then the original function is convex. * `strict_fderiv_of_cont_diff` : a C^1 function over the reals is strictly differentiable. (This is a corollary of the mean value inequality.) -/ variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] open metric set asymptotics continuous_linear_map filter open_locale classical topological_space nnreal /-! ### One-dimensional fencing inequalities -/ /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (f z - f x) / (z - x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[>] x, slope f x z < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin change Icc a b ⊆ {x | f x ≤ B x}, set s := {x | f x ≤ B x} ∩ Icc a b, have A : continuous_on (λ x, (f x, B x)) (Icc a b), from hf.prod hB, have : is_closed s, { simp only [s, inter_comm], exact A.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' }, apply this.Icc_subset_of_forall_exists_gt ha, rintros x ⟨hxB : f x ≤ B x, xab⟩ y hy, cases hxB.lt_or_eq with hxB hxB, { -- If `f x < B x`, then all we need is continuity of both sides refine nonempty_of_mem (inter_mem _ (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩)), have : ∀ᶠ x in 𝓝[Icc a b] x, f x < B x, from A x (Ico_subset_Icc_self xab) (is_open.mem_nhds (is_open_lt continuous_fst continuous_snd) hxB), have : ∀ᶠ x in 𝓝[>] x, f x < B x, from nhds_within_le_of_mem (Icc_mem_nhds_within_Ioi xab) this, exact this.mono (λ y, le_of_lt) }, { rcases exists_between (bound x xab hxB) with ⟨r, hfr, hrB⟩, specialize hf' x xab r hfr, have HB : ∀ᶠ z in 𝓝[>] x, r < slope B x z, from (has_deriv_within_at_iff_tendsto_slope' $ lt_irrefl x).1 (hB' x xab).Ioi_of_Ici (Ioi_mem_nhds hrB), obtain ⟨z, hfz, hzB, hz⟩ : ∃ z, slope f x z < r ∧ r < slope B x z ∧ z ∈ Ioc x y, from (hf'.and_eventually (HB.and (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩))).exists, refine ⟨z, _, hz⟩, have := (hfz.trans hzB).le, rwa [slope_def_field, slope_def_field, div_le_div_right (sub_pos.2 hz.1), hxB, sub_le_sub_iff_right] at this } end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (f z - f x) / (z - x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[>] x, slope f x z < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by `B'`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_le_deriv_boundary {f : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) -- `bound` actually says `liminf (f z - f x) / (z - x) ≤ B' x` (bound : ∀ x ∈ Ico a b, ∀ r, B' x < r → ∃ᶠ z in 𝓝[>] x, slope f x z < r) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin have Hr : ∀ x ∈ Icc a b, ∀ r > 0, f x ≤ B x + r * (x - a), { intros x hx r hr, apply image_le_of_liminf_slope_right_lt_deriv_boundary' hf bound, { rwa [sub_self, mul_zero, add_zero] }, { exact hB.add (continuous_on_const.mul (continuous_id.continuous_on.sub continuous_on_const)) }, { assume x hx, exact (hB' x hx).add (((has_deriv_within_at_id x (Ici x)).sub_const a).const_mul r) }, { assume x hx _, rw [mul_one], exact (lt_add_iff_pos_right _).2 hr }, exact hx }, assume x hx, have : continuous_within_at (λ r, B x + r * (x - a)) (Ioi 0) 0, from continuous_within_at_const.add (continuous_within_at_id.mul continuous_within_at_const), convert continuous_within_at_const.closure_le _ this (Hr x hx); simp end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf (λ x hx r hr, (hf' x hx).liminf_right_slope_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x ≤ B' x` on `[a, b)`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_le_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f' x ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary hf ha hB hB' $ assume x hx r hr, (hf' x hx).liminf_right_slope_le (lt_of_le_of_lt (bound x hx) hr) /-! ### Vector-valued functions `f : ℝ → E` -/ section variables {f : ℝ → E} {a b : ℝ} /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `‖f a‖ ≤ B a`; * `B` has right derivative at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(‖f z‖ - ‖f x‖) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `‖f x‖ = B x`. Then `‖f x‖ ≤ B x` everywhere on `[a, b]`. -/ lemma image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary {E : Type*} [normed_add_comm_group E] {f : ℝ → E} {f' : ℝ → ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (‖f z‖ - ‖f x‖) / (z - x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[>] x, slope (norm ∘ f) x z < r) {B B' : ℝ → ℝ} (ha : ‖f a‖ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ‖f x‖ = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ‖f x‖ ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' (continuous_norm.comp_continuous_on hf) hf' ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `‖f a‖ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * the norm of `f'` is strictly less than `B'` whenever `‖f x‖ = B x`. Then `‖f x‖ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ‖f a‖ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ‖f x‖ = B x → ‖f' x‖ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ‖f x‖ ≤ B x := image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary hf (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `‖f a‖ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * the norm of `f'` is strictly less than `B'` whenever `‖f x‖ = B x`. Then `‖f x‖ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ‖f a‖ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ‖f x‖ = B x → ‖f' x‖ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ‖f x‖ ≤ B x := image_norm_le_of_norm_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `‖f a‖ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * we have `‖f' x‖ ≤ B x` everywhere on `[a, b)`. Then `‖f x‖ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ‖f a‖ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ‖f' x‖ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ‖f x‖ ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary (continuous_norm.comp_continuous_on hf) ha hB hB' $ (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le (lt_of_le_of_lt (bound x hx) hr)) /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `‖f a‖ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * we have `‖f' x‖ ≤ B x` everywhere on `[a, b)`. Then `‖f x‖ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ‖f a‖ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ‖f' x‖ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ‖f x‖ ≤ B x := image_norm_le_of_norm_deriv_right_le_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- A function on `[a, b]` with the norm of the right derivative bounded by `C` satisfies `‖f x - f a‖ ≤ C * (x - a)`. -/ theorem norm_image_sub_le_of_norm_deriv_right_le_segment {f' : ℝ → E} {C : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (bound : ∀x ∈ Ico a b, ‖f' x‖ ≤ C) : ∀ x ∈ Icc a b, ‖f x - f a‖ ≤ C * (x - a) := begin let g := λ x, f x - f a, have hg : continuous_on g (Icc a b), from hf.sub continuous_on_const, have hg' : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x, { assume x hx, simpa using (hf' x hx).sub (has_deriv_within_at_const _ _ _) }, let B := λ x, C * (x - a), have hB : ∀ x, has_deriv_at B C x, { assume x, simpa using (has_deriv_at_const x C).mul ((has_deriv_at_id x).sub (has_deriv_at_const x a)) }, convert image_norm_le_of_norm_deriv_right_le_deriv_boundary hg hg' _ hB bound, simp only [g, B], rw [sub_self, norm_zero, sub_self, mul_zero] end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `‖f x - f a‖ ≤ C * (x - a)`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc a b, has_deriv_within_at f (f' x) (Icc a b) x) (bound : ∀x ∈ Ico a b, ‖f' x‖ ≤ C) : ∀ x ∈ Icc a b, ‖f x - f a‖ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_right_le_segment (λ x hx, (hf x hx).continuous_within_at) (λ x hx, _) bound, exact (hf x $ Ico_subset_Icc_self hx).nhds_within (Icc_mem_nhds_within_Ici hx) end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `‖f x - f a‖ ≤ C * (x - a)`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment {C : ℝ} (hf : differentiable_on ℝ f (Icc a b)) (bound : ∀x ∈ Ico a b, ‖deriv_within f (Icc a b) x‖ ≤ C) : ∀ x ∈ Icc a b, ‖f x - f a‖ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_le_segment' _ bound, exact λ x hx, (hf x hx).has_deriv_within_at end /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `‖f 1 - f 0‖ ≤ C`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc (0:ℝ) 1, has_deriv_within_at f (f' x) (Icc (0:ℝ) 1) x) (bound : ∀x ∈ Ico (0:ℝ) 1, ‖f' x‖ ≤ C) : ‖f 1 - f 0‖ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment' hf bound 1 (right_mem_Icc.2 zero_le_one) /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `‖f 1 - f 0‖ ≤ C`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01 {C : ℝ} (hf : differentiable_on ℝ f (Icc (0:ℝ) 1)) (bound : ∀x ∈ Ico (0:ℝ) 1, ‖deriv_within f (Icc (0:ℝ) 1) x‖ ≤ C) : ‖f 1 - f 0‖ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment hf bound 1 (right_mem_Icc.2 zero_le_one) theorem constant_of_has_deriv_right_zero (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at f 0 (Ici x) x) : ∀ x ∈ Icc a b, f x = f a := by simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using λ x hx, norm_image_sub_le_of_norm_deriv_right_le_segment hcont hderiv (λ y hy, by rw norm_le_zero_iff) x hx theorem constant_of_deriv_within_zero (hdiff : differentiable_on ℝ f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, deriv_within f (Icc a b) x = 0) : ∀ x ∈ Icc a b, f x = f a := begin have H : ∀ x ∈ Ico a b, ‖deriv_within f (Icc a b) x‖ ≤ 0 := by simpa only [norm_le_zero_iff] using λ x hx, hderiv x hx, simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using λ x hx, norm_image_sub_le_of_norm_deriv_le_segment hdiff H x hx, end variables {f' g : ℝ → E} /-- If two continuous functions on `[a, b]` have the same right derivative and are equal at `a`, then they are equal everywhere on `[a, b]`. -/ theorem eq_of_has_deriv_right_eq (derivf : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (derivg : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x) (fcont : continuous_on f (Icc a b)) (gcont : continuous_on g (Icc a b)) (hi : f a = g a) : ∀ y ∈ Icc a b, f y = g y := begin simp only [← @sub_eq_zero _ _ (f _)] at hi ⊢, exact hi ▸ constant_of_has_deriv_right_zero (fcont.sub gcont) (λ y hy, by simpa only [sub_self] using (derivf y hy).sub (derivg y hy)), end /-- If two differentiable functions on `[a, b]` have the same derivative within `[a, b]` everywhere on `[a, b)` and are equal at `a`, then they are equal everywhere on `[a, b]`. -/ theorem eq_of_deriv_within_eq (fdiff : differentiable_on ℝ f (Icc a b)) (gdiff : differentiable_on ℝ g (Icc a b)) (hderiv : eq_on (deriv_within f (Icc a b)) (deriv_within g (Icc a b)) (Ico a b)) (hi : f a = g a) : ∀ y ∈ Icc a b, f y = g y := begin have A : ∀ y ∈ Ico a b, has_deriv_within_at f (deriv_within f (Icc a b) y) (Ici y) y := λ y hy, (fdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within (Icc_mem_nhds_within_Ici hy), have B : ∀ y ∈ Ico a b, has_deriv_within_at g (deriv_within g (Icc a b) y) (Ici y) y := λ y hy, (gdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within (Icc_mem_nhds_within_Ici hy), exact eq_of_has_deriv_right_eq A (λ y hy, (hderiv hy).symm ▸ B y hy) fdiff.continuous_on gdiff.continuous_on hi end end /-! ### Vector-valued functions `f : E → G` Theorems in this section work both for real and complex differentiable functions. We use assumptions `[is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 G]` to achieve this result. For the domain `E` we also assume `[normed_space ℝ E]` to have a notion of a `convex` set. -/ section variables {𝕜 G : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_add_comm_group G] [normed_space 𝕜 G] namespace convex variables {f : E → G} {C : ℝ} {s : set E} {x y : E} {f' : E → E →L[𝕜] G} {φ : E →L[𝕜] G} /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `has_fderiv_within`. -/ theorem norm_image_sub_le_of_norm_has_fderiv_within_le (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ‖f' x‖ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ‖f y - f x‖ ≤ C * ‖y - x‖ := begin letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G, /- By composition with `t ↦ x + t • (y-x)`, we reduce to a statement for functions defined on `[0,1]`, for which it is proved in `norm_image_sub_le_of_norm_deriv_le_segment`. We just have to check the differentiability of the composition and bounds on its derivative, which is straightforward but tedious for lack of automation. -/ have C0 : 0 ≤ C := le_trans (norm_nonneg _) (bound x xs), set g : ℝ → E := λ t, x + t • (y - x), have Dg : ∀ t, has_deriv_at g (y-x) t, { assume t, simpa only [one_smul] using ((has_deriv_at_id t).smul_const (y - x)).const_add x }, have segm : Icc 0 1 ⊆ g ⁻¹' s, { rw [← image_subset_iff, ← segment_eq_image'], apply hs.segment_subset xs ys }, have : f x = f (g 0), by { simp only [g], rw [zero_smul, add_zero] }, rw this, have : f y = f (g 1), by { simp only [g], rw [one_smul, add_sub_cancel'_right] }, rw this, have D2: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) (f' (g t) (y - x)) (Icc 0 1) t, { intros t ht, have : has_fderiv_within_at f ((f' (g t)).restrict_scalars ℝ) s (g t), from hf (g t) (segm ht), exact this.comp_has_deriv_within_at _ (Dg t).has_deriv_within_at segm }, apply norm_image_sub_le_of_norm_deriv_le_segment_01' D2, refine λ t ht, le_of_op_norm_le _ _ _, exact bound (g t) (segm $ Ico_subset_Icc_self ht) end /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `has_fderiv_within` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_has_fderiv_within_le {C : ℝ≥0} (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ‖f' x‖₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := begin rw lipschitz_on_with_iff_norm_sub_le, intros x x_in y y_in, exact hs.norm_image_sub_le_of_norm_has_fderiv_within_le hf bound y_in x_in end /-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `‖f' x‖₊`, `f` is `K`-Lipschitz on some neighborhood of `x` within `s`. See also `convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at` for a version that claims existence of `K` instead of an explicit estimate. -/ lemma exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt (hs : convex ℝ s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y) (hcont : continuous_within_at f' s x) (K : ℝ≥0) (hK : ‖f' x‖₊ < K) : ∃ t ∈ 𝓝[s] x, lipschitz_on_with K f t := begin obtain ⟨ε, ε0, hε⟩ : ∃ ε > 0, ball x ε ∩ s ⊆ {y | has_fderiv_within_at f (f' y) s y ∧ ‖f' y‖₊ < K}, from mem_nhds_within_iff.1 (hder.and $ hcont.nnnorm.eventually (gt_mem_nhds hK)), rw inter_comm at hε, refine ⟨s ∩ ball x ε, inter_mem_nhds_within _ (ball_mem_nhds _ ε0), _⟩, exact (hs.inter (convex_ball _ _)).lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ y hy, (hε hy).1.mono (inter_subset_left _ _)) (λ y hy, (hε hy).2.le) end /-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `‖f' x‖₊`, `f` is Lipschitz on some neighborhood of `x` within `s`. See also `convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt` for a version with an explicit estimate on the Lipschitz constant. -/ lemma exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at (hs : convex ℝ s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y) (hcont : continuous_within_at f' s x) : ∃ K (t ∈ 𝓝[s] x), lipschitz_on_with K f t := (exists_gt _).imp $ hs.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt hder hcont /-- The mean value theorem on a convex set: if the derivative of a function within this set is bounded by `C`, then the function is `C`-Lipschitz. Version with `fderiv_within`. -/ theorem norm_image_sub_le_of_norm_fderiv_within_le (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ‖fderiv_within 𝕜 f s x‖ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ‖f y - f x‖ ≤ C * ‖y - x‖ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) bound xs ys /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv_within` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_fderiv_within_le {C : ℝ≥0} (hf : differentiable_on 𝕜 f s) (bound : ∀ x ∈ s, ‖fderiv_within 𝕜 f s x‖₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s:= hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) bound /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `fderiv`. -/ theorem norm_image_sub_le_of_norm_fderiv_le (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ‖fderiv 𝕜 f x‖ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ‖f y - f x‖ ≤ C * ‖y - x‖ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_fderiv_le {C : ℝ≥0} (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ‖fderiv 𝕜 f x‖₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound /-- Variant of the mean value inequality on a convex set, using a bound on the difference between the derivative and a fixed linear map, rather than a bound on the derivative itself. Version with `has_fderiv_within`. -/ theorem norm_image_sub_le_of_norm_has_fderiv_within_le' (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ‖f' x - φ‖ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ‖f y - f x - φ (y - x)‖ ≤ C * ‖y - x‖ := begin /- We subtract `φ` to define a new function `g` for which `g' = 0`, for which the previous theorem applies, `convex.norm_image_sub_le_of_norm_has_fderiv_within_le`. Then, we just need to glue together the pieces, expressing back `f` in terms of `g`. -/ let g := λy, f y - φ y, have hg : ∀ x ∈ s, has_fderiv_within_at g (f' x - φ) s x := λ x xs, (hf x xs).sub φ.has_fderiv_within_at, calc ‖f y - f x - φ (y - x)‖ = ‖f y - f x - (φ y - φ x)‖ : by simp ... = ‖(f y - φ y) - (f x - φ x)‖ : by abel ... = ‖g y - g x‖ : by simp ... ≤ C * ‖y - x‖ : convex.norm_image_sub_le_of_norm_has_fderiv_within_le hg bound hs xs ys, end /-- Variant of the mean value inequality on a convex set. Version with `fderiv_within`. -/ theorem norm_image_sub_le_of_norm_fderiv_within_le' (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ‖fderiv_within 𝕜 f s x - φ‖ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ‖f y - f x - φ (y - x)‖ ≤ C * ‖y - x‖ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le' (λ x hx, (hf x hx).has_fderiv_within_at) bound xs ys /-- Variant of the mean value inequality on a convex set. Version with `fderiv`. -/ theorem norm_image_sub_le_of_norm_fderiv_le' (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ‖fderiv 𝕜 f x - φ‖ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ‖f y - f x - φ (y - x)‖ ≤ C * ‖y - x‖ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le' (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys /-- If a function has zero Fréchet derivative at every point of a convex set, then it is a constant on this set. -/ theorem is_const_of_fderiv_within_eq_zero (hs : convex ℝ s) (hf : differentiable_on 𝕜 f s) (hf' : ∀ x ∈ s, fderiv_within 𝕜 f s x = 0) (hx : x ∈ s) (hy : y ∈ s) : f x = f y := have bound : ∀ x ∈ s, ‖fderiv_within 𝕜 f s x‖ ≤ 0, from λ x hx, by simp only [hf' x hx, norm_zero], by simpa only [(dist_eq_norm _ _).symm, zero_mul, dist_le_zero, eq_comm] using hs.norm_image_sub_le_of_norm_fderiv_within_le hf bound hx hy theorem _root_.is_const_of_fderiv_eq_zero (hf : differentiable 𝕜 f) (hf' : ∀ x, fderiv 𝕜 f x = 0) (x y : E) : f x = f y := convex_univ.is_const_of_fderiv_within_eq_zero hf.differentiable_on (λ x _, by rw fderiv_within_univ; exact hf' x) trivial trivial end convex namespace convex variables {f f' : 𝕜 → G} {s : set 𝕜} {x y : 𝕜} /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `has_deriv_within`. -/ theorem norm_image_sub_le_of_norm_has_deriv_within_le {C : ℝ} (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ‖f' x‖ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ‖f y - f x‖ ≤ C * ‖y - x‖ := convex.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) (λ x hx, le_trans (by simp) (bound x hx)) hs xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `has_deriv_within` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_has_deriv_within_le {C : ℝ≥0} (hs : convex ℝ s) (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ‖f' x‖₊ ≤ C) : lipschitz_on_with C f s := convex.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) (λ x hx, le_trans (by simp) (bound x hx)) hs /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function within this set is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv_within` -/ theorem norm_image_sub_le_of_norm_deriv_within_le {C : ℝ} (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ‖deriv_within f s x‖ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ‖f y - f x‖ ≤ C * ‖y - x‖ := hs.norm_image_sub_le_of_norm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at) bound xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `deriv_within` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_deriv_within_le {C : ℝ≥0} (hs : convex ℝ s) (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ‖deriv_within f s x‖₊ ≤ C) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at) bound /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv`. -/ theorem norm_image_sub_le_of_norm_deriv_le {C : ℝ} (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ‖deriv f x‖ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ‖f y - f x‖ ≤ C * ‖y - x‖ := hs.norm_image_sub_le_of_norm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `deriv` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_deriv_le {C : ℝ≥0} (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ‖deriv f x‖₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound /-- The mean value theorem set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv` and `lipschitz_with`. -/ theorem _root_.lipschitz_with_of_nnnorm_deriv_le {C : ℝ≥0} (hf : differentiable 𝕜 f) (bound : ∀ x, ‖deriv f x‖₊ ≤ C) : lipschitz_with C f := lipschitz_on_univ.1 $ convex_univ.lipschitz_on_with_of_nnnorm_deriv_le (λ x hx, hf x) (λ x hx, bound x) /-- If `f : 𝕜 → G`, `𝕜 = R` or `𝕜 = ℂ`, is differentiable everywhere and its derivative equal zero, then it is a constant function. -/ theorem _root_.is_const_of_deriv_eq_zero (hf : differentiable 𝕜 f) (hf' : ∀ x, deriv f x = 0) (x y : 𝕜) : f x = f y := is_const_of_fderiv_eq_zero hf (λ z, by { ext, simp [← deriv_fderiv, hf'] }) _ _ end convex end /-! ### Functions `[a, b] → ℝ`. -/ section interval -- Declare all variables here to make sure they come in a correct order variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hfd : differentiable_on ℝ f (Ioo a b)) (g g' : ℝ → ℝ) (hgc : continuous_on g (Icc a b)) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hgd : differentiable_on ℝ g (Ioo a b)) include hab hfc hff' hgc hgg' /-- Cauchy's **Mean Value Theorem**, `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * f' c = (f b - f a) * g' c := begin let h := λ x, (g b - g a) * f x - (f b - f a) * g x, have hI : h a = h b, { simp only [h], ring }, let h' := λ x, (g b - g a) * f' x - (f b - f a) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, from λ x hx, ((hff' x hx).const_mul (g b - g a)).sub ((hgg' x hx).const_mul (f b - f a)), have hhc : continuous_on h (Icc a b), from (continuous_on_const.mul hfc).sub (continuous_on_const.mul hgc), rcases exists_has_deriv_at_eq_zero h h' hab hhc hI hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end omit hfc hgc /-- Cauchy's **Mean Value Theorem**, extended `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope' {lfa lga lfb lgb : ℝ} (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hfa : tendsto f (𝓝[>] a) (𝓝 lfa)) (hga : tendsto g (𝓝[>] a) (𝓝 lga)) (hfb : tendsto f (𝓝[<] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[<] b) (𝓝 lgb)) : ∃ c ∈ Ioo a b, (lgb - lga) * (f' c) = (lfb - lfa) * (g' c) := begin let h := λ x, (lgb - lga) * f x - (lfb - lfa) * g x, have hha : tendsto h (𝓝[>] a) (𝓝 $ lgb * lfa - lfb * lga), { have : tendsto h (𝓝[>] a)(𝓝 $ (lgb - lga) * lfa - (lfb - lfa) * lga) := (tendsto_const_nhds.mul hfa).sub (tendsto_const_nhds.mul hga), convert this using 2, ring }, have hhb : tendsto h (𝓝[<] b) (𝓝 $ lgb * lfa - lfb * lga), { have : tendsto h (𝓝[<] b)(𝓝 $ (lgb - lga) * lfb - (lfb - lfa) * lgb) := (tendsto_const_nhds.mul hfb).sub (tendsto_const_nhds.mul hgb), convert this using 2, ring }, let h' := λ x, (lgb - lga) * f' x - (lfb - lfa) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, { intros x hx, exact ((hff' x hx).const_mul _ ).sub (((hgg' x hx)).const_mul _) }, rcases exists_has_deriv_at_eq_zero' hab hha hhb hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end include hfc omit hgg' /-- Lagrange's Mean Value Theorem, `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_slope : ∃ c ∈ Ioo a b, f' c = (f b - f a) / (b - a) := begin rcases exists_ratio_has_deriv_at_eq_ratio_slope f f' hab hfc hff' id 1 continuous_id.continuous_on (λ x hx, has_deriv_at_id x) with ⟨c, cmem, hc⟩, use [c, cmem], simp only [_root_.id, pi.one_apply, mul_one] at hc, rw [← hc, mul_div_cancel_left], exact ne_of_gt (sub_pos.2 hab) end omit hff' /-- Cauchy's Mean Value Theorem, `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * (deriv f c) = (f b - f a) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at) g (deriv g) hgc $ λ x hx, ((hgd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at omit hfc /-- Cauchy's Mean Value Theorem, extended `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope' {lfa lga lfb lgb : ℝ} (hdf : differentiable_on ℝ f $ Ioo a b) (hdg : differentiable_on ℝ g $ Ioo a b) (hfa : tendsto f (𝓝[>] a) (𝓝 lfa)) (hga : tendsto g (𝓝[>] a) (𝓝 lga)) (hfb : tendsto f (𝓝[<] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[<] b) (𝓝 lgb)) : ∃ c ∈ Ioo a b, (lgb - lga) * (deriv f c) = (lfb - lfa) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope' _ _ hab _ _ (λ x hx, ((hdf x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at) (λ x hx, ((hdg x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at) hfa hga hfb hgb /-- Lagrange's **Mean Value Theorem**, `deriv` version. -/ lemma exists_deriv_eq_slope : ∃ c ∈ Ioo a b, deriv f c = (f b - f a) / (b - a) := exists_has_deriv_at_eq_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at) end interval /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C < f'`, then `f` grows faster than `C * x` on `D`, i.e., `C * (y - x) < f y - f x` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.mul_sub_lt_image_sub_of_lt_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_gt : ∀ x ∈ interior D, C < deriv f x) : ∀ x y ∈ D, x < y → C * (y - x) < f y - f x := begin assume x hx y hy hxy, have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), have : C < (f y - f x) / (y - x), by { rw [← ha], exact hf'_gt _ (hxyD' a_mem) }, exact (lt_div_iff (sub_pos.2 hxy)).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C < f'`, then `f` grows faster than `C * x`, i.e., `C * (y - x) < f y - f x` whenever `x < y`. -/ theorem mul_sub_lt_image_sub_of_lt_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_gt : ∀ x, C < deriv f x) ⦃x y⦄ (hxy : x < y) : C * (y - x) < f y - f x := convex_univ.mul_sub_lt_image_sub_of_lt_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_gt x) x trivial y trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C ≤ f'`, then `f` grows at least as fast as `C * x` on `D`, i.e., `C * (y - x) ≤ f y - f x` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.mul_sub_le_image_sub_of_le_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_ge : ∀ x ∈ interior D, C ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → C * (y - x) ≤ f y - f x := begin assume x hx y hy hxy, cases eq_or_lt_of_le hxy with hxy' hxy', by rw [hxy', sub_self, sub_self, mul_zero], have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy' (hf.mono hxyD) (hf'.mono hxyD'), have : C ≤ (f y - f x) / (y - x), by { rw [← ha], exact hf'_ge _ (hxyD' a_mem) }, exact (le_div_iff (sub_pos.2 hxy')).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C ≤ f'`, then `f` grows at least as fast as `C * x`, i.e., `C * (y - x) ≤ f y - f x` whenever `x ≤ y`. -/ theorem mul_sub_le_image_sub_of_le_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_ge : ∀ x, C ≤ deriv f x) ⦃x y⦄ (hxy : x ≤ y) : C * (y - x) ≤ f y - f x := convex_univ.mul_sub_le_image_sub_of_le_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_ge x) x trivial y trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.image_sub_lt_mul_sub_of_deriv_lt {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (lt_hf' : ∀ x ∈ interior D, deriv f x < C) : ∀ x y ∈ D, x < y → f y - f x < C * (y - x) := begin assume x hx y hy hxy, have hf'_gt : ∀ x ∈ interior D, -C < deriv (λ y, -f y) x, { assume x hx, rw [deriv.neg, neg_lt_neg_iff], exact lt_hf' x hx }, simpa [-neg_lt_neg_iff] using neg_lt_neg (hD.mul_sub_lt_image_sub_of_lt_deriv hf.neg hf'.neg hf'_gt x hx y hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x < y`. -/ theorem image_sub_lt_mul_sub_of_deriv_lt {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (lt_hf' : ∀ x, deriv f x < C) ⦃x y⦄ (hxy : x < y) : f y - f x < C * (y - x) := convex_univ.image_sub_lt_mul_sub_of_deriv_lt hf.continuous.continuous_on hf.differentiable_on (λ x _, lt_hf' x) x trivial y trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' ≤ C`, then `f` grows at most as fast as `C * x` on `D`, i.e., `f y - f x ≤ C * (y - x)` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.image_sub_le_mul_sub_of_deriv_le {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (le_hf' : ∀ x ∈ interior D, deriv f x ≤ C) : ∀ x y ∈ D, x ≤ y → f y - f x ≤ C * (y - x) := begin assume x hx y hy hxy, have hf'_ge : ∀ x ∈ interior D, -C ≤ deriv (λ y, -f y) x, { assume x hx, rw [deriv.neg, neg_le_neg_iff], exact le_hf' x hx }, simpa [-neg_le_neg_iff] using neg_le_neg (hD.mul_sub_le_image_sub_of_le_deriv hf.neg hf'.neg hf'_ge x hx y hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' ≤ C`, then `f` grows at most as fast as `C * x`, i.e., `f y - f x ≤ C * (y - x)` whenever `x ≤ y`. -/ theorem image_sub_le_mul_sub_of_deriv_le {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (le_hf' : ∀ x, deriv f x ≤ C) ⦃x y⦄ (hxy : x ≤ y) : f y - f x ≤ C * (y - x) := convex_univ.image_sub_le_mul_sub_of_deriv_le hf.continuous.continuous_on hf.differentiable_on (λ x _, le_hf' x) x trivial y trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is positive, then `f` is a strictly monotone function on `D`. Note that we don't require differentiability explicitly as it already implied by the derivative being strictly positive. -/ theorem convex.strict_mono_on_of_deriv_pos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : ∀ x ∈ interior D, 0 < deriv f x) : strict_mono_on f D := begin rintro x hx y hy, simpa only [zero_mul, sub_pos] using hD.mul_sub_lt_image_sub_of_lt_deriv hf _ hf' x hx y hy, exact λ z hz, (differentiable_at_of_deriv_ne_zero (hf' z hz).ne').differentiable_within_at, end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is positive, then `f` is a strictly monotone function. Note that we don't require differentiability explicitly as it already implied by the derivative being strictly positive. -/ theorem strict_mono_of_deriv_pos {f : ℝ → ℝ} (hf' : ∀ x, 0 < deriv f x) : strict_mono f := strict_mono_on_univ.1 $ convex_univ.strict_mono_on_of_deriv_pos (λ z _, (differentiable_at_of_deriv_ne_zero (hf' z).ne').differentiable_within_at .continuous_within_at) (λ x _, hf' x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonnegative, then `f` is a monotone function on `D`. -/ theorem convex.monotone_on_of_deriv_nonneg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonneg : ∀ x ∈ interior D, 0 ≤ deriv f x) : monotone_on f D := λ x hx y hy hxy, by simpa only [zero_mul, sub_nonneg] using hD.mul_sub_le_image_sub_of_le_deriv hf hf' hf'_nonneg x hx y hy hxy /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonnegative, then `f` is a monotone function. -/ theorem monotone_of_deriv_nonneg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, 0 ≤ deriv f x) : monotone f := monotone_on_univ.1 $ convex_univ.monotone_on_of_deriv_nonneg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is negative, then `f` is a strictly antitone function on `D`. -/ theorem convex.strict_anti_on_of_deriv_neg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : ∀ x ∈ interior D, deriv f x < 0) : strict_anti_on f D := λ x hx y, by simpa only [zero_mul, sub_lt_zero] using hD.image_sub_lt_mul_sub_of_deriv_lt hf (λ z hz, (differentiable_at_of_deriv_ne_zero (hf' z hz).ne).differentiable_within_at) hf' x hx y /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is negative, then `f` is a strictly antitone function. Note that we don't require differentiability explicitly as it already implied by the derivative being strictly negative. -/ theorem strict_anti_of_deriv_neg {f : ℝ → ℝ} (hf' : ∀ x, deriv f x < 0) : strict_anti f := strict_anti_on_univ.1 $ convex_univ.strict_anti_on_of_deriv_neg (λ z _, (differentiable_at_of_deriv_ne_zero (hf' z).ne).differentiable_within_at .continuous_within_at) (λ x _, hf' x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonpositive, then `f` is an antitone function on `D`. -/ theorem convex.antitone_on_of_deriv_nonpos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonpos : ∀ x ∈ interior D, deriv f x ≤ 0) : antitone_on f D := λ x hx y hy hxy, by simpa only [zero_mul, sub_nonpos] using hD.image_sub_le_mul_sub_of_deriv_le hf hf' hf'_nonpos x hx y hy hxy /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonpositive, then `f` is an antitone function. -/ theorem antitone_of_deriv_nonpos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x ≤ 0) : antitone f := antitone_on_univ.1 $ convex_univ.antitone_on_of_deriv_nonpos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is monotone on the interior, then `f` is convex on `D`. -/ theorem monotone_on.convex_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_mono : monotone_on (deriv f) (interior D)) : convex_on ℝ D f := convex_on_of_slope_mono_adjacent hD begin intros x y z hx hz hxy hyz, -- First we prove some trivial inclusions have hxzD : Icc x z ⊆ D, from hD.ord_connected.out hx hz, have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD, have hyzD' : Ioo y z ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩, -- Then we apply MVT to both `[x, y]` and `[y, z]` obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b = (f z - f y) / (z - y), from exists_deriv_eq_slope f hyz (hf.mono hyzD) (hf'.mono hyzD'), rw [← ha, ← hb], exact hf'_mono (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (hay.trans hyb).le end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is antitone on the interior, then `f` is concave on `D`. -/ theorem antitone_on.concave_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (h_anti : antitone_on (deriv f) (interior D)) : concave_on ℝ D f := begin have : monotone_on (deriv (-f)) (interior D), { intros x hx y hy hxy, convert neg_le_neg (h_anti hx hy hxy); convert deriv.neg }, exact neg_convex_on_iff.mp (this.convex_on_of_deriv hD hf.neg hf'.neg), end lemma strict_mono_on.exists_slope_lt_deriv_aux {x y : ℝ} {f : ℝ → ℝ} (hf : continuous_on f (Icc x y)) (hxy : x < y) (hf'_mono : strict_mono_on (deriv f) (Ioo x y)) (h : ∀ w ∈ Ioo x y, deriv f w ≠ 0) : ∃ a ∈ Ioo x y, (f y - f x) / (y - x) < deriv f a := begin have A : differentiable_on ℝ f (Ioo x y), from λ w wmem, (differentiable_at_of_deriv_ne_zero (h w wmem)).differentiable_within_at, obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy hf A, rcases nonempty_Ioo.2 hay with ⟨b, ⟨hab, hby⟩⟩, refine ⟨b, ⟨hxa.trans hab, hby⟩, _⟩, rw ← ha, exact hf'_mono ⟨hxa, hay⟩ ⟨hxa.trans hab, hby⟩ hab end lemma strict_mono_on.exists_slope_lt_deriv {x y : ℝ} {f : ℝ → ℝ} (hf : continuous_on f (Icc x y)) (hxy : x < y) (hf'_mono : strict_mono_on (deriv f) (Ioo x y)) : ∃ a ∈ Ioo x y, (f y - f x) / (y - x) < deriv f a := begin by_cases h : ∀ w ∈ Ioo x y, deriv f w ≠ 0, { apply strict_mono_on.exists_slope_lt_deriv_aux hf hxy hf'_mono h }, { push_neg at h, rcases h with ⟨w, ⟨hxw, hwy⟩, hw⟩, obtain ⟨a, ⟨hxa, haw⟩, ha⟩ : ∃ (a : ℝ) (H : a ∈ Ioo x w), (f w - f x) / (w - x) < deriv f a, { apply strict_mono_on.exists_slope_lt_deriv_aux _ hxw _ _, { exact hf.mono (Icc_subset_Icc le_rfl hwy.le) }, { exact hf'_mono.mono (Ioo_subset_Ioo le_rfl hwy.le) }, { assume z hz, rw ← hw, apply ne_of_lt, exact hf'_mono ⟨hz.1, hz.2.trans hwy⟩ ⟨hxw, hwy⟩ hz.2 } }, obtain ⟨b, ⟨hwb, hby⟩, hb⟩ : ∃ (b : ℝ) (H : b ∈ Ioo w y), (f y - f w) / (y - w) < deriv f b, { apply strict_mono_on.exists_slope_lt_deriv_aux _ hwy _ _, { refine hf.mono (Icc_subset_Icc hxw.le le_rfl), }, { exact hf'_mono.mono (Ioo_subset_Ioo hxw.le le_rfl) }, { assume z hz, rw ← hw, apply ne_of_gt, exact hf'_mono ⟨hxw, hwy⟩ ⟨hxw.trans hz.1, hz.2⟩ hz.1, } }, refine ⟨b, ⟨hxw.trans hwb, hby⟩, _⟩, simp only [div_lt_iff, hxy, hxw, hwy, sub_pos] at ⊢ ha hb, have : deriv f a * (w - x) < deriv f b * (w - x), { apply mul_lt_mul _ le_rfl (sub_pos.2 hxw) _, { exact hf'_mono ⟨hxa, haw.trans hwy⟩ ⟨hxw.trans hwb, hby⟩ (haw.trans hwb) }, { rw ← hw, exact (hf'_mono ⟨hxw, hwy⟩ ⟨hxw.trans hwb, hby⟩ hwb).le } }, linarith } end lemma strict_mono_on.exists_deriv_lt_slope_aux {x y : ℝ} {f : ℝ → ℝ} (hf : continuous_on f (Icc x y)) (hxy : x < y) (hf'_mono : strict_mono_on (deriv f) (Ioo x y)) (h : ∀ w ∈ Ioo x y, deriv f w ≠ 0) : ∃ a ∈ Ioo x y, deriv f a < (f y - f x) / (y - x) := begin have A : differentiable_on ℝ f (Ioo x y), from λ w wmem, (differentiable_at_of_deriv_ne_zero (h w wmem)).differentiable_within_at, obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy hf A, rcases nonempty_Ioo.2 hxa with ⟨b, ⟨hxb, hba⟩⟩, refine ⟨b, ⟨hxb, hba.trans hay⟩, _⟩, rw ← ha, exact hf'_mono ⟨hxb, hba.trans hay⟩ ⟨hxa, hay⟩ hba end lemma strict_mono_on.exists_deriv_lt_slope {x y : ℝ} {f : ℝ → ℝ} (hf : continuous_on f (Icc x y)) (hxy : x < y) (hf'_mono : strict_mono_on (deriv f) (Ioo x y)) : ∃ a ∈ Ioo x y, deriv f a < (f y - f x) / (y - x) := begin by_cases h : ∀ w ∈ Ioo x y, deriv f w ≠ 0, { apply strict_mono_on.exists_deriv_lt_slope_aux hf hxy hf'_mono h }, { push_neg at h, rcases h with ⟨w, ⟨hxw, hwy⟩, hw⟩, obtain ⟨a, ⟨hxa, haw⟩, ha⟩ : ∃ (a : ℝ) (H : a ∈ Ioo x w), deriv f a < (f w - f x) / (w - x), { apply strict_mono_on.exists_deriv_lt_slope_aux _ hxw _ _, { exact hf.mono (Icc_subset_Icc le_rfl hwy.le) }, { exact hf'_mono.mono (Ioo_subset_Ioo le_rfl hwy.le) }, { assume z hz, rw ← hw, apply ne_of_lt, exact hf'_mono ⟨hz.1, hz.2.trans hwy⟩ ⟨hxw, hwy⟩ hz.2 } }, obtain ⟨b, ⟨hwb, hby⟩, hb⟩ : ∃ (b : ℝ) (H : b ∈ Ioo w y), deriv f b < (f y - f w) / (y - w), { apply strict_mono_on.exists_deriv_lt_slope_aux _ hwy _ _, { refine hf.mono (Icc_subset_Icc hxw.le le_rfl), }, { exact hf'_mono.mono (Ioo_subset_Ioo hxw.le le_rfl) }, { assume z hz, rw ← hw, apply ne_of_gt, exact hf'_mono ⟨hxw, hwy⟩ ⟨hxw.trans hz.1, hz.2⟩ hz.1, } }, refine ⟨a, ⟨hxa, haw.trans hwy⟩, _⟩, simp only [lt_div_iff, hxy, hxw, hwy, sub_pos] at ⊢ ha hb, have : deriv f a * (y - w) < deriv f b * (y - w), { apply mul_lt_mul _ le_rfl (sub_pos.2 hwy) _, { exact hf'_mono ⟨hxa, haw.trans hwy⟩ ⟨hxw.trans hwb, hby⟩ (haw.trans hwb) }, { rw ← hw, exact (hf'_mono ⟨hxw, hwy⟩ ⟨hxw.trans hwb, hby⟩ hwb).le } }, linarith } end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, and `f'` is strictly monotone on the interior, then `f` is strictly convex on `D`. Note that we don't require differentiability, since it is guaranteed at all but at most one point by the strict monotonicity of `f'`. -/ lemma strict_mono_on.strict_convex_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : strict_mono_on (deriv f) (interior D)) : strict_convex_on ℝ D f := strict_convex_on_of_slope_strict_mono_adjacent hD begin intros x y z hx hz hxy hyz, -- First we prove some trivial inclusions have hxzD : Icc x z ⊆ D, from hD.ord_connected.out hx hz, have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD, have hyzD' : Ioo y z ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩, -- Then we get points `a` and `b` in each interval `[x, y]` and `[y, z]` where the derivatives -- can be compared to the slopes between `x, y` and `y, z` respectively. obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, (f y - f x) / (y - x) < deriv f a, from strict_mono_on.exists_slope_lt_deriv (hf.mono hxyD) hxy (hf'.mono hxyD'), obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b < (f z - f y) / (z - y), from strict_mono_on.exists_deriv_lt_slope (hf.mono hyzD) hyz (hf'.mono hyzD'), apply ha.trans (lt_trans _ hb), exact hf' (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (hay.trans hyb), end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ` and `f'` is strictly antitone on the interior, then `f` is strictly concave on `D`. Note that we don't require differentiability, since it is guaranteed at all but at most one point by the strict antitonicity of `f'`. -/ lemma strict_anti_on.strict_concave_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (h_anti : strict_anti_on (deriv f) (interior D)) : strict_concave_on ℝ D f := begin have : strict_mono_on (deriv (-f)) (interior D), { intros x hx y hy hxy, convert neg_lt_neg (h_anti hx hy hxy); convert deriv.neg }, exact neg_strict_convex_on_iff.mp (this.strict_convex_on_of_deriv hD hf.neg), end /-- If a function `f` is differentiable and `f'` is monotone on `ℝ` then `f` is convex. -/ theorem monotone.convex_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_mono : monotone (deriv f)) : convex_on ℝ univ f := (hf'_mono.monotone_on _).convex_on_of_deriv convex_univ hf.continuous.continuous_on hf.differentiable_on /-- If a function `f` is differentiable and `f'` is antitone on `ℝ` then `f` is concave. -/ theorem antitone.concave_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_anti : antitone (deriv f)) : concave_on ℝ univ f := (hf'_anti.antitone_on _).concave_on_of_deriv convex_univ hf.continuous.continuous_on hf.differentiable_on /-- If a function `f` is continuous and `f'` is strictly monotone on `ℝ` then `f` is strictly convex. Note that we don't require differentiability, since it is guaranteed at all but at most one point by the strict monotonicity of `f'`. -/ lemma strict_mono.strict_convex_on_univ_of_deriv {f : ℝ → ℝ} (hf : continuous f) (hf'_mono : strict_mono (deriv f)) : strict_convex_on ℝ univ f := (hf'_mono.strict_mono_on _).strict_convex_on_of_deriv convex_univ hf.continuous_on /-- If a function `f` is continuous and `f'` is strictly antitone on `ℝ` then `f` is strictly concave. Note that we don't require differentiability, since it is guaranteed at all but at most one point by the strict antitonicity of `f'`. -/ lemma strict_anti.strict_concave_on_univ_of_deriv {f : ℝ → ℝ} (hf : continuous f) (hf'_anti : strict_anti (deriv f)) : strict_concave_on ℝ univ f := (hf'_anti.strict_anti_on _).strict_concave_on_of_deriv convex_univ hf.continuous_on /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonnegative on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv2_nonneg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonneg : ∀ x ∈ interior D, 0 ≤ (deriv^[2] f x)) : convex_on ℝ D f := (hD.interior.monotone_on_of_deriv_nonneg hf''.continuous_on (by rwa interior_interior) $ by rwa interior_interior).convex_on_of_deriv hD hf hf' /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonpositive on the interior, then `f` is concave on `D`. -/ theorem concave_on_of_deriv2_nonpos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonpos : ∀ x ∈ interior D, deriv^[2] f x ≤ 0) : concave_on ℝ D f := (hD.interior.antitone_on_of_deriv_nonpos hf''.continuous_on (by rwa interior_interior) $ by rwa interior_interior).concave_on_of_deriv hD hf hf' /-- If a function `f` is continuous on a convex set `D ⊆ ℝ` and `f''` is strictly positive on the interior, then `f` is strictly convex on `D`. Note that we don't require twice differentiability explicitly as it is already implied by the second derivative being strictly positive, except at at most one point. -/ lemma strict_convex_on_of_deriv2_pos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf'' : ∀ x ∈ interior D, 0 < (deriv^[2] f) x) : strict_convex_on ℝ D f := (hD.interior.strict_mono_on_of_deriv_pos (λ z hz, (differentiable_at_of_deriv_ne_zero (hf'' z hz).ne').differentiable_within_at .continuous_within_at) $ by rwa interior_interior).strict_convex_on_of_deriv hD hf /-- If a function `f` is continuous on a convex set `D ⊆ ℝ` and `f''` is strictly negative on the interior, then `f` is strictly concave on `D`. Note that we don't require twice differentiability explicitly as it already implied by the second derivative being strictly negative, except at at most one point. -/ lemma strict_concave_on_of_deriv2_neg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf'' : ∀ x ∈ interior D, deriv^[2] f x < 0) : strict_concave_on ℝ D f := (hD.interior.strict_anti_on_of_deriv_neg (λ z hz, (differentiable_at_of_deriv_ne_zero (hf'' z hz).ne).differentiable_within_at .continuous_within_at) $ by rwa interior_interior).strict_concave_on_of_deriv hD hf /-- If a function `f` is twice differentiable on a open convex set `D ⊆ ℝ` and `f''` is nonnegative on `D`, then `f` is convex on `D`. -/ theorem convex_on_of_deriv2_nonneg' {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D) (hf''_nonneg : ∀ x ∈ D, 0 ≤ (deriv^[2] f) x) : convex_on ℝ D f := convex_on_of_deriv2_nonneg hD hf'.continuous_on (hf'.mono interior_subset) (hf''.mono interior_subset) (λ x hx, hf''_nonneg x (interior_subset hx)) /-- If a function `f` is twice differentiable on an open convex set `D ⊆ ℝ` and `f''` is nonpositive on `D`, then `f` is concave on `D`. -/ theorem concave_on_of_deriv2_nonpos' {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D) (hf''_nonpos : ∀ x ∈ D, deriv^[2] f x ≤ 0) : concave_on ℝ D f := concave_on_of_deriv2_nonpos hD hf'.continuous_on (hf'.mono interior_subset) (hf''.mono interior_subset) (λ x hx, hf''_nonpos x (interior_subset hx)) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ` and `f''` is strictly positive on `D`, then `f` is strictly convex on `D`. Note that we don't require twice differentiability explicitly as it is already implied by the second derivative being strictly positive, except at at most one point. -/ lemma strict_convex_on_of_deriv2_pos' {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf'' : ∀ x ∈ D, 0 < (deriv^[2] f) x) : strict_convex_on ℝ D f := strict_convex_on_of_deriv2_pos hD hf $ λ x hx, hf'' x (interior_subset hx) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ` and `f''` is strictly negative on `D`, then `f` is strictly concave on `D`. Note that we don't require twice differentiability explicitly as it is already implied by the second derivative being strictly negative, except at at most one point. -/ lemma strict_concave_on_of_deriv2_neg' {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf'' : ∀ x ∈ D, deriv^[2] f x < 0) : strict_concave_on ℝ D f := strict_concave_on_of_deriv2_neg hD hf $ λ x hx, hf'' x (interior_subset hx) /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonnegative on `ℝ`, then `f` is convex on `ℝ`. -/ theorem convex_on_univ_of_deriv2_nonneg {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonneg : ∀ x, 0 ≤ (deriv^[2] f) x) : convex_on ℝ univ f := convex_on_of_deriv2_nonneg' convex_univ hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonneg x) /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonpositive on `ℝ`, then `f` is concave on `ℝ`. -/ theorem concave_on_univ_of_deriv2_nonpos {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonpos : ∀ x, deriv^[2] f x ≤ 0) : concave_on ℝ univ f := concave_on_of_deriv2_nonpos' convex_univ hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonpos x) /-- If a function `f` is continuous on `ℝ`, and `f''` is strictly positive on `ℝ`, then `f` is strictly convex on `ℝ`. Note that we don't require twice differentiability explicitly as it is already implied by the second derivative being strictly positive, except at at most one point. -/ lemma strict_convex_on_univ_of_deriv2_pos {f : ℝ → ℝ} (hf : continuous f) (hf'' : ∀ x, 0 < (deriv^[2] f) x) : strict_convex_on ℝ univ f := strict_convex_on_of_deriv2_pos' convex_univ hf.continuous_on $ λ x _, hf'' x /-- If a function `f` is continuous on `ℝ`, and `f''` is strictly negative on `ℝ`, then `f` is strictly concave on `ℝ`. Note that we don't require twice differentiability explicitly as it is already implied by the second derivative being strictly negative, except at at most one point. -/ lemma strict_concave_on_univ_of_deriv2_neg {f : ℝ → ℝ} (hf : continuous f) (hf'' : ∀ x, deriv^[2] f x < 0) : strict_concave_on ℝ univ f := strict_concave_on_of_deriv2_neg' convex_univ hf.continuous_on $ λ x _, hf'' x /-! ### Functions `f : E → ℝ` -/ /-- Lagrange's Mean Value Theorem, applied to convex domains. -/ theorem domain_mvt {f : E → ℝ} {s : set E} {x y : E} {f' : E → (E →L[ℝ] ℝ)} (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∃ z ∈ segment ℝ x y, f y - f x = f' z (y - x) := begin have hIccIoo := @Ioo_subset_Icc_self ℝ _ 0 1, -- parametrize segment set g : ℝ → E := λ t, x + t • (y - x), have hseg : ∀ t ∈ Icc (0:ℝ) 1, g t ∈ segment ℝ x y, { rw segment_eq_image', simp only [mem_image, and_imp, add_right_inj], intros t ht, exact ⟨t, ht, rfl⟩ }, have hseg' : Icc 0 1 ⊆ g ⁻¹' s, { rw ← image_subset_iff, unfold image, change ∀ _, _, intros z Hz, rw mem_set_of_eq at Hz, rcases Hz with ⟨t, Ht, hgt⟩, rw ← hgt, exact hs.segment_subset xs ys (hseg t Ht) }, -- derivative of pullback of f under parametrization have hfg: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) ((f' (g t) : E → ℝ) (y-x)) (Icc (0:ℝ) 1) t, { intros t Ht, have hg : has_deriv_at g (y-x) t, { have := ((has_deriv_at_id t).smul_const (y - x)).const_add x, rwa one_smul at this }, exact (hf (g t) $ hseg' Ht).comp_has_deriv_within_at _ hg.has_deriv_within_at hseg' }, -- apply 1-variable mean value theorem to pullback have hMVT : ∃ (t ∈ Ioo (0:ℝ) 1), ((f' (g t) : E → ℝ) (y-x)) = (f (g 1) - f (g 0)) / (1 - 0), { refine exists_has_deriv_at_eq_slope (f ∘ g) _ (by norm_num) _ _, { exact λ t Ht, (hfg t Ht).continuous_within_at }, { exact λ t Ht, (hfg t $ hIccIoo Ht).has_deriv_at (Icc_mem_nhds Ht.1 Ht.2) } }, -- reinterpret on domain rcases hMVT with ⟨t, Ht, hMVT'⟩, use g t, refine ⟨hseg t $ hIccIoo Ht, _⟩, simp [g, hMVT'], end section is_R_or_C /-! ### Vector-valued functions `f : E → F`. Strict differentiability. A `C^1` function is strictly differentiable, when the field is `ℝ` or `ℂ`. This follows from the mean value inequality on balls, which is a particular case of the above results after restricting the scalars to `ℝ`. Note that it does not make sense to talk of a convex set over `ℂ`, but balls make sense and are enough. Many formulations of the mean value inequality could be generalized to balls over `ℝ` or `ℂ`. For now, we only include the ones that we need. -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] {H : Type*} [normed_add_comm_group H] [normed_space 𝕜 H] {f : G → H} {f' : G → G →L[𝕜] H} {x : G} /-- Over the reals or the complexes, a continuously differentiable function is strictly differentiable. -/ lemma has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hder : ∀ᶠ y in 𝓝 x, has_fderiv_at f (f' y) y) (hcont : continuous_at f' x) : has_strict_fderiv_at f (f' x) x := begin -- turn little-o definition of strict_fderiv into an epsilon-delta statement refine is_o_iff.mpr (λ c hc, metric.eventually_nhds_iff_ball.mpr _), -- the correct ε is the modulus of continuity of f' rcases metric.mem_nhds_iff.mp (inter_mem hder (hcont $ ball_mem_nhds _ hc)) with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, _⟩, -- simplify formulas involving the product E × E rintros ⟨a, b⟩ h, rw [← ball_prod_same, prod_mk_mem_set_prod_eq] at h, -- exploit the choice of ε as the modulus of continuity of f' have hf' : ∀ x' ∈ ball x ε, ‖f' x' - f' x‖ ≤ c, { intros x' H', rw ← dist_eq_norm, exact le_of_lt (hε H').2 }, -- apply mean value theorem letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G, refine (convex_ball _ _).norm_image_sub_le_of_norm_has_fderiv_within_le' _ hf' h.2 h.1, exact λ y hy, (hε hy).1.has_fderiv_within_at end /-- Over the reals or the complexes, a continuously differentiable function is strictly differentiable. -/ lemma has_strict_deriv_at_of_has_deriv_at_of_continuous_at {f f' : 𝕜 → G} {x : 𝕜} (hder : ∀ᶠ y in 𝓝 x, has_deriv_at f (f' y) y) (hcont : continuous_at f' x) : has_strict_deriv_at f (f' x) x := has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hder.mono (λ y hy, hy.has_fderiv_at)) $ (smul_rightL 𝕜 𝕜 G 1).continuous.continuous_at.comp hcont end is_R_or_C
d4e1741b16d9c92df20deff8e94128469d6280ed
e9dbaaae490bc072444e3021634bf73664003760
/src/Problems/2013/IMO_2013_P3.lean
54fe8434d4e1b41ae8d28d352a80ebd9c3a80e6f
[ "Apache-2.0" ]
permissive
liaofei1128/geometry
566d8bfe095ce0c0113d36df90635306c60e975b
3dd128e4eec8008764bb94e18b932f9ffd66e6b3
refs/heads/master
1,678,996,510,399
1,581,454,543,000
1,583,337,839,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
416
lean
import Geo.Geo.Core namespace Geo open Triangle def IMO_2013_P3 : Prop := ∀ (A B C A₁ B₁ C₁ : Point), tangentAt (excircles ⟨A, B, C⟩).A (Seg.mk B C) A₁ → tangentAt (excircles ⟨A, B, C⟩).B (Seg.mk A C) B₁ → tangentAt (excircles ⟨A, B, C⟩).C (Seg.mk A B) C₁ → on (circumcenter ⟨A₁, B₁, C₁⟩) (Triangle.circumcircle ⟨A, B, C⟩) → Triangle.isRight ⟨A, B, C⟩ end Geo
b6ed1f42fdc0449c6d0dc8afae27f22a1ce13698
dfd42d30132c2867977fefe7edae98b6dc703aeb
/src/surfaces_we_need.lean
8f04e4bfb8d1ecd44b0dab9dc31cd512ddc5d537
[]
no_license
justadzr/lean-2021
1e42057ac75c794c94b8f148a27a24150c685f68
dfc6b30de2f27bdba5fbc51183e2b84e73a920d1
refs/heads/master
1,689,652,366,522
1,630,313,809,000
1,630,313,809,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,472
lean
--- Will clean up these imports import tactic import analysis.calculus.iterated_deriv import topology.continuous_function.polynomial import topology.separation import analysis.convex.topology import topology.path_connected import analysis.complex.basic import analysis.calculus.tangent_cone import analysis.normed_space.units import analysis.asymptotics.asymptotic_equivalent import analysis.analytic.basic import geometry.manifold.algebra.smooth_functions import linear_algebra.finite_dimensional import analysis.normed_space.inner_product import topology.metric_space.basic import analysis.calculus.formal_multilinear_series import complex_analysis_prep import riemann_surfaces open set complex classical filter asymptotics continuous_linear_map set metric is_open differentiable open_locale topological_space classical nnreal asymptotics filter ennreal unit_interval noncomputable theory def uhalf_plane : set ℂ := {z : ℂ | z.im > 0} localized "notation `ℍ` := uhalf_plane" in uhalf_plane section upper_half_plane @[simp] lemma uhalf_plane.is_open : is_open ℍ := begin have : ℍ = complex.im⁻¹' Ioi 0 := set.ext (λ z, iff.intro (λ hz, mem_preimage.mp hz) $ λ hz, hz), exact is_open.preimage complex.continuous_im is_open_Ioi, end @[simp] lemma uhalf_plane.nonempty : set.nonempty ℍ := begin rw set.nonempty_def, use complex.I, --- Very bad proof here have : complex.I.im > 0 := by rw complex.I_im; exact zero_lt_one, exact this, end @[simp] lemma uhalf_plane.convex : convex ℍ := begin rw convex_iff_forall_pos, intros x y hx hy a b ha hb hab, simp, exact calc (↑a * x + ↑b * y).im = (↑a * x).im + (↑b * y).im : by simp ... = a * x.im + b * y.im : by repeat {rw of_real_mul_im} ... > 0 + b * y.im : add_lt_add_of_lt_of_le (mul_pos ha hx) $ le_refl $ b * y.im ... > 0 + 0 : add_lt_add_of_le_of_lt (le_refl 0) $ mul_pos hb hy ... = 0 : by ring, end lemma uhalf_plane.is_path_connected : is_path_connected ℍ := convex.is_path_connected uhalf_plane.convex uhalf_plane.nonempty @[simp] lemma uhalf_plane.is_connected : is_connected ℍ := (is_open.is_connected_iff_is_path_connected uhalf_plane.is_open).mp uhalf_plane.is_path_connected instance uhalf_plane_connected : connected_space ℍ := is_connected_iff_connected_space.mp uhalf_plane.is_connected instance uhalf_plane_charted : charted_space ℂ ℍ := topological_space.opens.charted_space ⟨ℍ, uhalf_plane.is_open⟩ instance uhalf_plane_riemann_surface : riemann_surface ℍ := topological_space.opens.riemann_surface ⟨ℍ, uhalf_plane.is_open⟩ --- The ℍ here is the coersed subtype ↥ℍ end upper_half_plane section extended_upper_half_plane inductive uhalf_and_cusps | of_complex (z : ℂ) (hz : 0 < z.im) : uhalf_and_cusps | of_rational (r : ℚ) : uhalf_and_cusps | of_infinity : uhalf_and_cusps /- TODO: has_one has_zero has_add has_mul topological_sapce -/ end extended_upper_half_plane section ctorus def clattice {ω : fin 2 → ℂ} (h : linear_independent ℝ ω) : set ℂ := {z : ℂ | ∃ (m n : ℤ), z = (m : ℂ) * (ω 0) + (n : ℂ) * (ω 1)} lemma clattice.add_subgroup {ω : fin 2 → ℂ} (h : linear_independent ℝ ω) : add_subgroup ℂ := { carrier := clattice h, zero_mem' := --- Very bad proof here. WHY is this proof so slow? begin have : ∃ (m n : ℤ), (0 : ℂ) = (m : ℂ) * (ω 0) + (n : ℂ) * (ω 1) := begin repeat {use 0}, rw [int.cast_zero, zero_mul, zero_mul, zero_add], end, exact this, end, add_mem' := begin intros a b ha hb, rcases ha with ⟨na, ma, ha'⟩, rcases hb with ⟨nb, mb, hb'⟩, use (na + nb), use (ma + mb), exact calc a + b = ↑na * ω 0 + ↑ma * ω 1 + (↑nb * ω 0 + ↑mb * ω 1) : by rw [ha', hb'] ... = (↑na + ↑nb) * ω 0 + (↑ma + ↑mb) * ω 1 : by ring ... = ↑(na + nb) * ω 0 + ↑(ma + mb) * ω 1 : by repeat {rw ← int.cast_add}, end, neg_mem' := begin intros z hz, rcases hz with ⟨n, m, hz'⟩, use (-n), use (-m), rw [hz', neg_add], simp only [int.cast_neg, neg_mul_eq_neg_mul], end } def ctorus {ω : fin 2 → ℂ} (h : linear_independent ℝ ω) : Type* := quotient_add_group.quotient (clattice.add_subgroup h) instance {ω : fin 2 → ℂ} (h : linear_independent ℝ ω) : topological_space (ctorus h) := quotient_add_group.quotient.topological_space _ /- TODO: riemann_surface ctorus -/ end ctorus
a6389d1d499e5595b2cd57b39d633be7658dfd60
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/instances/real.lean
61911f3c07c593a3bc29dc202695acfdc3bb1806
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
16,185
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.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring import ring_theory.subring.basic import group_theory.archimedean import algebra.periodic import order.filter.archimedean /-! # Topological properties of ℝ -/ noncomputable theory open classical filter int metric set topological_space open_locale classical topological_space filter uniformity interval universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space namespace rat theorem dist_eq (x y : ℚ) : dist x y = |x - y| := rfl @[norm_cast, simp] lemma dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl theorem uniform_continuous_coe_real : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_coe_real : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_coe_real : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_coe_real.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_coe_real : embedding (coe : ℚ → ℝ) := dense_embedding_coe_real.to_embedding theorem continuous_coe_real : continuous (coe : ℚ → ℝ) := uniform_continuous_coe_real.continuous end rat namespace int instance : has_dist ℤ := ⟨λ x y, dist (x : ℝ) y⟩ theorem dist_eq (x y : ℤ) : dist x y = |x - y| := rfl @[norm_cast, simp] theorem dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast lemma pairwise_one_le_dist : pairwise (λ m n : ℤ, 1 ≤ dist m n) := begin intros m n hne, rw dist_eq, norm_cast, rwa [← zero_add (1 : ℤ), int.add_one_le_iff, abs_pos, sub_ne_zero] end lemma uniform_embedding_coe_rat : uniform_embedding (coe : ℤ → ℚ) := uniform_embedding_bot_of_pairwise_le_dist zero_lt_one $ by simpa using pairwise_one_le_dist lemma closed_embedding_coe_rat : closed_embedding (coe : ℤ → ℚ) := closed_embedding_of_pairwise_le_dist zero_lt_one $ by simpa using pairwise_one_le_dist lemma uniform_embedding_coe_real : uniform_embedding (coe : ℤ → ℝ) := uniform_embedding_bot_of_pairwise_le_dist zero_lt_one pairwise_one_le_dist lemma closed_embedding_coe_real : closed_embedding (coe : ℤ → ℝ) := closed_embedding_of_pairwise_le_dist zero_lt_one pairwise_one_le_dist instance : metric_space ℤ := int.uniform_embedding_coe_real.comap_metric_space _ theorem preimage_ball (x : ℤ) (r : ℝ) : coe ⁻¹' (ball (x : ℝ) r) = ball x r := rfl theorem preimage_closed_ball (x : ℤ) (r : ℝ) : coe ⁻¹' (closed_ball (x : ℝ) r) = closed_ball x r := rfl theorem ball_eq_Ioo (x : ℤ) (r : ℝ) : ball x r = Ioo ⌊↑x - r⌋ ⌈↑x + r⌉ := by rw [← preimage_ball, real.ball_eq_Ioo, preimage_Ioo] theorem closed_ball_eq_Icc (x : ℤ) (r : ℝ) : closed_ball x r = Icc ⌈↑x - r⌉ ⌊↑x + r⌋ := by rw [← preimage_closed_ball, real.closed_ball_eq_Icc, preimage_Icc] instance : proper_space ℤ := ⟨ begin intros x r, rw closed_ball_eq_Icc, exact (set.finite_Icc _ _).is_compact, end ⟩ @[simp] lemma cocompact_eq : cocompact ℤ = at_bot ⊔ at_top := by simp only [← comap_dist_right_at_top_eq_cocompact (0 : ℤ), dist_eq, sub_zero, cast_zero, ← cast_abs, ← @comap_comap _ _ _ _ abs, int.comap_coe_at_top, comap_abs_at_top] instance : noncompact_space ℤ := noncompact_space_of_ne_bot $ by simp [at_top_ne_bot] end int instance : noncompact_space ℚ := int.closed_embedding_coe_rat.noncompact_space instance : noncompact_space ℝ := int.closed_embedding_coe_real.noncompact_space theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := rat.uniform_embedding_coe_real.to_uniform_inducing.uniform_continuous_iff.2 $ by simp only [(∘), rat.cast_add]; exact real.uniform_continuous_add.comp (rat.uniform_continuous_coe_real.prod_map rat.uniform_continuous_coe_real) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) instance : proper_space ℝ := { is_compact_closed_ball := λx r, by { rw real.closed_ball_eq_Icc, apply is_compact_Icc } } instance : second_countable_topology ℝ := second_countable_of_proper lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, ⟨hl, hu⟩, h⟩ := mem_nhds_iff_exists_Ioo_subset.mp (is_open.mem_nhds hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by { simp only [mem_Union], exact ⟨q, p, rat.cast_lt.1 $ hqa.trans hap, rfl⟩ }, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h ⟨hlq.trans hqa', ha'p.trans hpu⟩⟩) @[simp] lemma real.cocompact_eq : cocompact ℝ = at_bot ⊔ at_top := by simp only [← comap_dist_right_at_top_eq_cocompact (0 : ℝ), real.dist_eq, sub_zero, comap_abs_at_top] /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.mem_closure_iff {s : set ℝ} {x : ℝ} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, |y - x| < ε := by simp [mem_closure_iff_nhds_basis nhds_basis_ball, real.dist_eq] lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ |x|) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | |r| / 2 < |x|} (half_pos r0) (λ x h, le_of_lt h)) (is_open.mem_nhds ((is_open_lt' (|r| / 2)).preimage continuous_abs) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases exists_gt (|x|) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, |(x : ℝ × ℝ).1| < r₁ ∧ |x.2| < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | |x| < |a₁| + 1} ×ˢ {x | |x| < |a₂| + 1}) (λ x, id)) (is_open.mem_nhds (((is_open_gt' (|a₁| + 1)).preimage continuous_abs).prod ((is_open_gt' (|a₂| + 1)).preimage continuous_abs )) ⟨lt_add_one (|a₁|), lt_add_one (|a₂|)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := rat.embedding_coe_real.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((rat.continuous_coe_real.prod_map rat.continuous_coe_real)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, metric.cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply totally_bounded_Ioo lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage rat.uniform_embedding_coe_real (totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((is_closed_ge' _).closure_subset_iff.2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw real.closed_ball_eq_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨bdd_below_Icc.mono hr, bdd_above_Icc.mono hr⟩ end, λ h, bounded_of_bdd_above_of_bdd_below h.2 h.1⟩ lemma real.subset_Icc_Inf_Sup_of_bounded {s : set ℝ} (h : bounded s) : s ⊆ Icc (Inf s) (Sup s) := subset_Icc_cInf_cSup (real.bounded_iff_bdd_below_bdd_above.1 h).1 (real.bounded_iff_bdd_below_bdd_above.1 h).2 end section periodic namespace function lemma periodic.compact_of_continuous' [topological_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : 0 < c) (hf : continuous f) : is_compact (range f) := begin convert is_compact_Icc.image hf, ext x, refine ⟨_, mem_range_of_mem_image f (Icc 0 c)⟩, rintros ⟨y, h1⟩, obtain ⟨z, hz, h2⟩ := hp.exists_mem_Ico₀ hc y, exact ⟨z, mem_Icc_of_Ico hz, h2.symm.trans h1⟩, end /-- A continuous, periodic function has compact range. -/ lemma periodic.compact_of_continuous [topological_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) : is_compact (range f) := begin cases lt_or_gt_of_ne hc with hneg hpos, exacts [hp.neg.compact_of_continuous' (neg_pos.mpr hneg) hf, hp.compact_of_continuous' hpos hf], end /-- A continuous, periodic function is bounded. -/ lemma periodic.bounded_of_continuous [pseudo_metric_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) : bounded (range f) := (hp.compact_of_continuous hc hf).bounded end function end periodic section subgroups /-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/ lemma real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0) (H' : ¬ ∃ a : ℝ, is_least {g : ℝ | g ∈ G ∧ 0 < g} a) : dense (G : set ℝ) := begin let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, push_neg at H', intros x, suffices : ∀ ε > (0 : ℝ), ∃ g ∈ G, |x - g| < ε, by simpa only [real.mem_closure_iff, abs_sub_comm], intros ε ε_pos, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℝ, g₁ ∈ G ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, G.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha⟩ : ∃ a, is_glb G_pos a := ⟨Inf G_pos, is_glb_cInf ⟨g₁, g₁_in, g₁_pos⟩ ⟨0, λ _ hx, le_of_lt hx.2⟩⟩, have a_notin : a ∉ G_pos, { intros H, exact H' a ⟨H, ha.1⟩ }, obtain ⟨g₂, g₂_in, g₂_pos, g₂_lt⟩ : ∃ g₂ : ℝ, g₂ ∈ G ∧ 0 < g₂ ∧ g₂ < ε, { obtain ⟨b, hb, hb', hb''⟩ := ha.exists_between_self_add' a_notin ε_pos, obtain ⟨c, hc, hc', hc''⟩ := ha.exists_between_self_add' a_notin (sub_pos.2 hb'), refine ⟨b - c, G.sub_mem hb.1 hc.1, _, _⟩ ; linarith }, refine ⟨floor (x/g₂) * g₂, _, _⟩, { exact add_subgroup.int_mul_mem _ g₂_in }, { rw abs_of_nonneg (sub_floor_div_mul_nonneg x g₂_pos), linarith [sub_floor_div_mul_lt x g₂_pos] } end /-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and `subgroup_cyclic_of_min` for more precise statements. -/ lemma real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) : dense (G : set ℝ) ∨ ∃ a : ℝ, G = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero G with H H, { right, use 0, rw [H, add_subgroup.closure_singleton_zero] }, { let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, by_cases H' : ∃ a, is_least G_pos a, { right, rcases H' with ⟨a, ha⟩, exact ⟨a, add_subgroup.cyclic_of_min ha⟩ }, { left, rcases H with ⟨g₀, g₀_in, g₀_ne⟩, exact real.subgroup_dense_of_no_min g₀_in g₀_ne H' } } end end subgroups
d07d0289a9229482ad725d5e8cb62b41485d7187
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/data/nat/power.lean
e794585f566e08e43f4a96879b3b2f067517326d
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,240
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad The power function on the natural numbers. -/ import data.nat.basic data.nat.order data.nat.div data.nat.gcd algebra.ring_power namespace nat section migrate_algebra open [classes] algebra local attribute nat.comm_semiring [instance] local attribute nat.decidable_linear_ordered_semiring [instance] definition pow (a : ℕ) (n : ℕ) : ℕ := algebra.pow a n infix ^ := pow theorem pow_le_pow_of_le {x y : ℕ} (i : ℕ) (H : x ≤ y) : x^i ≤ y^i := algebra.pow_le_pow_of_le i !zero_le H migrate from algebra with nat replacing dvd → dvd, has_le.ge → ge, has_lt.gt → gt, pow → pow hiding add_pos_of_pos_of_nonneg, add_pos_of_nonneg_of_pos, add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg, le_add_of_nonneg_of_le, le_add_of_le_of_nonneg, lt_add_of_nonneg_of_lt, lt_add_of_lt_of_nonneg, lt_of_mul_lt_mul_left, lt_of_mul_lt_mul_right, pos_of_mul_pos_left, pos_of_mul_pos_right, pow_nonneg_of_nonneg end migrate_algebra theorem eq_zero_of_pow_eq_zero {a m : ℕ} (H : a^m = 0) : a = 0 := or.elim (eq_zero_or_pos m) (suppose m = 0, by rewrite [`m = 0` at H, pow_zero at H]; contradiction) (suppose m > 0, have h₁ : ∀ m, a^succ m = 0 → a = 0, begin intro m, induction m with m ih, {rewrite pow_one; intros; assumption}, rewrite pow_succ, intro H, cases eq_zero_or_eq_zero_of_mul_eq_zero H with h₃ h₄, assumption, exact ih h₄ end, obtain m' (h₂ : m = succ m'), from exists_eq_succ_of_pos `m > 0`, show a = 0, by rewrite h₂ at H; apply h₁ m' H) -- generalize to semirings? theorem le_pow_self {x : ℕ} (H : x > 1) : ∀ i, i ≤ x^i | 0 := !zero_le | (succ j) := have x > 0, from lt.trans zero_lt_one H, have x^j ≥ 1, from succ_le_of_lt (pow_pos_of_pos _ this), have x ≥ 2, from succ_le_of_lt H, calc succ j = j + 1 : rfl ... ≤ x^j + 1 : add_le_add_right (le_pow_self j) ... ≤ x^j + x^j : add_le_add_left `x^j ≥ 1` ... = x^j * (1 + 1) : by rewrite [mul.left_distrib, *mul_one] ... = x^j * 2 : rfl ... ≤ x^j * x : mul_le_mul_left _ `x ≥ 2` ... = x^(succ j) : pow_succ' -- TODO: eventually this will be subsumed under the algebraic theorems theorem mul_self_eq_pow_2 (a : nat) : a * a = pow a 2 := show a * a = pow a (succ (succ zero)), from by rewrite [*pow_succ, *pow_zero, mul_one] theorem pow_cancel_left : ∀ {a b c : nat}, a > 1 → pow a b = pow a c → b = c | a 0 0 h₁ h₂ := rfl | a (succ b) 0 h₁ h₂ := assert a = 1, by rewrite [pow_succ at h₂, pow_zero at h₂]; exact (eq_one_of_mul_eq_one_right h₂), assert 1 < 1, by rewrite [this at h₁]; exact h₁, absurd `1 < 1` !lt.irrefl | a 0 (succ c) h₁ h₂ := assert a = 1, by rewrite [pow_succ at h₂, pow_zero at h₂]; exact (eq_one_of_mul_eq_one_right (eq.symm h₂)), assert 1 < 1, by rewrite [this at h₁]; exact h₁, absurd `1 < 1` !lt.irrefl | a (succ b) (succ c) h₁ h₂ := assert a ≠ 0, from assume aeq0, by rewrite [aeq0 at h₁]; exact (absurd h₁ dec_trivial), assert pow a b = pow a c, by rewrite [*pow_succ at h₂]; exact (eq_of_mul_eq_mul_left (pos_of_ne_zero this) h₂), by rewrite [pow_cancel_left h₁ this] theorem pow_div_cancel : ∀ {a b : nat}, a ≠ 0 → pow a (succ b) div a = pow a b | a 0 h := by rewrite [pow_succ, pow_zero, mul_one, div_self (pos_of_ne_zero h)] | a (succ b) h := by rewrite [pow_succ, mul_div_cancel_left _ (pos_of_ne_zero h)] lemma dvd_pow : ∀ (i : nat) {n : nat}, n > 0 → i ∣ i^n | i 0 h := absurd h !lt.irrefl | i (succ n) h := by rewrite [pow_succ']; apply dvd_mul_left lemma dvd_pow_of_dvd_of_pos : ∀ {i j n : nat}, i ∣ j → n > 0 → i ∣ j^n | i j 0 h₁ h₂ := absurd h₂ !lt.irrefl | i j (succ n) h₁ h₂ := by rewrite [pow_succ']; apply dvd_mul_of_dvd_right h₁ lemma pow_mod_eq_zero (i : nat) {n : nat} (h : n > 0) : (i^n) mod i = 0 := iff.mp !dvd_iff_mod_eq_zero (dvd_pow i h) lemma pow_dvd_of_pow_succ_dvd {p i n : nat} : p^(succ i) ∣ n → p^i ∣ n := suppose p^(succ i) ∣ n, assert p^i ∣ p^(succ i), from by rewrite [pow_succ']; apply dvd_of_eq_mul; apply rfl, dvd.trans `p^i ∣ p^(succ i)` `p^(succ i) ∣ n` lemma dvd_of_pow_succ_dvd_mul_pow {p i n : nat} (Ppos : p > 0) : p^(succ i) ∣ (n * p^i) → p ∣ n := by rewrite [pow_succ]; apply dvd_of_mul_dvd_mul_right; apply pow_pos_of_pos _ Ppos lemma coprime_pow_right {a b} : ∀ n, coprime b a → coprime b (a^n) | 0 h := !comprime_one_right | (succ n) h := begin rewrite [pow_succ'], apply coprime_mul_right, exact coprime_pow_right n h, exact h end lemma coprime_pow_left {a b} : ∀ n, coprime b a → coprime (b^n) a := take n, suppose coprime b a, coprime_swap (coprime_pow_right n (coprime_swap this)) end nat
8c70ce0c8a56798e68b7883bda3fff49c598a0d8
a9fe717b93ccfa4b2e64faeb24f96dfefb390240
/int/rev.lean
4b735cded281ac67ebb5abd69272bc215192b1e2
[]
no_license
skbaek/omega
ab1f4a6daadfc8c855f14c39d9459ab841527141
715e384ed14e8eb177a326700066e7c98269e078
refs/heads/master
1,588,000,876,352
1,552,645,917,000
1,552,645,917,000
174,442,914
1
0
null
null
null
null
UTF-8
Lean
false
false
648
lean
import ..tactic open tactic namespace int meta def is_form_aux : expr → bool | `(¬ %% p) := is_form_aux p | `(%% p ∨ %%q) := is_form_aux p && is_form_aux q | `(%% p ∧ %%q) := is_form_aux p && is_form_aux q | `(@eq int _ _) := true | `(@has_le.le int _ _ _) := true | _ := false meta def is_form (x : expr) : tactic bool := do tx ← infer_type x, return $ is_form_aux tx meta def is_term (x : expr) : tactic bool := do tx ← infer_type x, return $ `(int).to_expr = tx meta def rev : tactic unit := do revert_cond_all is_form, revert_cond_all is_term end int
f4e2b19fac7cd9b3116d23be38afb454036f9945
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1892.lean
d273225f9551a74a1b316a5faf6fabb2495b8f9c
[ "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
311
lean
def OrderDual (α : Type u) : Type u := α variable (α : Type u) [LE α] {a b : α} instance : LE (OrderDual α) := ⟨fun x y : α => y ≤ x⟩ theorem foo' (c : α) : a ≤ b := sorry example : a ≤ b := foo' (OrderDual α) a theorem foo : a ≤ b := sorry example : a ≤ b := foo (OrderDual α)
74f6878cfe0aa82e98b81a9eff78e76dac505116
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/fixed.lean
eb7d527720fe8d2c4b1088aaf8c2fce9b0ab5a53
[ "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
14,527
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.group_ring_action.invariant import algebra.polynomial.group_ring_action import field_theory.normal import field_theory.separable import field_theory.tower /-! # Fixed field under a group action. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This is the basis of the Fundamental Theorem of Galois Theory. Given a (finite) group `G` that acts on a field `F`, we define `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`. This subfield is then normal and separable, and in addition (TODO) if `G` acts faithfully on `F` then `finrank (fixed_points G F) F = fintype.card G`. ## Main Definitions - `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`, where `G` is a group that acts on `F`. -/ noncomputable theory open_locale classical big_operators open mul_action finset finite_dimensional universes u v w variables {M : Type u} [monoid M] variables (G : Type u) [group G] variables (F : Type v) [field F] [mul_semiring_action M F] [mul_semiring_action G F] (m : M) /-- The subfield of F fixed by the field endomorphism `m`. -/ def fixed_by.subfield : subfield F := { carrier := fixed_by M F m, zero_mem' := smul_zero m, add_mem' := λ x y hx hy, (smul_add m x y).trans $ congr_arg2 _ hx hy, neg_mem' := λ x hx, (smul_neg m x).trans $ congr_arg _ hx, one_mem' := smul_one m, mul_mem' := λ x y hx hy, (smul_mul' m x y).trans $ congr_arg2 _ hx hy, inv_mem' := λ x hx, (smul_inv'' m x).trans $ congr_arg _ hx } section invariant_subfields variables (M) {F} /-- A typeclass for subrings invariant under a `mul_semiring_action`. -/ class is_invariant_subfield (S : subfield F) : Prop := (smul_mem : ∀ (m : M) {x : F}, x ∈ S → m • x ∈ S) variable (S : subfield F) instance is_invariant_subfield.to_mul_semiring_action [is_invariant_subfield M S] : mul_semiring_action M S := { smul := λ m x, ⟨m • x, is_invariant_subfield.smul_mem m x.2⟩, one_smul := λ s, subtype.eq $ one_smul M s, mul_smul := λ m₁ m₂ s, subtype.eq $ mul_smul m₁ m₂ s, smul_add := λ m s₁ s₂, subtype.eq $ smul_add m s₁ s₂, smul_zero := λ m, subtype.eq $ smul_zero m, smul_one := λ m, subtype.eq $ smul_one m, smul_mul := λ m s₁ s₂, subtype.eq $ smul_mul' m s₁ s₂ } instance [is_invariant_subfield M S] : is_invariant_subring M (S.to_subring) := { smul_mem := is_invariant_subfield.smul_mem } end invariant_subfields namespace fixed_points variable (M) -- we use `subfield.copy` so that the underlying set is `fixed_points M F` /-- The subfield of fixed points by a monoid action. -/ def subfield : subfield F := subfield.copy (⨅ (m : M), fixed_by.subfield F m) (fixed_points M F) (by { ext z, simp [fixed_points, fixed_by.subfield, infi, subfield.mem_Inf] }) instance : is_invariant_subfield M (fixed_points.subfield M F) := { smul_mem := λ g x hx g', by rw [hx, hx] } instance : smul_comm_class M (fixed_points.subfield M F) F := { smul_comm := λ m f f', show m • (↑f * f') = f * (m • f'), by rw [smul_mul', f.prop m] } instance smul_comm_class' : smul_comm_class (fixed_points.subfield M F) M F := smul_comm_class.symm _ _ _ @[simp] theorem smul (m : M) (x : fixed_points.subfield M F) : m • x = x := subtype.eq $ x.2 m -- Why is this so slow? @[simp] theorem smul_polynomial (m : M) (p : polynomial (fixed_points.subfield M F)) : m • p = p := polynomial.induction_on p (λ x, by rw [polynomial.smul_C, smul]) (λ p q ihp ihq, by rw [smul_add, ihp, ihq]) (λ n x ih, by rw [smul_mul', polynomial.smul_C, smul, smul_pow', polynomial.smul_X]) instance : algebra (fixed_points.subfield M F) F := by apply_instance theorem coe_algebra_map : algebra_map (fixed_points.subfield M F) F = subfield.subtype (fixed_points.subfield M F) := rfl lemma linear_independent_smul_of_linear_independent {s : finset F} : linear_independent (fixed_points.subfield G F) (λ i : (s : set F), (i : F)) → linear_independent F (λ i : (s : set F), mul_action.to_fun G F i) := begin haveI : is_empty ((∅ : finset F) : set F) := ⟨subtype.prop⟩, refine finset.induction_on s (λ _, linear_independent_empty_type) (λ a s has ih hs, _), rw coe_insert at hs ⊢, rw linear_independent_insert (mt mem_coe.1 has) at hs, rw linear_independent_insert' (mt mem_coe.1 has), refine ⟨ih hs.1, λ ha, _⟩, rw finsupp.mem_span_image_iff_total at ha, rcases ha with ⟨l, hl, hla⟩, rw [finsupp.total_apply_of_mem_supported F hl] at hla, suffices : ∀ i ∈ s, l i ∈ fixed_points.subfield G F, { replace hla := (sum_apply _ _ (λ i, l i • to_fun G F i)).symm.trans (congr_fun hla 1), simp_rw [pi.smul_apply, to_fun_apply, one_smul] at hla, refine hs.2 (hla ▸ submodule.sum_mem _ (λ c hcs, _)), change (⟨l c, this c hcs⟩ : fixed_points.subfield G F) • c ∈ _, exact submodule.smul_mem _ _ (submodule.subset_span $ mem_coe.2 hcs) }, intros i his g, refine eq_of_sub_eq_zero (linear_independent_iff'.1 (ih hs.1) s.attach (λ i, g • l i - l i) _ ⟨i, his⟩ (mem_attach _ _) : _), refine (@sum_attach _ _ s _ (λ i, (g • l i - l i) • mul_action.to_fun G F i)).trans _, ext g', dsimp only, conv_lhs { rw sum_apply, congr, skip, funext, rw [pi.smul_apply, sub_smul, smul_eq_mul] }, rw [sum_sub_distrib, pi.zero_apply, sub_eq_zero], conv_lhs { congr, skip, funext, rw [to_fun_apply, ← mul_inv_cancel_left g g', mul_smul, ← smul_mul', ← to_fun_apply _ x] }, show ∑ x in s, g • (λ y, l y • mul_action.to_fun G F y) x (g⁻¹ * g') = ∑ x in s, (λ y, l y • mul_action.to_fun G F y) x g', rw [← smul_sum, ← sum_apply _ _ (λ y, l y • to_fun G F y), ← sum_apply _ _ (λ y, l y • to_fun G F y)], dsimp only, rw [hla, to_fun_apply, to_fun_apply, smul_smul, mul_inv_cancel_left] end section fintype variables [fintype G] (x : F) /-- `minpoly G F x` is the minimal polynomial of `(x : F)` over `fixed_points G F`. -/ def minpoly : polynomial (fixed_points.subfield G F) := (prod_X_sub_smul G F x).to_subring (fixed_points.subfield G F).to_subring $ λ c hc g, let ⟨n, hc0, hn⟩ := polynomial.mem_frange_iff.1 hc in hn.symm ▸ prod_X_sub_smul.coeff G F x g n namespace minpoly theorem monic : (minpoly G F x).monic := by { simp only [minpoly, polynomial.monic_to_subring], exact prod_X_sub_smul.monic G F x } theorem eval₂ : polynomial.eval₂ (subring.subtype $ (fixed_points.subfield G F).to_subring) x (minpoly G F x) = 0 := begin rw [← prod_X_sub_smul.eval G F x, polynomial.eval₂_eq_eval_map], simp only [minpoly, polynomial.map_to_subring], end theorem eval₂' : polynomial.eval₂ (subfield.subtype $ (fixed_points.subfield G F)) x (minpoly G F x) = 0 := eval₂ G F x theorem ne_one : minpoly G F x ≠ (1 : polynomial (fixed_points.subfield G F)) := λ H, have _ := eval₂ G F x, (one_ne_zero : (1 : F) ≠ 0) $ by rwa [H, polynomial.eval₂_one] at this theorem of_eval₂ (f : polynomial (fixed_points.subfield G F)) (hf : polynomial.eval₂ (subfield.subtype $ fixed_points.subfield G F) x f = 0) : minpoly G F x ∣ f := begin erw [← polynomial.map_dvd_map' (subfield.subtype $ fixed_points.subfield G F), minpoly, polynomial.map_to_subring _ (subfield G F).to_subring, prod_X_sub_smul], refine fintype.prod_dvd_of_coprime (polynomial.pairwise_coprime_X_sub_C $ mul_action.injective_of_quotient_stabilizer G x) (λ y, quotient_group.induction_on y $ λ g, _), rw [polynomial.dvd_iff_is_root, polynomial.is_root.def, mul_action.of_quotient_stabilizer_mk, polynomial.eval_smul', ← subfield.to_subring.subtype_eq_subtype, ← is_invariant_subring.coe_subtype_hom' G (fixed_points.subfield G F).to_subring, ← mul_semiring_action_hom.coe_polynomial, ← mul_semiring_action_hom.map_smul, smul_polynomial, mul_semiring_action_hom.coe_polynomial, is_invariant_subring.coe_subtype_hom', polynomial.eval_map, subfield.to_subring.subtype_eq_subtype, hf, smul_zero] end /- Why is this so slow? -/ theorem irreducible_aux (f g : polynomial (fixed_points.subfield G F)) (hf : f.monic) (hg : g.monic) (hfg : f * g = minpoly G F x) : f = 1 ∨ g = 1 := begin have hf2 : f ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_right _ _ }, have hg2 : g ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_left _ _ }, have := eval₂ G F x, rw [← hfg, polynomial.eval₂_mul, mul_eq_zero] at this, cases this, { right, have hf3 : f = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hf (monic G F x) (associated_of_dvd_dvd hf2 $ @of_eval₂ G _ F _ _ _ x f this) }, rwa [← mul_one (minpoly G F x), hf3, mul_right_inj' (monic G F x).ne_zero] at hfg }, { left, have hg3 : g = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hg (monic G F x) (associated_of_dvd_dvd hg2 $ @of_eval₂ G _ F _ _ _ x g this) }, rwa [← one_mul (minpoly G F x), hg3, mul_left_inj' (monic G F x).ne_zero] at hfg } end theorem irreducible : irreducible (minpoly G F x) := (polynomial.irreducible_of_monic (monic G F x) (ne_one G F x)).2 (irreducible_aux G F x) end minpoly end fintype theorem is_integral [finite G] (x : F) : is_integral (fixed_points.subfield G F) x := by { casesI nonempty_fintype G, exact ⟨minpoly G F x, minpoly.monic G F x, minpoly.eval₂ G F x⟩ } section fintype variables [fintype G] (x : F) theorem minpoly_eq_minpoly : minpoly G F x = _root_.minpoly (fixed_points.subfield G F) x := minpoly.eq_of_irreducible_of_monic (minpoly.irreducible G F x) (minpoly.eval₂ G F x) (minpoly.monic G F x) lemma rank_le_card : module.rank (fixed_points.subfield G F) F ≤ fintype.card G := rank_le $ λ s hs, by simpa only [rank_fun', cardinal.mk_coe_finset, finset.coe_sort_coe, cardinal.lift_nat_cast, cardinal.nat_cast_le] using cardinal_lift_le_rank_of_linear_independent' (linear_independent_smul_of_linear_independent G F hs) end fintype section finite variables [finite G] instance normal : normal (fixed_points.subfield G F) F := ⟨λ x, (is_integral G F x).is_algebraic _, λ x, (polynomial.splits_id_iff_splits _).1 $ begin casesI nonempty_fintype G, rw [←minpoly_eq_minpoly, minpoly, coe_algebra_map, ←subfield.to_subring.subtype_eq_subtype, polynomial.map_to_subring _ (subfield G F).to_subring, prod_X_sub_smul], exact polynomial.splits_prod _ (λ _ _, polynomial.splits_X_sub_C _), end⟩ instance separable : is_separable (fixed_points.subfield G F) F := ⟨is_integral G F, λ x, by { casesI nonempty_fintype G, -- this was a plain rw when we were using unbundled subrings erw [← minpoly_eq_minpoly, ← polynomial.separable_map (fixed_points.subfield G F).subtype, minpoly, polynomial.map_to_subring _ ((subfield G F).to_subring) ], exact polynomial.separable_prod_X_sub_C_iff.2 (injective_of_quotient_stabilizer G x) }⟩ instance : finite_dimensional (subfield G F) F := by { casesI nonempty_fintype G, exact is_noetherian.iff_fg.1 (is_noetherian.iff_rank_lt_aleph_0.2 $ (rank_le_card G F).trans_lt $ cardinal.nat_lt_aleph_0 _) } end finite lemma finrank_le_card [fintype G] : finrank (subfield G F) F ≤ fintype.card G := begin rw [← cardinal.nat_cast_le, finrank_eq_rank], apply rank_le_card, end end fixed_points lemma linear_independent_to_linear_map (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [ring A] [algebra R A] [comm_ring B] [is_domain B] [algebra R B] : linear_independent B (alg_hom.to_linear_map : (A →ₐ[R] B) → (A →ₗ[R] B)) := have linear_independent B (linear_map.lto_fun R A B ∘ alg_hom.to_linear_map), from ((linear_independent_monoid_hom A B).comp (coe : (A →ₐ[R] B) → (A →* B)) (λ f g hfg, alg_hom.ext $ monoid_hom.ext_iff.1 hfg) : _), this.of_comp _ lemma cardinal_mk_alg_hom (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : cardinal.mk (V →ₐ[K] W) ≤ finrank W (V →ₗ[K] W) := cardinal_mk_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V W noncomputable instance alg_equiv.fintype (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype (V ≃ₐ[K] V) := fintype.of_equiv (V →ₐ[K] V) (alg_equiv_equiv_alg_hom K V).symm lemma finrank_alg_hom (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype.card (V →ₐ[K] V) ≤ finrank V (V →ₗ[K] V) := fintype_card_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V V namespace fixed_points theorem finrank_eq_card (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_smul G F] : finrank (fixed_points.subfield G F) F = fintype.card G := le_antisymm (fixed_points.finrank_le_card G F) $ calc fintype.card G ≤ fintype.card (F →ₐ[fixed_points.subfield G F] F) : fintype.card_le_of_injective _ (mul_semiring_action.to_alg_hom_injective _ F) ... ≤ finrank F (F →ₗ[fixed_points.subfield G F] F) : finrank_alg_hom (fixed_points G F) F ... = finrank (fixed_points.subfield G F) F : finrank_linear_map' _ _ _ /-- `mul_semiring_action.to_alg_hom` is bijective. -/ theorem to_alg_hom_bijective (G : Type u) (F : Type v) [group G] [field F] [finite G] [mul_semiring_action G F] [has_faithful_smul G F] : function.bijective (mul_semiring_action.to_alg_hom _ _ : G → F →ₐ[subfield G F] F) := begin casesI nonempty_fintype G, rw fintype.bijective_iff_injective_and_card, split, { exact mul_semiring_action.to_alg_hom_injective _ F }, { apply le_antisymm, { exact fintype.card_le_of_injective _ (mul_semiring_action.to_alg_hom_injective _ F) }, { rw ← finrank_eq_card G F, exact has_le.le.trans_eq (finrank_alg_hom _ F) (finrank_linear_map' _ _ _) } }, end /-- Bijection between G and algebra homomorphisms that fix the fixed points -/ def to_alg_hom_equiv (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_smul G F] : G ≃ (F →ₐ[fixed_points.subfield G F] F) := equiv.of_bijective _ (to_alg_hom_bijective G F) end fixed_points
9882743323b8840b694efbb18b922c71c80cdcd1
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/prod.lean
6bba37101a3868660e362f29aa22aa748aec5960
[ "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
2,925
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 theory on products -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} @[simp] theorem prod.forall {p : α × β → Prop} : (∀ x, p x) ↔ (∀ a b, p (a, b)) := ⟨assume h a b, h (a, b), assume h ⟨a, b⟩, h a b⟩ @[simp] theorem prod.exists {p : α × β → Prop} : (∃ x, p x) ↔ (∃ a b, p (a, b)) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ namespace prod attribute [simp] prod.map @[simp] lemma map_fst (f : α → γ) (g : β → δ) : ∀(p : α × β), (map f g p).1 = f (p.1) | ⟨a, b⟩ := rfl @[simp] lemma map_snd (f : α → γ) (g : β → δ) : ∀(p : α × β), (map f g p).2 = g (p.2) | ⟨a, b⟩ := rfl @[simp] theorem mk.inj_iff {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ (a₁ = a₂ ∧ b₁ = b₂) := ⟨prod.mk.inj, by cc⟩ lemma ext_iff {p q : α × β} : p = q ↔ p.1 = q.1 ∧ p.2 = q.2 := by rw [← @mk.eta _ _ p, ← @mk.eta _ _ q, mk.inj_iff] lemma ext {α β} {p q : α × β} (h₁ : p.1 = q.1) (h₂ : p.2 = q.2) : p = q := ext_iff.2 ⟨h₁, h₂⟩ lemma map_def {f : α → γ} {g : β → δ} : prod.map f g = λ (p : α × β), (f p.1, g p.2) := funext (λ p, ext (map_fst f g p) (map_snd f g p)) lemma id_prod : (λ (p : α × α), (p.1, p.2)) = id := funext $ λ ⟨a, b⟩, rfl /-- Swap the factors of a product. `swap (a, b) = (b, a)` -/ def swap : α × β → β × α := λp, (p.2, p.1) @[simp] lemma swap_swap : ∀ x : α × β, swap (swap x) = x | ⟨a, b⟩ := rfl @[simp] lemma fst_swap {p : α × β} : (swap p).1 = p.2 := rfl @[simp] lemma snd_swap {p : α × β} : (swap p).2 = p.1 := rfl @[simp] lemma swap_prod_mk {a : α} {b : β} : swap (a, b) = (b, a) := rfl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (α × β) := funext swap_swap @[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap := swap_swap @[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap := swap_swap lemma eq_iff_fst_eq_snd_eq : ∀{p q : α × β}, p = q ↔ (p.1 = q.1 ∧ p.2 = q.2) | ⟨p₁, p₂⟩ ⟨q₁, q₂⟩ := by simp theorem lex_def (r : α → α → Prop) (s : β → β → Prop) {p q : α × β} : prod.lex r s p q ↔ r p.1 q.1 ∨ p.1 = q.1 ∧ s p.2 q.2 := ⟨λ h, by cases h; simp *, λ h, match p, q, h with | (a, b), (c, d), or.inl h := lex.left _ _ _ h | (a, b), (c, d), or.inr ⟨e, h⟩ := by change a = c at e; subst e; exact lex.right _ _ h end⟩ instance lex.decidable [decidable_eq α] [decidable_eq β] (r : α → α → Prop) (s : β → β → Prop) [decidable_rel r] [decidable_rel s] : decidable_rel (prod.lex r s) := λ p q, decidable_of_decidable_of_iff (by apply_instance) (lex_def r s).symm end prod
fb64e5f30ba2b574351f039b32e0701c5b8a2f1c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/transform_decl_auto.lean
cdaa3e6a5d78006edaf901e24e27b713aabf1040
[]
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
339
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.meta.expr import Mathlib.meta.rb_map import Mathlib.PostPort namespace Mathlib namespace tactic end Mathlib
9bf0bd0f24aadb65d2a4735134ca8bdbb361dafd
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/sites/pretopology.lean
b8d0f9f3fa741350e98c95ba062dac422f510a27
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,481
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.sites.grothendieck /-! # Grothendieck pretopologies Definition and lemmas about Grothendieck pretopologies. A Grothendieck pretopology for a category `C` is a set of families of morphisms with fixed codomain, satisfying certain closure conditions. We show that a pretopology generates a genuine Grothendieck topology, and every topology has a maximal pretopology which generates it. The pretopology associated to a topological space is defined in `spaces.lean`. ## Tags coverage, pretopology, site ## References * [nLab, *Grothendieck pretopology*](https://ncatlab.org/nlab/show/Grothendieck+pretopology) * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] * [Stacks, *00VG*](https://stacks.math.columbia.edu/tag/00VG) -/ universes v u noncomputable theory namespace category_theory open category_theory category limits presieve variables {C : Type u} [category.{v} C] [has_pullbacks C] variables (C) /-- A (Grothendieck) pretopology on `C` consists of a collection of families of morphisms with a fixed target `X` for every object `X` in `C`, called "coverings" of `X`, which satisfies the following three axioms: 1. Every family consisting of a single isomorphism is a covering family. 2. The collection of covering families is stable under pullback. 3. Given a covering family, and a covering family on each domain of the former, the composition is a covering family. In some sense, a pretopology can be seen as Grothendieck topology with weaker saturation conditions, in that each covering is not necessarily downward closed. See: https://ncatlab.org/nlab/show/Grothendieck+pretopology, or https://stacks.math.columbia.edu/tag/00VH, or [MM92] Chapter III, Section 2, Definition 2. Note that Stacks calls a category together with a pretopology a site, and [MM92] calls this a basis for a topology. -/ @[ext] structure pretopology := (coverings : Π (X : C), set (presieve X)) (has_isos : ∀ ⦃X Y⦄ (f : Y ⟶ X) [is_iso f], presieve.singleton f ∈ coverings X) (pullbacks : ∀ ⦃X Y⦄ (f : Y ⟶ X) S, S ∈ coverings X → pullback_arrows f S ∈ coverings Y) (transitive : ∀ ⦃X : C⦄ (S : presieve X) (Ti : Π ⦃Y⦄ (f : Y ⟶ X), S f → presieve Y), S ∈ coverings X → (∀ ⦃Y⦄ f (H : S f), Ti f H ∈ coverings Y) → S.bind Ti ∈ coverings X) namespace pretopology instance : has_coe_to_fun (pretopology C) (λ _, Π X : C, set (presieve X)) := ⟨coverings⟩ variable {C} instance : has_le (pretopology C) := { le := λ K₁ K₂, (K₁ : Π (X : C), set (presieve X)) ≤ K₂ } lemma le_def {K₁ K₂ : pretopology C} : K₁ ≤ K₂ ↔ (K₁ : Π (X : C), set (presieve X)) ≤ K₂ := iff.rfl variable (C) instance : partial_order (pretopology C) := { le_refl := λ K, le_def.mpr le_rfl, le_trans := λ K₁ K₂ K₃ h₁₂ h₂₃, le_def.mpr (le_trans h₁₂ h₂₃), le_antisymm := λ K₁ K₂ h₁₂ h₂₁, pretopology.ext _ _ (le_antisymm h₁₂ h₂₁), ..pretopology.has_le } instance : order_top (pretopology C) := { top := { coverings := λ _, set.univ, has_isos := λ _ _ _ _, set.mem_univ _, pullbacks := λ _ _ _ _ _, set.mem_univ _, transitive := λ _ _ _ _ _, set.mem_univ _ }, le_top := λ K X S hS, set.mem_univ _ } instance : inhabited (pretopology C) := ⟨⊤⟩ /-- A pretopology `K` can be completed to a Grothendieck topology `J` by declaring a sieve to be `J`-covering if it contains a family in `K`. See <https://stacks.math.columbia.edu/tag/00ZC>, or [MM92] Chapter III, Section 2, Equation (2). -/ def to_grothendieck (K : pretopology C) : grothendieck_topology C := { sieves := λ X S, ∃ R ∈ K X, R ≤ (S : presieve _), top_mem' := λ X, ⟨presieve.singleton (𝟙 _), K.has_isos _, λ _ _ _, ⟨⟩⟩, pullback_stable' := λ X Y S g, begin rintro ⟨R, hR, RS⟩, refine ⟨_, K.pullbacks g _ hR, _⟩, rw [← sieve.sets_iff_generate, sieve.pullback_arrows_comm], apply sieve.pullback_monotone, rwa sieve.gi_generate.gc, end, transitive' := begin rintro X S ⟨R', hR', RS⟩ R t, choose t₁ t₂ t₃ using t, refine ⟨_, K.transitive _ _ hR' (λ _ f hf, t₂ (RS _ hf)), _⟩, rintro Y _ ⟨Z, g, f, hg, hf, rfl⟩, apply t₃ (RS _ hg) _ hf, end } lemma mem_to_grothendieck (K : pretopology C) (X S) : S ∈ to_grothendieck C K X ↔ ∃ R ∈ K X, R ≤ (S : presieve X) := iff.rfl /-- The largest pretopology generating the given Grothendieck topology. See [MM92] Chapter III, Section 2, Equations (3,4). -/ def of_grothendieck (J : grothendieck_topology C) : pretopology C := { coverings := λ X R, sieve.generate R ∈ J X, has_isos := λ X Y f i, by exactI J.covering_of_eq_top (by simp), pullbacks := λ X Y f R hR, begin rw [set.mem_def, sieve.pullback_arrows_comm], apply J.pullback_stable f hR, end, transitive := λ X S Ti hS hTi, begin apply J.transitive hS, intros Y f, rintros ⟨Z, g, f, hf, rfl⟩, rw sieve.pullback_comp, apply J.pullback_stable g, apply J.superset_covering _ (hTi _ hf), rintro Y g ⟨W, h, g, hg, rfl⟩, exact ⟨_, h, _, ⟨_, _, _, hf, hg, rfl⟩, by simp⟩, end } /-- We have a galois insertion from pretopologies to Grothendieck topologies. -/ def gi : galois_insertion (to_grothendieck C) (of_grothendieck C) := { gc := λ K J, begin split, { intros h X R hR, exact h _ ⟨_, hR, sieve.le_generate R⟩ }, { rintro h X S ⟨R, hR, RS⟩, apply J.superset_covering _ (h _ hR), rwa sieve.gi_generate.gc } end, le_l_u := λ J X S hS, ⟨S, J.superset_covering S.le_generate hS, le_rfl⟩, choice := λ x hx, to_grothendieck C x, choice_eq := λ _ _, rfl } /-- The trivial pretopology, in which the coverings are exactly singleton isomorphisms. This topology is also known as the indiscrete, coarse, or chaotic topology. See <https://stacks.math.columbia.edu/tag/07GE> -/ def trivial : pretopology C := { coverings := λ X S, ∃ Y (f : Y ⟶ X) (h : is_iso f), S = presieve.singleton f, has_isos := λ X Y f i, ⟨_, _, i, rfl⟩, pullbacks := λ X Y f S, begin rintro ⟨Z, g, i, rfl⟩, refine ⟨pullback g f, pullback.snd, _, _⟩, { resetI, refine ⟨⟨pullback.lift (f ≫ inv g) (𝟙 _) (by simp), ⟨_, by tidy⟩⟩⟩, apply pullback.hom_ext, { rw [assoc, pullback.lift_fst, ←pullback.condition_assoc], simp }, { simp } }, { apply pullback_singleton }, end, transitive := begin rintro X S Ti ⟨Z, g, i, rfl⟩ hS, rcases hS g (singleton_self g) with ⟨Y, f, i, hTi⟩, refine ⟨_, f ≫ g, _, _⟩, { resetI, apply_instance }, ext W k, split, { rintro ⟨V, h, k, ⟨_⟩, hh, rfl⟩, rw hTi at hh, cases hh, apply singleton.mk }, { rintro ⟨_⟩, refine bind_comp g presieve.singleton.mk _, rw hTi, apply presieve.singleton.mk } end } instance : order_bot (pretopology C) := { bot := trivial C, bot_le := λ K X R, begin rintro ⟨Y, f, hf, rfl⟩, exactI K.has_isos f, end } /-- The trivial pretopology induces the trivial grothendieck topology. -/ lemma to_grothendieck_bot : to_grothendieck C ⊥ = ⊥ := (gi C).gc.l_bot end pretopology end category_theory
df0d375bf742203a5cf1aefe1c8fd03c6d13a84d
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/limits/shapes/biproducts.lean
55cc1e871b1fd07e6f3924a6cf3666080c7040ea
[ "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
31,869
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.binary_products import category_theory.preadditive /-! # Biproducts and binary biproducts We introduce the notion of (finite) biproducts and binary biproducts. These are slightly unusual relative to the other shapes in the library, as they are simultaneously limits and colimits. (Zero objects are similar; they are "biterminal".) We treat first the case of a general category with zero morphisms, and subsequently the case of a preadditive category. In a category with zero morphisms, we model the (binary) biproduct of `P Q : C` using a `binary_bicone`, which has a cone point `X`, and morphisms `fst : X ⟶ P`, `snd : X ⟶ Q`, `inl : P ⟶ X` and `inr : X ⟶ Q`, such that `inl ≫ fst = 𝟙 P`, `inl ≫ snd = 0`, `inr ≫ fst = 0`, and `inr ≫ snd = 𝟙 Q`. Such a `binary_bicone` is a biproduct if the cone is a limit cone, and the cocone is a colimit cocone. In a preadditive category, * any `binary_biproduct` satisfies `total : fst ≫ inl + snd ≫ inr = 𝟙 X` * any `binary_product` is a `binary_biproduct` * any `binary_coproduct` is a `binary_biproduct` For biproducts indexed by a `fintype J`, a `bicone` again consists of a cone point `X` and morphisms `π j : X ⟶ F j` and `ι j : F j ⟶ X` for each `j`, such that `ι j ≫ π j'` is the identity when `j = j'` and zero otherwise. In a preadditive category, * any `biproduct` satisfies `total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)` * any `product` is a `biproduct` * any `coproduct` is a `biproduct` ## Notation As `⊕` is already taken for the sum of types, we introduce the notation `X ⊞ Y` for a binary biproduct. We introduce `⨁ f` for the indexed biproduct. -/ universes v u open category_theory open category_theory.functor namespace category_theory.limits variables {J : Type v} [decidable_eq J] variables {C : Type u} [category.{v} C] [has_zero_morphisms C] /-- A `c : bicone F` is: * an object `c.X` and * morphisms `π j : X ⟶ F j` and `ι j : F j ⟶ X` for each `j`, * such that `ι j ≫ π j'` is the identity when `j = j'` and zero otherwise. -/ @[nolint has_inhabited_instance] structure bicone (F : J → C) := (X : C) (π : Π j, X ⟶ F j) (ι : Π j, F j ⟶ X) (ι_π : ∀ j j', ι j ≫ π j' = if h : j = j' then eq_to_hom (congr_arg F h) else 0) @[simp] lemma bicone_ι_π_self {F : J → C} (B : bicone F) (j : J) : B.ι j ≫ B.π j = 𝟙 (F j) := by simpa using B.ι_π j j @[simp] lemma bicone_ι_π_ne {F : J → C} (B : bicone F) {j j' : J} (h : j ≠ j') : B.ι j ≫ B.π j' = 0 := by simpa [h] using B.ι_π j j' variables {F : J → C} namespace bicone /-- Extract the cone from a bicone. -/ @[simps] def to_cone (B : bicone F) : cone (discrete.functor F) := { X := B.X, π := { app := λ j, B.π j }, } /-- Extract the cocone from a bicone. -/ @[simps] def to_cocone (B : bicone F) : cocone (discrete.functor F) := { X := B.X, ι := { app := λ j, B.ι j }, } end bicone /-- `has_biproduct F` represents a particular chosen bicone which is simultaneously a limit and a colimit of the diagram `F`. -/ class has_biproduct (F : J → C) := (bicone : bicone F) (is_limit : is_limit bicone.to_cone) (is_colimit : is_colimit bicone.to_cocone) @[priority 100] instance has_product_of_has_biproduct [has_biproduct F] : has_limit (discrete.functor F) := { cone := has_biproduct.bicone.to_cone, is_limit := has_biproduct.is_limit, } @[priority 100] instance has_coproduct_of_has_biproduct [has_biproduct F] : has_colimit (discrete.functor F) := { cocone := has_biproduct.bicone.to_cocone, is_colimit := has_biproduct.is_colimit, } variables (J C) /-- `C` has biproducts of shape `J` if we have chosen a particular limit and a particular colimit, with the same cone points, of every function `F : J → C`. -/ class has_biproducts_of_shape := (has_biproduct : Π F : J → C, has_biproduct F) attribute [instance, priority 100] has_biproducts_of_shape.has_biproduct /-- `has_finite_biproducts C` represents a choice of biproduct for every family of objects in `C` indexed by a finite type with decidable equality. -/ class has_finite_biproducts := (has_biproducts_of_shape : Π (J : Type v) [fintype J] [decidable_eq J], has_biproducts_of_shape J C) attribute [instance, priority 100] has_finite_biproducts.has_biproducts_of_shape @[priority 100] instance has_finite_products_of_has_finite_biproducts [has_finite_biproducts C] : has_finite_products C := ⟨λ J _ _, ⟨λ F, by exactI has_limit_of_iso discrete.nat_iso_functor.symm⟩⟩ @[priority 100] instance has_finite_coproducts_of_has_finite_biproducts [has_finite_biproducts C] : has_finite_coproducts C := ⟨λ J _ _, ⟨λ F, by exactI has_colimit_of_iso discrete.nat_iso_functor⟩⟩ variables {J C} /-- The isomorphism between the specified limit and the specified colimit for a functor with a bilimit. -/ def biproduct_iso (F : J → C) [has_biproduct F] : limits.pi_obj F ≅ limits.sigma_obj F := eq_to_iso rfl end category_theory.limits namespace category_theory.limits variables {J : Type v} [decidable_eq J] variables {C : Type u} [category.{v} C] [has_zero_morphisms C] /-- `biproduct f` computes the biproduct of a family of elements `f`. (It is defined as an abbreviation for `limit (discrete.functor f)`, so for most facts about `biproduct f`, you will just use general facts about limits and colimits.) -/ abbreviation biproduct (f : J → C) [has_biproduct f] : C := limit (discrete.functor f) notation `⨁ ` f:20 := biproduct f /-- The chosen bicone over a family of elements. -/ abbreviation biproduct.bicone (f : J → C) [has_biproduct f] : bicone f := has_biproduct.bicone /-- The cone coming from the chosen bicone is a limit cone. -/ abbreviation biproduct.is_limit (f : J → C) [has_biproduct f] : is_limit (biproduct.bicone f).to_cone := has_biproduct.is_limit /-- The cocone coming from the chosen bicone is a colimit cocone. -/ abbreviation biproduct.is_colimit (f : J → C) [has_biproduct f] : is_colimit (biproduct.bicone f).to_cocone := has_biproduct.is_colimit /-- The projection onto a summand of a biproduct. -/ abbreviation biproduct.π (f : J → C) [has_biproduct f] (b : J) : ⨁ f ⟶ f b := limit.π (discrete.functor f) b /-- The inclusion into a summand of a biproduct. -/ abbreviation biproduct.ι (f : J → C) [has_biproduct f] (b : J) : f b ⟶ ⨁ f := colimit.ι (discrete.functor f) b @[reassoc] lemma biproduct.ι_π (f : J → C) [has_biproduct f] (j j' : J) : biproduct.ι f j ≫ biproduct.π f j' = if h : j = j' then eq_to_hom (congr_arg f h) else 0 := has_biproduct.bicone.ι_π j j' @[simp,reassoc] lemma biproduct.ι_π_self (f : J → C) [has_biproduct f] (j : J) : biproduct.ι f j ≫ biproduct.π f j = 𝟙 _ := by simp [biproduct.ι_π] @[simp,reassoc] lemma biproduct.ι_π_ne (f : J → C) [has_biproduct f] {j j' : J} (h : j ≠ j') : biproduct.ι f j ≫ biproduct.π f j' = 0 := by simp [biproduct.ι_π, h] /-- Given a collection of maps into the summands, we obtain a map into the biproduct. -/ abbreviation biproduct.lift {f : J → C} [has_biproduct f] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ⨁ f := limit.lift _ (fan.mk p) /-- Given a collection of maps out of the summands, we obtain a map out of the biproduct. -/ abbreviation biproduct.desc {f : J → C} [has_biproduct f] {P : C} (p : Π b, f b ⟶ P) : ⨁ f ⟶ P := colimit.desc _ (cofan.mk p) /-- Given a collection of maps between corresponding summands of a pair of biproducts indexed by the same type, we obtain a map between the biproducts. -/ abbreviation biproduct.map [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g := lim_map (discrete.nat_trans p) /-- An alternative to `biproduct.map` constructed via colimits. This construction only exists in order to show it is equal to `biproduct.map`. -/ abbreviation biproduct.map' [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g := @colim_map _ _ _ _ (discrete.functor f) (discrete.functor g) _ _ (discrete.nat_trans p) @[ext] lemma biproduct.hom_ext {f : J → C} [has_biproduct f] {Z : C} (g h : Z ⟶ ⨁ f) (w : ∀ j, g ≫ biproduct.π f j = h ≫ biproduct.π f j) : g = h := limit.hom_ext w @[ext] lemma biproduct.hom_ext' {f : J → C} [has_biproduct f] {Z : C} (g h : ⨁ f ⟶ Z) (w : ∀ j, biproduct.ι f j ≫ g = biproduct.ι f j ≫ h) : g = h := colimit.hom_ext w lemma biproduct.map_eq_map' [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π b, f b ⟶ g b) : biproduct.map p = biproduct.map' p := begin ext j j', simp only [discrete.nat_trans_app, limits.ι_colim_map, limits.lim_map_π, category.assoc], rw [biproduct.ι_π_assoc, biproduct.ι_π], split_ifs, { subst h, rw [eq_to_hom_refl, category.id_comp], erw category.comp_id, }, { simp, }, end instance biproduct.ι_mono (f : J → C) [has_biproduct f] (b : J) : split_mono (biproduct.ι f b) := { retraction := biproduct.desc $ λ b', if h : b' = b then eq_to_hom (congr_arg f h) else biproduct.ι f b' ≫ biproduct.π f b } instance biproduct.π_epi (f : J → C) [has_biproduct f] (b : J) : split_epi (biproduct.π f b) := { section_ := biproduct.lift $ λ b', if h : b = b' then eq_to_hom (congr_arg f h) else biproduct.ι f b ≫ biproduct.π f b' } -- Because `biproduct.map` is defined in terms of `lim` rather than `colim`, -- we need to provide additional `simp` lemmas. @[simp] lemma biproduct.inl_map [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π j, f j ⟶ g j) (j : J) : biproduct.ι f j ≫ biproduct.map p = p j ≫ biproduct.ι g j := begin rw biproduct.map_eq_map', simp, end variables {C} /-- A binary bicone for a pair of objects `P Q : C` consists of the cone point `X`, maps from `X` to both `P` and `Q`, and maps from both `P` and `Q` to `X`, so that `inl ≫ fst = 𝟙 P`, `inl ≫ snd = 0`, `inr ≫ fst = 0`, and `inr ≫ snd = 𝟙 Q` -/ @[nolint has_inhabited_instance] structure binary_bicone (P Q : C) := (X : C) (fst : X ⟶ P) (snd : X ⟶ Q) (inl : P ⟶ X) (inr : Q ⟶ X) (inl_fst' : inl ≫ fst = 𝟙 P . obviously) (inl_snd' : inl ≫ snd = 0 . obviously) (inr_fst' : inr ≫ fst = 0 . obviously) (inr_snd' : inr ≫ snd = 𝟙 Q . obviously) restate_axiom binary_bicone.inl_fst' restate_axiom binary_bicone.inl_snd' restate_axiom binary_bicone.inr_fst' restate_axiom binary_bicone.inr_snd' attribute [simp, reassoc] binary_bicone.inl_fst binary_bicone.inl_snd binary_bicone.inr_fst binary_bicone.inr_snd namespace binary_bicone variables {P Q : C} /-- Extract the cone from a binary bicone. -/ def to_cone (c : binary_bicone P Q) : cone (pair P Q) := binary_fan.mk c.fst c.snd @[simp] lemma to_cone_X (c : binary_bicone P Q) : c.to_cone.X = c.X := rfl @[simp] lemma to_cone_π_app_left (c : binary_bicone P Q) : c.to_cone.π.app (walking_pair.left) = c.fst := rfl @[simp] lemma to_cone_π_app_right (c : binary_bicone P Q) : c.to_cone.π.app (walking_pair.right) = c.snd := rfl /-- Extract the cocone from a binary bicone. -/ def to_cocone (c : binary_bicone P Q) : cocone (pair P Q) := binary_cofan.mk c.inl c.inr @[simp] lemma to_cocone_X (c : binary_bicone P Q) : c.to_cocone.X = c.X := rfl @[simp] lemma to_cocone_ι_app_left (c : binary_bicone P Q) : c.to_cocone.ι.app (walking_pair.left) = c.inl := rfl @[simp] lemma to_cocone_ι_app_right (c : binary_bicone P Q) : c.to_cocone.ι.app (walking_pair.right) = c.inr := rfl end binary_bicone namespace bicone /-- Convert a `bicone` over a function on `walking_pair` to a binary_bicone. -/ @[simps] def to_binary_bicone {X Y : C} (b : bicone (pair X Y).obj) : binary_bicone X Y := { X := b.X, fst := b.π walking_pair.left, snd := b.π walking_pair.right, inl := b.ι walking_pair.left, inr := b.ι walking_pair.right, inl_fst' := by { simp [bicone.ι_π], refl, }, inr_fst' := by simp [bicone.ι_π], inl_snd' := by simp [bicone.ι_π], inr_snd' := by { simp [bicone.ι_π], refl, }, } /-- If the cone obtained from a bicone over `pair X Y` is a limit cone, so is the cone obtained by converting that bicone to a binary_bicone, then to a cone. -/ def to_binary_bicone_is_limit {X Y : C} {b : bicone (pair X Y).obj} (c : is_limit (b.to_cone)) : is_limit (b.to_binary_bicone.to_cone) := { lift := λ s, c.lift s, fac' := λ s j, by { cases j; erw c.fac, }, uniq' := λ s m w, begin apply c.uniq s, rintro (⟨⟩|⟨⟩), exact w walking_pair.left, exact w walking_pair.right, end, } /-- If the cocone obtained from a bicone over `pair X Y` is a colimit cocone, so is the cocone obtained by converting that bicone to a binary_bicone, then to a cocone. -/ def to_binary_bicone_is_colimit {X Y : C} {b : bicone (pair X Y).obj} (c : is_colimit (b.to_cocone)) : is_colimit (b.to_binary_bicone.to_cocone) := { desc := λ s, c.desc s, fac' := λ s j, by { cases j; erw c.fac, }, uniq' := λ s m w, begin apply c.uniq s, rintro (⟨⟩|⟨⟩), exact w walking_pair.left, exact w walking_pair.right, end, } end bicone /-- `has_binary_biproduct P Q` represents a particular chosen bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`. -/ class has_binary_biproduct (P Q : C) := (bicone : binary_bicone P Q) (is_limit : is_limit bicone.to_cone) (is_colimit : is_colimit bicone.to_cocone) section variable (C) /-- `has_binary_biproducts C` represents a particular chosen bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`, for every `P Q : C`. -/ class has_binary_biproducts := (has_binary_biproduct : Π (P Q : C), has_binary_biproduct P Q) attribute [instance, priority 100] has_binary_biproducts.has_binary_biproduct /-- A category with finite biproducts has binary biproducts. This is not an instance as typically in concrete categories there will be an alternative construction with nicer definitional properties. -/ def has_binary_biproducts_of_finite_biproducts [has_finite_biproducts C] : has_binary_biproducts C := { has_binary_biproduct := λ P Q, { bicone := (biproduct.bicone (pair P Q).obj).to_binary_bicone, is_limit := bicone.to_binary_bicone_is_limit (biproduct.is_limit _), is_colimit := bicone.to_binary_bicone_is_colimit (biproduct.is_colimit _) } } end variables {P Q : C} instance has_binary_biproduct.has_limit_pair [has_binary_biproduct P Q] : has_limit (pair P Q) := { cone := has_binary_biproduct.bicone.to_cone, is_limit := has_binary_biproduct.is_limit, } instance has_binary_biproduct.has_colimit_pair [has_binary_biproduct P Q] : has_colimit (pair P Q) := { cocone := has_binary_biproduct.bicone.to_cocone, is_colimit := has_binary_biproduct.is_colimit, } @[priority 100] instance has_limits_of_shape_walking_pair [has_binary_biproducts C] : has_limits_of_shape (discrete walking_pair) C := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } @[priority 100] instance has_colimits_of_shape_walking_pair [has_binary_biproducts C] : has_colimits_of_shape (discrete walking_pair) C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } @[priority 100] instance has_binary_products_of_has_binary_biproducts [has_binary_biproducts C] : has_binary_products C := ⟨by apply_instance⟩ @[priority 100] instance has_binary_coproducts_of_has_binary_biproducts [has_binary_biproducts C] : has_binary_coproducts C := ⟨by apply_instance⟩ /-- The isomorphism between the specified binary product and the specified binary coproduct for a pair for a binary biproduct. -/ def biprod_iso (X Y : C) [has_binary_biproduct X Y] : limits.prod X Y ≅ limits.coprod X Y := eq_to_iso rfl /-- The chosen biproduct of a pair of objects. -/ abbreviation biprod (X Y : C) [has_binary_biproduct X Y] := limit (pair X Y) notation X ` ⊞ `:20 Y:20 := biprod X Y /-- The projection onto the first summand of a binary biproduct. -/ abbreviation biprod.fst {X Y : C} [has_binary_biproduct X Y] : X ⊞ Y ⟶ X := limit.π (pair X Y) walking_pair.left /-- The projection onto the second summand of a binary biproduct. -/ abbreviation biprod.snd {X Y : C} [has_binary_biproduct X Y] : X ⊞ Y ⟶ Y := limit.π (pair X Y) walking_pair.right /-- The inclusion into the first summand of a binary biproduct. -/ abbreviation biprod.inl {X Y : C} [has_binary_biproduct X Y] : X ⟶ X ⊞ Y := colimit.ι (pair X Y) walking_pair.left /-- The inclusion into the second summand of a binary biproduct. -/ abbreviation biprod.inr {X Y : C} [has_binary_biproduct X Y] : Y ⟶ X ⊞ Y := colimit.ι (pair X Y) walking_pair.right @[simp,reassoc] lemma biprod.inl_fst {X Y : C} [has_binary_biproduct X Y] : (biprod.inl : X ⟶ X ⊞ Y) ≫ (biprod.fst : X ⊞ Y ⟶ X) = 𝟙 X := has_binary_biproduct.bicone.inl_fst @[simp,reassoc] lemma biprod.inl_snd {X Y : C} [has_binary_biproduct X Y] : (biprod.inl : X ⟶ X ⊞ Y) ≫ (biprod.snd : X ⊞ Y ⟶ Y) = 0 := has_binary_biproduct.bicone.inl_snd @[simp,reassoc] lemma biprod.inr_fst {X Y : C} [has_binary_biproduct X Y] : (biprod.inr : Y ⟶ X ⊞ Y) ≫ (biprod.fst : X ⊞ Y ⟶ X) = 0 := has_binary_biproduct.bicone.inr_fst @[simp,reassoc] lemma biprod.inr_snd {X Y : C} [has_binary_biproduct X Y] : (biprod.inr : Y ⟶ X ⊞ Y) ≫ (biprod.snd : X ⊞ Y ⟶ Y) = 𝟙 Y := has_binary_biproduct.bicone.inr_snd /-- Given a pair of maps into the summands of a binary biproduct, we obtain a map into the binary biproduct. -/ abbreviation biprod.lift {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⊞ Y := limit.lift _ (binary_fan.mk f g) /-- Given a pair of maps out of the summands of a binary biproduct, we obtain a map out of the binary biproduct. -/ abbreviation biprod.desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : X ⊞ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) /-- Given a pair of maps between the summands of a pair of binary biproducts, we obtain a map between the binary biproducts. -/ abbreviation biprod.map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z := lim_map (@map_pair _ _ (pair W X) (pair Y Z) f g) /-- Given a pair of isomorphisms between the summands of a pair of binary biproducts, we obtain an isomorphism between the binary biproducts. -/ @[simps] def biprod.map_iso {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ≅ Y) (g : X ≅ Z) : W ⊞ X ≅ Y ⊞ Z := { hom := biprod.map f.hom g.hom, inv := biprod.map f.inv g.inv, } /-- An alternative to `biprod.map` constructed via colimits. This construction only exists in order to show it is equal to `biprod.map`. -/ abbreviation biprod.map' {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z := colim_map (@map_pair _ _ (pair W X) (pair Y Z) f g) @[ext] lemma biprod.hom_ext {X Y Z : C} [has_binary_biproduct X Y] (f g : Z ⟶ X ⊞ Y) (h₀ : f ≫ biprod.fst = g ≫ biprod.fst) (h₁ : f ≫ biprod.snd = g ≫ biprod.snd) : f = g := binary_fan.is_limit.hom_ext has_binary_biproduct.is_limit h₀ h₁ @[ext] lemma biprod.hom_ext' {X Y Z : C} [has_binary_biproduct X Y] (f g : X ⊞ Y ⟶ Z) (h₀ : biprod.inl ≫ f = biprod.inl ≫ g) (h₁ : biprod.inr ≫ f = biprod.inr ≫ g) : f = g := binary_cofan.is_colimit.hom_ext has_binary_biproduct.is_colimit h₀ h₁ lemma biprod.map_eq_map' {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g = biprod.map' f g := begin ext, { simp only [map_pair_left, ι_colim_map, lim_map_π, biprod.inl_fst_assoc, category.assoc], erw [biprod.inl_fst, category.comp_id], }, { simp only [map_pair_left, ι_colim_map, lim_map_π, has_zero_morphisms.zero_comp, biprod.inl_snd_assoc, category.assoc], erw [biprod.inl_snd], simp, }, { simp only [map_pair_right, biprod.inr_fst_assoc, ι_colim_map, lim_map_π, has_zero_morphisms.zero_comp, category.assoc], erw [biprod.inr_fst], simp, }, { simp only [map_pair_right, ι_colim_map, lim_map_π, biprod.inr_snd_assoc, category.assoc], erw [biprod.inr_snd, category.comp_id], }, end instance biprod.inl_mono {X Y : C} [has_binary_biproduct X Y] : split_mono (biprod.inl : X ⟶ X ⊞ Y) := { retraction := biprod.desc (𝟙 X) (biprod.inr ≫ biprod.fst) } instance biprod.inr_mono {X Y : C} [has_binary_biproduct X Y] : split_mono (biprod.inr : Y ⟶ X ⊞ Y) := { retraction := biprod.desc (biprod.inl ≫ biprod.snd) (𝟙 Y)} instance biprod.fst_epi {X Y : C} [has_binary_biproduct X Y] : split_epi (biprod.fst : X ⊞ Y ⟶ X) := { section_ := biprod.lift (𝟙 X) (biprod.inl ≫ biprod.snd) } instance biprod.snd_epi {X Y : C} [has_binary_biproduct X Y] : split_epi (biprod.snd : X ⊞ Y ⟶ Y) := { section_ := biprod.lift (biprod.inr ≫ biprod.fst) (𝟙 Y) } @[simp,reassoc] lemma biprod.map_fst {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g ≫ biprod.fst = biprod.fst ≫ f := by simp @[simp,reassoc] lemma biprod.map_snd {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g ≫ biprod.snd = biprod.snd ≫ g := by simp -- Because `biprod.map` is defined in terms of `lim` rather than `colim`, -- we need to provide additional `simp` lemmas. @[simp,reassoc] lemma biprod.inl_map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.inl ≫ biprod.map f g = f ≫ biprod.inl := begin rw biprod.map_eq_map', simp, end @[simp,reassoc] lemma biprod.inr_map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.inr ≫ biprod.map f g = g ≫ biprod.inr := begin rw biprod.map_eq_map', simp, end section variables [has_binary_biproducts C] /-- The braiding isomorphism which swaps a binary biproduct. -/ @[simps] def biprod.braiding (P Q : C) : P ⊞ Q ≅ Q ⊞ P := { hom := biprod.lift biprod.snd biprod.fst, inv := biprod.lift biprod.snd biprod.fst } /-- An alternative formula for the braiding isomorphism which swaps a binary biproduct, using the fact that the biproduct is a coproduct. -/ @[simps] def biprod.braiding' (P Q : C) : P ⊞ Q ≅ Q ⊞ P := { hom := biprod.desc biprod.inr biprod.inl, inv := biprod.desc biprod.inr biprod.inl } lemma biprod.braiding'_eq_braiding {P Q : C} : biprod.braiding' P Q = biprod.braiding P Q := by tidy /-- The braiding isomorphism can be passed through a map by swapping the order. -/ @[reassoc] lemma biprod.braid_natural {W X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ W) : biprod.map f g ≫ (biprod.braiding _ _).hom = (biprod.braiding _ _).hom ≫ biprod.map g f := by tidy @[reassoc] lemma biprod.braiding_map_braiding {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : (biprod.braiding X W).hom ≫ biprod.map f g ≫ (biprod.braiding Y Z).hom = biprod.map g f := by tidy @[simp, reassoc] lemma biprod.symmetry' (P Q : C) : biprod.lift biprod.snd biprod.fst ≫ biprod.lift biprod.snd biprod.fst = 𝟙 (P ⊞ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ @[reassoc] lemma biprod.symmetry (P Q : C) : (biprod.braiding P Q).hom ≫ (biprod.braiding Q P).hom = 𝟙 _ := by simp end -- TODO: -- If someone is interested, they could provide the constructions: -- has_binary_biproducts ↔ has_finite_biproducts end category_theory.limits namespace category_theory.limits section preadditive variables {C : Type u} [category.{v} C] [preadditive C] variables {J : Type v} [fintype J] [decidable_eq J] open category_theory.preadditive open_locale big_operators /-- In a preadditive category, we can construct a biproduct for `f : J → C` from any bicone `b` for `f` satisfying `total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ def has_biproduct_of_total {f : J → C} (b : bicone f) (total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X) : has_biproduct f := { bicone := b, is_limit := { lift := λ s, ∑ j, s.π.app j ≫ b.ι j, uniq' := λ s m h, begin erw [←category.comp_id m, ←total, comp_sum], apply finset.sum_congr rfl, intros j m, erw [reassoc_of (h j)], end, fac' := λ s j, begin simp only [sum_comp, category.assoc, bicone.to_cone_π_app, b.ι_π, comp_dite], dsimp, simp, end }, is_colimit := { desc := λ s, ∑ j, b.π j ≫ s.ι.app j, uniq' := λ s m h, begin erw [←category.id_comp m, ←total, sum_comp], apply finset.sum_congr rfl, intros j m, erw [category.assoc, h], end, fac' := λ s j, begin simp only [comp_sum, ←category.assoc, bicone.to_cocone_ι_app, b.ι_π, dite_comp], dsimp, simp, end } } /-- In a preadditive category, if the product over `f : J → C` exists, then the biproduct over `f` exists. -/ def has_biproduct.of_has_product (f : J → C) [has_product f] : has_biproduct f := has_biproduct_of_total { X := pi_obj f, π := limits.pi.π f, ι := λ j, pi.lift (λ j', if h : j = j' then eq_to_hom (congr_arg f h) else 0), ι_π := λ j j', by simp, } (by { ext, simp [sum_comp, comp_dite] }) /-- In a preadditive category, if the coproduct over `f : J → C` exists, then the biproduct over `f` exists. -/ def has_biproduct.of_has_coproduct (f : J → C) [has_coproduct f] : has_biproduct f := has_biproduct_of_total { X := sigma_obj f, π := λ j, sigma.desc (λ j', if h : j' = j then eq_to_hom (congr_arg f h) else 0), ι := limits.sigma.ι f, ι_π := λ j j', by simp, } begin ext, simp only [comp_sum, limits.cofan.mk_π_app, limits.colimit.ι_desc_assoc, eq_self_iff_true, limits.colimit.ι_desc, category.comp_id], dsimp, simp only [dite_comp, finset.sum_dite_eq, finset.mem_univ, if_true, category.id_comp, eq_to_hom_refl, limits.has_zero_morphisms.zero_comp], end /-- A preadditive category with finite products has finite biproducts. -/ def has_finite_biproducts.of_has_finite_products [has_finite_products C] : has_finite_biproducts C := ⟨λ J _ _, { has_biproduct := λ F, by exactI has_biproduct.of_has_product _ }⟩ /-- A preadditive category with finite coproducts has finite biproducts. -/ def has_finite_biproducts.of_has_finite_coproducts [has_finite_coproducts C] : has_finite_biproducts C := ⟨λ J _ _, { has_biproduct := λ F, by exactI has_biproduct.of_has_coproduct _ }⟩ section variables {f : J → C} [has_biproduct f] /-- In any preadditive category, any biproduct satsifies `∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)` -/ @[simp] lemma biproduct.total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f) := begin ext j j', simp [comp_sum, sum_comp, biproduct.ι_π, comp_dite, dite_comp], end lemma biproduct.lift_eq {T : C} {g : Π j, T ⟶ f j} : biproduct.lift g = ∑ j, g j ≫ biproduct.ι f j := begin ext j, simp [sum_comp, biproduct.ι_π, comp_dite], end lemma biproduct.desc_eq {T : C} {g : Π j, f j ⟶ T} : biproduct.desc g = ∑ j, biproduct.π f j ≫ g j := begin ext j, simp [comp_sum, biproduct.ι_π_assoc, dite_comp], end @[simp, reassoc] lemma biproduct.lift_desc {T U : C} {g : Π j, T ⟶ f j} {h : Π j, f j ⟶ U} : biproduct.lift g ≫ biproduct.desc h = ∑ j : J, g j ≫ h j := by simp [biproduct.lift_eq, biproduct.desc_eq, comp_sum, sum_comp, biproduct.ι_π_assoc, comp_dite, dite_comp] lemma biproduct.map_eq [has_finite_biproducts C] {f g : J → C} {h : Π j, f j ⟶ g j} : biproduct.map h = ∑ j : J, biproduct.π f j ≫ h j ≫ biproduct.ι g j := begin ext, simp [biproduct.ι_π, biproduct.ι_π_assoc, comp_sum, sum_comp, comp_dite, dite_comp], end end /-- In a preadditive category, we can construct a binary biproduct for `X Y : C` from any binary bicone `b` satisfying `total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ def has_binary_biproduct_of_total {X Y : C} (b : binary_bicone X Y) (total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X) : has_binary_biproduct X Y := { bicone := b, is_limit := { lift := λ s, binary_fan.fst s ≫ b.inl + binary_fan.snd s ≫ b.inr, uniq' := λ s m h, by erw [←category.comp_id m, ←total, comp_add, reassoc_of (h walking_pair.left), reassoc_of (h walking_pair.right)], fac' := λ s j, by cases j; simp, }, is_colimit := { desc := λ s, b.fst ≫ binary_cofan.inl s + b.snd ≫ binary_cofan.inr s, uniq' := λ s m h, by erw [←category.id_comp m, ←total, add_comp, category.assoc, category.assoc, h walking_pair.left, h walking_pair.right], fac' := λ s j, by cases j; simp, } } /-- In a preadditive category, if the product of `X` and `Y` exists, then the binary biproduct of `X` and `Y` exists. -/ def has_binary_biproduct.of_has_binary_product (X Y : C) [has_binary_product X Y] : has_binary_biproduct X Y := has_binary_biproduct_of_total { X := X ⨯ Y, fst := category_theory.limits.prod.fst, snd := category_theory.limits.prod.snd, inl := prod.lift (𝟙 X) 0, inr := prod.lift 0 (𝟙 Y) } begin ext; simp [add_comp], end /-- In a preadditive category, if all binary products exist, then all binary biproducts exist. -/ def has_binary_biproducts.of_has_binary_products [has_binary_products C] : has_binary_biproducts C := { has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_product X Y, } /-- In a preadditive category, if the coproduct of `X` and `Y` exists, then the binary biproduct of `X` and `Y` exists. -/ def has_binary_biproduct.of_has_binary_coproduct (X Y : C) [has_binary_coproduct X Y] : has_binary_biproduct X Y := has_binary_biproduct_of_total { X := X ⨿ Y, fst := coprod.desc (𝟙 X) 0, snd := coprod.desc 0 (𝟙 Y), inl := category_theory.limits.coprod.inl, inr := category_theory.limits.coprod.inr } begin ext; simp [add_comp], end /-- In a preadditive category, if all binary coproducts exist, then all binary biproducts exist. -/ def has_binary_biproducts.of_has_binary_coproducts [has_binary_coproducts C] : has_binary_biproducts C := { has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_coproduct X Y, } section variables {X Y : C} [has_binary_biproduct X Y] /-- In any preadditive category, any binary biproduct satsifies `biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y)`. -/ @[simp] lemma biprod.total : biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y) := begin ext; simp [add_comp], end lemma biprod.lift_eq {T : C} {f : T ⟶ X} {g : T ⟶ Y} : biprod.lift f g = f ≫ biprod.inl + g ≫ biprod.inr := begin ext; simp [add_comp], end lemma biprod.desc_eq {T : C} {f : X ⟶ T} {g : Y ⟶ T} : biprod.desc f g = biprod.fst ≫ f + biprod.snd ≫ g := begin ext; simp [add_comp], end @[simp, reassoc] lemma biprod.lift_desc {T U : C} {f : T ⟶ X} {g : T ⟶ Y} {h : X ⟶ U} {i : Y ⟶ U} : biprod.lift f g ≫ biprod.desc h i = f ≫ h + g ≫ i := by simp [biprod.lift_eq, biprod.desc_eq] lemma biprod.map_eq [has_binary_biproducts C] {W X Y Z : C} {f : W ⟶ Y} {g : X ⟶ Z} : biprod.map f g = biprod.fst ≫ f ≫ biprod.inl + biprod.snd ≫ g ≫ biprod.inr := by apply biprod.hom_ext; apply biprod.hom_ext'; simp end end preadditive end category_theory.limits
a14ffe85377ef4c22d21e570b0030cc0b0b33829
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/order.lean
30a7d7cca21303db7966626d6a174b1409782e61
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
9,636
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ universe u variables {α : Type u} @[simp] lemma ge_iff_le [preorder α] {a b : α} : a ≥ b ↔ b ≤ a := iff.rfl @[simp] lemma gt_iff_lt [preorder α] {a b : α} : a > b ↔ b < a := iff.rfl lemma not_le_of_lt [preorder α] {a b : α} (h : a < b) : ¬ b ≤ a := (le_not_le_of_lt h).right lemma not_lt_of_le [preorder α] {a b : α} (h : a ≤ b) : ¬ b < a | hab := not_le_of_gt hab h lemma le_iff_eq_or_lt [partial_order α] {a b : α} : a ≤ b ↔ a = b ∨ a < b := le_iff_lt_or_eq.trans or.comm lemma lt_of_le_of_ne' [partial_order α] {a b : α} (h₁ : a ≤ b) (h₂ : a ≠ b) : a < b := lt_of_le_not_le h₁ $ mt (le_antisymm h₁) h₂ lemma lt_iff_le_and_ne [partial_order α] {a b : α} : a < b ↔ a ≤ b ∧ a ≠ b := ⟨λ h, ⟨le_of_lt h, ne_of_lt h⟩, λ ⟨h1, h2⟩, lt_of_le_of_ne h1 h2⟩ lemma eq_iff_le_not_lt [partial_order α] {a b : α} : a = b ↔ a ≤ b ∧ ¬ a < b := ⟨λ h, ⟨le_of_eq h, h ▸ lt_irrefl _⟩, λ ⟨h₁, h₂⟩, le_antisymm h₁ $ classical.by_contradiction $ λ h₃, h₂ (lt_of_le_not_le h₁ h₃)⟩ lemma eq_or_lt_of_le [partial_order α] {a b : α} (h : a ≤ b) : a = b ∨ a < b := (lt_or_eq_of_le h).symm lemma lt_of_not_ge' [linear_order α] {a b : α} (h : ¬ b ≤ a) : a < b := lt_of_le_not_le ((le_total _ _).resolve_right h) h lemma lt_iff_not_ge' [linear_order α] {x y : α} : x < y ↔ ¬ y ≤ x := ⟨not_le_of_gt, lt_of_not_ge'⟩ @[simp] lemma not_lt [linear_order α] {a b : α} : ¬ a < b ↔ b ≤ a := ⟨le_of_not_gt, not_lt_of_ge⟩ lemma le_of_not_lt [linear_order α] {a b : α} : ¬ a < b → b ≤ a := not_lt.1 @[simp] lemma not_le [linear_order α] {a b : α} : ¬ a ≤ b ↔ b < a := lt_iff_not_ge'.symm lemma lt_or_le [linear_order α] : ∀ a b : α, a < b ∨ b ≤ a := lt_or_ge lemma le_or_lt [linear_order α] : ∀ a b : α, a ≤ b ∨ b < a := le_or_gt lemma not_lt_iff_eq_or_lt [linear_order α] {a b : α} : ¬ a < b ↔ a = b ∨ b < a := not_lt.trans $ le_iff_eq_or_lt.trans $ or_congr eq_comm iff.rfl lemma exists_ge_of_linear [linear_order α] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c := match le_total a b with | or.inl h := ⟨_, h, le_refl _⟩ | or.inr h := ⟨_, le_refl _, h⟩ end lemma lt_imp_lt_of_le_imp_le {β} [linear_order α] [preorder β] {a b : α} {c d : β} (H : a ≤ b → c ≤ d) (h : d < c) : b < a := lt_of_not_ge' $ λ h', not_lt_of_ge (H h') h lemma le_imp_le_of_lt_imp_lt {β} [preorder α] [linear_order β] {a b : α} {c d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d := le_of_not_gt $ λ h', not_le_of_gt (H h') h lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b → c ≤ d) ↔ (d < c → b < a) := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ lemma lt_iff_lt_of_le_iff_le' {β} [preorder α] [preorder β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) (H' : b ≤ a ↔ d ≤ c) : b < a ↔ d < c := lt_iff_le_not_le.trans $ (and_congr H' (not_congr H)).trans lt_iff_le_not_le.symm lemma lt_iff_lt_of_le_iff_le {β} [linear_order α] [linear_order β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) : b < a ↔ d < c := not_le.symm.trans $ iff.trans (not_congr H) $ not_le lemma le_iff_le_iff_lt_iff_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ iff.trans (not_congr H) $ not_lt⟩ lemma eq_of_forall_le_iff [partial_order α] {a b : α} (H : ∀ c, c ≤ a ↔ c ≤ b) : a = b := le_antisymm ((H _).1 (le_refl _)) ((H _).2 (le_refl _)) lemma le_of_forall_le [preorder α] {a b : α} (H : ∀ c, c ≤ a → c ≤ b) : a ≤ b := H _ (le_refl _) lemma le_of_forall_le' [preorder α] {a b : α} (H : ∀ c, a ≤ c → b ≤ c) : b ≤ a := H _ (le_refl _) lemma le_of_forall_lt [linear_order α] {a b : α} (H : ∀ c, c < a → c < b) : a ≤ b := le_of_not_lt $ λ h, lt_irrefl _ (H _ h) lemma forall_lt_iff_le [linear_order α] {a b : α} : (∀ ⦃c⦄, c < a → c < b) ↔ a ≤ b := ⟨le_of_forall_lt, λ h c hca, lt_of_lt_of_le hca h⟩ lemma le_of_forall_lt' [linear_order α] {a b : α} (H : ∀ c, a < c → b < c) : b ≤ a := le_of_not_lt $ λ h, lt_irrefl _ (H _ h) lemma forall_lt_iff_le' [linear_order α] {a b : α} : (∀ ⦃c⦄, a < c → b < c) ↔ b ≤ a := ⟨le_of_forall_lt', λ h c hac, lt_of_le_of_lt h hac⟩ lemma eq_of_forall_ge_iff [partial_order α] {a b : α} (H : ∀ c, a ≤ c ↔ b ≤ c) : a = b := le_antisymm ((H _).2 (le_refl _)) ((H _).1 (le_refl _)) /-- monotonicity of `≤` with respect to `→` -/ lemma le_implies_le_of_le_of_le {a b c d : α} [preorder α] (h₀ : c ≤ a) (h₁ : b ≤ d) : a ≤ b → c ≤ d := assume h₂ : a ≤ b, calc c ≤ a : h₀ ... ≤ b : h₂ ... ≤ d : h₁ namespace decidable lemma lt_or_eq_of_le [partial_order α] [@decidable_rel α (≤)] {a b : α} (hab : a ≤ b) : a < b ∨ a = b := if hba : b ≤ a then or.inr (le_antisymm hab hba) else or.inl (lt_of_le_not_le hab hba) lemma eq_or_lt_of_le [partial_order α] [@decidable_rel α (≤)] {a b : α} (hab : a ≤ b) : a = b ∨ a < b := (lt_or_eq_of_le hab).swap lemma le_iff_lt_or_eq [partial_order α] [@decidable_rel α (≤)] {a b : α} : a ≤ b ↔ a < b ∨ a = b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ lemma le_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ b < a) : a ≤ b := decidable.by_contradiction $ λ h', h $ lt_of_le_not_le ((le_total _ _).resolve_right h') h' lemma not_lt [decidable_linear_order α] {a b : α} : ¬ a < b ↔ b ≤ a := ⟨le_of_not_lt, not_lt_of_ge⟩ lemma lt_or_le [decidable_linear_order α] (a b : α) : a < b ∨ b ≤ a := if hba : b ≤ a then or.inr hba else or.inl $ not_le.1 hba lemma le_or_lt [decidable_linear_order α] (a b : α) : a ≤ b ∨ b < a := (lt_or_le b a).swap lemma lt_trichotomy [decidable_linear_order α] (a b : α) : a < b ∨ a = b ∨ b < a := (lt_or_le _ _).imp_right $ λ h, (eq_or_lt_of_le h).imp_left eq.symm lemma lt_or_gt_of_ne [decidable_linear_order α] {a b : α} (h : a ≠ b) : a < b ∨ b < a := (lt_trichotomy a b).imp_right $ λ h', h'.resolve_left h def lt_by_cases [decidable_linear_order α] (x y : α) {P : Sort*} (h₁ : x < y → P) (h₂ : x = y → P) (h₃ : y < x → P) : P := begin by_cases h : x < y, { exact h₁ h }, by_cases h' : y < x, { exact h₃ h' }, apply h₂, apply le_antisymm; apply le_of_not_gt; assumption end lemma ne_iff_lt_or_gt [decidable_linear_order α] {a b : α} : a ≠ b ↔ a < b ∨ b < a := ⟨lt_or_gt_of_ne, λo, o.elim ne_of_lt ne_of_gt⟩ lemma le_imp_le_of_lt_imp_lt {β} [preorder α] [decidable_linear_order β] {a b : α} {c d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d := le_of_not_lt $ λ h', not_le_of_gt (H h') h lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [decidable_linear_order β] {a b : α} {c d : β} : (a ≤ b → c ≤ d) ↔ (d < c → b < a) := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ lemma le_iff_le_iff_lt_iff_lt {β} [decidable_linear_order α] [decidable_linear_order β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ iff.trans (not_congr H) $ not_lt⟩ end decidable namespace ordering /-- `compares o a b` means that `a` and `b` have the ordering relation `o` between them, assuming that the relation `a < b` is defined -/ @[simp] def compares [has_lt α] : ordering → α → α → Prop | lt a b := a < b | eq a b := a = b | gt a b := a > b theorem compares.eq_lt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = lt ↔ a < b) | lt a b h := ⟨λ _, h, λ _, rfl⟩ | eq a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h' h).elim⟩ | gt a b h := ⟨λ h, by injection h, λ h', (lt_asymm h h').elim⟩ theorem compares.eq_eq [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = eq ↔ a = b) | lt a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h h').elim⟩ | eq a b h := ⟨λ _, h, λ _, rfl⟩ | gt a b h := ⟨λ h, by injection h, λ h', (ne_of_gt h h').elim⟩ theorem compares.eq_gt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = gt ↔ a > b) | lt a b h := ⟨λ h, by injection h, λ h', (lt_asymm h h').elim⟩ | eq a b h := ⟨λ h, by injection h, λ h', (ne_of_gt h' h).elim⟩ | gt a b h := ⟨λ _, h, λ _, rfl⟩ theorem compares.inj [preorder α] {o₁} : ∀ {o₂} {a b : α}, compares o₁ a b → compares o₂ a b → o₁ = o₂ | lt a b h₁ h₂ := h₁.eq_lt.2 h₂ | eq a b h₁ h₂ := h₁.eq_eq.2 h₂ | gt a b h₁ h₂ := h₁.eq_gt.2 h₂ theorem swap_or_else (o₁ o₂) : (or_else o₁ o₂).swap = or_else o₁.swap o₂.swap := by cases o₁; try {refl}; cases o₂; refl theorem or_else_eq_lt (o₁ o₂) : or_else o₁ o₂ = lt ↔ o₁ = lt ∨ (o₁ = eq ∧ o₂ = lt) := by cases o₁; cases o₂; exact dec_trivial end ordering theorem cmp_compares [decidable_linear_order α] (a b : α) : (cmp a b).compares a b := begin unfold cmp cmp_using, by_cases a < b; simp [h], by_cases h₂ : b < a; simp [h₂, gt], exact (lt_or_eq_of_le (le_of_not_gt h₂)).resolve_left h end theorem cmp_swap [preorder α] [@decidable_rel α (<)] (a b : α) : (cmp a b).swap = cmp b a := begin unfold cmp cmp_using, by_cases a < b; by_cases h₂ : b < a; simp [h, h₂, gt, ordering.swap], exact lt_asymm h h₂ end
ff761937bfb336cd28baa087d2271f80f185ae6f
ad3e8f15221a986da27c99f371922c0b3f5792b6
/src/week-02/solutions/e01-sets.lean
1550af0d0f1833ebdcc82c13581075f551db1af7
[]
no_license
VArtem/lean-itmo
a0e1424c8cc4c2de2ac85ab6fd4a12d80e9b85f1
dc44cd06f9f5b984d051831b3aaa7364e64c2dc4
refs/heads/main
1,683,761,214,467
1,622,821,295,000
1,622,821,295,000
357,236,048
12
0
null
null
null
null
UTF-8
Lean
false
false
13,069
lean
import data.set.basic import data.set.lattice /- Первые несколько строк файла на Lean импортируют нужные файлы. Если вы скачали репозиторий с помощью `leanproject`, то у вас автоматически в _target/deps/mathlib установлена библиотека mathlib: GitHub: https://github.com/leanprover-community/mathlib Документация: https://leanprover-community.github.io/mathlib_docs/ В VSCode с помощью Ctrl + Click по названию можно удобно перейти к импортированному файлу или определению леммы/функции. Lean поддерживает Unicode и много команд из LaTeX! Наведите курсор на символ, чтобы увидеть команду, с помощью которой его можно набрать. Часто используемые символы: → = \r, \to ← = \l ↔ = \iff, \lr ∀ = \all, \forall ∃ = \ex, \exists ∈ = \in, \mem ¬ = \not, \neg ⟨ = \<, ⟩ = \> ≠ = \neq, ≤ = \le ≥ = \ge ⊆ = \ss, \sub ⊂ = \ssub Sᶜ = \compl, \^c ∧ = \and, \wedge ∨ = \or, \vee ⊢ = \goal, \|- ∩ = \cap, \inter ∪ = \cup, \union -/ -- -- `variables (X : Type) (x : X)` позволяет в текущем контексте объявить переменные, чтобы не писать их каждый раз в сигнатурах: если вы используете `x` в определении леммы/теоремы, он автоматически добавится аргументом -- В фигурных скобках (`{X : Type}`) записываются неявные аргументы, про них чуть позже variables {X : Type} (A B C : set X) (p q : X) -- По определению, `set X` это функции из `X` в `Prop` (`X → Prop`). Если сделать Ctrl + Click по `set`, то вы перейдете к определению `set`, а там написано a ∈ X ↔ X a -- `a ∈ X` (\in или \mem) это по определению `X a` example : p ∈ A = A p := begin refl, end -- Вне tactic mode для обозначения равенства по определению используется `rfl` example : p ∈ A = A p := rfl -- Есть два специальных множества: `∅` (\empty) - пустое и `univ` - универсальное -- По определению, `p ∈ ∅ = false`, `p ∈ univ = true` lemma mem_empty : p ∈ (∅ : set X) ↔ false := begin refl, end lemma mem_univ : p ∈ (set.univ : set X) ↔ true := begin refl, end -- `lemma` и `theorem` обычно используют для утверждений (Prop), `def` для новых определений (типов или функций) -- Ко всему, что определено внутри namespace test, нужно обращаться с префиксом test -- Команда #check дает проверить тип выражения (использовать внутри begin-end блока нельзя) -- Обратите внимание на вставленные `∀ (X : Type) (A : set X) (p : X)`, которые пришли из `variables` -- `(B C : set X)` здесь нет, потому что `B` и `C` не используются namespace test lemma obviously_false : p ∈ A ↔ ¬ p ∈ A := sorry end test #check test.obviously_false -- `A ⊆ B` по определению то же самое, что `∀ ⦃x⦄, x ∈ A → x ∈ B` -- На выражение `∀ ⦃x⦄, x ∈ A → x ∈ B` следует смотреть, как на функцию, которая принимает `x` и доказательство того, что `x ∈ A`, а возвращает доказательство, что `x ∈ B` (`x` - необязательный аргумент, и можно сразу подавать `x ∈ A`) lemma subset_def : A ⊆ B = ∀ x : X, x ∈ A → x ∈ B := rfl lemma subset_refl : A ⊆ A := begin -- попробуйте начать сразу с `intro x`, `rw subset_def` делать не обязательно (но пока вы не знакомы с определениями, можно их раскрывать явно) intros x xA, exact xA, end lemma subset_trans : A ⊆ B → B ⊆ C → A ⊆ C := begin intros hAB hBC x xA, exact hBC (hAB xA), end -- Два множества равны, если в них содержатся одинаковые элементы -- "ext" означает extensionality, "объекты равны, если они внешне ведут себя одинаково" -- Чтобы доказать равенство каких-то объектов (множеств, функций, ...), используйте тактику `ext` lemma set_eq_def : A = B ↔ ∀ x, x ∈ A ↔ x ∈ B := set.ext_iff -- A ↔ B это просто пара ⟨A → B, B → A⟩ (обратите внимание, здесь угловые скобки \< \>) lemma subset_antisymm : A ⊆ B → B ⊆ A → A = B := begin intros hAB hBA, ext, split, { intro xA, exact hAB xA, }, { intro xB, exact hBA xB, }, end -- term mode, конструируем доказательство не тактиками, а напрямую example : A ⊆ B → B ⊆ A → A = B := λ hAB hBA, set.ext_iff.2 (λ x, ⟨λ xA, hAB xA, λ xB, hBA xB⟩) -- Аргументы бывают явные и неявные -- В сигнатуре функции до `:` можно написать именованные аргументы -- `lemma f (h : α) : β` по сути то же самое, что `lemma f : α → β` -- Некоторые аргументы можно делать неявными, если их можно вывести из последующих аргументов -- Иногда можно опустить тип аргументов (и явных, и неявных) lemma implicit_args {X} {A B : set X} {x : X} : x ∈ A → x ∈ B := sorry #check implicit_args #check @implicit_args lemma subset_trans' (X : Type) (A B C : set X) : A ⊆ B → B ⊆ C → A ⊆ C := sorry lemma subset_trans'' {X : Type} {A B C : set X} : A ⊆ B → B ⊆ C → A ⊆ C := sorry #check subset_trans #check subset_trans' #check subset_trans'' -- "@" перед названием функции делает все неявные аргументы явными #check @subset_trans'' -- Пересечение и объединение lemma union_def : (p ∈ A ∪ B) = (p ∈ A ∨ p ∈ B) := rfl lemma inter_def : (p ∈ A ∩ B) = (p ∈ A ∧ p ∈ B) := rfl -- Тактика `rcases` позволяет разбирать структуры на части за одно применение -- Если `h : α ∧ β ∧ γ`, то `rcases h with ⟨ha, hb, hc⟩` даст три нужные гипотезы -- Если `h : α ∨ β`, то `rcases h with (ha | hb)` даст две цели с `ha : α` в первой и `hb : β` во второй -- Если `h : example : (p ∈ A ∨ p ∈ B) ∧ (p ∈ C) → p ∈ (A ∪ B) ∩ C := begin intro h, rcases h with ⟨(hA | hB), hC⟩, -- Цель: `⊢ p ∈ (A ∪ B) ∩ C`, можно с помощью `exact` и `or.inl hA` сразу сконструировать ответ exact ⟨or.inl hA, hC⟩, -- Аналогично с `or.inr hB` exact ⟨or.inr hB, hC⟩, end -- На самом деле это верно по определению example : (p ∈ A ∨ p ∈ B) ∧ (p ∈ C) → p ∈ (A ∪ B) ∩ C := id -- Тактика `rintro` = `intros` + `rcases`: применяет `intros` и сразу `rcases` ко всем новым переменным -- Когда цель выглядит как `α ∧ β → γ`, вместо того, чтобы делать `intro h`, `cases h with ha hb`, можно использовать `rintro ⟨hA, hB⟩` и сразу получить `hA : α`, `hB : β` в контексте example : p ∈ A ∨ (p ∈ B ∧ p ∈ C) → p ∈ A ∪ (B ∩ C) := begin rintro (pA | ⟨pB, pC⟩), -- две цели, соответствующие двум конструкторам `or` left, exact pA, right, exact ⟨pB, pC⟩, end lemma inter_assoc (A B C : set X) : (A ∩ B) ∩ C = A ∩ (B ∩ C) := begin ext x, split, { rintro ⟨⟨hA, hB⟩, hC⟩, exact ⟨hA, ⟨hB, hC⟩⟩ }, { rintro ⟨hA, ⟨hB, hC⟩⟩, exact ⟨⟨hA, hB⟩, hC⟩}, end lemma union_assoc (A B C : set X) : (A ∪ B) ∪ C = A ∪ (B ∪ C) := begin ext x, split, { rintro ((hA | hB) | hC), left, exact hA, right, left, exact hB, right, right, exact hC, }, { rintro (hA | (hB | hC)), left, left, exact hA, left, right, exact hB, right, exact hC, }, end -- Тактика `all_goals {...}` применяет блок ко всем целям example (A B C : set X) : (A ∪ B) ∪ C = A ∪ (B ∪ C) := begin ext x, split, all_goals {repeat {rw set.mem_union}, tauto}, end lemma union_eq_of_subset (hAB : A ⊆ B) : A ∪ B = B := begin ext x, split, { rintro (hA | hB), exact (hAB hA), exact hB }, { intro hB, right, exact hB }, end lemma inter_eq_iff_subset : A ⊆ B ↔ A ∩ B = A := begin split, { intro hAB, ext, split, rintro ⟨xA, xB⟩, exact xA, intro xA, exact ⟨xA, hAB xA⟩, }, { rintro hInter x xA, rw ← hInter at xA, cases xA with xA xB, exact xB, }, end -- `Aᶜ` (A\^c) это дополнение `A`, то есть, `p ∈ Aᶜ = p ∉ A = ¬p ∈ A` #check @set.mem_compl example : p ∉ A = ¬p ∈ A := rfl example : p ∈ Aᶜ = (p ∉ A) := rfl lemma compl_subset_compl_of_subset (hAB : A ⊆ B) : Bᶜ ⊆ Aᶜ := begin intros x xBC xA, apply xBC, apply hAB, exact xA, end -- Закон де Моргана -- Полезные тактики: `simp at h ⊢` упростит локальную гипотезу и цель (можно также написать `simp at *`, что будет упрощать все локальные гипотезы и цель) -- `tauto` решает цели в логике высказываний, `tauto!` работает в классической логике и может использовать закон исключенного третьего lemma compl_inter_eq_compl_union_compl : (A ∩ B)ᶜ = Aᶜ ∪ Bᶜ := begin ext, split, { intro xABc, simp at xABc ⊢, tauto!, }, { intro xAcBc, simp at xAcBc ⊢, tauto, }, end -- Для объединения/пересечений нескольких множеств есть следующие операторы: -- Леммы про них лежат в `data.set.lattice` -- 1. Если `f : ι → set S`, то `⋃ (i : ι), f i` равно объединению `f i`, где `i` пробегает все элементы типа `ι` -- `x` принадлежит `⋃ (i : ι), f i` ↔ `∃ i, x ∈ f i` -- Леммы про такое объединение содержат `Union` в названии lemma Union_def {S ι} {F : ι → set S} : set.Union F = ⋃ i, F i := begin refl, end lemma mem_Union {S ι} {x : S} {F : ι → set S} : (x ∈ ⋃ i, F i) ↔ (∃ i, x ∈ F i) := begin exact set.mem_Union, end -- 2. `bUnion` (от bounded union) берет объединение только по `i`, лежащим в множестве `I : set ι` -- Обратите внимание на нотацию `∃ i ∈ I`, это сокращение от `∃ i (H : i ∈ I)`, то есть, "существует `i` и доказательство `i ∈ I`" lemma mem_bUnion {S ι} {x : S} {F : ι → set S} {I ∀ {S T}, f ⁻¹' S ⊆ f ⁻¹' T → S ⊆ T: set ι} : (x ∈ ⋃ i ∈ I, F i) ↔ (∃ i ∈ I, x ∈ F i) := begin exact set.mem_bUnion_iff, end -- 3. Если у нас есть (s : set (set S)), то `⋃₀ s : set S` объединяет все множества, лежащие в `s` -- Леммы про такое объединение содержат `sUnion` в названии lemma mem_sUnion {S} {x : S} {s : set (set S)} : (x ∈ ⋃₀ s) ↔ (∃ t ∈ s, x ∈ t) := begin exact set.mem_sUnion, end -- Пересечение всех множеств, содержащих `S` как подмножество, равно `S` def supersets {X : Type} (S : set X) : set (set X) := {T | S ⊆ T} lemma supersets_sInter {S : set X} : ⋂₀ (supersets S) = S := begin apply subset_antisymm, { intros x hx, rw [set.mem_sInter] at hx, apply hx S, dsimp [supersets], exact subset_refl _, }, { apply set.subset_sInter, intros x hx, exact hx, }, end
95dc6801b5ce311f1f3dfda5bd90233a83b1fd94
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/inv_bug.lean
9ddd36931a5bc001a9770cd3da77eb127f875180
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
457
lean
open nat open eq.ops inductive even : nat → Prop := even_zero : even zero, even_succ_of_odd : ∀ {a}, odd a → even (succ a) with odd : nat → Prop := odd_succ_of_even : ∀ {a}, even a → odd (succ a) example : even 1 → false := begin intro He1, cases He1 with (a, Ho0), cases Ho0 end example : even 3 → false := begin intro He3, cases He3 with (a, Ho2), cases Ho2 with (a, He1), cases He1 with (a, Ho0), cases Ho0 end
46cc3528d6a09ece2cb293be0b042451be4a50b5
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/new_compiler.lean
951600cc37d908e68ce1a918b63026a8af070b78
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,773
lean
universes u v w r s set_option trace.compiler.stage1 true -- setOption pp.implicit True set_option pp.binder_types false set_option pp.proofs true def foo (n : Nat) : Nat := let x := Nat.zero; let x1 := Nat.succ x; let x2 := Nat.succ x1; let x3 := Nat.succ x2; let x4 := Nat.succ x3; let x5 := Nat.succ x4; let x6 := Nat.succ x5; let x7 := Nat.succ x ; let x8 := Nat.succ x7; let y1 := x; let y2 := y1; y2 + n def cseTst (n : Nat) : Nat := let y := Nat.succ ((fun x => x) n); let z := Nat.succ n; y + z def tst1 (n : Nat) : Nat := let p := (Nat.succ n, n); let q := (p, p); Prod.casesOn q (fun x y => Prod.casesOn x (fun z w => z)) def tst2 (n : Nat) : Nat := let p := (fun x => Nat.succ x, Nat.zero) ; let f := fun (p : (Nat → Nat) × Nat) => p.1; f p n def add' : Nat → Nat → Nat | 0, b => Nat.succ b | a+1, b => Nat.succ (Nat.succ (add' a b)) def aux (i : Nat) (h : i > 0) := i axiom bad (α : Sort u) : α unsafe def foo2 : Nat := @False.rec (fun _ => Nat) (bad _) set_option pp.notation false def foo3 (n : Nat) : Nat := (fun (a : Nat) => a + a + a) (n*n) def boo (a : Nat) (l : List Nat) : List Nat := let f := @List.cons Nat; f a (f a l) def bla (i : Nat) (h : i > 0 ∧ i ≠ 10) : Nat := @And.rec _ _ (fun _ => Nat) (fun h₁ h₂ => aux i h₁ + aux i h₁) h def bla' (i : Nat) (h : i > 0 ∧ i ≠ 10) : Nat := @And.casesOn _ _ (fun _ => Nat) h (fun h₁ h₂ => aux i h₁ + aux i h₁) inductive vec (α : Type u) : Nat → Type u | nil : vec 0 | cons : ∀ {n}, α → vec n → vec (Nat.succ n) def vec.map {α β σ : Type u} (f : α → β → σ) : ∀ {n : Nat}, vec α n → vec β n → vec σ n | _, vec.nil, vec.nil => vec.nil | _, vec.cons a as, vec.cons b bs => vec.cons (f a b) (vec.map as bs)