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
2cd6eaf305ff2f52901afe441ddb347eb6fd1c00
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/aops/2017-Indonesia_MO-Problem_4.lean
f03143dd6a7c2557b832c9d778c7d95358045ae4
[]
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
188
lean
import data.real.basic theorem indonesia_MO_Probel_4_2017 (x y : ℝ): (x^100 - y^100 = 2^99 * (x-y)) ∧ (x^200 - y^200 = 2^199 * (x-y)) → ((x,y) = (0,2) ∨ (x,y) = (2,0)) := sorry
afc51e6b890516536c30df7a605693d80f73dff2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monoidal/End.lean
0cbccfb3b54e11497111cb176a8b60397ab1c284
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,748
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.monoidal.functor import Mathlib.PostPort universes u v namespace Mathlib /-! # Endofunctors as a monoidal category. We give the monoidal category structure on `C ⥤ C`, and show that when `C` itself is monoidal, it embeds via a monoidal functor into `C ⥤ C`. ## TODO Can we use this to show coherence results, e.g. a cheap proof that `λ_ (𝟙_ C) = ρ_ (𝟙_ C)`? I suspect this is harder than is usually made out. -/ namespace category_theory /-- The category of endofunctors of any category is a monoidal category, with tensor product given by composition of functors (and horizontal composition of natural transformations). -/ def endofunctor_monoidal_category (C : Type u) [category C] : monoidal_category (C ⥤ C) := monoidal_category.mk (fun (F G : C ⥤ C) => F ⋙ G) (fun (F G F' G' : C ⥤ C) (α : F ⟶ G) (β : F' ⟶ G') => α ◫ β) 𝟭 (fun (F G H : C ⥤ C) => functor.associator F G H) (fun (F : C ⥤ C) => functor.left_unitor F) fun (F : C ⥤ C) => functor.right_unitor F /-- Tensoring on the right gives a monoidal functor from `C` into endofunctors of `C`. -/ @[simp] theorem tensoring_right_monoidal_to_lax_monoidal_functor_to_functor (C : Type u) [category C] [monoidal_category C] : lax_monoidal_functor.to_functor (monoidal_functor.to_lax_monoidal_functor (tensoring_right_monoidal C)) = monoidal_category.tensoring_right C := Eq.refl (lax_monoidal_functor.to_functor (monoidal_functor.to_lax_monoidal_functor (tensoring_right_monoidal C)))
83e285301fc846bc3356bd1c5ed1e8f704b72890
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Std/Data/DList.lean
1105f698f534fbf057fabd6082a651d7df63fe27
[ "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
1,820
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 -/ namespace Std universes u /-- A difference List is a Function that, given a List, returns the original contents of the difference List prepended to the given List. This structure supports `O(1)` `append` and `concat` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ structure DList (α : Type u) := (apply : List α → List α) (invariant : ∀ l, apply l = apply [] ++ l) namespace DList variables {α : Type u} open List def ofList (l : List α) : DList α := ⟨Append.append l, fun t => by rw appendNil; rfl⟩ def empty : DList α := ⟨id, fun t => rfl⟩ instance : EmptyCollection (DList α) := ⟨DList.empty⟩ def toList : DList α → List α | ⟨f, h⟩ => f [] def singleton (a : α) : DList α := { apply := fun t => a :: t, invariant := fun t => rfl } def cons : α → DList α → DList α | a, ⟨f, h⟩ => { apply := fun t => a :: f t, invariant := by intro t show a :: f t = a :: f [] ++ t rw [consAppend, h] rfl } def append : DList α → DList α → DList α | ⟨f, h₁⟩, ⟨g, h₂⟩ => { apply := f ∘ g, invariant := by intro t show f (g t) = (f (g [])) ++ t rw [h₁ (g t), h₂ t, ← appendAssoc (f []) (g []) t, ← h₁ (g [])] rfl } def push : DList α → α → DList α | ⟨f, h⟩, a => { apply := fun t => f (a :: t), invariant := by intro t show f (a :: t) = f (a :: nil) ++ t rw [h [a], h (a::t), appendAssoc (f []) [a] t] rfl } instance : Append (DList α) := ⟨DList.append⟩ end DList end Std
21a37e651c396783e340db69f0df6f0c770045c0
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/algebra/category/Group/biproducts.lean
1dabdd71f9109fb465d3c1c2f4d66b1206b36015
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
2,989
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Group.basic import algebra.category.Group.preadditive import category_theory.limits.shapes.biproducts import algebra.group.pi /-! # The category of abelian groups has finite biproducts -/ open category_theory open category_theory.limits open_locale big_operators universe u namespace AddCommGroup instance has_binary_product (G H : AddCommGroup.{u}) : has_binary_product G H := { cone := { X := AddCommGroup.of (G × H), π := { app := λ j, walking_pair.cases_on j (add_monoid_hom.fst G H) (add_monoid_hom.snd G H) }}, is_limit := { lift := λ s, add_monoid_hom.prod (s.π.app walking_pair.left) (s.π.app walking_pair.right), fac' := begin rintros s (⟨⟩|⟨⟩); { ext x, simp, }, end, uniq' := λ s m w, begin ext; [rw ← w walking_pair.left, rw ← w walking_pair.right]; refl, end, } } instance (G H : AddCommGroup.{u}) : has_binary_biproduct G H := has_binary_biproduct.of_has_binary_product _ _ -- We verify that the underlying type of the biproduct we've just defined is definitionally -- the cartesian product of the underlying types: example (G H : AddCommGroup.{u}) : ((G ⊞ H : AddCommGroup) : Type u) = (G × H) := rfl -- Furthermore, our biproduct will automatically function as a coproduct. example (G H : AddCommGroup.{u}) : has_colimit (pair G H) := by apply_instance variables {J : Type u} (F : (discrete J) ⥤ AddCommGroup.{u}) namespace has_limit /-- The map from an arbitrary cone over a indexed family of abelian groups to the cartesian product of those groups. -/ def lift (s : cone F) : s.X ⟶ AddCommGroup.of (Π j, F.obj j) := { to_fun := λ x j, s.π.app j x, map_zero' := by { ext, simp }, map_add' := λ x y, by { ext, simp }, } @[simp] lemma lift_apply (s : cone F) (x : s.X) (j : J) : (lift F s) x j = s.π.app j x := rfl instance has_limit_discrete : has_limit F := { cone := { X := AddCommGroup.of (Π j, F.obj j), π := discrete.nat_trans (λ j, add_monoid_hom.apply (λ j, F.obj j) j), }, is_limit := { lift := lift F, fac' := λ s j, by { ext, simp, }, uniq' := λ s m w, begin ext x j, dsimp only [has_limit.lift], simp only [add_monoid_hom.coe_mk], exact congr_arg (λ f : s.X ⟶ F.obj j, (f : s.X → F.obj j) x) (w j), end, }, } end has_limit section open has_limit variables [decidable_eq J] [fintype J] instance (f : J → AddCommGroup.{u}) : has_biproduct f := has_biproduct.of_has_product _ -- We verify that the underlying type of the biproduct we've just defined is definitionally -- the dependent function type: example (f : J → AddCommGroup.{u}) : ((⨁ f : AddCommGroup) : Type u) = (Π j, f j) := rfl end instance : has_finite_biproducts AddCommGroup := ⟨λ J _ _, { has_biproduct := λ f, by exactI infer_instance }⟩ end AddCommGroup
8b137c0bd5ac8e4e6667d8064c682ca032d7db05
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/omega/nat/form.lean
8fca60f27030289506b62bb7a057daf98fedd23e
[]
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
2,842
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.omega.nat.preterm import Mathlib.PostPort universes l namespace Mathlib /- Linear natural number arithmetic preformulas in pre-normalized preform. -/ namespace omega namespace nat /-- Intermediate shadow syntax for LNA formulas that includes unreified exprs -/ /-- Intermediate shadow syntax for LNA formulas that includes non-canonical terms -/ inductive preform where | eq : preterm → preterm → preform | le : preterm → preterm → preform | not : preform → preform | or : preform → preform → preform | and : preform → preform → preform namespace preform /-- Evaluate a preform into prop using the valuation `v`. -/ @[simp] def holds (v : ℕ → ℕ) : preform → Prop := sorry end preform /-- `univ_close p n` := `p` closed by prepending `n` universal quantifiers -/ @[simp] def univ_close (p : preform) : (ℕ → ℕ) → ℕ → Prop := sorry namespace preform /-- Argument is free of negations -/ def neg_free : preform → Prop := sorry /-- Return expr of proof that argument is free of subtractions -/ def sub_free : preform → Prop := sorry /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preform → ℕ := sorry theorem holds_constant {v : ℕ → ℕ} {w : ℕ → ℕ} (p : preform) : (∀ (x : ℕ), x < fresh_index p → v x = w x) → (holds v p ↔ holds w p) := sorry /-- All valuations satisfy argument -/ def valid (p : preform) := ∀ (v : ℕ → ℕ), holds v p /-- There exists some valuation that satisfies argument -/ def sat (p : preform) := ∃ (v : ℕ → ℕ), holds v p /-- `implies p q` := under any valuation, `q` holds if `p` holds -/ def implies (p : preform) (q : preform) := ∀ (v : ℕ → ℕ), holds v p → holds v q /-- `equiv p q` := under any valuation, `p` holds iff `q` holds -/ def equiv (p : preform) (q : preform) := ∀ (v : ℕ → ℕ), holds v p ↔ holds v q theorem sat_of_implies_of_sat {p : preform} {q : preform} : implies p q → sat p → sat q := fun (h1 : implies p q) (h2 : sat p) => exists_imp_exists h1 h2 theorem sat_or {p : preform} {q : preform} : sat (or p q) ↔ sat p ∨ sat q := sorry /-- There does not exist any valuation that satisfies argument -/ def unsat (p : preform) := ¬sat p def repr : preform → string := sorry protected instance has_repr : has_repr preform := has_repr.mk repr end preform theorem univ_close_of_valid {p : preform} {m : ℕ} {v : ℕ → ℕ} : preform.valid p → univ_close p v m := sorry theorem valid_of_unsat_not {p : preform} : preform.unsat (preform.not p) → preform.valid p := sorry
a5d6f5b4eb6b1c840ffa5a8b92313fc3320a6230
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
/src/sheaves/presheaf.lean
7b1759a077cfbb3fd69e3e69c38d2b4047bf3d09
[]
no_license
alreadydone/lean-scheme
04c51ab08eca7ccf6c21344d45d202780fa667af
52d7624f57415eea27ed4dfa916cd94189221a1c
refs/heads/master
1,599,418,221,423
1,562,248,559,000
1,562,248,559,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,054
lean
/- Presheaf (of types). https://stacks.math.columbia.edu/tag/006D -/ import topology.basic import topology.opens universes u v -- Definition of a presheaf. open topological_space lattice structure presheaf (α : Type u) [topological_space α] := (F : opens α → Type v) (res : ∀ (U V) (HVU : V ⊆ U), F U → F V) (Hid : ∀ (U), res U U (set.subset.refl U) = id) (Hcomp : ∀ (U V W) (HWV : W ⊆ V) (HVU : V ⊆ U), res U W (set.subset.trans HWV HVU) = res V W HWV ∘ res U V HVU) namespace presheaf variables {α : Type u} [topological_space α] instance : has_coe_to_fun (presheaf α) := { F := λ _, opens α → Type v, coe := presheaf.F } -- Simplification lemmas for Hid and Hcomp. @[simp] lemma Hcomp' (F : presheaf α) : ∀ (U V W) (HWV : W ⊆ V) (HVU : V ⊆ U) (s : F U), (F.res U W (set.subset.trans HWV HVU)) s = (F.res V W HWV) ((F.res U V HVU) s) := λ U V W HWV HVU s, by rw F.Hcomp U V W HWV HVU @[simp] lemma Hid' (F : presheaf α) : ∀ (U) (s : F U), (F.res U U (set.subset.refl U)) s = s := λ U s, by rw F.Hid U; simp -- Morphism of presheaves. structure morphism (F G : presheaf α) := (map : ∀ (U), F U → G U) (commutes : ∀ (U V) (HVU : V ⊆ U), (G.res U V HVU) ∘ (map U) = (map V) ∘ (F.res U V HVU)) infix `⟶`:80 := morphism section morphism def comp {F G H : presheaf α} (fg : F ⟶ G) (gh : G ⟶ H) : F ⟶ H := { map := λ U, gh.map U ∘ fg.map U, commutes := λ U V HVU, begin rw [←function.comp.assoc, gh.commutes U V HVU], symmetry, rw [function.comp.assoc, ←fg.commutes U V HVU] end } infix `⊚`:80 := comp def id (F : presheaf α) : F ⟶ F := { map := λ U, id, commutes := λ U V HVU, by simp, } structure iso (F G : presheaf α) := (mor : F ⟶ G) (inv : G ⟶ F) (mor_inv_id : mor ⊚ inv = id F) (inv_mor_id : inv ⊚ mor = id G) infix `≅`:80 := iso end morphism -- Equality lemma lemma presheaf_eq_of_subset_eq (F : presheaf α) (U V : opens α) : U = V → F U = F V := λ h, by rw h end presheaf
aef65edbbcea9a9a46b53363bcf89cd9c5985171
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/appParserIssue.lean
d80c2582ac7a3f28ffd43e733a8e6013bc526ece
[ "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
321
lean
def f (x : Nat) (g : Nat → Nat) := g x #check f 1 fun x => x -- should work #check f 1 (fun x => x) -- should work #check f 1 $ fun x => x -- should work syntax "foo" term:max term:max : term macro_rules `(foo $x $y) => `(f $x $y) #check foo 1 (fun x => x) -- should work #check foo 1 fun x => x -- should work
d04fd12f7e8239e9eee0960a77562201b89dd008
9028d228ac200bbefe3a711342514dd4e4458bff
/src/category_theory/limits/preserves/shapes.lean
5fd8f73dee2181ade71b967adea4a29da5d687ef
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,744
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.preserves.basic import category_theory.limits.shapes.products universes v u₁ u₂ noncomputable theory open category_theory open category_theory.limits variables {C : Type u₁} [category.{v} C] variables {D : Type u₂} [category.{v} D] variables (G : C ⥤ D) [preserves_limits G] section variables {J : Type v} [small_category J] /-- If `G` preserves limits, we have an isomorphism from the image of the limit of a functor `F` to the limit of the functor `F ⋙ G`. -/ def preserves_limits_iso (F : J ⥤ C) [has_limit F] [has_limit (F ⋙ G)] : G.obj (limit F) ≅ limit (F ⋙ G) := (cones.forget _).map_iso (is_limit.unique_up_to_iso (preserves_limit.preserves (limit.is_limit F)) (limit.is_limit (F ⋙ G))) @[simp, reassoc] lemma preserves_limits_iso_hom_π (F : J ⥤ C) [has_limit F] [has_limit (F ⋙ G)] (j) : (preserves_limits_iso G F).hom ≫ limit.π _ j = G.map (limit.π F j) := begin dsimp [preserves_limits_iso, has_limit.iso_of_nat_iso, cones.postcompose, is_limit.unique_up_to_iso, is_limit.lift_cone_morphism], simp, end /-- If `G` preserves limits, we have an isomorphism from the image of a product to the product of the images. -/ -- TODO perhaps weaken the assumptions here, to just require the relevant limits? def preserves_products_iso {J : Type v} (f : J → C) [has_limits C] [has_limits D] : G.obj (pi_obj f) ≅ pi_obj (λ j, G.obj (f j)) := preserves_limits_iso G (discrete.functor f) ≪≫ has_limit.iso_of_nat_iso (discrete.nat_iso (λ j, iso.refl _)) @[simp, reassoc] lemma preserves_products_iso_hom_π {J : Type v} (f : J → C) [has_limits C] [has_limits D] (j) : (preserves_products_iso G f).hom ≫ pi.π _ j = G.map (pi.π f j) := begin dsimp [preserves_products_iso, preserves_limits_iso, has_limit.iso_of_nat_iso, cones.postcompose, is_limit.unique_up_to_iso, is_limit.lift_cone_morphism, is_limit.map], simp only [limit.lift_π, discrete.nat_iso_hom_app, limit.cone_π, limit.lift_π_assoc, nat_trans.comp_app, category.assoc, functor.map_cone_π, is_limit.map_π], dsimp, simp, -- See note [dsimp, simp], end @[simp, reassoc] lemma map_lift_comp_preserves_products_iso_hom {J : Type v} (f : J → C) [has_limits C] [has_limits D] (P : C) (g : Π j, P ⟶ f j) : G.map (pi.lift g) ≫ (preserves_products_iso G f).hom = pi.lift (λ j, G.map (g j)) := begin ext, simp only [limit.lift_π, fan.mk_π_app, preserves_products_iso_hom_π, category.assoc], simp only [←G.map_comp], simp only [limit.lift_π, fan.mk_π_app], end end
e2c338bca4395b0cb592a014bc78a639bef9704e
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/topology/algebra/group.lean
36b71eb4a6b9c39454e7516ad5f79f90d892cc38
[ "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
26,414
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 order.filter.pointwise import group_theory.quotient_group import topology.algebra.monoid import topology.homeomorph /-! # Theory of topological groups This file defines the following typeclasses: * `topological_group`, `topological_add_group`: multiplicative and additive topological groups, i.e., groups with continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`; * `has_continuous_sub G` means that `G` has a continuous subtraction operation. There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate typeclass because, e.g., `ℕ` and `ℝ≥0` have continuous subtraction but are not additive groups. We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`, `homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in groups. ## Tags topological space, group, topological group -/ open classical set filter topological_space function open_locale classical topological_space filter universes u v w x variables {α : Type u} {β : Type v} {G : Type w} {H : Type x} section continuous_mul_group /-! ### Groups with continuous multiplication In this section we prove a few statements about groups with continuous `(*)`. -/ variables [topological_space G] [group G] [has_continuous_mul G] /-- Multiplication from the left in a topological group as a homeomorphism. -/ @[to_additive "Addition from the left in a topological additive group as a homeomorphism."] protected def homeomorph.mul_left (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[simp, to_additive] lemma homeomorph.coe_mul_left (a : G) : ⇑(homeomorph.mul_left a) = (*) a := rfl @[to_additive] lemma homeomorph.mul_left_symm (a : G) : (homeomorph.mul_left a).symm = homeomorph.mul_left a⁻¹ := by { ext, refl } @[to_additive] lemma is_open_map_mul_left (a : G) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive] lemma is_closed_map_mul_left (a : G) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map /-- Multiplication from the right in a topological group as a homeomorphism. -/ @[to_additive "Addition from the right in a topological additive group as a homeomorphism."] protected def homeomorph.mul_right (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[to_additive] lemma is_open_map_mul_right (a : G) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive] lemma is_closed_map_mul_right (a : G) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map @[to_additive] lemma is_open_map_div_right (a : G) : is_open_map (λ x, x / a) := by simpa only [div_eq_mul_inv] using is_open_map_mul_right (a⁻¹) @[to_additive] lemma is_closed_map_div_right (a : G) : is_closed_map (λ x, x / a) := by simpa only [div_eq_mul_inv] using is_closed_map_mul_right (a⁻¹) end continuous_mul_group section topological_group /-! ### Topological groups A topological group is a group in which the multiplication and inversion operations are continuous. Topological additive groups are defined in the same way. Equivalently, we can require that the division operation `λ x y, x * y⁻¹` (resp., subtraction) is continuous. -/ /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (G : Type u) [topological_space G] [add_group G] extends has_continuous_add G : Prop := (continuous_neg : continuous (λa:G, -a)) /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ @[to_additive] class topological_group (G : Type*) [topological_space G] [group G] extends has_continuous_mul G : Prop := (continuous_inv : continuous (has_inv.inv : G → G)) variables [topological_space G] [group G] [topological_group G] export topological_group (continuous_inv) export topological_add_group (continuous_neg) @[to_additive] lemma continuous_on_inv {s : set G} : continuous_on has_inv.inv s := continuous_inv.continuous_on @[to_additive] lemma continuous_within_at_inv {s : set G} {x : G} : continuous_within_at has_inv.inv s x := continuous_inv.continuous_within_at @[to_additive] lemma continuous_at_inv {x : G} : continuous_at has_inv.inv x := continuous_inv.continuous_at @[to_additive] lemma tendsto_inv (a : G) : tendsto has_inv.inv (𝓝 a) (𝓝 (a⁻¹)) := continuous_at_inv /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive] lemma filter.tendsto.inv {f : α → G} {l : filter α} {y : G} (h : tendsto f l (𝓝 y)) : tendsto (λ x, (f x)⁻¹) l (𝓝 y⁻¹) := (continuous_inv.tendsto y).comp h variables [topological_space α] {f : α → G} {s : set α} {x : α} @[continuity, to_additive] lemma continuous.inv (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf attribute [continuity] continuous.neg -- TODO @[to_additive] lemma continuous_on.inv (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf @[to_additive] lemma continuous_within_at.inv (hf : continuous_within_at f s x) : continuous_within_at (λ x, (f x)⁻¹) s x := hf.inv @[instance, to_additive] instance [topological_space H] [group H] [topological_group H] : topological_group (G × H) := { continuous_inv := continuous_inv.prod_map continuous_inv } variable (G) /-- Inversion in a topological group as a homeomorphism. -/ @[to_additive "Negation in a topological group as a homeomorphism."] protected def homeomorph.inv : G ≃ₜ G := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv G } @[to_additive] lemma nhds_one_symm : comap has_inv.inv (𝓝 (1 : G)) = 𝓝 (1 : G) := ((homeomorph.inv G).comap_nhds_eq _).trans (congr_arg nhds one_inv) /-- The map `(x, y) ↦ (x, xy)` as a homeomorphism. This is a shear mapping. -/ @[to_additive "The map `(x, y) ↦ (x, x + y)` as a homeomorphism. This is a shear mapping."] protected def homeomorph.shear_mul_right : G × G ≃ₜ G × G := { continuous_to_fun := continuous_fst.prod_mk continuous_mul, continuous_inv_fun := continuous_fst.prod_mk $ continuous_fst.inv.mul continuous_snd, .. equiv.prod_shear (equiv.refl _) equiv.mul_left } @[simp, to_additive] lemma homeomorph.shear_mul_right_coe : ⇑(homeomorph.shear_mul_right G) = λ z : G × G, (z.1, z.1 * z.2) := rfl @[simp, to_additive] lemma homeomorph.shear_mul_right_symm_coe : ⇑(homeomorph.shear_mul_right G).symm = λ z : G × G, (z.1, z.1⁻¹ * z.2) := rfl variable {G} @[to_additive] lemma inv_closure (s : set G) : (closure s)⁻¹ = closure s⁻¹ := (homeomorph.inv G).preimage_closure s @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv {s : set G} (hs : s ∈ 𝓝 (1 : G)) : ∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v / w ∈ s := have ((λp : G × G, p.1 * p.2⁻¹) ⁻¹' s) ∈ 𝓝 ((1, 1) : G × G), from continuous_at_fst.mul continuous_at_snd.inv (by simpa), by simpa only [div_eq_mul_inv, nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage] using this @[to_additive] lemma nhds_translation_mul_inv (x : G) : comap (λ y : G, y * x⁻¹) (𝓝 1) = 𝓝 x := ((homeomorph.mul_right x⁻¹).comap_nhds_eq 1).trans $ show 𝓝 (1 * x⁻¹⁻¹) = 𝓝 x, by simp @[simp, to_additive] lemma map_mul_left_nhds (x y : G) : map ((*) x) (𝓝 y) = 𝓝 (x * y) := (homeomorph.mul_left x).map_nhds_eq y @[to_additive] lemma map_mul_left_nhds_one (x : G) : map ((*) x) (𝓝 1) = 𝓝 x := by simp @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] @[to_additive] lemma topological_group.of_nhds_aux {G : Type*} [group G] [topological_space G] (hinv : tendsto (λ (x : G), x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ (x₀ : G), 𝓝 x₀ = map (λ (x : G), x₀ * x) (𝓝 1)) (hconj : ∀ (x₀ : G), map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) ≤ 𝓝 1) : continuous (λ x : G, x⁻¹) := begin rw continuous_iff_continuous_at, rintros x₀, have key : (λ x, (x₀*x)⁻¹) = (λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹) ∘ (λ x, x⁻¹), by {ext ; simp[mul_assoc] }, calc map (λ x, x⁻¹) (𝓝 x₀) = map (λ x, x⁻¹) (map (λ x, x₀*x) $ 𝓝 1) : by rw hleft ... = map (λ x, (x₀*x)⁻¹) (𝓝 1) : by rw filter.map_map ... = map (((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) ∘ (λ x, x⁻¹)) (𝓝 1) : by rw key ... = map ((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) _ : by rw ← filter.map_map ... ≤ map ((λ x, x₀⁻¹ * x) ∘ λ x, x₀ * x * x₀⁻¹) (𝓝 1) : map_mono hinv ... = map (λ x, x₀⁻¹ * x) (map (λ x, x₀ * x * x₀⁻¹) (𝓝 1)) : filter.map_map ... ≤ map (λ x, x₀⁻¹ * x) (𝓝 1) : map_mono (hconj x₀) ... = 𝓝 x₀⁻¹ : (hleft _).symm end @[to_additive] lemma topological_group.of_nhds_one' {G : Type*} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : topological_group G := begin refine { continuous_mul := (has_continuous_mul.of_nhds_one hmul hleft hright).continuous_mul, continuous_inv := topological_group.of_nhds_aux hinv hleft _ }, intros x₀, suffices : map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) = 𝓝 1, by simp [this, le_refl], rw [show (λ x, x₀ * x * x₀⁻¹) = (λ x, x₀ * x) ∘ λ x, x*x₀⁻¹, by {ext, simp [mul_assoc] }, ← filter.map_map, ← hright, hleft x₀⁻¹, filter.map_map], convert map_id, ext, simp end @[to_additive] lemma topological_group.of_nhds_one {G : Type*} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hconj : ∀ x₀ : G, tendsto (λ x, x₀*x*x₀⁻¹) (𝓝 1) (𝓝 1)) : topological_group G := { continuous_mul := begin rw continuous_iff_continuous_at, rintros ⟨x₀, y₀⟩, have key : (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) = ((λ x, x₀*y₀*x) ∘ (uncurry (*)) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id)), by { ext, simp [uncurry, prod.map, mul_assoc] }, specialize hconj y₀⁻¹, rw inv_inv at hconj, calc map (λ (p : G × G), p.1 * p.2) (𝓝 (x₀, y₀)) = map (λ (p : G × G), p.1 * p.2) ((𝓝 x₀) ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [hleft x₀, hleft y₀, prod_map_map_eq, filter.map_map] ... = map (((λ x, x₀*y₀*x) ∘ (uncurry (*))) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id))((𝓝 1) ×ᶠ (𝓝 1)) : by rw key ... = map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((map (λ x, y₀⁻¹*x*y₀) $ 𝓝 1) ×ᶠ (𝓝 1)) : by rw [← filter.map_map, ← prod_map_map_eq', map_id] ... ≤ map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((𝓝 1) ×ᶠ (𝓝 1)) : map_mono (filter.prod_mono hconj $ le_refl _) ... = map (λ x, x₀*y₀*x) (map (uncurry (*)) ((𝓝 1) ×ᶠ (𝓝 1))) : by rw filter.map_map ... ≤ map (λ x, x₀*y₀*x) (𝓝 1) : map_mono hmul ... = 𝓝 (x₀*y₀) : (hleft _).symm end, continuous_inv := topological_group.of_nhds_aux hinv hleft hconj} @[to_additive] lemma topological_group.of_comm_of_nhds_one {G : Type*} [comm_group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : topological_group G := topological_group.of_nhds_one hmul hinv hleft (by simpa using tendsto_id) end topological_group section quotient_topological_group variables [topological_space G] [group G] [topological_group G] (N : subgroup G) (n : N.normal) @[to_additive] instance {G : Type*} [group G] [topological_space G] (N : subgroup G) : topological_space (quotient_group.quotient N) := quotient.topological_space open quotient_group @[to_additive] lemma quotient_group.is_open_map_coe : is_open_map (coe : G → quotient N) := begin intros s s_op, change is_open ((coe : G → quotient N) ⁻¹' (coe '' s)), rw quotient_group.preimage_image_coe N s, exact is_open_Union (λ n, is_open_map_mul_right n s s_op) end @[to_additive] instance topological_group_quotient [N.normal] : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : G → quotient N) ∘ (λ (p : G × G), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : G × G, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact (quotient_group.is_open_map_coe N).prod (quotient_group.is_open_map_coe N) }, { exact continuous_quot_mk.prod_map continuous_quot_mk }, { exact (surjective_quot_mk _).prod_map (surjective_quot_mk _) } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin have : continuous ((coe : G → quotient N) ∘ (λ (a : G), a⁻¹)) := continuous_quot_mk.comp continuous_inv, convert continuous_quotient_lift _ this, end } attribute [instance] topological_add_group_quotient end quotient_topological_group /-- A typeclass saying that `λ p : G × G, p.1 - p.2` is a continuous function. This property automatically holds for topological additive groups but it also holds, e.g., for `ℝ≥0`. -/ class has_continuous_sub (G : Type*) [topological_space G] [has_sub G] : Prop := (continuous_sub : continuous (λ p : G × G, p.1 - p.2)) @[priority 100] -- see Note [lower instance priority] instance topological_add_group.to_has_continuous_sub [topological_space G] [add_group G] [topological_add_group G] : has_continuous_sub G := ⟨by { simp only [sub_eq_add_neg], exact continuous_fst.add continuous_snd.neg }⟩ export has_continuous_sub (continuous_sub) section has_continuous_sub variables [topological_space G] [has_sub G] [has_continuous_sub G] lemma filter.tendsto.sub {f g : α → G} {l : filter α} {a b : G} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) : tendsto (λx, f x - g x) l (𝓝 (a - b)) := (continuous_sub.tendsto (a, b)).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → G} {s : set α} {x : α} @[continuity] lemma continuous.sub (hf : continuous f) (hg : continuous g) : continuous (λ x, f x - g x) := continuous_sub.comp (hf.prod_mk hg : _) lemma continuous_within_at.sub (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ x, f x - g x) s x := hf.sub hg lemma continuous_on.sub (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s := λ x hx, (hf x hx).sub (hg x hx) end has_continuous_sub lemma nhds_translation [topological_space G] [add_group G] [topological_add_group G] (x : G) : comap (λy:G, y - x) (𝓝 0) = 𝓝 x := by simpa only [sub_eq_add_neg] using nhds_translation_add_neg x /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (G : Type u) extends add_comm_group G := (Z [] : filter G) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:G×G, p.1 - p.2) (Z ×ᶠ Z) Z) namespace add_group_with_zero_nhd variables (G) [add_group_with_zero_nhd G] local notation `Z` := add_group_with_zero_nhd.Z @[priority 100] -- see Note [lower instance priority] instance : topological_space G := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z G) variables {G} lemma neg_Z : tendsto (λa:G, - a) (Z G) (Z G) := have tendsto (λa, (0:G)) (Z G) (Z G), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:G, 0 - a) (Z G) (Z G), from sub_Z.comp (tendsto.prod_mk this tendsto_id), by simpa lemma add_Z : tendsto (λp:G×G, p.1 + p.2) (Z G ×ᶠ Z G) (Z G) := suffices tendsto (λp:G×G, p.1 - -p.2) (Z G ×ᶠ Z G) (Z G), by simpa [sub_eq_add_neg], sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd)) lemma exists_Z_half {s : set G} (hs : s ∈ Z G) : ∃ V ∈ Z G, ∀ (v ∈ V) (w ∈ V), v + w ∈ s := begin have : ((λa:G×G, a.1 + a.2) ⁻¹' s) ∈ Z G ×ᶠ Z G := add_Z (by simpa using hs), rcases mem_prod_self_iff.1 this with ⟨V, H, H'⟩, exact ⟨V, H, prod_subset_iff.1 H'⟩ end lemma nhds_eq (a : G) : 𝓝 a = map (λx, x + a) (Z G) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:G) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:G, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 t0 b hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z G).sets_of_superset ht (assume x hxt, _), simpa [add_assoc] using eqt _ hxt _ hb } end) lemma nhds_zero_eq_Z : 𝓝 0 = Z G := by simp [nhds_eq]; exact filter.map_id @[priority 100] -- see Note [lower instance priority] instance : has_continuous_add G := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, (a + b) + x) ∘ (λp:G×G,p.1 + p.2)) (Z G ×ᶠ Z G) (map (λx:G, (a + b) + x) (Z G)), { simpa [(∘), add_comm, add_left_comm] }, exact tendsto_map.comp add_Z end ⟩ @[priority 100] -- see Note [lower instance priority] instance : topological_add_group G := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, x - a) ∘ (λx:G, -x)) (Z G) (map (λx:G, x - a) (Z G)), { simpa [(∘), add_comm, sub_eq_add_neg] using this }, exact tendsto_map.comp neg_Z end⟩ end add_group_with_zero_nhd section filter_mul section variables [topological_space G] [group G] [topological_group G] @[to_additive] lemma is_open.mul_left {s t : set G} : is_open t → is_open (s * t) := λ ht, begin have : ∀a, is_open ((λ (x : G), a * x) '' t) := assume a, is_open_map_mul_left a t ht, rw ← Union_mul_left_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end @[to_additive] lemma is_open.mul_right {s t : set G} : is_open s → is_open (s * t) := λ hs, begin have : ∀a, is_open ((λ (x : G), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw ← Union_mul_right_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end variables (G) lemma topological_group.t1_space (h : @is_closed G _ {1}) : t1_space G := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space G] : regular_space G := ⟨assume s a hs ha, let f := λ p : G × G, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_fst.mul continuous_snd.inv, -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s) let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ := is_open_prod_iff.1 ((is_open_compl_iff.2 hs).preimage hf) a (1:G) (by simpa [f]) in begin use [s * t₂, ht₂.mul_left, λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩], apply inf_principal_eq_bot, rw mem_nhds_sets_iff, refine ⟨t₁, _, ht₁, a_mem_t₁⟩, rintros x hx ⟨y, z, hy, hz, yz⟩, have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw ← yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space G] : t2_space G := regular_space.t2_space G end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space G] [group G] [topological_group G] /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `KV ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul {K U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V : set G, is_open V ∧ (1 : G) ∈ V ∧ K * V ⊆ U := begin let W : G → set G := λ x, (λ y, x * y) ⁻¹' U, have h1W : ∀ x, is_open (W x) := λ x, hU.preimage (continuous_mul_left x), have h2W : ∀ x ∈ K, (1 : G) ∈ W x := λ x hx, by simp only [mem_preimage, mul_one, hKU hx], choose V hV using λ x : K, exists_open_nhds_one_mul_subset (mem_nhds_sets (h1W x) (h2W x.1 x.2)), let X : K → set G := λ x, (λ y, (x : G)⁻¹ * y) ⁻¹' (V x), cases hK.elim_finite_subcover X (λ x, (hV x).1.preimage (continuous_mul_left x⁻¹)) _ with t ht, swap, { intros x hx, rw [mem_Union], use ⟨x, hx⟩, rw [mem_preimage], convert (hV _).2.1, simp only [mul_left_inv, subtype.coe_mk] }, refine ⟨⋂ x ∈ t, V x, is_open_bInter (finite_mem_finset _) (λ x hx, (hV x).1), _, _⟩, { simp only [mem_Inter], intros x hx, exact (hV x).2.1 }, rintro _ ⟨x, y, hx, hy, rfl⟩, simp only [mem_Inter] at hy, have := ht hx, simp only [mem_Union, mem_preimage] at this, rcases this with ⟨z, h1z, h2z⟩, have : (z : G)⁻¹ * x * y ∈ W z := (hV z).2.2 (mul_mem_mul h2z (hy z h1z)), rw [mem_preimage] at this, convert this using 1, simp only [mul_assoc, mul_inv_cancel_left] end /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset G, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin cases hV with g₀ hg₀, rcases is_compact.elim_finite_subcover hK (λ x : G, interior $ (λ h, x * h) ⁻¹' V) _ _ with ⟨t, ht⟩, { refine ⟨t, subset.trans ht _⟩, apply Union_subset_Union, intro g, apply Union_subset_Union, intro hg, apply interior_subset }, { intro g, apply is_open_interior }, { intros g hg, rw [mem_Union], use g₀ * g⁻¹, apply preimage_interior_subset_interior_preimage, exact continuous_const.mul continuous_id, rwa [mem_preimage, inv_mul_cancel_right] } end /-- Every locally compact separable topological group is σ-compact. Note: this is not true if we drop the topological group hypothesis. -/ @[priority 100] instance separable_locally_compact_group.sigma_compact_space [separable_space G] [locally_compact_space G] : sigma_compact_space G := begin obtain ⟨L, hLc, hL1⟩ := exists_compact_mem_nhds (1 : G), refine ⟨⟨λ n, (λ x, x * dense_seq G n) ⁻¹' L, _, _⟩⟩, { intro n, exact (homeomorph.mul_right _).compact_preimage.mpr hLc }, { refine Union_eq_univ_iff.2 (λ x, _), obtain ⟨_, ⟨n, rfl⟩, hn⟩ : (range (dense_seq G) ∩ (λ y, x * y) ⁻¹' L).nonempty, { rw [← (homeomorph.mul_left x).apply_symm_apply 1] at hL1, exact (dense_range_dense_seq G).inter_nhds_nonempty ((homeomorph.mul_left x).continuous.continuous_at $ hL1) }, exact ⟨n, hn⟩ } end end section variables [topological_space G] [comm_group G] [topological_group G] @[to_additive] lemma nhds_mul (x y : G) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_one_split ht with ⟨V, V1, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V1, subset.refl _⟩, ⟨V, V1, subset.refl _⟩, _⟩, rintros a ⟨v, w, v_mem, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) v_mem (w * y⁻¹) w_mem }, { rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, y, _, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_nhds hd }, { simp only [inv_mul_cancel_right] } } end @[to_additive] lemma nhds_is_mul_hom : is_mul_hom (λx:G, 𝓝 x) := ⟨λ_ _, nhds_mul _ _⟩ end end filter_mul instance additive.topological_add_group {G} [h : topological_space G] [group G] [topological_group G] : @topological_add_group (additive G) h _ := { continuous_neg := @continuous_inv G _ _ _ } instance multiplicative.topological_group {G} [h : topological_space G] [add_group G] [topological_add_group G] : @topological_group (multiplicative G) h _ := { continuous_inv := @continuous_neg G _ _ _ }
9399a4aced93c9aef3644ca9a32f4a4f0ea840ac
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0414.lean
51c855397679b79fe69a71d447ab1ef8f8790fbe
[]
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
494
lean
example (p q r : Prop) : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := begin apply iff.intro, { intro h, cases h.right with hq hr, { show (p ∧ q) ∨ (p ∧ r), exact or.inl ⟨h.left, hq⟩ }, { show (p ∧ q) ∨ (p ∧ r), exact or.inr ⟨h.left, hr⟩ }}, { intro h, cases h with hpq hpr, { show p ∧ (q ∨ r), exact ⟨hpq.left, or.inl hpq.right⟩ }, { show p ∧ (q ∨ r), exact ⟨hpr.left, or.inr hpr.right⟩ }} end
298aa8595e0f24f36e623026fc2dc92e5c82c06c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/continuous_function/zero_at_infty.lean
60e0bb52fd6dfa9f1814ad84aed49c0ae36d81c7
[ "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
23,044
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import topology.continuous_function.bounded import topology.continuous_function.cocompact_map /-! # Continuous functions vanishing at infinity > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The type of continuous functions vanishing at infinity. When the domain is compact `C(α, β) ≃ C₀(α, β)` via the identity map. When the codomain is a metric space, every continuous map which vanishes at infinity is a bounded continuous function. When the domain is a locally compact space, this type has nice properties. ## TODO * Create more intances of algebraic structures (e.g., `non_unital_semiring`) once the necessary type classes (e.g., `topological_ring`) are sufficiently generalized. * Relate the unitization of `C₀(α, β)` to the Alexandroff compactification. -/ universes u v w variables {F : Type*} {α : Type u} {β : Type v} {γ : Type w} [topological_space α] open_locale bounded_continuous_function topology open filter metric /-- `C₀(α, β)` is the type of continuous functions `α → β` which vanish at infinity from a topological space to a metric space with a zero element. When possible, instead of parametrizing results over `(f : C₀(α, β))`, you should parametrize over `(F : Type*) [zero_at_infty_continuous_map_class F α β] (f : F)`. When you extend this structure, make sure to extend `zero_at_infty_continuous_map_class`. -/ structure zero_at_infty_continuous_map (α : Type u) (β : Type v) [topological_space α] [has_zero β] [topological_space β] extends continuous_map α β : Type (max u v) := (zero_at_infty' : tendsto to_fun (cocompact α) (𝓝 0)) localized "notation [priority 2000] (name := zero_at_infty_continuous_map) `C₀(` α `, ` β `)` := zero_at_infty_continuous_map α β" in zero_at_infty localized "notation (name := zero_at_infty_continuous_map.arrow) α ` →C₀ ` β := zero_at_infty_continuous_map α β" in zero_at_infty section set_option old_structure_cmd true /-- `zero_at_infty_continuous_map_class F α β` states that `F` is a type of continuous maps which vanish at infinity. You should also extend this typeclass when you extend `zero_at_infty_continuous_map`. -/ class zero_at_infty_continuous_map_class (F : Type*) (α β : out_param $ Type*) [topological_space α] [has_zero β] [topological_space β] extends continuous_map_class F α β := (zero_at_infty (f : F) : tendsto f (cocompact α) (𝓝 0)) end export zero_at_infty_continuous_map_class (zero_at_infty) namespace zero_at_infty_continuous_map section basics variables [topological_space β] [has_zero β] [zero_at_infty_continuous_map_class F α β] instance : zero_at_infty_continuous_map_class C₀(α, β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_continuous := λ f, f.continuous_to_fun, zero_at_infty := λ f, f.zero_at_infty' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun C₀(α, β) (λ _, α → β) := fun_like.has_coe_to_fun instance : has_coe_t F C₀(α, β) := ⟨λ f, { to_fun := f, continuous_to_fun := map_continuous f, zero_at_infty' := zero_at_infty f }⟩ @[simp] lemma coe_to_continuous_fun (f : C₀(α, β)) : (f.to_continuous_map : α → β) = f := rfl @[ext] lemma ext {f g : C₀(α, β)} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h /-- Copy of a `zero_at_infinity_continuous_map` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : C₀(α, β)) (f' : α → β) (h : f' = f) : C₀(α, β) := { to_fun := f', continuous_to_fun := by { rw h, exact f.continuous_to_fun }, zero_at_infty' := by { simp_rw h, exact f.zero_at_infty' } } @[simp] lemma coe_copy (f : C₀(α, β)) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : C₀(α, β)) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h lemma eq_of_empty [is_empty α] (f g : C₀(α, β)) : f = g := ext $ is_empty.elim ‹_› /-- A continuous function on a compact space is automatically a continuous function vanishing at infinity. -/ @[simps] def continuous_map.lift_zero_at_infty [compact_space α] : C(α, β) ≃ C₀(α, β) := { to_fun := λ f, { to_fun := f, continuous_to_fun := f.continuous, zero_at_infty' := by simp }, inv_fun := λ f, f, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- A continuous function on a compact space is automatically a continuous function vanishing at infinity. This is not an instance to avoid type class loops. -/ @[simps] def zero_at_infty_continuous_map_class.of_compact {G : Type*} [continuous_map_class G α β] [compact_space α] : zero_at_infty_continuous_map_class G α β := { coe := λ g, g, coe_injective' := λ f g h, fun_like.coe_fn_eq.mp h, map_continuous := map_continuous, zero_at_infty := by simp } end basics /-! ### Algebraic structure Whenever `β` has suitable algebraic structure and a compatible topological structure, then `C₀(α, β)` inherits a corresponding algebraic structure. The primary exception to this is that `C₀(α, β)` will not have a multiplicative identity. -/ section algebraic_structure variables [topological_space β] (x : α) instance [has_zero β] : has_zero C₀(α, β) := ⟨⟨0, tendsto_const_nhds⟩⟩ instance [has_zero β] : inhabited C₀(α, β) := ⟨0⟩ @[simp] lemma coe_zero [has_zero β] : ⇑(0 : C₀(α, β)) = 0 := rfl lemma zero_apply [has_zero β] : (0 : C₀(α, β)) x = 0 := rfl instance [mul_zero_class β] [has_continuous_mul β] : has_mul C₀(α, β) := ⟨λ f g, ⟨f * g, by simpa only [mul_zero] using (zero_at_infty f).mul (zero_at_infty g)⟩⟩ @[simp] lemma coe_mul [mul_zero_class β] [has_continuous_mul β] (f g : C₀(α, β)) : ⇑(f * g) = f * g := rfl lemma mul_apply [mul_zero_class β] [has_continuous_mul β] (f g : C₀(α, β)) : (f * g) x = f x * g x := rfl instance [mul_zero_class β] [has_continuous_mul β] : mul_zero_class C₀(α, β) := fun_like.coe_injective.mul_zero_class _ coe_zero coe_mul instance [semigroup_with_zero β] [has_continuous_mul β] : semigroup_with_zero C₀(α, β) := fun_like.coe_injective.semigroup_with_zero _ coe_zero coe_mul instance [add_zero_class β] [has_continuous_add β] : has_add C₀(α, β) := ⟨λ f g, ⟨f + g, by simpa only [add_zero] using (zero_at_infty f).add (zero_at_infty g)⟩⟩ @[simp] lemma coe_add [add_zero_class β] [has_continuous_add β] (f g : C₀(α, β)) : ⇑(f + g) = f + g := rfl lemma add_apply [add_zero_class β] [has_continuous_add β] (f g : C₀(α, β)) : (f + g) x = f x + g x := rfl instance [add_zero_class β] [has_continuous_add β] : add_zero_class C₀(α, β) := fun_like.coe_injective.add_zero_class _ coe_zero coe_add section add_monoid variables [add_monoid β] [has_continuous_add β] (f g : C₀(α, β)) @[simp] lemma coe_nsmul_rec : ∀ n, ⇑(nsmul_rec n f) = n • f | 0 := by rw [nsmul_rec, zero_smul, coe_zero] | (n + 1) := by rw [nsmul_rec, succ_nsmul, coe_add, coe_nsmul_rec] instance has_nat_scalar : has_smul ℕ C₀(α, β) := ⟨λ n f, ⟨n • f, by simpa [coe_nsmul_rec] using zero_at_infty (nsmul_rec n f)⟩⟩ instance : add_monoid C₀(α, β) := fun_like.coe_injective.add_monoid _ coe_zero coe_add (λ _ _, rfl) end add_monoid instance [add_comm_monoid β] [has_continuous_add β] : add_comm_monoid C₀(α, β) := fun_like.coe_injective.add_comm_monoid _ coe_zero coe_add (λ _ _, rfl) section add_group variables [add_group β] [topological_add_group β] (f g : C₀(α, β)) instance : has_neg C₀(α, β) := ⟨λ f, ⟨-f, by simpa only [neg_zero] using (zero_at_infty f).neg⟩⟩ @[simp] lemma coe_neg : ⇑(-f) = -f := rfl lemma neg_apply : (-f) x = -f x := rfl instance : has_sub C₀(α, β) := ⟨λ f g, ⟨f - g, by simpa only [sub_zero] using (zero_at_infty f).sub (zero_at_infty g)⟩⟩ @[simp] lemma coe_sub : ⇑(f - g) = f - g := rfl lemma sub_apply : (f - g) x = f x - g x := rfl @[simp] lemma coe_zsmul_rec : ∀ z, ⇑(zsmul_rec z f) = z • f | (int.of_nat n) := by rw [zsmul_rec, int.of_nat_eq_coe, coe_nsmul_rec, coe_nat_zsmul] | -[1+ n] := by rw [zsmul_rec, zsmul_neg_succ_of_nat, coe_neg, coe_nsmul_rec] instance has_int_scalar : has_smul ℤ C₀(α, β) := ⟨λ n f, ⟨n • f, by simpa using zero_at_infty (zsmul_rec n f)⟩⟩ instance : add_group C₀(α, β) := fun_like.coe_injective.add_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) end add_group instance [add_comm_group β] [topological_add_group β] : add_comm_group C₀(α, β) := fun_like.coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] : has_smul R C₀(α, β) := ⟨λ r f, ⟨r • f, by simpa [smul_zero] using (zero_at_infty f).const_smul r⟩⟩ @[simp] lemma coe_smul [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] (r : R) (f : C₀(α, β)) : ⇑(r • f) = r • f := rfl lemma smul_apply [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] (r : R) (f : C₀(α, β)) (x : α) : (r • f) x = r • f x := rfl instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [smul_with_zero Rᵐᵒᵖ β] [has_continuous_const_smul R β] [is_central_scalar R β] : is_central_scalar R C₀(α, β) := ⟨λ r f, ext $ λ x, op_smul_eq_smul _ _⟩ instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] : smul_with_zero R C₀(α, β) := function.injective.smul_with_zero ⟨_, coe_zero⟩ fun_like.coe_injective coe_smul instance [has_zero β] {R : Type*} [monoid_with_zero R] [mul_action_with_zero R β] [has_continuous_const_smul R β] : mul_action_with_zero R C₀(α, β) := function.injective.mul_action_with_zero ⟨_, coe_zero⟩ fun_like.coe_injective coe_smul instance [add_comm_monoid β] [has_continuous_add β] {R : Type*} [semiring R] [module R β] [has_continuous_const_smul R β] : module R C₀(α, β) := function.injective.module R ⟨_, coe_zero, coe_add⟩ fun_like.coe_injective coe_smul instance [non_unital_non_assoc_semiring β] [topological_semiring β] : non_unital_non_assoc_semiring C₀(α, β) := fun_like.coe_injective.non_unital_non_assoc_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_semiring β] [topological_semiring β] : non_unital_semiring C₀(α, β) := fun_like.coe_injective.non_unital_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_comm_semiring β] [topological_semiring β] : non_unital_comm_semiring C₀(α, β) := fun_like.coe_injective.non_unital_comm_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_non_assoc_ring β] [topological_ring β] : non_unital_non_assoc_ring C₀(α, β) := fun_like.coe_injective.non_unital_non_assoc_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_ring β] [topological_ring β] : non_unital_ring C₀(α, β) := fun_like.coe_injective.non_unital_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_comm_ring β] [topological_ring β] : non_unital_comm_ring C₀(α, β) := fun_like.coe_injective.non_unital_comm_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance {R : Type*} [semiring R] [non_unital_non_assoc_semiring β] [topological_semiring β] [module R β] [has_continuous_const_smul R β] [is_scalar_tower R β β] : is_scalar_tower R C₀(α, β) C₀(α, β) := { smul_assoc := λ r f g, begin ext, simp only [smul_eq_mul, coe_mul, coe_smul, pi.mul_apply, pi.smul_apply], rw [←smul_eq_mul, ←smul_eq_mul, smul_assoc], end } instance {R : Type*} [semiring R] [non_unital_non_assoc_semiring β] [topological_semiring β] [module R β] [has_continuous_const_smul R β] [smul_comm_class R β β] : smul_comm_class R C₀(α, β) C₀(α, β) := { smul_comm := λ r f g, begin ext, simp only [smul_eq_mul, coe_smul, coe_mul, pi.smul_apply, pi.mul_apply], rw [←smul_eq_mul, ←smul_eq_mul, smul_comm], end } end algebraic_structure section uniform variables [uniform_space β] [uniform_space γ] [has_zero γ] [zero_at_infty_continuous_map_class F β γ] lemma uniform_continuous (f : F) : uniform_continuous (f : β → γ) := (map_continuous f).uniform_continuous_of_tendsto_cocompact (zero_at_infty f) end uniform /-! ### Metric structure When `β` is a metric space, then every element of `C₀(α, β)` is bounded, and so there is a natural inclusion map `zero_at_infty_continuous_map.to_bcf : C₀(α, β) → (α →ᵇ β)`. Via this map `C₀(α, β)` inherits a metric as the pullback of the metric on `α →ᵇ β`. Moreover, this map has closed range in `α →ᵇ β` and consequently `C₀(α, β)` is a complete space whenever `β` is complete. -/ section metric open metric set variables [metric_space β] [has_zero β] [zero_at_infty_continuous_map_class F α β] protected lemma bounded (f : F) : ∃ C, ∀ x y : α, dist ((f : α → β) x) (f y) ≤ C := begin obtain ⟨K : set α, hK₁, hK₂⟩ := mem_cocompact.mp (tendsto_def.mp (zero_at_infty (f : F)) _ (closed_ball_mem_nhds (0 : β) zero_lt_one)), obtain ⟨C, hC⟩ := (hK₁.image (map_continuous f)).bounded.subset_ball (0 : β), refine ⟨max C 1 + max C 1, (λ x y, _)⟩, have : ∀ x, f x ∈ closed_ball (0 : β) (max C 1), { intro x, by_cases hx : x ∈ K, { exact (mem_closed_ball.mp $ hC ⟨x, hx, rfl⟩).trans (le_max_left _ _) }, { exact (mem_closed_ball.mp $ mem_preimage.mp (hK₂ hx)).trans (le_max_right _ _) } }, exact (dist_triangle (f x) 0 (f y)).trans (add_le_add (mem_closed_ball.mp $ this x) (mem_closed_ball'.mp $ this y)), end lemma bounded_range (f : C₀(α, β)) : bounded (range f) := bounded_range_iff.2 f.bounded lemma bounded_image (f : C₀(α, β)) (s : set α) : bounded (f '' s) := f.bounded_range.mono $ image_subset_range _ _ @[priority 100] instance : bounded_continuous_map_class F α β := { map_bounded := λ f, zero_at_infty_continuous_map.bounded f, ..‹zero_at_infty_continuous_map_class F α β› } /-- Construct a bounded continuous function from a continuous function vanishing at infinity. -/ @[simps] def to_bcf (f : C₀(α, β)) : α →ᵇ β := ⟨f, map_bounded f⟩ section variables (α) (β) lemma to_bcf_injective : function.injective (to_bcf : C₀(α, β) → α →ᵇ β) := λ f g h, by { ext, simpa only using fun_like.congr_fun h x, } end variables {C : ℝ} {f g : C₀(α, β)} /-- The type of continuous functions vanishing at infinity, with the uniform distance induced by the inclusion `zero_at_infinity_continuous_map.to_bcf`, is a metric space. -/ noncomputable instance : metric_space C₀(α, β) := metric_space.induced _ (to_bcf_injective α β) (by apply_instance) @[simp] lemma dist_to_bcf_eq_dist {f g : C₀(α, β)} : dist f.to_bcf g.to_bcf = dist f g := rfl open bounded_continuous_function /-- Convergence in the metric on `C₀(α, β)` is uniform convergence. -/ lemma tendsto_iff_tendsto_uniformly {ι : Type*} {F : ι → C₀(α, β)} {f : C₀(α, β)} {l : filter ι} : tendsto F l (𝓝 f) ↔ tendsto_uniformly (λ i, F i) f l := by simpa only [metric.tendsto_nhds] using @bounded_continuous_function.tendsto_iff_tendsto_uniformly _ _ _ _ _ (λ i, (F i).to_bcf) f.to_bcf l lemma isometry_to_bcf : isometry (to_bcf : C₀(α, β) → α →ᵇ β) := by tauto lemma closed_range_to_bcf : is_closed (range (to_bcf : C₀(α, β) → α →ᵇ β)) := begin refine is_closed_iff_cluster_pt.mpr (λ f hf, _), rw cluster_pt_principal_iff at hf, have : tendsto f (cocompact α) (𝓝 0), { refine metric.tendsto_nhds.mpr (λ ε hε, _), obtain ⟨_, hg, g, rfl⟩ := hf (ball f (ε / 2)) (ball_mem_nhds f $ half_pos hε), refine (metric.tendsto_nhds.mp (zero_at_infty g) (ε / 2) (half_pos hε)).mp (eventually_of_forall $ λ x hx, _), calc dist (f x) 0 ≤ dist (g.to_bcf x) (f x) + dist (g x) 0 : dist_triangle_left _ _ _ ... < dist g.to_bcf f + ε / 2 : add_lt_add_of_le_of_lt (dist_coe_le_dist x) hx ... < ε : by simpa [add_halves ε] using add_lt_add_right hg (ε / 2) }, exact ⟨⟨f.to_continuous_map, this⟩, by {ext, refl}⟩, end /-- Continuous functions vanishing at infinity taking values in a complete space form a complete space. -/ instance [complete_space β] : complete_space C₀(α, β) := (complete_space_iff_is_complete_range isometry_to_bcf.uniform_inducing).mpr closed_range_to_bcf.is_complete end metric section norm /-! ### Normed space The norm structure on `C₀(α, β)` is the one induced by the inclusion `to_bcf : C₀(α, β) → (α →ᵇ b)`, viewed as an additive monoid homomorphism. Then `C₀(α, β)` is naturally a normed space over a normed field `𝕜` whenever `β` is as well. -/ section normed_space variables [normed_add_comm_group β] {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] noncomputable instance : normed_add_comm_group C₀(α, β) := normed_add_comm_group.induced C₀(α, β) (α →ᵇ β) (⟨to_bcf, rfl, λ x y, rfl⟩ : C₀(α, β) →+ (α →ᵇ β)) (to_bcf_injective α β) @[simp] lemma norm_to_bcf_eq_norm {f : C₀(α, β)} : ‖f.to_bcf‖ = ‖f‖ := rfl instance : normed_space 𝕜 C₀(α, β) := { norm_smul_le := λ k f, (norm_smul_le k f.to_bcf : _) } end normed_space section normed_ring variables [non_unital_normed_ring β] noncomputable instance : non_unital_normed_ring C₀(α, β) := { norm_mul := λ f g, norm_mul_le f.to_bcf g.to_bcf, ..zero_at_infty_continuous_map.non_unital_ring, ..zero_at_infty_continuous_map.normed_add_comm_group } end normed_ring end norm section star /-! ### Star structure It is possible to equip `C₀(α, β)` with a pointwise `star` operation whenever there is a continuous `star : β → β` for which `star (0 : β) = 0`. We don't have quite this weak a typeclass, but `star_add_monoid` is close enough. The `star_add_monoid` and `normed_star_group` classes on `C₀(α, β)` are inherited from their counterparts on `α →ᵇ β`. Ultimately, when `β` is a C⋆-ring, then so is `C₀(α, β)`. -/ variables [topological_space β] [add_monoid β] [star_add_monoid β] [has_continuous_star β] instance : has_star C₀(α, β) := { star := λ f, { to_fun := λ x, star (f x), continuous_to_fun := (map_continuous f).star, zero_at_infty' := by simpa only [star_zero] using (continuous_star.tendsto (0 : β)).comp (zero_at_infty f) } } @[simp] lemma coe_star (f : C₀(α, β)) : ⇑(star f) = star f := rfl lemma star_apply (f : C₀(α, β)) (x : α) : (star f) x = star (f x) := rfl instance [has_continuous_add β] : star_add_monoid C₀(α, β) := { star_involutive := λ f, ext $ λ x, star_star (f x), star_add := λ f g, ext $ λ x, star_add (f x) (g x) } end star section normed_star variables [normed_add_comm_group β] [star_add_monoid β] [normed_star_group β] instance : normed_star_group C₀(α, β) := { norm_star := λ f, (norm_star f.to_bcf : _) } end normed_star section star_module variables {𝕜 : Type*} [has_zero 𝕜] [has_star 𝕜] [add_monoid β] [star_add_monoid β] [topological_space β] [has_continuous_star β] [smul_with_zero 𝕜 β] [has_continuous_const_smul 𝕜 β] [star_module 𝕜 β] instance : star_module 𝕜 C₀(α, β) := { star_smul := λ k f, ext $ λ x, star_smul k (f x) } end star_module section star_ring variables [non_unital_semiring β] [star_ring β] [topological_space β] [has_continuous_star β] [topological_semiring β] instance : star_ring C₀(α, β) := { star_mul := λ f g, ext $ λ x, star_mul (f x) (g x), ..zero_at_infty_continuous_map.star_add_monoid } end star_ring section cstar_ring instance [non_unital_normed_ring β] [star_ring β] [cstar_ring β] : cstar_ring C₀(α, β) := { norm_star_mul_self := λ f, @cstar_ring.norm_star_mul_self _ _ _ _ f.to_bcf } end cstar_ring /-! ### C₀ as a functor For each `β` with sufficient structure, there is a contravariant functor `C₀(-, β)` from the category of topological spaces with morphisms given by `cocompact_map`s. -/ variables {δ : Type*} [topological_space β] [topological_space γ] [topological_space δ] local notation α ` →co ` β := cocompact_map α β section variables [has_zero δ] /-- Composition of a continuous function vanishing at infinity with a cocompact map yields another continuous function vanishing at infinity. -/ def comp (f : C₀(γ, δ)) (g : β →co γ) : C₀(β, δ) := { to_continuous_map := (f : C(γ, δ)).comp g, zero_at_infty' := (zero_at_infty f).comp (cocompact_tendsto g) } @[simp] lemma coe_comp_to_continuous_fun (f : C₀(γ, δ)) (g : β →co γ) : ((f.comp g).to_continuous_map : β → δ) = f ∘ g := rfl @[simp] lemma comp_id (f : C₀(γ, δ)) : f.comp (cocompact_map.id γ) = f := ext (λ x, rfl) @[simp] lemma comp_assoc (f : C₀(γ, δ)) (g : β →co γ) (h : α →co β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma zero_comp (g : β →co γ) : (0 : C₀(γ, δ)).comp g = 0 := rfl end /-- Composition as an additive monoid homomorphism. -/ def comp_add_monoid_hom [add_monoid δ] [has_continuous_add δ] (g : β →co γ) : C₀(γ, δ) →+ C₀(β, δ) := { to_fun := λ f, f.comp g, map_zero' := zero_comp g, map_add' := λ f₁ f₂, rfl } /-- Composition as a semigroup homomorphism. -/ def comp_mul_hom [mul_zero_class δ] [has_continuous_mul δ] (g : β →co γ) : C₀(γ, δ) →ₙ* C₀(β, δ) := { to_fun := λ f, f.comp g, map_mul' := λ f₁ f₂, rfl } /-- Composition as a linear map. -/ def comp_linear_map [add_comm_monoid δ] [has_continuous_add δ] {R : Type*} [semiring R] [module R δ] [has_continuous_const_smul R δ] (g : β →co γ) : C₀(γ, δ) →ₗ[R] C₀(β, δ) := { to_fun := λ f, f.comp g, map_add' := λ f₁ f₂, rfl, map_smul' := λ r f, rfl } /-- Composition as a non-unital algebra homomorphism. -/ def comp_non_unital_alg_hom {R : Type*} [semiring R] [non_unital_non_assoc_semiring δ] [topological_semiring δ] [module R δ] [has_continuous_const_smul R δ] (g : β →co γ) : C₀(γ, δ) →ₙₐ[R] C₀(β, δ) := { to_fun := λ f, f.comp g, map_smul' := λ r f, rfl, map_zero' := rfl, map_add' := λ f₁ f₂, rfl, map_mul' := λ f₁ f₂, rfl } end zero_at_infty_continuous_map
98cb4eb180abcdc5deb3ed2efee5140bdbfe0f1c
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/algebra/big_operators.lean
4af79e6f6d2a2365f238bfd27429ff2beac6d707
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
40,828
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Some big operators for lists and finite sets. -/ import tactic.tauto data.list.defs data.finset data.nat.enat universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) : ∃ M, ∀ i ∈ s, i ≤ M := directed.finset_le (by apply_instance) directed_order.directed s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl end finset @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (s.prod f) = s.prod (λx, g (f x)) := by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map] lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (s.prod f) = s.prod (λx, g (f x)) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_sum [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (s.sum f) = s.sum (λx, g (f x)) := g.to_add_monoid_hom.map_sum f s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : ({a, b} : finset α).prod f = f a * f b := by simp [prod_insert (not_mem_singleton.2 h.symm), mul_comm] @[simp, priority 1100] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp, priority 1100] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (s.map e).prod f = s.prod (λa, f (e a)) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[simp, to_additive] lemma prod_sum_elim [decidable_eq (α ⊕ γ)] (s : finset α) (t : finset γ) (f : α → β) (g : γ → β) : (s.image sum.inl ∪ t.image sum.inr).prod (sum.elim f g) = s.prod f * t.prod g := begin rw [prod_union, prod_image, prod_image], { simp only [sum.elim_inl, sum.elim_inr] }, { exact λ _ _ _ _, sum.inr.inj }, { exact λ _ _ _ _, sum.inl.inj }, { rintros i hi, erw [finset.mem_inter, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨⟨i, hi, rfl⟩, ⟨j, hj, H⟩⟩, cases H } end @[to_additive] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y)) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bind s t), from (disjoint_bind_right _ _ _).mpr this, by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end @[to_additive] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, by simp only [disjoint_iff_ne, mem_image]; rintro ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] @[to_additive] lemma prod_hom [comm_monoid γ] (s : finset α) {f : α → β} (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := ((monoid_hom.of g).map_prod f s).symm @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (s.filter $ λx, f x ≠ 1).prod f = s.prod f := prod_subset (filter_subset _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact and.intro } @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_apply_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : s.prod (λ x, h (if p x then f x else g x)) = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) := by letI := classical.dec_eq α; exact calc s.prod (λ x, h (if p x then f x else g x)) = (s.filter p ∪ s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : by rw [filter_union_filter_neg_eq] ... = (s.filter p).prod (λ x, h (if p x then f x else g x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) : congr_arg2 _ (prod_congr rfl (by simp {contextual := tt})) (prod_congr rfl (by simp {contextual := tt})) @[to_additive] lemma prod_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → β) : s.prod (λ x, if p x then f x else g x) = (s.filter p).prod (λ x, f x) * (s.filter (λ x, ¬ p x)).prod (λ x, g x) := by simp [prod_apply_ite _ _ (λ x, x)] @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) : s.prod (λ x, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 := begin rw ←finset.prod_filter, split_ifs; simp only [filter_eq, if_true, if_false, h, prod_empty, prod_singleton, insert_empty_eq_singleton], end /-- When a product is taken over a conditional whose condition is an equality test on the index and whose alternative is 1, then the product's value is either the term at that index or `1`. The difference with `prod_ite_eq` is that the arguments to `eq` are swapped. -/ @[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) : s.prod (λ x, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 := begin rw ←prod_ite_eq, congr, ext x, by_cases x = a; finish end @[to_additive] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.prod f = t.prod g := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by classical; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : prod_filter_ne_one.symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : prod_filter_ne_one @[to_additive] lemma nonempty_of_prod_ne_one (h : s.prod f ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : s.prod f ≠ 1) : ∃a∈s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ lemma sum_Ico_add {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (m n k : ℕ) : (Ico m n).sum (λ l, f (k + l)) = (Ico (m + k) (n + k)).sum f := Ico.image_add m n k ▸ eq.symm $ sum_image $ λ x hx y hy h, nat.add_left_cancel h @[to_additive] lemma prod_Ico_add (f : ℕ → β) (m n k : ℕ) : (Ico m n).prod (λ l, f (k + l)) = (Ico (m + k) (n + k)).prod f := Ico.image_add m n k ▸ eq.symm $ prod_image $ λ x hx y hy h, nat.add_left_cancel h lemma sum_Ico_succ_top {δ : Type*} [add_comm_monoid δ] {a b : ℕ} (hab : a ≤ b) (f : ℕ → δ) : (Ico a (b + 1)).sum f = (Ico a b).sum f + f b := by rw [Ico.succ_top hab, sum_insert Ico.not_mem_top, add_comm] @[to_additive] lemma prod_Ico_succ_top {a b : ℕ} (hab : a ≤ b) (f : ℕ → β) : (Ico a b.succ).prod f = (Ico a b).prod f * f b := @sum_Ico_succ_top (additive β) _ _ _ hab _ lemma sum_eq_sum_Ico_succ_bot {δ : Type*} [add_comm_monoid δ] {a b : ℕ} (hab : a < b) (f : ℕ → δ) : (Ico a b).sum f = f a + (Ico (a + 1) b).sum f := have ha : a ∉ Ico (a + 1) b, by simp, by rw [← sum_insert ha, Ico.insert_succ_bot hab] @[to_additive] lemma prod_eq_prod_Ico_succ_bot {a b : ℕ} (hab : a < b) (f : ℕ → β) : (Ico a b).prod f = f a * (Ico (a + 1) b).prod f := @sum_eq_sum_Ico_succ_bot (additive β) _ _ _ hab _ @[to_additive] lemma prod_Ico_consecutive (f : ℕ → β) {m n k : ℕ} (hmn : m ≤ n) (hnk : n ≤ k) : (Ico m n).prod f * (Ico n k).prod f = (Ico m k).prod f := Ico.union_consecutive hmn hnk ▸ eq.symm $ prod_union $ Ico.disjoint_consecutive m n k @[to_additive] lemma prod_range_mul_prod_Ico (f : ℕ → β) {m n : ℕ} (h : m ≤ n) : (range m).prod f * (Ico m n).prod f = (range n).prod f := Ico.zero_bot m ▸ Ico.zero_bot n ▸ prod_Ico_consecutive f (nat.zero_le m) h @[to_additive sum_Ico_eq_add_neg] lemma prod_Ico_eq_div {δ : Type*} [comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).prod f = (range n).prod f * ((range m).prod f)⁻¹ := eq_mul_inv_iff_mul_eq.2 $ by rw [mul_comm]; exact prod_range_mul_prod_Ico f h lemma sum_Ico_eq_sub {δ : Type*} [add_comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).sum f = (range n).sum f - (range m).sum f := sum_Ico_eq_add_neg f h @[to_additive] lemma prod_Ico_eq_prod_range (f : ℕ → β) (m n : ℕ) : (Ico m n).prod f = (range (n - m)).prod (λ l, f (m + l)) := begin by_cases h : m ≤ n, { rw [← Ico.zero_bot, prod_Ico_add, zero_add, nat.sub_add_cancel h] }, { replace h : n ≤ m := le_of_not_ge h, rw [Ico.eq_empty_of_le h, nat.sub_eq_zero_of_le h, range_zero, prod_empty, prod_empty] } end @[to_additive] lemma prod_range_zero (f : ℕ → β) : (range 0).prod f = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : (range 1).prod f = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : (range 1).sum f = f 0 := by { rw [range_one], apply @sum_singleton ℕ δ 0 f } attribute [to_additive finset.sum_range_one] prod_range_one @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx])) @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one /-- A product over all subsets of `s ∪ {x}` is obtained by multiplying the product over all subsets of `s`, and over all subsets of `s` to which one adds `x`. -/ @[to_additive] lemma prod_powerset_insert [decidable_eq α] {s : finset α} {x : α} (h : x ∉ s) (f : finset α → β) : (insert x s).powerset.prod f = s.powerset.prod f * s.powerset.prod (λt, f (insert x t)) := begin rw [powerset_insert, finset.prod_union, finset.prod_image], { assume t₁ h₁ t₂ h₂ heq, rw [← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₁ h), ← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₂ h), heq] }, { rw finset.disjoint_iff_ne, assume t₁ h₁ t₂ h₂, rcases finset.mem_image.1 h₂ with ⟨t₃, h₃, H₃₂⟩, rw ← H₃₂, exact ne_insert_of_not_mem _ _ (not_mem_of_mem_powerset_of_not_mem h₁ h) } end @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : s.prod (t.piecewise f g) = (s ∩ t).prod f * (s \ t).prod g := by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], } /-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/ @[to_additive] lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r] (h : ∀ x ∈ s, (s.filter (λy, y ≈ x)).prod f = 1) : s.prod f = 1 := begin suffices : (s.image quotient.mk).prod (λ xbar, (s.filter (λ y, ⟦y⟧ = xbar)).prod f) = s.prod f, { rw [←this, ←finset.prod_eq_one], intros xbar xbar_in_s, rcases (mem_image).mp xbar_in_s with ⟨x, x_in_s, xbar_eq_x⟩, rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)], apply h x x_in_s }, apply finset.prod_image' f, intros, refl end @[to_additive] lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∉ s) (f : α → β) (b : β) : s.prod (function.update f i b) = s.prod f := begin apply prod_congr rfl (λj hj, _), have : j ≠ i, by { assume eq, rw eq at hj, exact h hj }, simp [this] end lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : s.prod (function.update f i b) = b * (s \ (singleton i)).prod f := by { rw [update_eq_piecewise, prod_piecewise], simp [h] } end comm_monoid lemma sum_update_of_mem [add_comm_monoid β] [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : s.sum (function.update f i b) = b + (s \ (singleton i)).sum f := by { rw [update_eq_piecewise, sum_piecewise], simp [h] } attribute [to_additive] prod_update_of_mem lemma sum_smul' [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_smul'] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const @[simp] lemma sum_boole {s : finset α} {p : α → Prop} [semiring β] {hp : decidable_pred p} : s.sum (λ x, if p x then (1 : β) else (0 : β)) = (s.filter p).card := by simp [sum_ite] lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (s.sum_hom _).symm lemma prod_nat_cast [comm_semiring β] (s : finset α) (f : α → ℕ) : ↑(s.prod f) = s.prod (λa, f a : α → β) := (s.prod_hom _).symm protected lemma sum_nat_coe_enat [decidable_eq α] (s : finset α) (f : α → ℕ) : s.sum (λ x, (f x : enat)) = (s.sum f : ℕ) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has, ih] } end theorem dvd_sum [comm_semiring α] {a : α} {s : finset β} {f : β → α} (h : ∀ x ∈ s, a ∣ f x) : a ∣ s.sum f := multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx) lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := s.prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) := by letI := classical.dec_eq α; exact calc s.card = ((s.image f).bind (λ a, s.filter (λ x, f x = a))).card : congr_arg _ (finset.ext.2 $ λ x, ⟨λ hs, mem_bind.2 ⟨f x, mem_image_of_mem _ hs, mem_filter.2 ⟨hs, rfl⟩⟩, λ h, let ⟨a, ha₁, ha₂⟩ := mem_bind.1 h in by convert filter_subset s ha₂⟩) ... = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_bind (by simp [disjoint_left, finset.ext] {contextual := tt}) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (s.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section comm_monoid variables [comm_monoid β] lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.prod (λ x, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 := by simp end comm_monoid section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (s.sum_hom (λ x, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (s.sum_hom _).symm lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 := by simp lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 := by simp end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)), { assume x hx y hy h, simp only [disjoint_iff_ne, mem_image], rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq₂, eq₃, eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union sdiff_disjoint).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := @sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _ _ lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero [@decidable_rel β (≤)] (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid β] theorem sum_lt_sum (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) : s.sum f < s.sum g := begin classical, rcases Hlt with ⟨i, hi, hlt⟩, rw [← insert_erase hi, sum_insert (not_mem_erase _ _), sum_insert (not_mem_erase _ _)], exact add_lt_add_of_lt_of_le hlt (sum_le_sum $ λ j hj, Hle j $ mem_of_mem_erase hj) end end ordered_cancel_comm_monoid section decidable_linear_ordered_cancel_comm_monoid variables [decidable_linear_ordered_cancel_comm_monoid β] theorem exists_le_of_sum_le (hs : s.nonempty) (Hle : s.sum f ≤ s.sum g) : ∃ i ∈ s, f i ≤ g i := begin classical, contrapose! Hle with Hlt, rcases hs with ⟨i, hi⟩, exact sum_lt_sum (λ i hi, le_of_lt (Hlt i hi)) ⟨i, hi, Hlt i hi⟩ end end decidable_linear_ordered_cancel_comm_monoid section linear_ordered_comm_ring variables [decidable_eq α] [linear_ordered_comm_ring β] /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_le_one] }, { simp [has], apply mul_nonneg, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_lt_one] }, { simp [has], apply mul_pos, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : s.prod f ≤ s.prod g := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end end linear_ordered_comm_ring @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ theorem card_le_mul_card_image [decidable_eq β] {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := calc s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_image _ _ ... ≤ (s.image f).sum (λ _, n) : sum_le_sum hn ... = _ : by simp [mul_comm] @[simp] lemma prod_Ico_id_eq_fact : ∀ n : ℕ, (Ico 1 n.succ).prod (λ x, x) = nat.fact n | 0 := rfl | (n+1) := by rw [prod_Ico_succ_top $ nat.succ_le_succ $ zero_le n, nat.fact_succ, prod_Ico_id_eq_fact n, nat.succ_eq_add_one, mul_comm] end finset namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum lemma card_eq_sum_ones (s : finset α) : s.card = s.sum (λ _, 1) := by simp end finset section group open list variables [group α] [group β] theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.map_one f, simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := { map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] } attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset namespace with_top open finset variables [decidable_eq α] /-- sum of finite numbers is still finite -/ lemma sum_lt_top [ordered_comm_monoid β] {s : finset α} {f : α → with_top β} : (∀a∈s, f a < ⊤) → s.sum f < ⊤ := finset.induction_on s (by { intro h, rw sum_empty, exact coe_lt_top _ }) (λa s ha ih h, begin rw [sum_insert ha, add_lt_top], split, { apply h, apply mem_insert_self }, { apply ih, intros a ha, apply h, apply mem_insert_of_mem ha } end) /-- sum of finite numbers is still finite -/ lemma sum_lt_top_iff [canonically_ordered_monoid β] {s : finset α} {f : α → with_top β} : s.sum f < ⊤ ↔ (∀a∈s, f a < ⊤) := iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top end with_top
5c3e4264d1e1d64a1f3b522a856d4c6d690cf268
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/stage0/src/Lean/Elab/App.lean
5ba3c8cf85fd3fbdba365d6a1ab97bf2d898deb8
[ "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
31,244
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.Util.FindMVar import Lean.Elab.Term import Lean.Elab.Binders namespace Lean namespace Elab namespace Term open Meta /-- Auxiliary inductive datatype for combining unelaborated syntax and already elaborated expressions. It is used to elaborate applications. -/ inductive Arg | stx (val : Syntax) | expr (val : Expr) instance Arg.inhabited : Inhabited Arg := ⟨Arg.stx (arbitrary _)⟩ instance Arg.hasToString : HasToString Arg := ⟨fun arg => match arg with | Arg.stx val => toString val | Arg.expr val => toString val⟩ /-- Named arguments created using the notation `(x := val)` -/ structure NamedArg := (name : Name) (val : Arg) instance NamedArg.hasToString : HasToString NamedArg := ⟨fun s => "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")"⟩ instance NamedArg.inhabited : Inhabited NamedArg := ⟨{ name := arbitrary _, val := arbitrary _ }⟩ /-- Add a new named argument to `namedArgs`, and throw an error if it already contains a named argument with the same name. -/ def addNamedArg (namedArgs : Array NamedArg) (namedArg : NamedArg) : TermElabM (Array NamedArg) := do when (namedArgs.any $ fun namedArg' => namedArg.name == namedArg'.name) $ throwError ("argument '" ++ toString namedArg.name ++ "' was already set"); pure $ namedArgs.push namedArg def synthesizeAppInstMVars (instMVars : Array MVarId) : TermElabM Unit := instMVars.forM $ fun mvarId => unlessM (synthesizeInstMVarCore mvarId) $ registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass private def ensureArgType (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do argType ← inferType arg; ensureHasTypeAux expectedType argType arg f private def elabArg (f : Expr) (arg : Arg) (expectedType : Expr) : TermElabM Expr := match arg with | Arg.expr val => ensureArgType f val expectedType | Arg.stx val => do val ← elabTerm val expectedType; ensureArgType f val expectedType private def mkArrow (d b : Expr) : TermElabM Expr := do n ← mkFreshAnonymousName; pure $ Lean.mkForall n BinderInfo.default d b /- Relevant definitions: ``` class CoeFun (α : Sort u) (γ : α → outParam (Sort v)) abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a ``` -/ private def tryCoeFun (α : Expr) (a : Expr) : TermElabM Expr := do v ← mkFreshLevelMVar; type ← mkArrow α (mkSort v); γ ← mkFreshExprMVar type; u ← getLevel α; let coeFunInstType := mkAppN (Lean.mkConst `CoeFun [u, v]) #[α, γ]; mvar ← mkFreshExprMVar coeFunInstType MetavarKind.synthetic; let mvarId := mvar.mvarId!; synthesized ← catch (withoutMacroStackAtErr $ synthesizeInstMVarCore mvarId) (fun ex => match ex with | Exception.error _ msg => throwError $ "function expected" ++ Format.line ++ msg | _ => throwError "function expected"); if synthesized then pure $ mkAppN (Lean.mkConst `coeFun [u, v]) #[α, γ, a, mvar] else throwError "function expected" /-- Auxiliary structure used to elaborate function application arguments. -/ structure ElabAppArgsCtx := (ref : Syntax) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) -- if true, all arguments are treated as explicit (argIdx : Nat := 0) -- position of next explicit argument to be processed (namedArgs : Array NamedArg) -- remaining named arguments to be processed (instMVars : Array MVarId := #[]) -- metavariables for the instance implicit arguments that have already been processed (typeMVars : Array MVarId := #[]) -- metavariables for implicit arguments of the form `{α : Sort u}` that have already been processed (toSetErrorCtx : Array MVarId := #[]) -- metavariables that we need the set the error context using the application being built (foundExplicit : Bool := false) -- true if an explicit argument has already been processed /- Auxiliary function for retrieving the resulting type of a function application. See `propagateExpectedType`. -/ private partial def getForallBody : Nat → Array NamedArg → Expr → Option Expr | i, namedArgs, type@(Expr.forallE n d b c) => match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => getForallBody i (namedArgs.eraseIdx idx) b | none => if !c.binderInfo.isExplicit then getForallBody i namedArgs b else if i > 0 then getForallBody (i-1) namedArgs b else if d.isAutoParam || d.isOptParam then getForallBody i namedArgs b else some type | i, namedArgs, type => if i == 0 && namedArgs.isEmpty then some type else none private def hasTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool := (type.findMVar? (fun mvarId => ctx.typeMVars.contains mvarId)).isSome private def hasOnlyTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool := (type.findMVar? (fun mvarId => !ctx.typeMVars.contains mvarId)).isNone /- Auxiliary method for propagating the expected type. We call it as soon as we find the first explict argument. The goal is to propagate the expected type in applications of functions such as ```lean HasAdd.add {α : Type u} : α → α → α List.cons {α : Type u} : α → List α → List α ``` This is particularly useful when there applicable coercions. For example, assume we have a coercion from `Nat` to `Int`, and we have `(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function, the elaborator will fail to elaborate ``` List.cons x [] ``` First, the elaborator creates a new metavariable `?α` for the implicit argument `{α : Type u}`. Then, when it processes `x`, it assigns `?α := Nat`, and then obtain the resultant type `List Nat` which is **not** definitionally equal to `List Int`. We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example). This method infers that the resultant type is `List ?α` and unifies it with `List Int`. Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the term ``` @List.cons Int (coe x) (@List.nil Int) ``` is produced. The method will do nothing if 1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`) 2- The resultant type does not contain any type metavariable. 3- The resultant type contains a nontype metavariable. We added conditions 2&3 to be able to restrict this method to simple functions that are "morally" in the Hindley&Milner fragment. For example, consider the following definitions ``` def foo {n m : Nat} (a : bv n) (b : bv m) : bv (n - m) ``` Now, consider ``` def test (x1 : bv 32) (x2 : bv 31) (y1 : bv 64) (y2 : bv 63) : bv 1 := foo x1 x2 = foo y1 y2 ``` When the elaborator reaches the term `foo y1 y2`, the expected type is `bv (32-31)`. If we apply this method, we would solve the unification problem `bv (?n - ?m) =?= bv (32 - 31)`, by assigning `?n := 32` and `?m := 31`. Then, the elaborator fails elaborating `y1` since `bv 64` is **not** definitionally equal to `bv 32`. -/ private def propagateExpectedType (ctx : ElabAppArgsCtx) (eType : Expr) : TermElabM Unit := withRef ctx.ref $ unless (ctx.explicit || ctx.foundExplicit || ctx.typeMVars.isEmpty) $ do match ctx.expectedType? with | none => pure () | some expectedType => let numRemainingArgs := ctx.args.size - ctx.argIdx; match getForallBody numRemainingArgs ctx.namedArgs eType with | none => pure () | some eTypeBody => unless eTypeBody.hasLooseBVars $ when (hasTypeMVar ctx eTypeBody && hasOnlyTypeMVar ctx eTypeBody) $ do _ ← isDefEq expectedType eTypeBody; pure () private def nextArgIsHole (ctx : ElabAppArgsCtx) : Bool := if h : ctx.argIdx < ctx.args.size then match ctx.args.get ⟨ctx.argIdx, h⟩ with | Arg.stx (Syntax.node `Lean.Parser.Term.hole _) => true | _ => false else false /- Elaborate function application arguments. -/ private partial def elabAppArgsAux : ElabAppArgsCtx → Expr → Expr → TermElabM Expr | ctx, e, eType => withRef ctx.ref do let finalize : Unit → TermElabM Expr := fun _ => do { -- all user explicit arguments have been consumed trace `Elab.app.finalize $ fun _ => e; match ctx.expectedType? with | none => pure () | some expectedType => do { -- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it. _ ← isDefEq expectedType eType; pure () }; synthesizeAppInstMVars ctx.instMVars; ctx.toSetErrorCtx.forM fun mvarId => registerMVarErrorContext mvarId ctx.ref e; pure e }; eType ← whnfForall eType; match eType with | Expr.forallE n d b c => match ctx.namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let arg := ctx.namedArgs.get! idx; let namedArgs := ctx.namedArgs.eraseIdx idx; argElab ← elabArg e arg.val d; propagateExpectedType ctx eType; elabAppArgsAux { ctx with foundExplicit := true, namedArgs := namedArgs } (mkApp e argElab) (b.instantiate1 argElab) | none => let processExplictArg : Unit → TermElabM Expr := fun _ => do { propagateExpectedType ctx eType; let ctx := { ctx with foundExplicit := true }; if h : ctx.argIdx < ctx.args.size then do argElab ← elabArg e (ctx.args.get ⟨ctx.argIdx, h⟩) d; elabAppArgsAux { ctx with argIdx := ctx.argIdx + 1 } (mkApp e argElab) (b.instantiate1 argElab) else match ctx.explicit, d.getOptParamDefault?, d.getAutoParamTactic? with | false, some defVal, _ => elabAppArgsAux ctx (mkApp e defVal) (b.instantiate1 defVal) | false, _, some (Expr.const tacticDecl _ _) => do env ← getEnv; match evalSyntaxConstant env tacticDecl with | Except.error err => throwError err | Except.ok tacticSyntax => do tacticBlock ← `(by { $(tacticSyntax.getArgs)* }); -- tacticBlock does not have any position information. -- So, we use ctx.ref let tacticBlock := tacticBlock.copyInfo ctx.ref; let d := d.getArg! 0; -- `autoParam type := by tactic` ==> `type` argElab ← elabArg e (Arg.stx tacticBlock) d; elabAppArgsAux ctx (mkApp e argElab) (b.instantiate1 argElab) | false, _, some _ => throwError "invalid autoParam, argument must be a constant" | _, _, _ => if ctx.namedArgs.isEmpty then finalize () else throwError ("explicit parameter '" ++ n ++ "' is missing, unused named arguments " ++ toString (ctx.namedArgs.map $ fun narg => narg.name)) }; match c.binderInfo with | BinderInfo.implicit => if ctx.explicit then processExplictArg () else do a ← mkFreshExprMVar d; typeMVars ← condM (isTypeFormer a) (pure $ ctx.typeMVars.push a.mvarId!) (pure ctx.typeMVars); elabAppArgsAux { ctx with typeMVars := typeMVars, toSetErrorCtx := ctx.toSetErrorCtx.push a.mvarId! } (mkApp e a) (b.instantiate1 a) | BinderInfo.instImplicit => if ctx.explicit && nextArgIsHole ctx then do /- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/ a ← mkFreshExprMVar d MetavarKind.synthetic; elabAppArgsAux { ctx with argIdx := ctx.argIdx + 1, instMVars := ctx.instMVars.push a.mvarId! } (mkApp e a) (b.instantiate1 a) else if ctx.explicit then processExplictArg () else do a ← mkFreshExprMVar d MetavarKind.synthetic; elabAppArgsAux { ctx with instMVars := ctx.instMVars.push a.mvarId! } (mkApp e a) (b.instantiate1 a) | _ => processExplictArg () | _ => if ctx.namedArgs.isEmpty && ctx.argIdx == ctx.args.size then finalize () else do e ← tryCoeFun eType e; eType ← inferType e; elabAppArgsAux ctx e eType private def elabAppArgs (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do fType ← inferType f; fType ← instantiateMVars fType; trace `Elab.app.args $ fun _ => "explicit: " ++ toString explicit ++ ", " ++ f ++ " : " ++ fType; unless (namedArgs.isEmpty && args.isEmpty) $ tryPostponeIfMVar fType; ref ← getRef; elabAppArgsAux {ref := ref, args := args, expectedType? := expectedType?, explicit := explicit, namedArgs := namedArgs } f fType /-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/ inductive LValResolution | projFn (baseStructName : Name) (structName : Name) (fieldName : Name) | projIdx (structName : Name) (idx : Nat) | const (baseStructName : Name) (structName : Name) (constName : Name) | localRec (baseName : Name) (fullName : Name) (fvar : Expr) | getOp (fullName : Name) (idx : Syntax) private def throwLValError {α} (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α := throwError $ msg ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr eType /-- `findMethod? env S fName`. 1- If `env` contains `S ++ fName`, return `(S, S++fName)` 2- Otherwise if `env` contains private name `prv` for `S ++ fName`, return `(S, prv)`, o 3- Otherwise for each parent structure `S'` of `S`, we try `findMethod? env S' fname` -/ private partial def findMethod? (env : Environment) : Name → Name → Option (Name × Name) | structName, fieldName => let fullName := structName ++ fieldName; match env.find? fullName with | some _ => some (structName, fullName) | none => let fullNamePrv := mkPrivateName env fullName; match env.find? fullNamePrv with | some _ => some (structName, fullNamePrv) | none => if isStructureLike env structName then (getParentStructures env structName).findSome? fun parentStructName => findMethod? parentStructName fieldName else none private def resolveLValAux (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := match eType.getAppFn, lval with | Expr.const structName _ _, LVal.fieldIdx idx => do when (idx == 0) $ throwError "invalid projection, index must be greater than 0"; env ← getEnv; unless (isStructureLike env structName) $ throwLValError e eType "invalid projection, structure expected"; let fieldNames := getStructureFields env structName; if h : idx - 1 < fieldNames.size then if isStructure env structName then pure $ LValResolution.projFn structName structName (fieldNames.get ⟨idx - 1, h⟩) else /- `structName` was declared using `inductive` command. So, we don't projection functions for it. Thus, we use `Expr.proj` -/ pure $ LValResolution.projIdx structName (idx - 1) else throwLValError e eType ("invalid projection, structure has only " ++ toString fieldNames.size ++ " field(s)") | Expr.const structName _ _, LVal.fieldName fieldName => do env ← getEnv; let searchEnv : Unit → TermElabM LValResolution := fun _ => do { match findMethod? env structName fieldName with | some (baseStructName, fullName) => pure $ LValResolution.const baseStructName structName fullName | none => throwLValError e eType $ "invalid field notation, '" ++ fieldName ++ "' is not a valid \"field\" because environment does not contain '" ++ (structName ++ fieldName) ++ "'" }; -- search local context first, then environment let searchCtx : Unit → TermElabM LValResolution := fun _ => do { let fullName := structName ++ fieldName; currNamespace ← getCurrNamespace; let localName := fullName.replacePrefix currNamespace Name.anonymous; lctx ← getLCtx; match lctx.findFromUserName? localName with | some localDecl => if localDecl.binderInfo == BinderInfo.auxDecl then /- LVal notation is being used to make a "local" recursive call. -/ pure $ LValResolution.localRec structName fullName localDecl.toExpr else searchEnv () | none => searchEnv () }; if isStructure env structName then match findField? env structName fieldName with | some baseStructName => pure $ LValResolution.projFn baseStructName structName fieldName | none => searchCtx () else searchCtx () | Expr.const structName _ _, LVal.getOp idx => do env ← getEnv; let fullName := mkNameStr structName "getOp"; match env.find? fullName with | some _ => pure $ LValResolution.getOp fullName idx | none => throwLValError e eType $ "invalid [..] notation because environment does not contain '" ++ fullName ++ "'" | _, LVal.getOp idx => throwLValError e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant" | _, _ => throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant" private partial def resolveLValLoop (e : Expr) (lval : LVal) : Expr → Array Exception → TermElabM LValResolution | eType, previousExceptions => do eType ← whnfCore eType; tryPostponeIfMVar eType; catch (resolveLValAux e eType lval) (fun ex => match ex with | Exception.error _ _ => do eType? ← unfoldDefinition? eType; match eType? with | some eType => resolveLValLoop eType (previousExceptions.push ex) | none => do previousExceptions.forM $ fun ex => logException ex; throw ex | Exception.internal _ => throw ex) private def resolveLVal (e : Expr) (lval : LVal) : TermElabM LValResolution := do eType ← inferType e; resolveLValLoop e lval eType #[] private partial def mkBaseProjections (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do env ← getEnv; match getPathToBaseStructure? env baseStructName structName with | none => throwError "failed to access field in parent structure" | some path => path.foldlM (fun e projFunName => do projFn ← mkConst projFunName; elabAppArgs projFn #[{ name := `self, val := Arg.expr e }] #[] none false) e /- Auxiliary method for field notation. It tries to add `e` to `args` as the first explicit parameter which takes an element of type `(C ...)` where `C` is `baseName`. `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/ private def addLValArg (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) : Nat → Array NamedArg → Expr → TermElabM (Array Arg) | i, namedArgs, Expr.forallE n d b c => if !c.binderInfo.isExplicit then addLValArg i namedArgs b else /- If there is named argument with name `n`, then we should skip. -/ match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let namedArgs := namedArgs.eraseIdx idx; addLValArg i namedArgs b | none => do if d.consumeMData.isAppOf baseName then pure $ args.insertAt i (Arg.expr e) else if i < args.size then addLValArg (i+1) namedArgs b else throwError $ "invalid field notation, insufficient number of arguments for '" ++ fullName ++ "'" | _, _, fType => throwError $ "invalid field notation, function '" ++ fullName ++ "' does not have explicit argument with type (" ++ baseName ++ " ...)" private def elabAppLValsAux (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : Expr → List LVal → TermElabM Expr | f, [] => elabAppArgs f namedArgs args expectedType? explicit | f, lval::lvals => do lvalRes ← resolveLVal f lval; match lvalRes with | LValResolution.projIdx structName idx => let f := mkProj structName idx f; elabAppLValsAux f lvals | LValResolution.projFn baseStructName structName fieldName => do f ← mkBaseProjections baseStructName structName f; projFn ← mkConst (baseStructName ++ fieldName); if lvals.isEmpty then do namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f }; elabAppArgs projFn namedArgs args expectedType? explicit else do f ← elabAppArgs projFn #[{ name := `self, val := Arg.expr f }] #[] none false; elabAppLValsAux f lvals | LValResolution.const baseStructName structName constName => do f ← if baseStructName != structName then mkBaseProjections baseStructName structName f else pure f; projFn ← mkConst constName; if lvals.isEmpty then do projFnType ← inferType projFn; args ← addLValArg baseStructName constName f args 0 namedArgs projFnType; elabAppArgs projFn namedArgs args expectedType? explicit else do f ← elabAppArgs projFn #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.localRec baseName fullName fvar => if lvals.isEmpty then do fvarType ← inferType fvar; args ← addLValArg baseName fullName f args 0 namedArgs fvarType; elabAppArgs fvar namedArgs args expectedType? explicit else do f ← elabAppArgs fvar #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.getOp fullName idx => do getOpFn ← mkConst fullName; if lvals.isEmpty then do namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f }; namedArgs ← addNamedArg namedArgs { name := `idx, val := Arg.stx idx }; elabAppArgs getOpFn namedArgs args expectedType? explicit else do f ← elabAppArgs getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }] #[] none false; elabAppLValsAux f lvals private def elabAppLVals (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do when (!lvals.isEmpty && explicit) $ throwError "invalid use of field notation with `@` modifier"; elabAppLValsAux namedArgs args expectedType? explicit f lvals def elabExplicitUnivs (lvls : Array Syntax) : TermElabM (List Level) := do lvls.foldrM (fun stx lvls => do lvl ← elabLevel stx; pure (lvl::lvls)) [] /- Interaction between `errToSorry` and `observing`. - The method `elabTerm` catches exceptions, log them, and returns a synthetic sorry (IF `ctx.errToSorry` == true). - When we elaborate choice nodes (and overloaded identifiers), we track multiple results using the `observing x` combinator. The `observing x` executes `x` and returns a `TermElabResult`. `observing `x does not check for synthetic sorry's, just an exception. Thus, it may think `x` worked when it didn't if a synthetic sorry was introduced. We decided that checking for synthetic sorrys at `observing` is not a good solution because it would not be clear to decide what the "main" error message for the alternative is. When the result contains a synthetic `sorry`, it is not clear which error message corresponds to the `sorry`. Moreover, while executing `x`, many error messages may have been logged. Recall that we need an error per alternative at `mergeFailures`. Thus, we decided to set `errToSorry` to `false` whenever processing choice nodes and overloaded symbols. Important: we rely on the property that after `errToSorry` is set to false, no elaboration function executed by `x` will reset it to `true`. -/ private partial def elabAppFnId (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) (acc : Array TermElabResult) : TermElabM (Array TermElabResult) := match fIdent with | Syntax.ident _ _ n preresolved => do funLVals ← withRef fIdent $ resolveName n preresolved fExplicitUnivs; -- Set `errToSorry` to `false` if `funLVals` > 1. See comment above about the interaction between `errToSorry` and `observing`. adaptReader (fun (ctx : Context) => { ctx with errToSorry := funLVals.length == 1 && ctx.errToSorry }) $ funLVals.foldlM (fun acc ⟨f, fields⟩ => do let lvals' := fields.map LVal.fieldName; s ← observing $ elabAppLVals f (lvals' ++ lvals) namedArgs args expectedType? explicit; pure $ acc.push s) acc | _ => throwUnsupportedSyntax private partial def elabAppFn : Syntax → List LVal → Array NamedArg → Array Arg → Option Expr → Bool → Array TermElabResult → TermElabM (Array TermElabResult) | f, lvals, namedArgs, args, expectedType?, explicit, acc => if f.getKind == choiceKind then -- Set `errToSorry` to `false` when processing choice nodes. See comment above about the interaction between `errToSorry` and `observing`. adaptReader (fun (ctx : Context) => { ctx with errToSorry := false }) $ f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit acc) acc else match_syntax f with | `($(e).$idx:fieldIdx) => let idx := idx.isFieldIdx?.get!; elabAppFn e (LVal.fieldIdx idx :: lvals) namedArgs args expectedType? explicit acc | `($(e).$field:ident) => let newLVals := field.getId.eraseMacroScopes.components.map (fun n => LVal.fieldName (toString n)); elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit acc | `($e[$idx]) => elabAppFn e (LVal.getOp idx :: lvals) namedArgs args expectedType? explicit acc | `($id:ident@$t:term) => throwError "unexpected occurrence of named pattern" | `($id:ident) => do elabAppFnId id [] lvals namedArgs args expectedType? explicit acc | `($id:ident.{$us*}) => do us ← elabExplicitUnivs us.getSepElems; elabAppFnId id us lvals namedArgs args expectedType? explicit acc | `(@$id:ident) => elabAppFn id lvals namedArgs args expectedType? true acc | `(@$id:ident.{$us*}) => elabAppFn (f.getArg 1) lvals namedArgs args expectedType? true acc | `(@$t) => throwUnsupportedSyntax -- invalid occurrence of `@` | `(_) => throwError "placeholders '_' cannot be used where a function is expected" | _ => do s ← observing $ do { f ← elabTerm f none; elabAppLVals f lvals namedArgs args expectedType? explicit }; pure $ acc.push s private def getSuccess (candidates : Array TermElabResult) : Array TermElabResult := candidates.filter $ fun c => match c with | EStateM.Result.ok _ _ => true | _ => false private def toMessageData (ex : Exception) : TermElabM MessageData := do pos ← getRefPos; match ex.getRef.getPos with | none => pure ex.toMessageData | some exPos => if pos == exPos then pure ex.toMessageData else do fileMap ← getFileMap; let exPosition := fileMap.toPosition exPos; pure $ toString exPosition.line ++ ":" ++ toString exPosition.column ++ " " ++ ex.toMessageData private def mergeFailures {α} (failures : Array TermElabResult) : TermElabM α := do msgs ← failures.mapM $ fun failure => match failure with | EStateM.Result.ok _ _ => unreachable! | EStateM.Result.error ex _ => toMessageData ex; throwError ("overloaded, errors " ++ MessageData.ofArray msgs) private def elabAppAux (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) : TermElabM Expr := do /- TODO: if `f` contains `choice` or overloaded symbols, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we should postpone until `?m` is assigned. Another (more expensive) option is: execute, and if successes > 1, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we postpone `elabAppAux`. It is more expensive because we would have to re-elaborate the whole thing after we assign `?m`. We **can't** continue from `TermElabResult` since they contain a snapshot of the state, and state has changed. -/ candidates ← elabAppFn f [] namedArgs args expectedType? false #[]; if candidates.size == 1 then applyResult $ candidates.get! 0 else let successes := getSuccess candidates; if successes.size == 1 then applyResult $ successes.get! 0 else if successes.size > 1 then do env ← getEnv; lctx ← getLCtx; mctx ← getMCtx; opts ← getOptions; let msgs : Array MessageData := successes.map $ fun success => match success with | EStateM.Result.ok e s => MessageData.withContext { env := env, mctx := mctx, lctx := lctx, opts := opts } e | _ => unreachable!; throwErrorAt f ("ambiguous, possible interpretations " ++ MessageData.ofArray msgs) else withRef f $ mergeFailures candidates partial def expandApp (stx : Syntax) : TermElabM (Syntax × Array NamedArg × Array Arg) := do let f := stx.getArg 0; (namedArgs, args) ← (stx.getArg 1).getArgs.foldlM (fun (acc : Array NamedArg × Array Arg) (stx : Syntax) => do let (namedArgs, args) := acc; if stx.getKind == `Lean.Parser.Term.namedArgument then do -- tparser! try ("(" >> ident >> " := ") >> termParser >> ")" let name := (stx.getArg 1).getId.eraseMacroScopes; let val := stx.getArg 3; namedArgs ← addNamedArg namedArgs { name := name, val := Arg.stx val }; pure (namedArgs, args) else pure (namedArgs, args.push $ Arg.stx stx)) (#[], #[]); pure (f, namedArgs, args) @[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? => do (f, namedArgs, args) ← expandApp stx; elabAppAux f namedArgs args expectedType? def elabAtom : TermElab := fun stx expectedType? => elabAppAux stx #[] #[] expectedType? @[builtinTermElab ident] def elabIdent : TermElab := elabAtom @[builtinTermElab namedPattern] def elabNamedPattern : TermElab := elabAtom @[builtinTermElab explicitUniv] def elabExplicitUniv : TermElab := elabAtom @[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? => match_syntax stx with | `(@$id:ident) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@` | `(@$id:ident.{$us*}) => elabAtom stx expectedType? | `(@($t)) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas | `(@$t) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas | _ => throwUnsupportedSyntax @[builtinTermElab choice] def elabChoice : TermElab := elabAtom @[builtinTermElab proj] def elabProj : TermElab := elabAtom @[builtinTermElab arrayRef] def elabArrayRef : TermElab := elabAtom /- A raw identiier is not a valid term, but it is nice to have a handler for them because it allows `macros` to insert them into terms. -/ @[builtinTermElab ident] def elabRawIdent : TermElab := elabAtom @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.app; pure () end Term end Elab end Lean
ce45c2c9f45c99b60bb73c6918362de5805cc994
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/constructions/over/products.lean
ce355f86a05b25bdac5018feb8875bd831a3a589
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
6,270
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import category_theory.over import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.finite_products /-! # Products in the over category Shows that products in the over category can be derived from wide pullbacks in the base category. The main result is `over_product_of_wide_pullback`, which says that if `C` has `J`-indexed wide pullbacks, then `over B` has `J`-indexed products. -/ universes w v u -- morphism levels before object levels. See note [category_theory universes]. open category_theory category_theory.limits variables {J : Type w} variables {C : Type u} [category.{v} C] variable {X : C} namespace category_theory.over namespace construct_products /-- (Implementation) Given a product diagram in `C/B`, construct the corresponding wide pullback diagram in `C`. -/ @[reducible] def wide_pullback_diagram_of_diagram_over (B : C) {J : Type w} (F : discrete J ⥤ over B) : wide_pullback_shape J ⥤ C := wide_pullback_shape.wide_cospan B (λ j, (F.obj ⟨j⟩).left) (λ j, (F.obj ⟨j⟩).hom) /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_inverse_obj (B : C) {J : Type w} (F : discrete J ⥤ over B) (c : cone F) : cone (wide_pullback_diagram_of_diagram_over B F) := { X := c.X.left, π := { app := λ X, option.cases_on X c.X.hom (λ (j : J), (c.π.app ⟨j⟩).left), -- `tidy` can do this using `case_bash`, but let's try to be a good `-T50000` citizen: naturality' := λ X Y f, begin dsimp, cases X; cases Y; cases f, { rw [category.id_comp, category.comp_id], }, { rw [over.w, category.id_comp], }, { rw [category.id_comp, category.comp_id], }, end } } /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_inverse (B : C) {J : Type w} (F : discrete J ⥤ over B) : cone F ⥤ cone (wide_pullback_diagram_of_diagram_over B F) := { obj := cones_equiv_inverse_obj B F, map := λ c₁ c₂ f, { hom := f.hom.left, w' := λ j, begin cases j, { simp }, { dsimp, rw ← f.w ⟨j⟩, refl } end } } local attribute [tidy] tactic.discrete_cases /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_functor (B : C) {J : Type w} (F : discrete J ⥤ over B) : cone (wide_pullback_diagram_of_diagram_over B F) ⥤ cone F := { obj := λ c, { X := over.mk (c.π.app none), π := { app := λ ⟨j⟩, over.hom_mk (c.π.app (some j)) (by apply c.w (wide_pullback_shape.hom.term j)) } }, map := λ c₁ c₂ f, { hom := over.hom_mk f.hom } } local attribute [tidy] tactic.case_bash /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simp] def cones_equiv_unit_iso (B : C) (F : discrete J ⥤ over B) : 𝟭 (cone (wide_pullback_diagram_of_diagram_over B F)) ≅ cones_equiv_functor B F ⋙ cones_equiv_inverse B F := nat_iso.of_components (λ _, cones.ext {hom := 𝟙 _, inv := 𝟙 _} (by tidy)) (by tidy) /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simp] def cones_equiv_counit_iso (B : C) (F : discrete J ⥤ over B) : cones_equiv_inverse B F ⋙ cones_equiv_functor B F ≅ 𝟭 (cone F) := nat_iso.of_components (λ _, cones.ext {hom := over.hom_mk (𝟙 _), inv := over.hom_mk (𝟙 _)} (by tidy)) (by tidy) -- TODO: Can we add `. obviously` to the second arguments of `nat_iso.of_components` and -- `cones.ext`? /-- (Impl) Establish an equivalence between the category of cones for `F` and for the "grown" `F`. -/ @[simps] def cones_equiv (B : C) (F : discrete J ⥤ over B) : cone (wide_pullback_diagram_of_diagram_over B F) ≌ cone F := { functor := cones_equiv_functor B F, inverse := cones_equiv_inverse B F, unit_iso := cones_equiv_unit_iso B F, counit_iso := cones_equiv_counit_iso B F, } /-- Use the above equivalence to prove we have a limit. -/ lemma has_over_limit_discrete_of_wide_pullback_limit {B : C} (F : discrete J ⥤ over B) [has_limit (wide_pullback_diagram_of_diagram_over B F)] : has_limit F := has_limit.mk { cone := _, is_limit := is_limit.of_right_adjoint (cones_equiv B F).functor (limit.is_limit (wide_pullback_diagram_of_diagram_over B F)) } /-- Given a wide pullback in `C`, construct a product in `C/B`. -/ lemma over_product_of_wide_pullback [has_limits_of_shape (wide_pullback_shape J) C] {B : C} : has_limits_of_shape (discrete J) (over B) := { has_limit := λ F, has_over_limit_discrete_of_wide_pullback_limit F } /-- Given a pullback in `C`, construct a binary product in `C/B`. -/ lemma over_binary_product_of_pullback [has_pullbacks C] {B : C} : has_binary_products (over B) := over_product_of_wide_pullback /-- Given all wide pullbacks in `C`, construct products in `C/B`. -/ lemma over_products_of_wide_pullbacks [has_wide_pullbacks.{w} C] {B : C} : has_products.{w} (over B) := λ J, over_product_of_wide_pullback /-- Given all finite wide pullbacks in `C`, construct finite products in `C/B`. -/ lemma over_finite_products_of_finite_wide_pullbacks [has_finite_wide_pullbacks C] {B : C} : has_finite_products (over B) := ⟨λ J 𝒥, by exactI over_product_of_wide_pullback⟩ end construct_products local attribute [tidy] tactic.discrete_cases /-- Construct terminal object in the over category. This isn't an instance as it's not typically the way we want to define terminal objects. (For instance, this gives a terminal object which is different from the generic one given by `over_product_of_wide_pullback` above.) -/ lemma over_has_terminal (B : C) : has_terminal (over B) := { has_limit := λ F, has_limit.mk { cone := { X := over.mk (𝟙 _), π := { app := λ p, p.as.elim } }, is_limit := { lift := λ s, over.hom_mk _, fac' := λ _ j, j.as.elim, uniq' := λ s m _, begin ext, rw over.hom_mk_left, have := m.w, dsimp at this, rwa [category.comp_id, category.comp_id] at this end } } } end category_theory.over
ac301b84c7286e3439d1e3238d1c60e7e4aca96b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/metric_space/emetric_paracompact.lean
0d46182da5e39c58d23d8de74b4963e043ba2581
[ "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,420
lean
/- Copyright (c) 202 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import set_theory.ordinal.basic import topology.metric_space.emetric_space import topology.paracompact /-! # (Extended) metric spaces are paracompact In this file we provide two instances: * `emetric.paracompact_space`: a `pseudo_emetric_space` is paracompact; formalization is based on [MR0236876]; * `emetric.normal_of_metric`: an `emetric_space` is a normal topological space. ## Tags metric space, paracompact space, normal space -/ variable {α : Type*} open_locale ennreal topological_space open set namespace emetric /-- A `pseudo_emetric_space` is always a paracompact space. Formalization is based on [MR0236876]. -/ @[priority 100] -- See note [lower instance priority] instance [pseudo_emetric_space α] : paracompact_space α := begin classical, /- We start with trivial observations about `1 / 2 ^ k`. Here and below we use `1 / 2 ^ k` in the comments and `2⁻¹ ^ k` in the code. -/ have pow_pos : ∀ k : ℕ, (0 : ℝ≥0∞) < 2⁻¹ ^ k, from λ k, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _, have hpow_le : ∀ {m n : ℕ}, m ≤ n → (2⁻¹ : ℝ≥0∞) ^ n ≤ 2⁻¹ ^ m, from λ m n h, ennreal.pow_le_pow_of_le_one (ennreal.inv_le_one.2 ennreal.one_lt_two.le) h, have h2pow : ∀ n : ℕ, 2 * (2⁻¹ : ℝ≥0∞) ^ (n + 1) = 2⁻¹ ^ n, by { intro n, simp [pow_succ, ← mul_assoc, ennreal.mul_inv_cancel] }, -- Consider an open covering `S : set (set α)` refine ⟨λ ι s ho hcov, _⟩, simp only [Union_eq_univ_iff] at hcov, -- choose a well founded order on `S` letI : linear_order ι := linear_order_of_STO well_ordering_rel, have wf : well_founded ((<) : ι → ι → Prop) := @is_well_founded.wf ι well_ordering_rel _, -- Let `ind x` be the minimal index `s : S` such that `x ∈ s`. set ind : α → ι := λ x, wf.min {i : ι | x ∈ s i} (hcov x), have mem_ind : ∀ x, x ∈ s (ind x), from λ x, wf.min_mem _ (hcov x), have nmem_of_lt_ind : ∀ {x i}, i < (ind x) → x ∉ s i, from λ x i hlt hxi, wf.not_lt_min _ (hcov x) hxi hlt, /- The refinement `D : ℕ → ι → set α` is defined recursively. For each `n` and `i`, `D n i` is the union of balls `ball x (1 / 2 ^ n)` over all points `x` such that * `ind x = i`; * `x` does not belong to any `D m j`, `m < n`; * `ball x (3 / 2 ^ n) ⊆ s i`; We define this sequence using `nat.strong_rec_on'`, then restate it as `Dn` and `memD`. -/ set D : ℕ → ι → set α := λ n, nat.strong_rec_on' n (λ n D' i, ⋃ (x : α) (hxs : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D' m ‹_› j), ball x (2⁻¹ ^ n)), have Dn : ∀ n i, D n i = ⋃ (x : α) (hxs : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D m j), ball x (2⁻¹ ^ n), from λ n s, by { simp only [D], rw nat.strong_rec_on_beta' }, have memD : ∀ {n i y}, y ∈ D n i ↔ ∃ x (hi : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D m j), edist y x < 2⁻¹ ^ n, { intros n i y, rw [Dn n i], simp only [mem_Union, mem_ball] }, -- The sets `D n i` cover the whole space. Indeed, for each `x` we can choose `n` such that -- `ball x (3 / 2 ^ n) ⊆ s (ind x)`, then either `x ∈ D n i`, or `x ∈ D m i` for some `m < n`. have Dcov : ∀ x, ∃ n i, x ∈ D n i, { intro x, obtain ⟨n, hn⟩ : ∃ n : ℕ, ball x (3 * 2⁻¹ ^ n) ⊆ s (ind x), { -- This proof takes 5 lines because we can't import `specific_limits` here rcases is_open_iff.1 (ho $ ind x) x (mem_ind x) with ⟨ε, ε0, hε⟩, have : 0 < ε / 3 := ennreal.div_pos_iff.2 ⟨ε0.lt.ne', ennreal.coe_ne_top⟩, rcases ennreal.exists_inv_two_pow_lt this.ne' with ⟨n, hn⟩, refine ⟨n, subset.trans (ball_subset_ball _) hε⟩, simpa only [div_eq_mul_inv, mul_comm] using (ennreal.mul_lt_of_lt_div hn).le }, by_contra' h, apply h n (ind x), exact memD.2 ⟨x, rfl, hn, λ _ _ _, h _ _, mem_ball_self (pow_pos _)⟩ }, -- Each `D n i` is a union of open balls, hence it is an open set have Dopen : ∀ n i, is_open (D n i), { intros n i, rw Dn, iterate 4 { refine is_open_Union (λ _, _) }, exact is_open_ball }, -- the covering `D n i` is a refinement of the original covering: `D n i ⊆ s i` have HDS : ∀ n i, D n i ⊆ s i, { intros n s x, rw memD, rintro ⟨y, rfl, hsub, -, hyx⟩, refine hsub (lt_of_lt_of_le hyx _), calc 2⁻¹ ^ n = 1 * 2⁻¹ ^ n : (one_mul _).symm ... ≤ 3 * 2⁻¹ ^ n : ennreal.mul_le_mul _ le_rfl, -- TODO: use `norm_num` have : ((1 : ℕ) : ℝ≥0∞) ≤ (3 : ℕ), from ennreal.coe_nat_le_coe_nat.2 (by norm_num1), exact_mod_cast this }, -- Let us show the rest of the properties. Since the definition expects a family indexed -- by a single parameter, we use `ℕ × ι` as the domain. refine ⟨ℕ × ι, λ ni, D ni.1 ni.2, λ _, Dopen _ _, _, _, λ ni, ⟨ni.2, HDS _ _⟩⟩, -- The sets `D n i` cover the whole space as we proved earlier { refine Union_eq_univ_iff.2 (λ x, _), rcases Dcov x with ⟨n, i, h⟩, exact ⟨⟨n, i⟩, h⟩ }, { /- Let us prove that the covering `D n i` is locally finite. Take a point `x` and choose `n`, `i` so that `x ∈ D n i`. Since `D n i` is an open set, we can choose `k` so that `B = ball x (1 / 2 ^ (n + k + 1)) ⊆ D n i`. -/ intro x, rcases Dcov x with ⟨n, i, hn⟩, have : D n i ∈ 𝓝 x, from is_open.mem_nhds (Dopen _ _) hn, rcases (nhds_basis_uniformity uniformity_basis_edist_inv_two_pow).mem_iff.1 this with ⟨k, -, hsub : ball x (2⁻¹ ^ k) ⊆ D n i⟩, set B := ball x (2⁻¹ ^ (n + k + 1)), refine ⟨B, ball_mem_nhds _ (pow_pos _), _⟩, -- The sets `D m i`, `m > n + k`, are disjoint with `B` have Hgt : ∀ (m ≥ n + k + 1) (i : ι), disjoint (D m i) B, { rintros m hm i, rw disjoint_iff_inf_le, rintros y ⟨hym, hyx⟩, rcases memD.1 hym with ⟨z, rfl, hzi, H, hz⟩, have : z ∉ ball x (2⁻¹ ^ k), from λ hz, H n (by linarith) i (hsub hz), apply this, calc edist z x ≤ edist y z + edist y x : edist_triangle_left _ _ _ ... < (2⁻¹ ^ m) + (2⁻¹ ^ (n + k + 1)) : ennreal.add_lt_add hz hyx ... ≤ (2⁻¹ ^ (k + 1)) + (2⁻¹ ^ (k + 1)) : add_le_add (hpow_le $ by linarith) (hpow_le $ by linarith) ... = (2⁻¹ ^ k) : by rw [← two_mul, h2pow] }, -- For each `m ≤ n + k` there is at most one `j` such that `D m j ∩ B` is nonempty. have Hle : ∀ m ≤ n + k, set.subsingleton {j | (D m j ∩ B).nonempty}, { rintros m hm j₁ ⟨y, hyD, hyB⟩ j₂ ⟨z, hzD, hzB⟩, by_contra h, wlog h : j₁ < j₂ := ne.lt_or_lt h using [j₁ j₂ y z, j₂ j₁ z y], rcases memD.1 hyD with ⟨y', rfl, hsuby, -, hdisty⟩, rcases memD.1 hzD with ⟨z', rfl, -, -, hdistz⟩, suffices : edist z' y' < 3 * 2⁻¹ ^ m, from nmem_of_lt_ind h (hsuby this), calc edist z' y' ≤ edist z' x + edist x y' : edist_triangle _ _ _ ... ≤ (edist z z' + edist z x) + (edist y x + edist y y') : add_le_add (edist_triangle_left _ _ _) (edist_triangle_left _ _ _) ... < (2⁻¹ ^ m + 2⁻¹ ^ (n + k + 1)) + (2⁻¹ ^ (n + k + 1) + 2⁻¹ ^ m) : by apply_rules [ennreal.add_lt_add] ... = 2 * (2⁻¹ ^ m + 2⁻¹ ^ (n + k + 1)) : by simp only [two_mul, add_comm] ... ≤ 2 * (2⁻¹ ^ m + 2⁻¹ ^ (m + 1)) : ennreal.mul_le_mul le_rfl $ add_le_add le_rfl $ hpow_le (add_le_add hm le_rfl) ... = 3 * 2⁻¹ ^ m : by rw [mul_add, h2pow, bit1, add_mul, one_mul] }, -- Finally, we glue `Hgt` and `Hle` have : (⋃ (m ≤ n + k) (i ∈ {i : ι | (D m i ∩ B).nonempty}), {(m, i)}).finite := (finite_le_nat _).bUnion' (λ i hi, (Hle i hi).finite.bUnion' (λ _ _, finite_singleton _)), refine this.subset (λ I hI, _), simp only [mem_Union], refine ⟨I.1, _, I.2, hI, prod.mk.eta.symm⟩, exact not_lt.1 (λ hlt, (Hgt I.1 hlt I.2).le_bot hI.some_spec) } end @[priority 100] -- see Note [lower instance priority] instance normal_of_emetric [emetric_space α] : normal_space α := normal_of_paracompact_t2 end emetric
adf289ad15162896ca7cb2327d27a82969d9b5dc
d5ecf6c46a2f605470a4a7724909dc4b9e7350e0
/set_theory/cofinality.lean
a64897545e96d3816f9ca2450bf89fb9ce9bd4ff
[ "Apache-2.0" ]
permissive
MonoidMusician/mathlib
41f79df478987a636b735c338396813d2e8e44c4
72234ef1a050eea3a2197c23aeb345fc13c08ff3
refs/heads/master
1,583,672,205,771
1,522,892,143,000
1,522,892,143,000
128,144,032
0
0
Apache-2.0
1,522,892,144,000
1,522,890,892,000
Lean
UTF-8
Lean
false
false
16,736
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Cofinality on ordinals, regular cardinals. -/ import set_theory.ordinal noncomputable theory open function cardinal local attribute [instance] classical.prop_decidable universes u v w variables {α : Type*} {r : α → α → Prop} /-- Cofinality of a reflexive order `≼`. This is the smallest cardinality of a subset `S : set α` such that `∀ a, ∃ b ∈ S, a ≼ b`. -/ def order.cof (r : α → α → Prop) [is_refl α r] : cardinal := @cardinal.min {S : set α // ∀ a, ∃ b ∈ S, r a b} ⟨⟨set.univ, λ a, ⟨a, ⟨⟩, refl _⟩⟩⟩ (λ S, mk S) theorem order_iso.cof.aux {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃o s) : cardinal.lift.{u (max u v)} (order.cof r) ≤ cardinal.lift.{v (max u v)} (order.cof s) := begin rw [order.cof, order.cof, lift_min, lift_min, cardinal.le_min], intro S, cases S with S H, simp [(∘)], refine le_trans (min_le _ _) _, { exact ⟨f ⁻¹' S, λ a, let ⟨b, bS, h⟩ := H (f a) in ⟨f.symm b, by simp [bS, f.ord', h]⟩⟩ }, { exact lift_mk_le.{u v (max u v)}.2 ⟨⟨λ ⟨x, h⟩, ⟨f x, h⟩, λ ⟨x, h₁⟩ ⟨y, h₂⟩ h₃, by congr; injection h₃ with h'; exact f.to_equiv.bijective.1 h'⟩⟩ } end theorem order_iso.cof {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃o s) : cardinal.lift.{u (max u v)} (order.cof r) = cardinal.lift.{v (max u v)} (order.cof s) := le_antisymm (order_iso.cof.aux f) (order_iso.cof.aux f.symm) namespace ordinal /-- Cofinality of an ordinal. This is the smallest cardinal of a subset `S` of the ordinal which is unbounded, in the sense `∀ a, ∃ b ∈ S, a ≤ b`. It is defined for all ordinals, but `cof 0 = 0` and `cof (succ o) = 1`, so it is only really interesting on limit ordinals (when it is an infinite cardinal). -/ def cof (o : ordinal.{u}) : cardinal.{u} := quot.lift_on o (λ ⟨α, r, _⟩, @order.cof α (λ x y, ¬ r y x) ⟨λ a, by resetI; apply irrefl⟩) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨⟨f, hf⟩⟩, begin show @order.cof α (λ x y, ¬ r y x) ⟨_⟩ = @order.cof β (λ x y, ¬ s y x) ⟨_⟩, refine cardinal.lift_inj.1 (@order_iso.cof _ _ _ _ ⟨_⟩ ⟨_⟩ _), exact ⟨f, λ a b, not_congr hf⟩, end theorem le_cof_type [is_well_order α r] {c} : c ≤ cof (type r) ↔ ∀ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) → c ≤ mk S := by dsimp [cof, order.cof, type, quotient.mk, quot.lift_on]; rw [cardinal.le_min, subtype.forall]; refl theorem cof_type_le [is_well_order α r] (S : set α) (h : ∀ a, ∃ b ∈ S, ¬ r b a) : cof (type r) ≤ mk S := le_cof_type.1 (le_refl _) S h theorem lt_cof_type [is_well_order α r] (S : set α) (hl : mk S < cof (type r)) : ∃ a, ∀ b ∈ S, r b a := not_forall_not.1 $ λ h, not_le_of_lt hl $ cof_type_le S (λ a, not_ball.1 (h a)) theorem cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ mk S = cof (type r) := begin have : ∃ i, cof (type r) = _, { dsimp [cof, order.cof, type, quotient.mk, quot.lift_on], apply cardinal.min_eq }, exact let ⟨⟨S, hl⟩, e⟩ := this in ⟨S, hl, e.symm⟩, end theorem ord_cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ type (subrel r S) = (cof (type r)).ord := let ⟨S, hS, e⟩ := cof_eq r, ⟨s, _, e'⟩ := cardinal.ord_eq S, T : set α := {a | ∃ aS : a ∈ S, ∀ b : S, s b ⟨_, aS⟩ → r b a} in begin resetI, suffices, { refine ⟨T, this, le_antisymm _ (cardinal.ord_le.2 $ cof_type_le T this)⟩, rw [← e, e'], refine type_le'.2 ⟨order_embedding.of_monotone (λ a, ⟨a, let ⟨aS, _⟩ := a.2 in aS⟩) (λ a b h, _)⟩, rcases a with ⟨a, aS, ha⟩, rcases b with ⟨b, bS, hb⟩, change s ⟨a, _⟩ ⟨b, _⟩, refine ((trichotomous_of s _ _).resolve_left (λ hn, _)).resolve_left _, { exact asymm h (ha _ hn) }, { intro e, injection e with e, subst b, exact irrefl _ h } }, { intro a, have : {b : S | ¬ r b a} ≠ ∅ := let ⟨b, bS, ba⟩ := hS a in @set.ne_empty_of_mem S {b | ¬ r b a} ⟨b, bS⟩ ba, let b := (is_well_order.wf s).min _ this, have ba : ¬r b a := (is_well_order.wf s).min_mem _ this, refine ⟨b, ⟨b.2, λ c, not_imp_not.1 $ λ h, _⟩, ba⟩, rw [show ∀b:S, (⟨b, b.2⟩:S) = b, by intro b; cases b; refl], exact (is_well_order.wf s).not_lt_min _ this (is_order_connected.neg_trans r h ba) } end theorem lift_cof (o) : (cof o).lift = cof o.lift := induction_on o $ begin introsI α r _, cases lift_type r with _ e, rw e, apply le_antisymm, { refine le_cof_type.2 (λ S H, _), have : (mk (ulift.up ⁻¹' S)).lift ≤ mk S := ⟨⟨λ ⟨⟨x, h⟩⟩, ⟨⟨x⟩, h⟩, λ ⟨⟨x, h₁⟩⟩ ⟨⟨y, h₂⟩⟩ e, by simp at e; congr; injection e⟩⟩, refine le_trans (cardinal.lift_le.2 $ cof_type_le _ _) this, exact λ a, let ⟨⟨b⟩, bs, br⟩ := H ⟨a⟩ in ⟨b, bs, br⟩ }, { rcases cof_eq r with ⟨S, H, e'⟩, have : mk (ulift.down ⁻¹' S) ≤ (mk S).lift := ⟨⟨λ ⟨⟨x⟩, h⟩, ⟨⟨x, h⟩⟩, λ ⟨⟨x⟩, h₁⟩ ⟨⟨y⟩, h₂⟩ e, by simp at e; congr; injections⟩⟩, rw e' at this, refine le_trans (cof_type_le _ _) this, exact λ ⟨a⟩, let ⟨b, bs, br⟩ := H a in ⟨⟨b⟩, bs, br⟩ } end theorem cof_le_card (o) : cof o ≤ card o := induction_on o $ λ α r _, begin resetI, have : mk (@set.univ α) = card (type r) := quotient.sound ⟨equiv.set.univ _⟩, rw ← this, exact cof_type_le set.univ (λ a, ⟨a, ⟨⟩, irrefl a⟩) end theorem cof_ord_le (c : cardinal) : cof c.ord ≤ c := by simpa using cof_le_card c.ord @[simp] theorem cof_zero : cof 0 = 0 := le_antisymm (by simpa using cof_le_card 0) (cardinal.zero_le _) @[simp] theorem cof_eq_zero {o} : cof o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ z, by exactI let ⟨S, hl, e⟩ := cof_eq r in type_eq_zero_iff_empty.2 $ λ ⟨a⟩, let ⟨b, h, _⟩ := hl a in ne_zero_iff_nonempty.2 (by exact ⟨⟨_, h⟩⟩) (e.trans z), λ e, by simp [e]⟩ @[simp] theorem cof_succ (o) : cof (succ o) = 1 := begin apply le_antisymm, { refine induction_on o (λ α r _, _), change cof (type _) ≤ _, rw [← (_ : mk _ = 1)], apply cof_type_le, { refine λ a, ⟨sum.inr ⟨()⟩, set.mem_singleton _, _⟩, rcases a with a|⟨⟨⟨⟩⟩⟩; simp [empty_relation] }, { rw [cardinal.fintype_card, set.card_singleton], simp } }, { rw [← cardinal.succ_zero, cardinal.succ_le], simpa [lt_iff_le_and_ne, cardinal.zero_le] using λ h, succ_ne_zero o (cof_eq_zero.1 (eq.symm h)) } end @[simp] theorem cof_eq_one_iff_is_succ {o} : cof.{u} o = 1 ↔ ∃ a, o = succ a := ⟨induction_on o $ λ α r _ z, begin resetI, rcases cof_eq r with ⟨S, hl, e⟩, rw z at e, cases ne_zero_iff_nonempty.1 (by rw e; exact one_ne_zero) with a, refine ⟨typein r a, eq.symm $ quotient.sound ⟨order_iso.of_surjective (order_embedding.of_monotone _ (λ x y, _)) (λ x, _)⟩⟩, { apply sum.rec; [exact subtype.val, exact λ _, a] }, { rcases x with x|⟨⟨⟨⟩⟩⟩; rcases y with y|⟨⟨⟨⟩⟩⟩; simp [subrel, order.preimage, empty_relation], exact x.2 }, { suffices : r x a ∨ ∃ (b : ulift unit), ↑a = x, {simpa}, rcases trichotomous_of r x a with h|h|h, { exact or.inl h }, { exact or.inr ⟨⟨()⟩, h.symm⟩ }, { rcases hl x with ⟨a', aS, hn⟩, rw (_ : ↑a = a') at h, {exact absurd h hn}, refine congr_arg subtype.val (_ : a = ⟨a', aS⟩), haveI := le_one_iff_subsingleton.1 (le_of_eq e), apply subsingleton.elim } } end, λ ⟨a, e⟩, by simp [e]⟩ @[simp] theorem cof_add (a b : ordinal) : b ≠ 0 → cof (a + b) = cof b := induction_on a $ λ α r _, induction_on b $ λ β s _ b0, begin resetI, change cof (type _) = _, refine eq_of_forall_le_iff (λ c, _), rw [le_cof_type, le_cof_type], split; intros H S hS, { refine le_trans (H {a | sum.rec_on a (∅:set α) S} (λ a, _)) ⟨⟨_, _⟩⟩, { cases a with a b, { cases type_ne_zero_iff_nonempty.1 b0 with b, rcases hS b with ⟨b', bs, _⟩, exact ⟨sum.inr b', bs, by simp⟩ }, { rcases hS b with ⟨b', bs, h⟩, exact ⟨sum.inr b', bs, by simp [h]⟩ } }, { exact λ a, match a with ⟨sum.inr b, h⟩ := ⟨b, h⟩ end }, { exact λ a b, match a, b with ⟨sum.inr a, h₁⟩, ⟨sum.inr b, h₂⟩, h := by congr; injection h end } }, { refine le_trans (H (sum.inr ⁻¹' S) (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS (sum.inr a) with ⟨a'|b', bs, h⟩; simp at h, { cases h }, { exact ⟨b', bs, h⟩ } }, { exact λ ⟨a, h⟩, ⟨_, h⟩ }, { exact λ ⟨a, h₁⟩ ⟨b, h₂⟩ h, by injection h with h; congr; injection h } } end @[simp] theorem cof_cof (o : ordinal) : cof (cof o).ord = cof o := le_antisymm (le_trans (cof_le_card _) (by simp)) $ induction_on o $ λ α r _, by exactI let ⟨S, hS, e₁⟩ := ord_cof_eq r, ⟨T, hT, e₂⟩ := cof_eq (subrel r S) in begin rw e₁ at e₂, rw ← e₂, refine le_trans (cof_type_le {a | ∃ h, (subtype.mk a h : S) ∈ T} (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS a with ⟨b, bS, br⟩, rcases hT ⟨b, bS⟩ with ⟨c, cT, cs⟩, cases c with c cS, exact ⟨c, ⟨cS, cT⟩, is_order_connected.neg_trans r cs br⟩ }, { exact λ ⟨a, h⟩, ⟨⟨a, h.fst⟩, h.snd⟩ }, { exact λ ⟨a, ha⟩ ⟨b, hb⟩ h, by injection h with h; congr; injection h }, end theorem omega_le_cof {o} : cardinal.omega ≤ cof o ↔ is_limit o := begin rcases zero_or_succ_or_limit o with rfl|⟨o,rfl⟩|l, { simp [not_zero_is_limit, cardinal.omega_pos] }, { simp [not_succ_is_limit, cardinal.one_lt_omega] }, { simp [l], refine le_of_not_lt (λ h, _), cases cardinal.lt_omega.1 h with n e, have := cof_cof o, rw [e, ord_nat] at this, cases n, { simp at e, simpa [e, not_zero_is_limit] using l }, { rw [← nat_cast_succ, cof_succ] at this, rw [← this, cof_eq_one_iff_is_succ] at e, rcases e with ⟨a, rfl⟩, exact not_succ_is_limit _ l } } end @[simp] theorem cof_omega : cof omega = cardinal.omega := le_antisymm (by rw ← card_omega; apply cof_le_card) (omega_le_cof.2 omega_is_limit) theorem cof_eq' (r : α → α → Prop) [is_well_order α r] (h : is_limit (type r)) : ∃ S : set α, (∀ a, ∃ b ∈ S, r a b) ∧ mk S = cof (type r) := let ⟨S, H, e⟩ := cof_eq r in ⟨S, λ a, let a' := enum r _ (h.2 _ (typein_lt_type r a)) in let ⟨b, h, ab⟩ := H a' in ⟨b, h, (is_order_connected.conn a b a' $ (typein_lt_typein r).1 (by rw typein_enum; apply ordinal.lt_succ_self)).resolve_right ab⟩, e⟩ theorem cof_sup_le_lift {ι} (f : ι → ordinal) (H : ∀ i, f i < sup f) : cof (sup f) ≤ (mk ι).lift := begin generalize e : sup f = o, refine ordinal.induction_on o _ e, introsI α r _ e', rw e' at H, refine le_trans (cof_type_le (set.range (λ i, enum r _ (H i))) _) ⟨embedding.of_surjective _⟩, { intro a, by_contra h, apply not_le_of_lt (typein_lt_type r a), rw [← e', sup_le], intro i, simp [set.range] at h, simpa using le_of_lt ((typein_lt_typein r).2 (h _ i rfl)) }, { exact λ i, ⟨_, set.mem_range_self i.1⟩ }, { intro a, rcases a with ⟨_, i, rfl⟩, exact ⟨⟨i⟩, by simp⟩ } end theorem cof_sup_le {ι} (f : ι → ordinal) (H : ∀ i, f i < sup.{u u} f) : cof (sup.{u u} f) ≤ mk ι := by simpa using cof_sup_le_lift.{u u} f H theorem cof_bsup_le_lift {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup o f) → cof (bsup o f) ≤ o.card.lift := induction_on o $ λ α r _ f H, by rw bsup_type; refine cof_sup_le_lift _ _; rw ← bsup_type; intro a; apply H theorem cof_bsup_le {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup.{u u} o f) → cof (bsup.{u u} o f) ≤ o.card := induction_on o $ λ α r _ f H, by simpa using cof_bsup_le_lift.{u u} f H @[simp] theorem cof_univ : cof univ.{u v} = cardinal.univ := le_antisymm (cof_le_card _) begin refine le_of_forall_lt (λ c h, _), rcases lt_univ'.1 h with ⟨c, rfl⟩, rcases @cof_eq ordinal.{u} (<) _ with ⟨S, H, Se⟩, rw [univ, ← lift_cof, ← cardinal.lift_lift, cardinal.lift_lt, ← Se], refine lt_of_not_ge (λ h, _), cases cardinal.lift_down h with a e, refine quotient.induction_on a (λ α e, _) e, cases quotient.exact e with f, have f := equiv.ulift.symm.trans f, let g := λ a, (f a).1, let o := succ (sup.{u u} g), rcases H o with ⟨b, h, l⟩, refine l (lt_succ.2 _), rw ← show g (f.symm ⟨b, h⟩) = b, by dsimp [g]; simp, apply le_sup end end ordinal namespace cardinal open ordinal local infix ` ^ ` := cardinal.power /-- A cardinal is a limit if it is not zero or a successor cardinal. Note that `ω` is a limit cardinal by this definition. -/ def is_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, succ x < c /-- A cardinal is a strong limit if it is not zero and it is closed under powersets. Note that `ω` is a strong limit by this definition. -/ def is_strong_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, 2 ^ x < c theorem is_strong_limit.is_limit {c} (H : is_strong_limit c) : is_limit c := ⟨H.1, λ x h, lt_of_le_of_lt (succ_le.2 $ cantor _) (H.2 _ h)⟩ /-- A cardinal is regular if it is infinite and it equals its own cofinality. -/ def is_regular (c : cardinal) : Prop := omega ≤ c ∧ c.ord.cof = c theorem cof_is_regular {o : ordinal} (h : o.is_limit) : is_regular o.cof := ⟨omega_le_cof.2 h, cof_cof _⟩ theorem omega_is_regular {o : ordinal} (h : o.is_limit) : is_regular omega := ⟨le_refl _, by simp⟩ theorem succ_is_regular {c : cardinal.{u}} (h : omega ≤ c) : is_regular (succ c) := ⟨le_trans h (le_of_lt $ lt_succ_self _), begin refine le_antisymm (cof_ord_le _) (succ_le.2 _), cases quotient.exists_rep (succ c) with α αe, simp at αe, rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit (le_trans h $ le_of_lt $ lt_succ_self _), rw [← αe, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, rw [← Se], apply le_imp_le_iff_lt_imp_lt.1 (mul_le_mul_right c), rw [mul_eq_self h, ← succ_le, ← αe, ← sum_const], refine le_trans _ (sum_le_sum (λ x:S, card (typein r x)) _ _), { simp [typein, sum_mk (λ x:S, {a//r a x})], refine ⟨embedding.of_surjective _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { intro i, rw [← lt_succ, ← lt_ord, ← αe, re], apply typein_lt_type } end⟩ /-- A cardinal is inaccessible if it is an uncountable regular strong limit cardinal. -/ def is_inaccessible (c : cardinal) := omega < c ∧ is_regular c ∧ is_strong_limit c theorem is_inaccessible.mk {c} (h₁ : omega < c) (h₂ : c ≤ c.ord.cof) (h₃ : ∀ x < c, 2 ^ x < c) : is_inaccessible c := ⟨h₁, ⟨le_of_lt h₁, le_antisymm (cof_ord_le _) h₂⟩, ne_of_gt (lt_trans omega_pos h₁), h₃⟩ /- Lean's foundations prove the existence of ω many inaccessible cardinals -/ theorem univ_inaccessible : is_inaccessible (univ.{u v}) := is_inaccessible.mk (by simpa using lift_lt_univ' omega) (by simp) (λ c h, begin rcases lt_univ'.1 h with ⟨c, rfl⟩, rw ← lift_two_power.{u (max (u+1) v)}, apply lift_lt_univ' end) theorem lt_power_cof {c : cardinal.{u}} : omega ≤ c → c < c ^ cof c.ord := quotient.induction_on c $ λ α h, begin rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit h, rw [mk_def, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, have := sum_lt_prod (λ a:S, mk {x // r x a}) (λ _, mk α) (λ i, _), { simp [Se.symm] at this ⊢, refine lt_of_le_of_lt _ this, refine ⟨embedding.of_surjective _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { have := typein_lt_type r i, rwa [← re, lt_ord] at this } end theorem lt_cof_power {a b : cardinal} (ha : omega ≤ a) (b1 : 1 < b) : a < cof (b ^ a).ord := begin have b0 : b ≠ 0 := ne_of_gt (lt_trans zero_lt_one b1), apply le_imp_le_iff_lt_imp_lt.1 (power_le_power_left $ power_ne_zero a b0), rw [power_mul, mul_eq_self ha], exact lt_power_cof (le_trans ha $ le_of_lt $ cantor' _ b1), end end cardinal
a09c8a2efab09a539d7954b46cacdaff603f9805
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/types/univ.hlean
a4ebb46d7f65bfa26e69c7497b05852b9f98a97c
[ "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
4,922
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 Theorems about the universe -/ -- see also init.ua import .bool .trunc .lift .pullback open is_trunc bool lift unit eq pi equiv sum sigma fiber prod pullback is_equiv sigma.ops pointed namespace univ universe variables u v variables {A B : Type.{u}} {a : A} {b : B} /- Pathovers -/ definition eq_of_pathover_ua {f : A ≃ B} (p : a =[ua f] b) : f a = b := !cast_ua⁻¹ ⬝ tr_eq_of_pathover p definition pathover_ua {f : A ≃ B} (p : f a = b) : a =[ua f] b := pathover_of_tr_eq (!cast_ua ⬝ p) definition pathover_ua_equiv (f : A ≃ B) : (a =[ua f] b) ≃ (f a = b) := equiv.MK eq_of_pathover_ua pathover_ua abstract begin intro p, unfold [pathover_ua,eq_of_pathover_ua], rewrite [to_right_inv !pathover_equiv_tr_eq, inv_con_cancel_left] end end abstract begin intro p, unfold [pathover_ua,eq_of_pathover_ua], rewrite [con_inv_cancel_left, to_left_inv !pathover_equiv_tr_eq] end end /- Properties which can be disproven for the universe -/ definition not_is_set_type0 : ¬is_set Type₀ := assume H : is_set Type₀, absurd !is_set.elim eq_bnot_ne_idp definition not_is_set_type : ¬is_set Type.{u} := assume H : is_set Type, absurd (is_trunc_is_embedding_closed lift !trunc_index.minus_one_le_succ) not_is_set_type0 definition not_double_negation_elimination0 : ¬Π(A : Type₀), ¬¬A → A := begin intro f, have u : ¬¬bool, by exact (λg, g tt), let H1 := apd f eq_bnot, note H2 := apo10 H1 u, have p : eq_bnot ▸ u = u, from !is_prop.elim, rewrite p at H2, note H3 := eq_of_pathover_ua H2, esimp at H3, --TODO: use apply ... at after #700 exact absurd H3 (bnot_ne (f bool u)), end definition not_double_negation_elimination : ¬Π(A : Type), ¬¬A → A := begin intro f, apply not_double_negation_elimination0, intro A nna, refine down (f _ _), intro na, have ¬A, begin intro a, exact absurd (up a) na end, exact absurd this nna end definition not_excluded_middle : ¬Π(A : Type), A + ¬A := begin intro f, apply not_double_negation_elimination, intro A nna, induction (f A) with a na, exact a, exact absurd na nna end definition characteristic_map [unfold 2] {B : Type.{u}} (p : Σ(A : Type.{max u v}), A → B) (b : B) : Type.{max u v} := by induction p with A f; exact fiber f b definition characteristic_map_inv [constructor] {B : Type.{u}} (P : B → Type.{max u v}) : Σ(A : Type.{max u v}), A → B := ⟨(Σb, P b), pr1⟩ definition sigma_arrow_equiv_arrow_univ [constructor] (B : Type.{u}) : (Σ(A : Type.{max u v}), A → B) ≃ (B → Type.{max u v}) := begin fapply equiv.MK, { exact characteristic_map}, { exact characteristic_map_inv}, { intro P, apply eq_of_homotopy, intro b, esimp, apply ua, apply fiber_pr1}, { intro p, induction p with A f, fapply sigma_eq: esimp, { apply ua, apply sigma_fiber_equiv }, { apply arrow_pathover_constant_right, intro v, rewrite [-cast_def _ v, cast_ua_fn], esimp [sigma_fiber_equiv,equiv.trans,equiv.symm,sigma_comm_equiv,comm_equiv_unc], induction v with b w, induction w with a p, esimp, exact p⁻¹}} end definition is_object_classifier (f : A → B) : pullback_square (pointed_fiber f) (fiber f) f pType.carrier := pullback_square.mk (λa, idp) (is_equiv_of_equiv_of_homotopy (calc A ≃ Σb, fiber f b : sigma_fiber_equiv ... ≃ Σb (v : ΣX, X = fiber f b), v.1 : sigma_equiv_sigma_right (λb, !sigma_equiv_of_is_contr_left) ... ≃ Σb X (p : X = fiber f b), X : sigma_equiv_sigma_right (λb, !sigma_assoc_equiv) ... ≃ Σb X (x : X), X = fiber f b : sigma_equiv_sigma_right (λb, sigma_equiv_sigma_right (λX, !comm_equiv_nondep)) ... ≃ Σb (v : ΣX, X), v.1 = fiber f b : sigma_equiv_sigma_right (λb, !sigma_assoc_equiv⁻¹ᵉ) ... ≃ Σb (Y : Type*), Y = fiber f b : sigma_equiv_sigma_right (λb, sigma_equiv_sigma (pType.sigma_char)⁻¹ᵉ (λv, sigma.rec_on v (λx y, equiv.rfl))) ... ≃ Σ(Y : Type*) b, Y = fiber f b : sigma_comm_equiv ... ≃ pullback pType.carrier (fiber f) : !pullback.sigma_char⁻¹ᵉ ) proof λb, idp qed) end univ
012f0a12d4a2b67dbb31db73bd6be58c513c2575
d31b9f832ff922a603f76cf32e0f3aa822640508
/src/hott/cubical/square.lean
5699bfab6188ebedb7568d10784b9490e2dc8079
[ "Apache-2.0" ]
permissive
javra/hott3
6e7a9e72a991a2fae32e5764982e521dca617b16
cd51f2ab2aa48c1246a188f9b525b30f76c3d651
refs/heads/master
1,585,819,679,148
1,531,232,382,000
1,536,682,965,000
154,294,022
0
0
Apache-2.0
1,540,284,376,000
1,540,284,375,000
null
UTF-8
Lean
false
false
37,193
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jakob von Raumer Squares in a type -/ import hott.types.eq universes u v w hott_theory namespace hott open eq hott.equiv hott.is_equiv namespace eq variables {A : Type _} {B : Type _} {C : Type _} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ a₁ a₂ a₃ a₄ : A} /-a₀₀-/ {p₁₀ p₁₀' : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/ {p₀₁ p₀₁' : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ p₂₁' : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂} /-a₀₂-/ {p₁₂ p₁₂' : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/ {p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄} /-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/ {b : B} {c : C} inductive square {A : Type u} {a₀₀ : A} : Π{a₂₀ a₀₂ a₂₂ : A}, a₀₀ = a₂₀ → a₀₂ = a₂₂ → a₀₀ = a₀₂ → a₂₀ = a₂₂ → Type u | ids : square idp idp idp idp /- square top bottom left right -/ variables {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁} {s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃} @[hott, reducible] def ids := @square.ids @[hott, reducible] def idsquare (a : A) := @square.ids A a @[hott] def hrefl (p : a = a') : square idp idp p p := by induction p; exact ids @[hott] def vrefl (p : a = a') : square p p idp idp := by induction p; exact ids @[hott, reducible] def hrfl {p : a = a'} : square idp idp p p := hrefl _ @[hott, reducible] def vrfl {p : a = a'} : square p p idp idp := vrefl _ @[hott] def hdeg_square {p q : a = a'} (r : p = q) : square idp idp p q := by induction r;apply hrefl @[hott] def vdeg_square {p q : a = a'} (r : p = q) : square p q idp idp := by induction r;apply vrefl @[hott, hsimp] def hdeg_square_idp (p : a = a') : hdeg_square (refl p) = hrfl := idp @[hott, hsimp] def vdeg_square_idp (p : a = a') : vdeg_square (refl p) = vrfl := idp @[hott] def hconcat (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁) : square (p₁₀ ⬝ p₃₀) (p₁₂ ⬝ p₃₂) p₀₁ p₄₁ := by induction s₃₁; exact s₁₁ @[hott] def vconcat (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃) : square p₁₀ p₁₄ (p₀₁ ⬝ p₀₃) (p₂₁ ⬝ p₂₃) := by induction s₁₃; exact s₁₁ @[hott] def dconcat {p₀₀ : a₀₀ = a} {p₂₂ : a = a₂₂} (s₂₁ : square p₀₀ p₁₂ p₀₁ p₂₂) (s₁₂ : square p₁₀ p₂₂ p₀₀ p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction s₁₂; exact s₂₁ @[hott] def hinverse (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀⁻¹ p₁₂⁻¹ p₂₁ p₀₁ := by induction s₁₁;exact ids @[hott] def vinverse (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₂ p₁₀ p₀₁⁻¹ p₂₁⁻¹ := by induction s₁₁;exact ids @[hott] def eq_vconcat {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p p₁₂ p₀₁ p₂₁ := by induction r; exact s₁₁ @[hott] def vconcat_eq {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : square p₁₀ p p₀₁ p₂₁ := by induction r; exact s₁₁ @[hott] def eq_hconcat {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ := by induction r; exact s₁₁ @[hott] def hconcat_eq {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p := by induction r; exact s₁₁ infix ` ⬝h `:69 := hconcat --type using \tr infix ` ⬝v `:70 := vconcat --type using \tr infixl ` ⬝hp `:71 := hconcat_eq --type using \tr infixl ` ⬝vp `:73 := vconcat_eq --type using \tr infixr ` ⬝ph `:72 := eq_hconcat --type using \tr infixr ` ⬝pv `:74 := eq_vconcat --type using \tr postfix `⁻¹ʰ`:(max+1) := hinverse --type using \-1h postfix `⁻¹ᵛ`:(max+1) := vinverse --type using \-1v @[hott] def transpose (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₀₁ p₂₁ p₁₀ p₁₂ := by induction s₁₁;exact ids @[hott] def aps (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (ap f p₁₀) (ap f p₁₂) (ap f p₀₁) (ap f p₂₁) := by induction s₁₁;exact ids /- canceling, whiskering and moving thinks along the sides of the square -/ @[hott] def whisker_tl (p : a = a₀₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁ := by induction s₁₁;induction p;constructor @[hott] def whisker_br (p : a₂₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p) := by induction p;exact s₁₁ @[hott] def whisker_rt (p : a = a₂₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁) := by induction s₁₁;induction p;constructor @[hott] def whisker_tr (p : a₂₀ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁) := by induction s₁₁;induction p;constructor @[hott] def whisker_bl (p : a = a₀₂) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁ := by induction s₁₁;induction p;constructor @[hott] def whisker_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁ := by induction s₁₁;induction p;constructor @[hott] def cancel_tl (p : a = a₀₀) (s₁₁ : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_br (p : a₂₂ = a) (s₁₁ : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p;exact s₁₁ @[hott] def cancel_rt (p : a = a₂₀) (s₁₁ : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_tr (p : a₂₀ = a) (s₁₁ : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_bl (p : a = a₀₂) (s₁₁ : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def move_top_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁) : square (p⁻¹ ⬝ p₁₀) p₁₂ q p₂₁ := by apply cancel_tl p; hsimp; exact s @[hott] def move_top_of_left' {p : a = a₀₀} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p⁻¹ ⬝ q) p₂₁) : square (p ⬝ p₁₀) p₁₂ q p₂₁ := by apply cancel_tl p⁻¹; hsimp; exact s @[hott] def move_left_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁) : square q p₁₂ (p⁻¹ ⬝ p₀₁) p₂₁ := by apply cancel_tl p; hsimp; exact s @[hott] def move_left_of_top' {p : a = a₀₀} {q : a = a₂₀} (s : square (p⁻¹ ⬝ q) p₁₂ p₀₁ p₂₁) : square q p₁₂ (p ⬝ p₀₁) p₂₁ := by apply cancel_tl p⁻¹; hsimp; exact s @[hott] def move_bot_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q)) : square p₁₀ (p₁₂ ⬝ q⁻¹) p₀₁ p := by apply cancel_br q; hsimp; exact s @[hott] def move_bot_of_right' {p : a₂₀ = a} {q : a₂₂ = a} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q⁻¹)) : square p₁₀ (p₁₂ ⬝ q) p₀₁ p := by apply cancel_br q⁻¹; hsimp; exact s @[hott] def move_right_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁) : square p₁₀ p p₀₁ (p₂₁ ⬝ q⁻¹) := by apply cancel_br q; hsimp; exact s @[hott] def move_right_of_bot' {p : a₀₂ = a} {q : a₂₂ = a} (s : square p₁₀ (p ⬝ q⁻¹) p₀₁ p₂₁) : square p₁₀ p p₀₁ (p₂₁ ⬝ q) := by apply cancel_br q⁻¹; hsimp; exact s @[hott] def move_top_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q)) : square (p₁₀ ⬝ p) p₁₂ p₀₁ q := by apply cancel_rt p; hsimp; exact s @[hott] def move_right_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁) : square p p₁₂ p₀₁ (q ⬝ p₂₁) := by apply cancel_tr q; hsimp; exact s @[hott] def move_bot_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁) : square p₁₀ (q ⬝ p₁₂) p p₂₁ := by apply cancel_lb q; hsimp; exact s @[hott] def move_left_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁) : square p₁₀ q (p₀₁ ⬝ p) p₂₁ := by apply cancel_bl p; hsimp; exact s /- some higher ∞-groupoid operations -/ @[hott] def vconcat_vrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝v vrefl p₁₂ = s₁₁ := by induction s₁₁; reflexivity @[hott] def hconcat_hrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝h hrefl p₂₁ = s₁₁ := by induction s₁₁; reflexivity /- equivalences -/ @[hott] def eq_of_square (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂ := by induction s₁₁; apply idp @[hott] def square_of_eq (r : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₁₂; dsimp at r; induction r; induction p₂₁; induction p₁₀; exact ids @[hott] def eq_top_of_square (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹ := by induction s₁₁; apply idp @[hott] def square_of_eq_top (r : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₂₁; induction p₁₂; dsimp at r;induction r;induction p₁₀;exact ids @[hott] def eq_bot_of_square (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₂ = p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ := by induction s₁₁; apply idp @[hott] def square_of_eq_bot (r : p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ = p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₂₁; induction p₁₀; dsimp at r; induction r; induction p₀₁; exact ids @[hott] def square_equiv_eq (t : a₀₀ = a₀₂) (b : a₂₀ = a₂₂) (l : a₀₀ = a₂₀) (r : a₀₂ = a₂₂) : square t b l r ≃ t ⬝ r = l ⬝ b := begin fapply equiv.MK, { exact eq_of_square}, { exact square_of_eq}, { intro s, induction b, dsimp [concat] at s, induction s, induction r, induction t, apply idp}, { intro s, induction s, apply idp}, end @[hott] def hdeg_square_equiv' (p q : a = a') : square idp idp p q ≃ p = q := begin transitivity, {apply square_equiv_eq}, transitivity, {apply eq_equiv_eq_symm}, {apply equiv_eq_closed_right, apply idp_con}, end @[hott] def vdeg_square_equiv' (p q : a = a') : square p q idp idp ≃ p = q := begin transitivity, {apply square_equiv_eq}, {apply equiv_eq_closed_right, apply idp_con}, end @[hott] def eq_of_hdeg_square {p q : a = a'} (s : square idp idp p q) : p = q := to_fun (hdeg_square_equiv' _ _) s @[hott] def eq_of_vdeg_square {p q : a = a'} (s : square p q idp idp) : p = q := to_fun (vdeg_square_equiv' _ _) s @[hott] def top_deg_square (l : a₁ = a₂) (b : a₂ = a₃) (r : a₄ = a₃) : square (l ⬝ b ⬝ r⁻¹) b l r := by induction r;induction b;induction l;constructor @[hott] def bot_deg_square (l : a₁ = a₂) (t : a₁ = a₃) (r : a₃ = a₄) : square t (l⁻¹ ⬝ t ⬝ r) l r := by induction r;induction t;induction l;constructor /- the following two equivalences have as underlying inverse function the functions hdeg_square and vdeg_square, respectively. See example below the @[hott] def -/ @[hott] def hdeg_square_equiv (p q : a = a') : square idp idp p q ≃ p = q := begin fapply equiv_change_fun, { fapply equiv_change_inv, apply hdeg_square_equiv', exact hdeg_square, intro s, induction s, induction p, reflexivity}, { exact eq_of_hdeg_square}, { reflexivity} end @[hott] def vdeg_square_equiv (p q : a = a') : square p q idp idp ≃ p = q := begin fapply equiv_change_fun, { fapply equiv_change_inv, apply vdeg_square_equiv',exact vdeg_square, intro s, induction s, induction p, reflexivity}, { exact eq_of_vdeg_square}, { reflexivity} end example (p q : a = a') : (hdeg_square_equiv p q)⁻¹ᶠ = hdeg_square := idp /- characterization of pathovers in a equality type. The type B of the equality is fixed here. A version where B may also varies over the path p is given in the file squareover -/ @[hott] def eq_pathover {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : square q r (ap f p) (ap g p)) : q =[p; λ a, f a = g a] r := begin induction p, apply pathover_idp_of_eq, exact eq_of_vdeg_square s end @[hott] def eq_pathover_constant_left {g : A → B} {p : a = a'} {b : B} {q : b = g a} {r : b = g a'} (s : square q r idp (ap g p)) : q =[p; λ a, b = g a] r := eq_pathover (ap_constant p b ⬝ph s) @[hott] def eq_pathover_id_left {g : A → A} {p : a = a'} {q : a = g a} {r : a' = g a'} (s : square q r p (ap g p)) : q =[p; λ a, a = g a] r := eq_pathover (ap_id p ⬝ph s) @[hott] def eq_pathover_constant_right {f : A → B} {p : a = a'} {b : B} {q : f a = b} {r : f a' = b} (s : square q r (ap f p) idp) : q =[p; λ a, f a = b] r := eq_pathover (s ⬝hp (ap_constant p b)⁻¹) @[hott] def eq_pathover_id_right {f : A → A} {p : a = a'} {q : f a = a} {r : f a' = a'} (s : square q r (ap f p) p) : q =[p; λ a, f a = a] r := eq_pathover (s ⬝hp (ap_id p)⁻¹) @[hott] def eq_pathover_compose_right {f : A → C} (h : B → C) (g : A → B) {p : a = a'} {q : f a = h (g a)} {r : f a' = h (g a')} (s : square q r (ap f p) (ap h (ap g p))) : q =[p; λ a, f a = h (g a)] r := eq_pathover (s ⬝hp (ap_compose h g p)⁻¹) @[hott] def eq_pathover_compose_left (h : B → C) (g : A → B) {f : A → C} {p : a = a'} {q : h (g a) = f a} {r : h (g a') = f a'} (s : square q r (ap h (ap g p)) (ap f p)) : q =[p; λ a, h (g a) = f a] r := eq_pathover (ap_compose h g p ⬝ph s) @[hott] def square_of_pathover {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : q =[p; λ a, f a = g a] r) : square q r (ap f p) (ap g p) := by induction p;apply vdeg_square;exact (eq_of_pathover_idp s) @[hott] def eq_pathover_constant_left_id_right {p : a = a'} {a₀ : A} {q : a₀ = a} {r : a₀ = a'} (s : square q r idp p) : q =[p] r := eq_pathover (ap_constant p a₀ ⬝ph s ⬝hp (ap_id p)⁻¹) @[hott] def eq_pathover_id_left_constant_right {p : a = a'} {a₀ : A} {q : a = a₀} {r : a' = a₀} (s : square q r p idp) : q =[p; λ a, a = a₀] r := eq_pathover (ap_id p ⬝ph s ⬝hp (ap_constant p a₀)⁻¹) @[hott] def loop_pathover {p : a = a'} {q : a = a} {r : a' = a'} (s : square q r p p) : q =[p; λ a, a = a] r := eq_pathover (ap_id p ⬝ph s ⬝hp (ap_id p)⁻¹) /- interaction of equivalences with operations on squares -/ @[hott] def eq_pathover_equiv_square {f g : A → B} (p : a = a') (q : f a = g a) (r : f a' = g a') : q =[p; λ a, f a = g a] r ≃ square q r (ap f p) (ap g p) := equiv.MK square_of_pathover eq_pathover begin intro s, induction p, dsimp [square_of_pathover,eq_pathover], transitivity, {apply ap vdeg_square, apply to_right_inv (pathover_idp _ _ _)}, {apply to_left_inv (vdeg_square_equiv _ _)} end begin intro s, induction p, dsimp [square_of_pathover,eq_pathover], transitivity, {apply ap (pathover_idp_of_eq _), apply to_right_inv (vdeg_square_equiv _ _)}, {apply to_left_inv (pathover_idp _ _ _)}, end @[hott] def square_of_pathover_eq_concato {f g : A → B} {p : a = a'} {q q' : f a = g a} {r : f a' = g a'} (s' : q = q') (s : q' =[p; λ a, f a = g a] r) : square_of_pathover (s' ⬝po s) = s' ⬝pv square_of_pathover s := by induction s;induction s';reflexivity @[hott] def square_of_pathover_concato_eq {f g : A → B} {p : a = a'} {q : f a = g a} {r r' : f a' = g a'} (s' : r = r') (s : q =[p; λ a, f a = g a] r) : square_of_pathover (s ⬝op s') = square_of_pathover s ⬝vp s' := by induction s;induction s';reflexivity @[hott] def square_of_pathover_concato {f g : A → B} {p : a = a'} {p' : a' = a''} {q : f a = g a} {q' : f a' = g a'} {q'' : f a'' = g a''} (s : q =[p; λ a, f a = g a] q') (s' : q' =[p'; λ a, f a = g a] q'') : square_of_pathover (s ⬝o s') = ap_con f p p' ⬝ph (square_of_pathover s ⬝v square_of_pathover s') ⬝hp (ap_con g p p')⁻¹ := by induction s'; induction s; symmetry; apply vconcat_vrfl @[hott] def eq_of_square_hrfl (p : a = a') : eq_of_square hrfl = idp_con p := by induction p;reflexivity @[hott] def eq_of_square_vrfl (p : a = a') : eq_of_square vrfl = (idp_con p)⁻¹ := by induction p;reflexivity @[hott] def eq_of_square_hdeg_square {p q : a = a'} (r : p = q) : eq_of_square (hdeg_square r) = !idp_con ⬝ r⁻¹ := by induction r;induction p;reflexivity @[hott] def eq_of_square_vdeg_square {p q : a = a'} (r : p = q) : eq_of_square (vdeg_square r) = r ⬝ !idp_con⁻¹ := by induction r;induction p;reflexivity @[hott] def eq_of_square_eq_vconcat {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : eq_of_square (r ⬝pv s₁₁) = whisker_right p₂₁ r ⬝ eq_of_square s₁₁ := by induction s₁₁; eq_cases r;reflexivity @[hott] def eq_of_square_eq_hconcat {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : eq_of_square (r ⬝ph s₁₁) = eq_of_square s₁₁ ⬝ (whisker_right p₁₂ r)⁻¹ := by induction r;reflexivity @[hott] def eq_of_square_vconcat_eq {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : eq_of_square (s₁₁ ⬝vp r) = eq_of_square s₁₁ ⬝ whisker_left p₀₁ r := by induction r;reflexivity @[hott] def eq_of_square_hconcat_eq {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : eq_of_square (s₁₁ ⬝hp r) = (whisker_left p₁₀ r)⁻¹ ⬝ eq_of_square s₁₁ := by induction s₁₁; induction r;reflexivity @[hott] def change_path_eq_pathover {A B : Type _} {a a' : A} {f g : A → B} {p p' : a = a'} (r : p = p') {q : f a = g a} {q' : f a' = g a'} (s : square q q' (ap f p) (ap g p)) : change_path r (eq_pathover s) = eq_pathover ((ap02 f r)⁻¹ ⬝ph s ⬝hp (ap02 g r)) := by induction r; reflexivity @[hott] def eq_hconcat_hdeg_square {A : Type _} {a a' : A} {p₁ p₂ p₃ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) : q₁ ⬝ph hdeg_square q₂ = hdeg_square (q₁ ⬝ q₂) := by induction q₁; induction q₂; reflexivity @[hott] def hdeg_square_hconcat_eq {A : Type _} {a a' : A} {p₁ p₂ p₃ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) : hdeg_square q₁ ⬝hp q₂ = hdeg_square (q₁ ⬝ q₂) := by induction q₁; induction q₂; reflexivity @[hott] def eq_hconcat_eq_hdeg_square {A : Type _} {a a' : A} {p₁ p₂ p₃ p₄ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) (q₃ : p₃ = p₄) : q₁ ⬝ph hdeg_square q₂ ⬝hp q₃ = hdeg_square (q₁ ⬝ q₂ ⬝ q₃) := by induction q₃; apply eq_hconcat_hdeg_square -- @[hott] def vconcat_eq [unfold 11] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : -- square p₁₀ p p₀₁ p₂₁ := -- by induction r; exact s₁₁ -- @[hott] def eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁) -- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ := -- by induction r; exact s₁₁ -- @[hott] def hconcat_eq [unfold 11] {p : a₂₀ = a₂₂} -- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p := -- by induction r; exact s₁₁ /- recursors for squares where some sides are reflexivity -/ @[hott,elab_as_eliminator] def rec_on_b {a₀₀ : A} {P : Π{a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂}, square t idp l r → Type _} {a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂} (s : square t idp l r) (H : P ids) : P s := have H2 : P (square_of_eq (eq_of_square s)), begin induction r, induction t, hgeneralize: eq_of_square s = es, dsimp at es, induction es, apply H end, left_inv (square_equiv_eq _ _ _ _).to_fun s ▸ H2 @[hott, elab_as_eliminator] def rec_on_r {a₀₀ : A} {P : Π{a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂}, square t b l idp → Type _} {a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂} (s : square t b l idp) (H : P ids) : P s := let p : l ⬝ b = t := (eq_of_square s)⁻¹ in have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹), from @eq.rec_on _ _ (λx p, P (square_of_eq p⁻¹)) _ p (by induction b; induction l; exact H), have H3 : square_of_eq (eq_of_square s) = s, from left_inv (square_equiv_eq _ _ _ _).to_fun s, by rwra [inv_inv, H3] at H2 @[hott, elab_as_eliminator] def rec_on_l {a₀₁ : A} {P : Π {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂}, square t b idp r → Type _} {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂} (s : square t b idp r) (H : P ids) : P s := let p : t ⬝ r = b := eq_of_square s ⬝ !idp_con in have H2 : P (square_of_eq (p ⬝ !idp_con⁻¹)), from eq.rec_on p (by induction r; induction t; exact H), have H3 : square_of_eq (eq_of_square s) = s, from left_inv (square_equiv_eq _ _ _ _).to_fun s, by rwra [con_inv_cancel_right, H3] at H2 @[hott, elab_as_eliminator] def rec_on_t {a₁₀ : A} {P : Π {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂}, square idp b l r → Type _} {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂} (s : square idp b l r) (H : P ids) : P s := let p : l ⬝ b = r := (eq_of_square s)⁻¹ ⬝ !idp_con in have H2 : P (square_of_eq ((p ⬝ !idp_con⁻¹)⁻¹)), from eq.rec_on p (by induction b; induction l; exact H), have H3 : P (square_of_eq ((eq_of_square s)⁻¹⁻¹)), by rwra con_inv_cancel_right at H2, have H4 : P (square_of_eq (eq_of_square s)), by hsimp at H3; apply H3, left_inv (square_equiv_eq _ _ _ _).to_fun s ▸ H4 @[hott, elab_as_eliminator] def rec_on_tb {a : A} {P : Π{b : A} {l : a = b} {r : a = b}, square idp idp l r → Type _} {b : A} {l : a = b} {r : a = b} (s : square idp idp l r) (H : P ids) : P s := have H2 : P (square_of_eq (eq_of_square s)), begin induction r, hgeneralize: eq_of_square s = es, dsimp at es, induction es, apply H, end, left_inv (square_equiv_eq _ _ _ _).to_fun s ▸ H2 @[hott, elab_as_eliminator] def rec_on_lr {a : A} {P : Π{a' : A} {t : a = a'} {b : a = a'}, square t b idp idp → Type _} {a' : A} {t : a = a'} {b : a = a'} (s : square t b idp idp) (H : P ids) : P s := let p : idp ⬝ b = t := (eq_of_square s)⁻¹ in have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹), from @eq.rec_on _ _ (λx q, P (square_of_eq q⁻¹)) _ p (by induction b; exact H), have H3 : square_of_eq (eq_of_square s) = s, from left_inv (square_equiv_eq _ _ _ _).to_fun s, by rwra [inv_inv, H3] at H2 --we can also do the other recursors (tl, tr, bl, br, tbl, tbr, tlr, blr), but let's postpone this until they are needed @[hott] def whisker_square (r₁₀ : p₁₀ = p₁₀') (r₁₂ : p₁₂ = p₁₂') (r₀₁ : p₀₁ = p₀₁') (r₂₁ : p₂₁ = p₂₁') (s : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀' p₁₂' p₀₁' p₂₁' := by induction r₁₀; induction r₁₂; induction r₀₁; induction r₂₁; exact s /- squares commute with some operations on 2-paths -/ @[hott] def square_inv2 {p₁ p₂ p₃ p₄ : a = a'} {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} (s : square t b l r) : square (inverse2 t) (inverse2 b) (inverse2 l) (inverse2 r) := by induction s;constructor @[hott] def square_con2 {p₁ p₂ p₃ p₄ : a₁ = a₂} {q₁ q₂ q₃ q₄ : a₂ = a₃} {t₁ : p₁ = p₂} {b₁ : p₃ = p₄} {l₁ : p₁ = p₃} {r₁ : p₂ = p₄} {t₂ : q₁ = q₂} {b₂ : q₃ = q₄} {l₂ : q₁ = q₃} {r₂ : q₂ = q₄} (s₁ : square t₁ b₁ l₁ r₁) (s₂ : square t₂ b₂ l₂ r₂) : square (t₁ ◾ t₂) (b₁ ◾ b₂) (l₁ ◾ l₂) (r₁ ◾ r₂) := by induction s₂;induction s₁;constructor open is_trunc @[hott] def is_set.elims [H : is_set A] : square p₁₀ p₁₂ p₀₁ p₂₁ := square_of_eq (is_set.elim _ _) @[hott, instance] def is_trunc_square (n : trunc_index) [H : is_trunc n .+2 A] : is_trunc n (square p₁₀ p₁₂ p₀₁ p₂₁) := is_trunc_equiv_closed_rev n (square_equiv_eq _ _ _ _) (by apply_instance) -- @[hott] def square_of_con_inv_hsquare {p₁ p₂ p₃ p₄ : a₁ = a₂} -- {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} -- (s : square (con_inv_eq_idp t) (con_inv_eq_idp b) (l ◾ r⁻²) idp) -- : square t b l r := -- sorry --by induction s /- Square fillers -/ -- TODO replace by "more algebraic" fillers? variables (p₁₀ p₁₂ p₀₁ p₂₁) @[hott] def square_fill_t : Σ (p : a₀₀ = a₂₀), square p p₁₂ p₀₁ p₂₁ := by induction p₀₁; induction p₂₁; exact ⟨_, vrefl _⟩ @[hott] def square_fill_b : Σ (p : a₀₂ = a₂₂), square p₁₀ p p₀₁ p₂₁ := by induction p₀₁; induction p₂₁; exact ⟨_, vrefl _⟩ @[hott] def square_fill_l : Σ (p : a₀₀ = a₀₂), square p₁₀ p₁₂ p p₂₁ := by induction p₁₀; induction p₁₂; exact ⟨_, hrefl _⟩ @[hott] def square_fill_r : Σ (p : a₂₀ = a₂₂) , square p₁₀ p₁₂ p₀₁ p := by induction p₁₀; induction p₁₂; exact ⟨_, hrefl _⟩ /- Squares having an 'ap' term on one face -/ --TODO find better names @[hott] def square_Flr_ap_idp {c : B} {f : A → B} (p : Π a, f a = c) {a b : A} (q : a = b) : square (p a) (p b) (ap f q) idp := by induction q; apply vrfl @[hott] def square_Flr_idp_ap {c : B} {f : A → B} (p : Π a, c = f a) {a b : A} (q : a = b) : square (p a) (p b) idp (ap f q) := by induction q; apply vrfl @[hott] def square_ap_idp_Flr {b : B} {f : A → B} (p : Π a, f a = b) {a b : A} (q : a = b) : square (ap f q) idp (p a) (p b) := by induction q; apply hrfl /- Matching eq_hconcat with hconcat etc. -/ -- TODO maybe rename hconcat_eq and the like? variable (s₁₁) @[hott] def ph_eq_pv_h_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) : r ⬝ph s₁₁ = !idp_con⁻¹ ⬝pv ((hdeg_square r) ⬝h s₁₁) ⬝vp !idp_con := by induction r; induction s₁₁; refl @[hott] def hdeg_h_eq_pv_ph_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) : hdeg_square r ⬝h s₁₁ = !idp_con ⬝pv (r ⬝ph s₁₁) ⬝vp !idp_con⁻¹ := by induction r; induction s₁₁; refl @[hott] def hp_eq_h {p : a₂₀ = a₂₂} (r : p₂₁ = p) : s₁₁ ⬝hp r = s₁₁ ⬝h hdeg_square r := by induction r; induction s₁₁; refl @[hott] def pv_eq_ph_vdeg_v_vh {p : a₀₀ = a₂₀} (r : p = p₁₀) : r ⬝pv s₁₁ = !idp_con⁻¹ ⬝ph ((vdeg_square r) ⬝v s₁₁) ⬝hp !idp_con := by induction r; induction s₁₁; refl @[hott] def vdeg_v_eq_ph_pv_hp {p : a₀₀ = a₂₀} (r : p = p₁₀) : vdeg_square r ⬝v s₁₁ = !idp_con ⬝ph (r ⬝pv s₁₁) ⬝hp !idp_con⁻¹ := by induction r; induction s₁₁; refl @[hott] def vp_eq_v {p : a₀₂ = a₂₂} (r : p₁₂ = p) : s₁₁ ⬝vp r = s₁₁ ⬝v vdeg_square r := by induction r; induction s₁₁; refl @[hott] def natural_square {f g : A → B} (p : f ~ g) (q : a = a') : square (p a) (p a') (ap f q) (ap g q) := square_of_pathover (apd p q) @[hott] def natural_square_tr {f g : A → B} (p : f ~ g) (q : a = a') : square (ap f q) (ap g q) (p a) (p a') := transpose (natural_square p q) @[hott] def natural_square011 {A A' : Type _} {B : A → Type _} {a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') {l r : Π⦃a⦄, B a → A'} (g : Π⦃a⦄ (b : B a), l b = r b) : square (apd011 l p q) (apd011 r p q) (g b) (g b') := begin induction q, exact hrfl end @[hott] def natural_square0111' {A A' : Type _} {B : A → Type _} (C : Π⦃a⦄, B a → Type _) {a a' : A} {p : a = a'} {b : B a} {b' : B a'} {q : b =[p] b'} {c : C b} {c' : C b'} (s : c =[apd011 C p q; id] c') {l r : Π⦃a⦄ {b : B a}, C b → A'} (g : Π⦃a⦄ {b : B a} (c : C b), l c = r c) : square (apd0111 l p q s) (apd0111 r p q s) (g c) (g c') := begin induction q, dsimp at s, apply idp_rec_on s, exact hrfl end -- this can be generalized a bit, by making the domain and codomain of k different, and also have -- a function at the RHS of s (similar to m) @[hott] def natural_square0111 {A A' : Type _} {B : A → Type _} (C : Π⦃a⦄, B a → Type _) {a a' : A} {p : a = a'} {b : B a} {b' : B a'} {q : b =[p] b'} {c : C b} {c' : C b'} (r : c =[apd011 C p q; id] c') {k : A → A} {l : Π⦃a⦄, B a → B (k a)} (m : Π⦃a⦄ {b : B a}, C b → C (l b)) {f : Π⦃a⦄ {b : B a}, C b → A'} (s : Π⦃a⦄ {b : B a} (c : C b), f (m c) = f c) : square (@apd0111 _ _ B _ _ _ _ _ _ _ (λa b (c : C b), f (m c)) p q r) (apd0111 f p q r) (s c) (s c') := begin induction q, dsimp at r, apply idp_rec_on r, exact hrfl end @[hott] def natural_square2 {A : Type _} {B : Type _} {C : A → B → Type _} {X : Type _} {a a₂ : A} {b b₂ : B} {c : C a b} {c₂ : C a₂ b₂} {f : A → X} {g : B → X} (h : Πa b, C a b → f a = g b) (p : a = a₂) (q : b = b₂) (r : transport11 C p q c = c₂) : square (h a b c) (h a₂ b₂ c₂) (ap f p) (ap g q) := by hinduction p; hinduction q; hinduction r; exact vrfl /- some higher coherence conditions -/ @[hott] theorem whisker_bl_whisker_tl_eq (p : a = a') : whisker_bl p (whisker_tl p ids) = con.right_inv p ⬝ph vrfl := by induction p; reflexivity @[hott] theorem ap_is_constant_natural_square {g : B → C} {f : A → B} (H : Πa, g (f a) = c) (p : a = a') : (ap_is_constant H p)⁻¹ ⬝ph natural_square H p ⬝hp ap_constant p c = whisker_bl (H a') (whisker_tl (H a) ids) := begin induction p, dsimp [ap_is_constant], rwr [inv_inv, whisker_bl_whisker_tl_eq] end @[hott] def inv_ph_eq_of_eq_ph {p : a₀₀ = a₀₂} {r : p₀₁ = p} {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₁₁' : square p₁₀ p₁₂ p p₂₁} (t : s₁₁ = r ⬝ph s₁₁') : r⁻¹ ⬝ph s₁₁ = s₁₁' := by induction r; exact t -- the following is used for torus.elim_surf @[hott] theorem whisker_square_aps_eq {f : A → B} {q₁₀ : f a₀₀ = f a₂₀} {q₀₁ : f a₀₀ = f a₀₂} {q₂₁ : f a₂₀ = f a₂₂} {q₁₂ : f a₀₂ = f a₂₂} {r₁₀ : ap f p₁₀ = q₁₀} {r₀₁ : ap f p₀₁ = q₀₁} {r₂₁ : ap f p₂₁ = q₂₁} {r₁₂ : ap f p₁₂ = q₁₂} {s₁₁ : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} {t₁₁ : square q₁₀ q₁₂ q₀₁ q₂₁} (u : square (ap02 f s₁₁) (eq_of_square t₁₁) (ap_con f p₁₀ p₂₁ ⬝ (r₁₀ ◾ r₂₁)) (ap_con f p₀₁ p₁₂ ⬝ (r₀₁ ◾ r₁₂))) : whisker_square r₁₀ r₁₂ r₀₁ r₂₁ (aps f (square_of_eq s₁₁)) = t₁₁ := begin induction r₁₀, induction r₀₁, induction r₁₂, induction r₂₁, induction p₁₂, induction p₁₀, induction p₂₁, dsimp at *, induction s₁₁, dsimp at *, dsimp [square_of_eq], apply eq_of_fn_eq_fn (square_equiv_eq _ _ _ _), dsimp, exact (eq_bot_of_square u)⁻¹ end @[hott] def natural_square_eq {A B : Type _} {a a' : A} {f g : A → B} (p : f ~ g) (q : a = a') : natural_square p q = square_of_pathover (apd p q) := idp @[hott] def eq_of_square_hrfl_hconcat_eq {A : Type _} {a a' : A} {p p' : a = a'} (q : p = p') : eq_of_square (hrfl ⬝hp q⁻¹) = !idp_con ⬝ q := by induction q; induction p; reflexivity @[hott, hsimp] def aps_vrfl {A B : Type _} {a a' : A} (f : A → B) (p : a = a') : aps f (vrefl p) = vrefl (ap f p) := by induction p; reflexivity @[hott, hsimp] def aps_hrfl {A B : Type _} {a a' : A} (f : A → B) (p : a = a') : aps f (hrefl p) = hrefl (ap f p) := by induction p; reflexivity -- should the following two equalities be cubes? @[hott] def natural_square_ap_fn {A B C : Type _} {a a' : A} {g h : A → B} (f : B → C) (p : g ~ h) (q : a = a') : natural_square (λa, ap f (p a)) q = ap_compose f g q ⬝ph (aps f (natural_square p q) ⬝hp (ap_compose f h q)⁻¹) := begin induction q, symmetry, exact (aps_vrfl _ _) end @[hott] def natural_square_compose {A B C : Type _} {a a' : A} {g g' : B → C} (p : g ~ g') (f : A → B) (q : a = a') : natural_square (λa, p (f a)) q = ap_compose g f q ⬝ph (natural_square p (ap f q) ⬝hp (ap_compose g' f q)⁻¹) := by induction q; reflexivity @[hott] def natural_square_eq2 {A B : Type _} {a a' : A} {f f' : A → B} (p : f ~ f') {q q' : a = a'} (r : q = q') : natural_square p q = ap02 f r ⬝ph (natural_square p q' ⬝hp (ap02 f' r)⁻¹) := by induction r; reflexivity @[hott, hsimp] def natural_square_refl {A B : Type _} {a a' : A} (f : A → B) (q : a = a') : natural_square (homotopy.refl f) q = hrfl := by induction q; reflexivity @[hott] def aps_eq_hconcat {p₀₁'} (f : A → B) (q : p₀₁' = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : aps f (q ⬝ph s₁₁) = ap02 f q ⬝ph aps f s₁₁ := by induction q; reflexivity @[hott] def aps_hconcat_eq {p₂₁'} (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁' = p₂₁) : aps f (s₁₁ ⬝hp r⁻¹) = aps f s₁₁ ⬝hp (ap02 f r)⁻¹ := by induction r; reflexivity @[hott] def aps_hconcat_eq' {p₂₁'} (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p₂₁') : aps f (s₁₁ ⬝hp r) = aps f s₁₁ ⬝hp ap02 f r := by induction r; reflexivity @[hott] def aps_square_of_eq (f : A → B) (s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) : aps f (square_of_eq s) = square_of_eq ((ap_con f p₁₀ p₂₁)⁻¹ ⬝ ap02 f s ⬝ ap_con f p₀₁ p₁₂) := by induction p₁₂; dsimp at *; induction s; induction p₂₁; induction p₁₀; reflexivity @[hott] def aps_eq_hconcat_eq {p₀₁' p₂₁'} (f : A → B) (q : p₀₁' = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁' = p₂₁) : aps f (q ⬝ph s₁₁ ⬝hp r⁻¹) = ap02 f q ⬝ph aps f s₁₁ ⬝hp (ap02 f r)⁻¹ := by induction q; induction r; reflexivity end eq end hott
a8ad39ce7e7a1abaf9271b4a6e54e2e0fbefa7ee
c055f4b7c29cf1aac2223bd8c1ac8d181a7c6447
/src/categories/tactics/default.lean
d8062865bf19433021edca31252934a440124dd9
[ "Apache-2.0" ]
permissive
rwbarton/lean-category-theory-pr
77207b6674eeec1e258ec85dea58f3bff8d27065
591847d70c6a11c4d5561cd0eaf69b1fe85a70ab
refs/heads/master
1,584,595,111,303
1,528,029,041,000
1,528,029,041,000
135,919,126
0
0
null
1,528,041,805,000
1,528,041,805,000
null
UTF-8
Lean
false
false
467
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import tidy.at_least_one import tidy.applicable import tidy.make_lemma import tidy.rewrite_all import tidy.injections import tidy.tidy import tidy.transport -- meta def obviously' := `[skip] universes u v open tactic set_option formatter.hide_full_terms false set_option pp.proofs false
1a589e1ecc542d887173665ba0128bab40698f19
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/PrettyPrinter/Delaborator/Builtins.lean
13645a5b864cf33cd4d679ff1513cc9406d88038
[ "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
28,459
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.PrettyPrinter.Delaborator.Basic import Lean.Parser namespace Lean.PrettyPrinter.Delaborator open Lean.Meta open Lean.Parser.Term @[builtinDelab fvar] def delabFVar : Delab := do let Expr.fvar id _ ← getExpr | unreachable! try let l ← getLocalDecl id pure $ mkIdent l.userName catch _ => -- loose free variable, use internal name pure $ mkIdent id -- loose bound variable, use pseudo syntax @[builtinDelab bvar] def delabBVar : Delab := do let Expr.bvar idx _ ← getExpr | unreachable! pure $ mkIdent $ Name.mkSimple $ "#" ++ toString idx @[builtinDelab mvar] def delabMVar : Delab := do let Expr.mvar n _ ← getExpr | unreachable! let mvarDecl ← getMVarDecl n let n := match mvarDecl.userName with | Name.anonymous => n.replacePrefix `_uniq `m | n => n `(?$(mkIdent n)) @[builtinDelab sort] def delabSort : Delab := do let Expr.sort l _ ← getExpr | unreachable! match l with | Level.zero _ => `(Prop) | Level.succ (Level.zero _) _ => `(Type) | _ => match l.dec with | some l' => `(Type $(Level.quote l' max_prec)) | none => `(Sort $(Level.quote l max_prec)) -- find shorter names for constants, in reverse to Lean.Elab.ResolveName private def unresolveQualifiedName (ns : Name) (c : Name) : DelabM Name := do let c' := c.replacePrefix ns Name.anonymous; let env ← getEnv guard $ c' != c && !c'.isAnonymous && (!c'.isAtomic || !isProtected env c) pure c' private def unresolveUsingNamespace (c : Name) : Name → DelabM Name | ns@(Name.str p _ _) => unresolveQualifiedName ns c <|> unresolveUsingNamespace c p | _ => failure private def unresolveOpenDecls (c : Name) : List OpenDecl → DelabM Name | [] => failure | OpenDecl.simple ns exs :: openDecls => let c' := c.replacePrefix ns Name.anonymous if c' != c && exs.elem c' then unresolveOpenDecls c openDecls else unresolveQualifiedName ns c <|> unresolveOpenDecls c openDecls | OpenDecl.explicit openedId resolvedId :: openDecls => guard (c == resolvedId) *> pure openedId <|> unresolveOpenDecls c openDecls -- NOTE: not a registered delaborator, as `const` is never called (see [delab] description) def delabConst : Delab := do let Expr.const c ls _ ← getExpr | unreachable! let c₀ := c let mut c ← if (← getPPOption getPPFullNames) then pure c else let ctx ← read let env ← getEnv let as := getRevAliases env c -- might want to use a more clever heuristic such as selecting the shortest alias... let c := as.headD c unresolveUsingNamespace c ctx.currNamespace <|> unresolveOpenDecls c ctx.openDecls <|> pure c unless (← getPPOption getPPPrivateNames) do c := (privateToUserName? c).getD c let ppUnivs ← getPPOption getPPUniverses if ls.isEmpty || !ppUnivs then if (← getLCtx).usesUserName c then -- `c` is also a local declaration if c == c₀ then -- `c` is the fully qualified named. So, we append the `_root_` prefix c := `_root_ ++ c else c := c₀ return mkIdent c else `($(mkIdent c).{$[$(ls.toArray.map quote)],*}) inductive ParamKind where | explicit -- combines implicit params, optParams, and autoParams | implicit (name : Name) (defVal : Option Expr) /-- Return array with n-th element set to kind of n-th parameter of `e`. -/ def getParamKinds (e : Expr) : MetaM (Array ParamKind) := do let t ← inferType e forallTelescopeReducing t fun params _ => params.mapM fun param => do let l ← getLocalDecl param.fvarId! match l.type.getOptParamDefault? with | some val => pure $ ParamKind.implicit l.userName val | _ => if l.type.isAutoParam || !l.binderInfo.isExplicit then pure $ ParamKind.implicit l.userName none else pure ParamKind.explicit @[builtinDelab app] def delabAppExplicit : Delab := do let (fnStx, argStxs) ← withAppFnArgs (do let fn ← getExpr let stx ← if fn.isConst then delabConst else delab let paramKinds ← liftM <| getParamKinds fn <|> pure #[] let stx ← if paramKinds.any (fun | ParamKind.explicit => false | _ => true) then `(@$stx) else pure stx pure (stx, #[])) (fun ⟨fnStx, argStxs⟩ => do let argStx ← delab pure (fnStx, argStxs.push argStx)) Syntax.mkApp fnStx argStxs def shouldShowMotive (motive : Expr) (opts : Options) : Bool := getPPMotivesAll opts || (getPPMotivesPi opts && returnsPi motive) || (getPPMotivesNonConst opts && isNonConstFun motive) where returnsPi (motive : Expr) : Bool := do match motive with | Expr.lam name d b _ => returnsPi b | Expr.forallE .. => true | _ => false isNonConstFun (motive : Expr) : Bool := do match motive with | Expr.lam name d b _ => isNonConstFun b | _ => motive.hasLooseBVars @[builtinDelab app] def delabAppImplicit : Delab := whenNotPPOption getPPExplicit do let (fnStx, _, argStxs) ← withAppFnArgs (do let fn ← getExpr let stx ← if fn.isConst then delabConst else delab let paramKinds ← liftM (getParamKinds fn <|> pure #[]) pure (stx, paramKinds.toList, #[])) (fun (fnStx, paramKinds, argStxs) => do let arg ← getExpr let opts ← getOptions let mkNamedArg (name : Name) (argStx : Syntax) : DelabM Syntax := do `(Parser.Term.namedArgument| ($(← mkIdent name):ident := $argStx:term)) let stx ← delab let argStx? : Option Syntax ← match paramKinds with | [ParamKind.implicit _ (some v)] => if !v.hasLooseBVars && v == arg then none else stx | ParamKind.implicit name none :: _ => do if name == `motive && shouldShowMotive arg opts then mkNamedArg name stx else none | _ => some stx let argStxs := match argStx? with | none => argStxs | some stx => argStxs.push stx pure (fnStx, paramKinds.tailD [], argStxs)) Syntax.mkApp fnStx argStxs /-- State for `delabAppMatch` and helpers. -/ structure AppMatchState where info : MatcherInfo matcherTy : Expr params : Array Expr := #[] motive : Option (Syntax × Expr) := none discrs : Array Syntax := #[] varNames : Array (Array Name) := #[] rhss : Array Syntax := #[] -- additional arguments applied to the result of the `match` expression moreArgs : Array Syntax := #[] /-- Extract arguments of motive applications from the matcher type. For the example below: `#[#[`([])], #[`(a::as)]]` -/ private partial def delabPatterns (st : AppMatchState) : DelabM (Array (Array Syntax)) := withReader (fun ctx => { ctx with inPattern := true }) do let ty ← instantiateForall st.matcherTy st.params forallTelescope ty fun params _ => do -- skip motive and discriminators let alts := Array.ofSubarray $ params[1 + st.discrs.size:] alts.mapIdxM fun idx alt => do let ty ← inferType alt withReader ({ · with expr := ty }) $ usingNames st.varNames[idx] do withAppFnArgs (pure #[]) (fun pats => do pure $ pats.push (← delab)) where usingNames {α} (varNames : Array Name) (x : DelabM α) : DelabM α := usingNamesAux 0 varNames x usingNamesAux {α} (i : Nat) (varNames : Array Name) (x : DelabM α) : DelabM α := if i < varNames.size then withBindingBody varNames[i] <| usingNamesAux (i+1) varNames x else x /-- Skip `numParams` binders, and execute `x varNames` where `varNames` contains the new binder names. -/ private partial def skippingBinders {α} (numParams : Nat) (x : Array Name → DelabM α) : DelabM α := loop numParams #[] where loop : Nat → Array Name → DelabM α | 0, varNames => x varNames | n+1, varNames => do let rec visitLambda : DelabM α := do let varName ← (← getExpr).bindingName!.eraseMacroScopes -- Pattern variables cannot shadow each other if varNames.contains varName then let varName := (← getLCtx).getUnusedName varName withBindingBody varName do loop n (varNames.push varName) else withBindingBodyUnusedName fun id => do loop n (varNames.push id.getId) let e ← getExpr if e.isLambda then visitLambda else -- eta expand `e` let e ← forallTelescopeReducing (← inferType e) fun xs _ => do if xs.size == 1 && (← inferType xs[0]).isConstOf ``Unit then -- `e` might be a thunk create by the dependent pattern matching compiler, and `xs[0]` may not even be a pattern variable. -- If it is a pattern variable, it doesn't look too bad to use `()` instead of the pattern variable. -- If it becomes a problem in the future, we should modify the dependent pattern matching compiler, and make sure -- it adds an annotation to distinguish these two cases. mkLambdaFVars xs (mkApp e (mkConst ``Unit.unit)) else mkLambdaFVars xs (mkAppN e xs) withReader (fun ctx => { ctx with expr := e }) visitLambda /-- Delaborate applications of "matchers" such as ``` List.map.match_1 : {α : Type _} → (motive : List α → Sort _) → (x : List α) → (Unit → motive List.nil) → ((a : α) → (as : List α) → motive (a :: as)) → motive x ``` -/ @[builtinDelab app] def delabAppMatch : Delab := whenPPOption getPPNotation do -- incrementally fill `AppMatchState` from arguments let st ← withAppFnArgs (do let (Expr.const c us _) ← getExpr | failure let (some info) ← getMatcherInfo? c | failure { matcherTy := (← getConstInfo c).instantiateTypeLevelParams us, info := info : AppMatchState }) (fun st => do if st.params.size < st.info.numParams then pure { st with params := st.params.push (← getExpr) } else if st.motive.isNone then -- store motive argument separately let lamMotive ← getExpr let piMotive ← lambdaTelescope lamMotive fun xs body => mkForallFVars xs body let piStx ← withReader (fun cfg => { cfg with expr := piMotive }) delab pure { st with motive := (piStx, lamMotive) } else if st.discrs.size < st.info.numDiscrs then pure { st with discrs := st.discrs.push (← delab) } else if st.rhss.size < st.info.altNumParams.size then /- We save the variables names here to be able to implement safe_shadowing. The pattern delaboration must use the names saved here. -/ let (varNames, rhs) ← skippingBinders st.info.altNumParams[st.rhss.size] fun varNames => do let rhs ← delab return (varNames, rhs) pure { st with rhss := st.rhss.push rhs, varNames := st.varNames.push varNames } else pure { st with moreArgs := st.moreArgs.push (← delab) }) if st.discrs.size < st.info.numDiscrs || st.rhss.size < st.info.altNumParams.size then -- underapplied failure match st.discrs, st.rhss with | #[discr], #[] => let stx ← `(nomatch $discr) Syntax.mkApp stx st.moreArgs | _, #[] => failure | _, _ => let pats ← delabPatterns st let stx ← do let (piStx, lamMotive) := st.motive.get! let opts ← getOptions if shouldShowMotive lamMotive opts then `(match $[$st.discrs:term],* : $piStx with $[| $pats,* => $st.rhss]*) else `(match $[$st.discrs:term],* with $[| $pats,* => $st.rhss]*) Syntax.mkApp stx st.moreArgs @[builtinDelab mdata] def delabMData : Delab := do if let some _ := Lean.Meta.Match.inaccessible? (← getExpr) then let s ← withMDataExpr delab if (← read).inPattern then `(.($s)) -- We only include the inaccessible annotation when we are delaborating patterns else return s else -- only interpret `pp.` values by default let Expr.mdata m _ _ ← getExpr | unreachable! let mut posOpts := (← read).optionsPerPos let pos := (← read).pos for (k, v) in m do if (`pp).isPrefixOf k then let opts := posOpts.find? pos |>.getD {} posOpts := posOpts.insert pos (opts.insert k v) withReader ({ · with optionsPerPos := posOpts }) do withMDataExpr delab /-- Check for a `Syntax.ident` of the given name anywhere in the tree. This is usually a bad idea since it does not check for shadowing bindings, but in the delaborator we assume that bindings are never shadowed. -/ partial def hasIdent (id : Name) : Syntax → Bool | Syntax.ident _ _ id' _ => id == id' | Syntax.node _ args => args.any (hasIdent id) | _ => false /-- Return `true` iff current binder should be merged with the nested binder, if any, into a single binder group: * both binders must have same binder info and domain * they cannot be inst-implicit (`[a b : A]` is not valid syntax) * `pp.binder_types` must be the same value for both terms * prefer `fun a b` over `fun (a b)` -/ private def shouldGroupWithNext : DelabM Bool := do let e ← getExpr let ppEType ← getPPOption getPPBinderTypes; let go (e' : Expr) := do let ppE'Type ← withBindingBody `_ $ getPPOption getPPBinderTypes pure $ e.binderInfo == e'.binderInfo && e.bindingDomain! == e'.bindingDomain! && e'.binderInfo != BinderInfo.instImplicit && ppEType == ppE'Type && (e'.binderInfo != BinderInfo.default || ppE'Type) match e with | Expr.lam _ _ e'@(Expr.lam _ _ _ _) _ => go e' | Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e' | _ => pure false private partial def delabBinders (delabGroup : Array Syntax → Syntax → Delab) : optParam (Array Syntax) #[] → Delab -- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished -- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping -- inside-out, on the Syntax level, because it depends on comparing the Expr binder types. | curNames => do if (← shouldGroupWithNext) then -- group with nested binder => recurse immediately withBindingBodyUnusedName fun stxN => delabBinders delabGroup (curNames.push stxN) else -- don't group => delab body and prepend current binder group let (stx, stxN) ← withBindingBodyUnusedName fun stxN => do (← delab, stxN) delabGroup (curNames.push stxN) stx @[builtinDelab lam] def delabLam : Delab := delabBinders fun curNames stxBody => do let e ← getExpr let stxT ← withBindingDomain delab let ppTypes ← getPPOption getPPBinderTypes let expl ← getPPOption getPPExplicit -- leave lambda implicit if possible let blockImplicitLambda := expl || e.binderInfo == BinderInfo.default || -- Note: the following restriction fixes many issues with roundtripping, -- but this condition may still not be perfectly in sync with the elaborator. e.binderInfo == BinderInfo.instImplicit || Elab.Term.blockImplicitLambda stxBody || curNames.any (fun n => hasIdent n.getId stxBody); if !blockImplicitLambda then pure stxBody else let group ← match e.binderInfo, ppTypes with | BinderInfo.default, true => -- "default" binder group is the only one that expects binder names -- as a term, i.e. a single `Syntax.ident` or an application thereof let stxCurNames ← if curNames.size > 1 then `($(curNames.get! 0) $(curNames.eraseIdx 0)*) else pure $ curNames.get! 0; `(funBinder| ($stxCurNames : $stxT)) | BinderInfo.default, false => pure curNames.back -- here `curNames.size == 1` | BinderInfo.implicit, true => `(funBinder| {$curNames* : $stxT}) | BinderInfo.implicit, false => `(funBinder| {$curNames*}) | BinderInfo.instImplicit, _ => `(funBinder| [$curNames.back : $stxT]) -- here `curNames.size == 1` | _ , _ => unreachable!; match stxBody with | `(fun $binderGroups* => $stxBody) => `(fun $group $binderGroups* => $stxBody) | _ => `(fun $group => $stxBody) @[builtinDelab forallE] def delabForall : Delab := delabBinders fun curNames stxBody => do let e ← getExpr let prop ← try isProp e catch _ => false let stxT ← withBindingDomain delab let group ← match e.binderInfo with | BinderInfo.implicit => `(bracketedBinderF|{$curNames* : $stxT}) -- here `curNames.size == 1` | BinderInfo.instImplicit => `(bracketedBinderF|[$curNames.back : $stxT]) | _ => -- heuristic: use non-dependent arrows only if possible for whole group to avoid -- noisy mix like `(α : Type) → Type → (γ : Type) → ...`. let dependent := curNames.any $ fun n => hasIdent n.getId stxBody -- NOTE: non-dependent arrows are available only for the default binder info if dependent then if prop && !(← getPPOption getPPBinderTypes) then return ← `(∀ $curNames:ident*, $stxBody) else `(bracketedBinderF|($curNames* : $stxT)) else return ← curNames.foldrM (fun _ stxBody => `($stxT → $stxBody)) stxBody if prop then match stxBody with | `(∀ $groups*, $stxBody) => `(∀ $group $groups*, $stxBody) | _ => `(∀ $group, $stxBody) else `($group:bracketedBinder → $stxBody) @[builtinDelab letE] def delabLetE : Delab := do let Expr.letE n t v b _ ← getExpr | unreachable! let n ← getUnusedName n b let stxT ← descend t 0 delab let stxV ← descend v 1 delab let stxB ← withLetDecl n t v fun fvar => let b := b.instantiate1 fvar descend b 2 delab `(let $(mkIdent n) : $stxT := $stxV; $stxB) @[builtinDelab lit] def delabLit : Delab := do let Expr.lit l _ ← getExpr | unreachable! match l with | Literal.natVal n => pure $ quote n | Literal.strVal s => pure $ quote s -- `@OfNat.ofNat _ n _` ~> `n` @[builtinDelab app.OfNat.ofNat] def delabOfNat : Delab := whenPPOption getPPCoercions do let (Expr.app (Expr.app _ (Expr.lit (Literal.natVal n) _) _) _ _) ← getExpr | failure return quote n -- `@OfDecimal.ofDecimal _ _ m s e` ~> `m*10^(sign * e)` where `sign == 1` if `s = false` and `sign = -1` if `s = true` @[builtinDelab app.OfScientific.ofScientific] def delabOfScientific : Delab := whenPPOption getPPCoercions do let expr ← getExpr guard <| expr.getAppNumArgs == 5 let Expr.lit (Literal.natVal m) _ ← pure (expr.getArg! 2) | failure let Expr.lit (Literal.natVal e) _ ← pure (expr.getArg! 4) | failure let s ← match expr.getArg! 3 with | Expr.const `Bool.true _ _ => pure true | Expr.const `Bool.false _ _ => pure false | _ => failure let str := toString m if s && e == str.length then return Syntax.mkScientificLit ("0." ++ str) else if s && e < str.length then let mStr := str.extract 0 (str.length - e) let eStr := str.extract (str.length - e) str.length return Syntax.mkScientificLit (mStr ++ "." ++ eStr) else return Syntax.mkScientificLit (str ++ "e" ++ (if s then "-" else "") ++ toString e) /-- Delaborate a projection primitive. These do not usually occur in user code, but are pretty-printed when e.g. `#print`ing a projection function. -/ @[builtinDelab proj] def delabProj : Delab := do let Expr.proj _ idx _ _ ← getExpr | unreachable! let e ← withProj delab -- not perfectly authentic: elaborates to the `idx`-th named projection -- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual -- `proj`. let idx := Syntax.mkLit fieldIdxKind (toString (idx + 1)); `($(e).$idx:fieldIdx) /-- Delaborate a call to a projection function such as `Prod.fst`. -/ @[builtinDelab app] def delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do let e@(Expr.app fn _ _) ← getExpr | failure let Expr.const c@(Name.str _ f _) _ _ ← pure fn.getAppFn | failure let env ← getEnv let some info ← pure $ env.getProjectionFnInfo? c | failure -- can't use with classes since the instance parameter is implicit guard $ !info.fromClass -- projection function should be fully applied (#struct params + 1 instance parameter) -- TODO: support over-application guard $ e.getAppNumArgs == info.nparams + 1 -- If pp.explicit is true, and the structure has parameters, we should not -- use field notation because we will not be able to see the parameters. let expl ← getPPOption getPPExplicit guard $ !expl || info.nparams == 0 let appStx ← withAppArg delab `($(appStx).$(mkIdent f):ident) @[builtinDelab app] def delabStructureInstance : Delab := whenPPOption getPPStructureInstances do let env ← getEnv let e ← getExpr let some s ← pure $ e.isConstructorApp? env | failure guard $ isStructure env s.induct; /- If implicit arguments should be shown, and the structure has parameters, we should not pretty print using { ... }, because we will not be able to see the parameters. -/ let explicit ← getPPOption getPPExplicit guard !(explicit && s.numParams > 0) let fieldNames := getStructureFields env s.induct let (_, fields) ← withAppFnArgs (pure (0, #[])) fun ⟨idx, fields⟩ => do if idx < s.numParams then pure (idx + 1, fields) else let val ← delab let field ← `(structInstField|$(mkIdent <| fieldNames.get! (idx - s.numParams)):ident := $val) pure (idx + 1, fields.push field) let lastField := fields[fields.size - 1] let fields := fields.pop let ty ← if (← getPPOption getPPStructureInstanceType) then let ty ← inferType e -- `ty` is not actually part of `e`, but since `e` must be an application or constant, we know that -- index 2 is unused. pure <| some (← descend ty 2 delab) else pure <| none `({ $[$fields, ]* $lastField $[: $ty]? }) @[builtinDelab app] def delabAppWithUnexpander : Delab := whenPPOption getPPNotation do let Expr.const c _ _ ← pure (← getExpr).getAppFn | failure let fs@(f::_) ← pure <| appUnexpanderAttribute.getValues (← getEnv) c | failure /- Note: the following example will take exponential time: ``` def foo (k : Nat → Nat) (n : Nat) : Nat := k (n+1) @[appUnexpander foo] def unexpandFooApp : Lean.PrettyPrinter.Unexpander | `(foo $k $a) => `(My.foo $k $a) | _ => throw () #check foo $ foo $ foo $ foo $ foo $ foo $ foo id -- exp-time ``` -/ let stx ← delabAppImplicit match stx with | `($cPP:ident $args*) => do go fs stx | `($cPP:ident) => do go fs stx | _ => pure stx where go fs stx := fs.firstM fun f => match f stx |>.run () with | EStateM.Result.ok stx _ => pure stx | _ => failure @[builtinDelab app.Prod.mk] def delabTuple : Delab := whenPPOption getPPNotation do let e ← getExpr guard $ e.getAppNumArgs == 4 let a ← withAppFn $ withAppArg delab let b ← withAppArg delab match b with | `(($b, $bs,*)) => `(($a, $b, $bs,*)) | _ => `(($a, $b)) -- abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β @[builtinDelab app.coe] def delabCoe : Delab := whenPPOption getPPCoercions do let e ← getExpr guard $ e.getAppNumArgs >= 4 -- delab as application, then discard function let stx ← delabAppImplicit match stx with | `($fn $arg) => arg | `($fn $args*) => `($(args.get! 0) $(args.eraseIdx 0)*) | _ => failure -- abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a @[builtinDelab app.coeFun] def delabCoeFun : Delab := delabCoe @[builtinDelab app.List.nil] def delabNil : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 1 `([]) @[builtinDelab app.List.cons] def delabConsList : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 3 let x ← withAppFn (withAppArg delab) match (← withAppArg delab) with | `([]) => `([$x]) | `([$xs,*]) => `([$x, $xs,*]) | _ => failure @[builtinDelab app.List.toArray] def delabListToArray : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 2 match (← withAppArg delab) with | `([$xs,*]) => `(#[$xs,*]) | _ => failure @[builtinDelab app.ite] def delabIte : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 5 let c ← withAppFn $ withAppFn $ withAppFn $ withAppArg delab let t ← withAppFn $ withAppArg delab let e ← withAppArg delab `(if $c then $t else $e) @[builtinDelab app.dite] def delabDIte : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 5 let c ← withAppFn $ withAppFn $ withAppFn $ withAppArg delab let (t, h) ← withAppFn $ withAppArg $ delabBranch none let (e, _) ← withAppArg $ delabBranch h `(if $(mkIdent h):ident : $c then $t else $e) where delabBranch (h? : Option Name) : DelabM (Syntax × Name) := do let e ← getExpr guard e.isLambda let h ← match h? with | some h => return (← withBindingBody h delab, h) | none => withBindingBodyUnusedName fun h => do return (← delab, h.getId) @[builtinDelab app.namedPattern] def delabNamedPattern : Delab := do guard $ (← getExpr).getAppNumArgs == 3 let x ← withAppFn $ withAppArg delab let p ← withAppArg delab guard x.isIdent `($x:ident@$p:term) partial def delabDoElems : DelabM (List Syntax) := do let e ← getExpr if e.isAppOfArity `Bind.bind 6 then -- Bind.bind.{u, v} : {m : Type u → Type v} → [self : Bind m] → {α β : Type u} → m α → (α → m β) → m β let ma ← withAppFn $ withAppArg delab withAppArg do match (← getExpr) with | Expr.lam _ _ body _ => withBindingBodyUnusedName fun n => do if body.hasLooseBVars then prependAndRec `(doElem|let $n:term ← $ma:term) else prependAndRec `(doElem|$ma:term) | _ => failure else if e.isLet then let Expr.letE n t v b _ ← getExpr | unreachable! let n ← getUnusedName n b let stxT ← descend t 0 delab let stxV ← descend v 1 delab withLetDecl n t v fun fvar => let b := b.instantiate1 fvar descend b 2 $ prependAndRec `(doElem|let $(mkIdent n) : $stxT := $stxV) else let stx ← delab [←`(doElem|$stx:term)] where prependAndRec x : DelabM _ := List.cons <$> x <*> delabDoElems @[builtinDelab app.Bind.bind] def delabDo : Delab := whenPPOption getPPNotation do guard <| (← getExpr).isAppOfArity `Bind.bind 6 let elems ← delabDoElems let items ← elems.toArray.mapM (`(doSeqItem|$(·):doElem)) `(do $items:doSeqItem*) @[builtinDelab app.sorryAx] def delabSorryAx : Delab := whenPPOption getPPNotation do guard <| (← getExpr).isAppOfArity ``sorryAx 2 `(sorry) @[builtinDelab app.Eq.ndrec] def delabEqNDRec : Delab := whenPPOption getPPNotation do guard <| (← getExpr).getAppNumArgs == 6 -- Eq.ndrec.{u1, u2} : {α : Sort u2} → {a : α} → {motive : α → Sort u1} → (m : motive a) → {b : α} → (h : a = b) → motive b let m ← withAppFn <| withAppFn <| withAppArg delab let h ← withAppArg delab `($h ▸ $m) @[builtinDelab app.Eq.rec] def delabEqRec : Delab := -- relevant signature parts as in `Eq.ndrec` delabEqNDRec def reifyName : Expr → DelabM Name | Expr.const ``Lean.Name.anonymous .. => Name.anonymous | Expr.app (Expr.app (Expr.const ``Lean.Name.mkStr ..) n _) (Expr.lit (Literal.strVal s) _) _ => do (← reifyName n).mkStr s | Expr.app (Expr.app (Expr.const ``Lean.Name.mkNum ..) n _) (Expr.lit (Literal.natVal i) _) _ => do (← reifyName n).mkNum i | _ => failure @[builtinDelab app.Lean.Name.mkStr] def delabNameMkStr : Delab := whenPPOption getPPNotation do let n ← reifyName (← getExpr) -- not guaranteed to be a syntactically valid name, but usually more helpful than the explicit version mkNode ``Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!"`{n}"] @[builtinDelab app.Lean.Name.mkNum] def delabNameMkNum : Delab := delabNameMkStr end Lean.PrettyPrinter.Delaborator
344e8f5b3624b66bb836db697584e3fb67128264
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/data/string/decl.lean
361fd6a5d27d2718e2db0aae53248c749b22d844
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
381
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import data.bool.decl inductive char : Type := mk : bool → bool → bool → bool → bool → bool → bool → bool → char inductive string : Type := empty : string, str : char → string → string
f10f981eb8b91b408cc058846beb621493329594
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/finset.lean
3b15d0011b5fb3b9c1425a21b98fe35a4471ecf2
[ "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
83,856
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro Finite sets. -/ import logic.embedding algebra.order_functions data.multiset data.sigma.basic data.set.lattice open multiset subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := erase_dup_eq_self.2 s.2 instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /- membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /- set coercion -/ /-- Convert a finset to a set in the natural way. -/ def to_set (s : finset α) : set α := {x | x ∈ s} instance : has_lift (finset α) (set α) := ⟨to_set⟩ @[simp] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = ↑s := rfl /- extensionality -/ theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[extensionality] theorem ext' {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext.2 @[simp] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ := (set.ext_iff _ _).trans ext.symm lemma to_set_injective {α} : function.injective (finset.to_set : finset α → set α) := λ s t, coe_inj.1 /- subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext.2 $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp] theorem coe_subset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff @[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp] lemma coe_ssubset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊂ s₂ := show (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_iff_subset_not_subset, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff /- empty -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ | e := not_mem_empty a $ e ▸ h @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero theorem exists_mem_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a : α, a ∈ s := exists_mem_of_ne_zero (mt val_eq_zero.1 h) @[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl lemma nonempty_iff_ne_empty (s : finset α) : nonempty (↑s : set α) ↔ s ≠ ∅ := begin rw [set.coe_nonempty_iff_ne_empty, ←coe_empty], apply not_congr, apply function.injective.eq_iff, exact to_set_injective end /-- `singleton a` is the set `{a}` containing `a` and nothing else. -/ def singleton (a : α) : finset α := ⟨_, nodup_singleton a⟩ local prefix `ι`:90 := singleton @[simp] theorem singleton_val (a : α) : (ι a).1 = a :: 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ι a ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ι b ↔ a ≠ b := not_iff_not_of_iff mem_singleton theorem mem_singleton_self (a : α) : a ∈ ι a := or.inl rfl theorem singleton_inj {a b : α} : ι a = ι b ↔ a = b := ⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩ @[simp] theorem singleton_ne_empty (a : α) : ι a ≠ ∅ := ne_empty_of_mem (mem_singleton_self _) @[simp] lemma coe_singleton (a : α) : ↑(ι a) = ({a} : set α) := rfl /- insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ @[simp] theorem has_insert_eq_insert (a : α) (s : finset α) : has_insert.insert a s = insert a s := rfl theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a ↑s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext.2 $ λ x, by simp only [finset.mem_insert, or.left_comm] @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext.2 $ λ x, by simp only [finset.mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := ne_empty_of_mem (mem_insert_self a s) theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert [h : decidable_eq α] (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a, a ∉ s ∧ insert a s ⊆ t) := iff.intro (assume ⟨h₁, h₂⟩, have ∃a ∈ t, a ∉ s, by simpa only [finset.subset_iff, classical.not_forall] using h₂, let ⟨a, hat, has⟩ := this in ⟨a, has, insert_subset.mpr ⟨hat, h₁⟩⟩) (assume ⟨a, hat, has⟩, let ⟨h₁, h₂⟩ := insert_subset.mp has in ⟨h₂, assume h, hat $ h h₁⟩) lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[recursor 6] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [insert_val, ndinsert_of_not_mem m] } end) nd @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s @[simp] theorem singleton_eq_singleton (a : α) : _root_.singleton a = ι a := rfl @[simp] theorem insert_empty_eq_singleton (a : α) : {a} = ι a := rfl @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a := insert_eq_of_mem $ mem_singleton_self _ /- union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ @[simp] theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext.2 $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext.2 $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext.2 $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext.2 $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext.2 $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] @[simp] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext.2 $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext.2 $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] /- inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext.2 $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and_assoc] @[simp] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and.left_comm] @[simp] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext.2 $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext.2 $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext.2 $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext.2 $ λ _, mem_inter.trans $ false_and _ @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext.2 $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext.2 $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : ι a ∩ s = ι a := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : ι a ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ ι a = ι a := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ ι a = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] /- lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice.lattice } instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.lattice.semilattice_inf_bot, ..finset.lattice.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right /- erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext.2 $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext.2 $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ /- sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩ @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 @[simp] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := ext.2 $ λ a, by simpa only [mem_sdiff, mem_union, or_comm, or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a) @[simp] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := (union_comm _ _).trans (sdiff_union_of_subset h) @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := (inter_comm _ _).trans (inter_sdiff_self _ _) theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂) @[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] lemma to_set_sdiff (s t : finset α) : (s \ t).to_set = s.to_set \ t.to_set := by apply finset.coe_sdiff end decidable_eq /- attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /- filter -/ section filter variables {p q : α → Prop} [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext.2 $ assume a, by simp only [mem_filter, and_comm, and.left_comm] @[simp] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext.2 $ assume a, by simp only [mem_filter, and_false]; refl lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext.2 $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (p q : α → Prop) [decidable_pred p] [decidable_pred q] (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext.2 $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] theorem filter_or (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext.2 $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext.2 $ λ _, by simp only [mem_sdiff, mem_filter] theorem filter_union_filter_neg_eq (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset s)] theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] @[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} [decidable_pred (∈ t₁)] (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, classical.or_not] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end end filter /- range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := finset.induction_on s ⟨0, empty_subset _⟩ $ λ a s ha ⟨n, hn⟩, ⟨max (a + 1) n, insert_subset.2 ⟨by simpa only [mem_range] using le_max_left (a+1) n, subset.trans hn (by simpa only [range_subset] using le_max_right (a+1) n)⟩⟩ end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset namespace option /-- Construct an empty or singleton finset from an `option` -/ def to_finset (o : option α) : finset α := match o with | none := ∅ | some a := finset.singleton a end @[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl @[simp] theorem to_finset_some {a : α} : (some a).to_finset = finset.singleton a := rfl @[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o := by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl end option /- erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 (erase_dup_eq_self.2 n).symm @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a :: s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext' $ by simp @[simp] lemma to_finset_smul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (add_monoid.smul n s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, add_monoid.one_smul] }, { rw [add_monoid.add_smul, to_finset_add, add_monoid.one_smul, to_finset_smul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext' $ by simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero end multiset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] end list namespace finset section map open function def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) (s : finset α) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_inj f.2 @[simp] theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] theorem map_refl : s.map (embedding.refl _) = s := ext.2 $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := by simp only [subset.antisymm_iff, map_subset_map] def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩ @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := ext.2 $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩, by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := ext.2 $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := ext.2 $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact ⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩, by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩ @[simp] theorem map_singleton (f : α ↪ β) (a : α) : (singleton a).map f = singleton (f a) := ext.2 $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, insert_empty_eq_singleton, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ_inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] @[simp] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ @[simp] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans $ by simp only [exists_prop]; refl theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] @[simp] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f := multiset.erase_dup_eq_self.2 (nodup_map_on H s.2) theorem image_id [decidable_eq α] : s.image id = s := ext.2 $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext.2 $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext.2 $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext.2 $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton [decidable_eq α] (f : α → β) (a : α) : (singleton a).image f = singleton (f a) := ext.2 $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, insert_empty_eq_singleton, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext.2 $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (assume h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (assume h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm lemma image_const [decidable_eq β] {s : finset α} (h : s ≠ ∅) (b : β) : s.image (λa, b) = singleton b := ext.2 $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, exists_mem_of_ne_empty h, true_and, mem_singleton, eq_comm] protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subset_image_iff [decidable_eq α] [decidable_eq β] {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, induction s using finset.induction with a s has ih h, { exact ⟨∅, set.empty_subset _, finset.image_empty _⟩ }, rw [finset.coe_insert, set.insert_subset] at h, rcases ih h.2 with ⟨s', hst, hsi⟩, rcases h.1 with ⟨x, hxt, rfl⟩, refine ⟨insert x s', _, _⟩, { rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ }, rw [finset.image_insert, hsi] end end image /- card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s ≠ ∅ := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = finset.singleton a := by cases s; simp [multiset.card_eq_one, finset.singleton, finset.card] @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by simpa only [card_cons, card, insert_val] using congr_arg multiset.card (ndinsert_of_not_mem h) theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card (singleton a) = 1 := card_singleton _ theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : function.injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h lemma card_eq_of_bijective [decidable_eq α] {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := have ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have card s > 0, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := finset.exists_mem_of_ne_empty $ card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma card_lt_card [decidable_eq α] {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on [decidable_eq α] [decidable_eq β] {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end lemma card_le_of_inj_on [decidable_eq α] {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂) @[elab_as_eliminator] lemma strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s | ⟨s, nd⟩ ih := multiset.strong_induction_on s (λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext.2 $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) (λ a, by by_cases a ∈ s; simp * {contextual := tt}) lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ le_add_right _ _ lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f (a.val) a.2) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a.1 a.2) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end end card section bind variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bind s t` is the union of `t x` over `x ∈ s` -/ protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bind_val (s : finset α) (t : α → finset β) : (s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl @[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t := ext.2 $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext.2 $ λ x, by simp [or_and_distrib_right, exists_or_distrib] @[simp] lemma singleton_bind [decidable_eq α] {a : α} : (singleton a).bind t = t a := show (insert a ∅ : finset α).bind t = t a, from bind_insert.trans $ union_empty _ theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bind t = s.bind (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bind_insert, ih]) theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bind t).image f = s.bind (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bind_insert, image_union, ih]) theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) := ext.2 $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop] lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop] lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f := ext.2 $ λ x, by simp only [mem_bind, mem_image, insert_empty_eq_singleton, mem_singleton, eq_comm] lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bind (λa, s.filter $ (λc, g c = a)) = s := begin ext b, simp, split, { rintros ⟨a, ⟨b', _, _⟩, hb, _⟩, exact hb }, { rintros hb, exact ⟨g b, ⟨b, hb, rfl⟩, hb, rfl⟩ } end end bind section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bind (λa, t.image $ λb, (a, b)) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ end prod section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bind [decidable_eq α] [∀a, decidable_eq (σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bind (λa, (t a).image $ λb, ⟨a, b⟩) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_sigma, mem_bind, mem_image, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, heq_iff_eq, exists_eq_right] end sigma section pi variables {δ : α → Type*} [decidable_eq α] def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) := ⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩ @[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) : (s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl @[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} : f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) := mem_pi _ _ _ def pi.empty (β : α → Sort*) [decidable_eq α] (a : α) (h : a ∈ (∅ : finset α)) : β a := multiset.pi.empty β a h def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' := multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h) @[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) : pi.cons s a b f a h = b := multiset.pi.cons_same _ lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') : pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) := multiset.pi.cons_ne _ _ lemma injective_pi_cons {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume e₁ e₂ eq, @multiset.injective_pi_cons α _ δ a b s.1 hs _ _ $ funext $ assume e, funext $ assume h, have pi.cons s a b e₁ e (by simpa only [mem_cons, mem_insert] using h) = pi.cons s a b e₂ e (by simpa only [mem_cons, mem_insert] using h), by rw [eq], this @[simp] lemma pi_empty {t : Πa:α, finset (δ a)} : pi (∅ : finset α) t = singleton (pi.empty δ) := rfl @[simp] lemma pi_insert [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) : pi (insert a s) t = (t a).bind (λb, (pi s t).image (pi.cons s a b)) := begin apply eq_of_veq, rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2, refine (λ s' (h : s' = a :: s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) = erase_dup ((t a).1.bind $ λ b, erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $ λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha), subst s', rw pi_cons, congr, funext b, rw multiset.erase_dup_eq_self.2, exact multiset.nodup_map (multiset.injective_pi_cons ha) (pi s t).2, end end pi section powerset def powerset (s : finset α) : finset (finset α) := ⟨s.1.powerset.pmap finset.mk (λ t h, nodup_of_le (mem_powerset.1 h) s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset.2 s.2)⟩ @[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff @[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s := mem_powerset.2 (empty_subset _) @[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s := mem_powerset.2 (subset.refl _) @[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _), λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩ @[simp] theorem card_powerset (s : finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (card_powerset s.1) end powerset section powerset_len def powerset_len (n : ℕ) (s : finset α) : finset (finset α) := ⟨(s.1.powerset_len n).pmap finset.mk (λ t h, nodup_of_le (mem_powerset_len.1 h).1 s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset_len s.2)⟩ theorem mem_powerset_len {n} {s t : finset α} : s ∈ powerset_len n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powerset_len, val_le_iff.symm]; refl @[simp] theorem powerset_len_mono {n} {s t : finset α} (h : s ⊆ t) : powerset_len n s ⊆ powerset_len n t := λ u h', mem_powerset_len.2 $ and.imp (λ h₂, subset.trans h₂ h) id (mem_powerset_len.1 h') @[simp] theorem card_powerset_len (n : ℕ) (s : finset α) : card (powerset_len n s) = nat.choose (card s) n := (card_pmap _ _ _).trans (card_powerset_len n s.1) end powerset_len section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation a * b := op a b include hc ha /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left] @[simp] theorem fold_singleton : (singleton a).fold op b f = f a * b := rfl @[simp] theorem fold_map [decidable_eq α] {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← map_add, union_val, inter_val, union_add_inter, map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := by haveI := classical.prop_decidable; rw [fold, insert_val', ← fold_erase_dup_idem op, erase_dup_map_erase_dup_eq, fold_erase_dup_idem op]; simp only [map_cons, fold_cons_left, fold] end fold section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_val : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton [decidable_eq β] {b : β} : ({b} : finset β).sup f = f b := calc _ = f b ⊔ (∅:finset β).sup f : sup_insert ... = f b : sup_bot_eq lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le_sup H.1 (ih H.2)) lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := by letI := classical.dec_eq β; from calc f b ≤ f b ⊔ s.sup f : le_sup_left ... = (insert b s).sup f : sup_insert.symm ... = s.sup f : by rw [insert_eq_of_mem hb] lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := by letI := classical.dec_eq β; from finset.induction_on s (λ _, bot_le) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le H.1 (ih H.2)) lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := iff.intro (assume h b hb, le_trans (le_sup hb) h) sup_le lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) lemma sup_lt [is_total α (≤)] {a : α} : (⊥ < a) → (∀b ∈ s, f b < a) → s.sup f < a := by letI := classical.dec_eq β; from finset.induction_on s (by simp) (by simp {contextual := tt}) lemma comp_sup_eq_sup_comp [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := have A : ∀x y, g (x ⊔ y) = g x ⊔ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [sup_of_le_right h, sup_of_le_right (mono_g h)] }, { simp [sup_of_le_left h, sup_of_le_left (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [A] {contextual := tt}) end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_val : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton [decidable_eq β] {b : β} : ({b} : finset β).inf f = f b := calc _ = f b ⊓ (∅:finset β).inf f : inf_insert ... = f b : inf_top_eq lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := finset.induction_on s₁ (by rw [empty_union, inf_empty, top_inf_eq]) $ λ a s has ih, by rw [insert_union, inf_insert, inf_insert, ih, inf_assoc] theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.inf f ≤ s.inf g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact inf_le_inf H.1 (ih H.2)) lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := by letI := classical.dec_eq β; from calc f b ≥ f b ⊓ s.inf f : inf_le_left ... = (insert b s).inf f : inf_insert.symm ... = s.inf f : by rw [insert_eq_of_mem hb] lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_top) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact le_inf H.1 (ih H.2)) lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ (∀b ∈ s, a ≤ f b) := iff.intro (assume h b hb, le_trans h (inf_le hb)) le_inf lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf [is_total α (≤)] {a : α} : (a < ⊤) → (∀b ∈ s, a < f b) → a < s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (by simp) (by simp {contextual := tt}) lemma comp_inf_eq_inf_comp [is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := have A : ∀x y, g (x ⊓ y) = g x ⊓ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [inf_of_le_left h, inf_of_le_left (mono_g h)] }, { simp [inf_of_le_right h, inf_of_le_right (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [top]) (by simp [A] {contextual := tt}) end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := le_antisymm (le_infi $ assume a, le_infi $ assume ha, inf_le ha) (finset.le_inf $ assume a ha, infi_le_of_le a $ infi_le _ ha) /- max and min of finite sets -/ section max_min variables [decidable_linear_order α] protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := max_insert @[simp] theorem max_singleton' {a : α} : finset.max (singleton a) = some a := max_singleton theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := exists_mem_of_ne_empty h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, by_contradiction $ λ hs, let ⟨a, ha⟩ := max_of_ne_empty hs in by rw [h] at ha; cases ha, λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := min_insert theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := exists_mem_of_ne_empty h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, by_contradiction $ λ hs, let ⟨a, ha⟩ := min_of_ne_empty hs in by rw [h] at ha; cases ha, λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := finset.induction_on s (λ _ H, by cases H) $ λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice min_choice (some b) s.min with q q; rw [min_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end theorem le_min_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption end max_min section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ end sort section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans singleton_disjoint @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_bind_left {ι : Type*} [decidable_eq ι] (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bind f) t ↔ (∀i∈s, disjoint (f i) t) := begin refine s.induction _ _, { simp only [forall_mem_empty_iff, bind_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bind_insert, his, forall_mem_insert, ih] } end lemma disjoint_bind_right {ι : Type*} [decidable_eq ι] (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bind f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bind_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] end disjoint theorem sort_sorted_lt [decidable_linear_order α] (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.mk.inj) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ a.1 ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a.1, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose theorem lt_wf {α} [decidable_eq α] : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf section decidable_linear_order variables {α} [decidable_linear_order α] def min' (S : finset α) (H : S ≠ ∅) : α := @option.get _ S.min $ let ⟨k, hk⟩ := exists_mem_of_ne_empty H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] def max' (S : finset α) (H : S ≠ ∅) : α := @option.get _ S.max $ let ⟨k, hk⟩ := exists_mem_of_ne_empty H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (S : finset α) (H : S ≠ ∅) theorem min'_mem : S.min' H ∈ S := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ S) : S.min' H ≤ x := le_min_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ S, x ≤ y) : x ≤ S.min' H := H2 _ $ min'_mem _ _ theorem max'_mem : S.max' H ∈ S := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ S) : x ≤ S.max' H := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ S, y ≤ x) : S.max' H ≤ x := H2 _ $ max'_mem _ _ theorem min'_lt_max' {i j} (H1 : i ∈ S) (H2 : j ∈ S) (H3 : i ≠ j) : S.min' H < S.max' H := begin rcases lt_trichotomy i j with H4 | H4 | H4, { have H5 := min'_le S H i H1, have H6 := le_max' S H j H2, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 }, { cc }, { have H5 := min'_le S H j H2, have H6 := le_max' S H i H1, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 } end end decidable_linear_order /- Ico (a closed openinterval) -/ variables {n m l : ℕ} /-- `Ico n m` is the set of natural numbers `n ≤ k < m`. -/ def Ico (n m : ℕ) : finset ℕ := ⟨_, Ico.nodup n m⟩ namespace Ico @[simp] theorem val (n m : ℕ) : (Ico n m).1 = multiset.Ico n m := rfl @[simp] theorem to_finset (n m : ℕ) : (multiset.Ico n m).to_finset = Ico n m := (multiset.to_finset_eq _).symm theorem image_add (n m k : ℕ) : (Ico n m).image ((+) k) = Ico (n + k) (m + k) := by simp [image, multiset.Ico.map_add] theorem image_sub (n m k : ℕ) (h : k ≤ n): (Ico n m).image (λ x, x - k) = Ico (n - k) (m - k) := begin dsimp [image], rw [multiset.Ico.map_sub _ _ _ h, ←multiset.to_finset_eq], refl, end theorem zero_bot (n : ℕ) : Ico 0 n = range n := eq_of_veq $ multiset.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := multiset.Ico.card _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := multiset.Ico.mem theorem eq_empty_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = ∅ := eq_of_veq $ multiset.Ico.eq_zero_of_le h @[simp] theorem self_eq_empty {n : ℕ} : Ico n n = ∅ := eq_empty_of_le $ le_refl n @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = ∅ ↔ m ≤ n := iff.trans val_eq_zero.symm multiset.Ico.eq_zero_iff lemma union_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ∪ Ico m l = Ico n l := by rw [← to_finset, ← to_finset, ← multiset.to_finset_add, multiset.Ico.add_consecutive hnm hml, to_finset] @[simp] lemma inter_consecutive {n m l : ℕ} : Ico n m ∩ Ico m l = ∅ := begin rw [← to_finset, ← to_finset, ← multiset.to_finset_inter, multiset.Ico.inter_consecutive], simp, end @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := eq_of_veq $ multiset.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = insert m (Ico n m) := by rw [← to_finset, multiset.Ico.succ_top h, multiset.to_finset_cons, to_finset] theorem succ_top' {n m : ℕ} (h : n < m) : Ico n m = insert (m - 1) (Ico n (m - 1)) := begin have w : m = m - 1 + 1 := (nat.sub_add_cancel (nat.one_le_of_lt h)).symm, conv { to_lhs, rw w }, rw succ_top, exact nat.le_pred_of_lt h end theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = insert n (Ico (n + 1) m) := by rw [← to_finset, multiset.Ico.eq_cons h, multiset.to_finset_cons, to_finset] @[simp] theorem pred_singleton {m : ℕ} (h : m > 0) : Ico (m - 1) m = {m - 1} := eq_of_veq $ multiset.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := multiset.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := eq_of_veq $ multiset.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := eq_of_veq $ multiset.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := eq_of_veq $ multiset.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := eq_of_veq $ multiset.Ico.filter_lt n m l lemma filter_ge_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x ≥ l) = Ico n m := eq_of_veq $ multiset.Ico.filter_ge_of_le_bot hln lemma filter_ge_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x ≥ l) = ∅ := eq_of_veq $ multiset.Ico.filter_ge_of_top_le hml lemma filter_ge_of_ge {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, x ≥ l) = Ico l m := eq_of_veq $ multiset.Ico.filter_ge_of_ge hnl @[simp] lemma filter_ge (n m l : ℕ) : (Ico n m).filter (λ x, x ≥ l) = Ico (max n l) m := eq_of_veq $ multiset.Ico.filter_ge n m l @[simp] lemma diff_left (l n m : ℕ) : (Ico n m) \ (Ico n l) = Ico (max n l) m := by ext k; by_cases n ≤ k; simp [h, and_comm] @[simp] lemma diff_right (l n m : ℕ) : (Ico n m) \ (Ico l m) = Ico n (min m l) := have ∀k, (k < m ∧ (l ≤ k → m ≤ k)) ↔ (k < m ∧ k < l) := assume k, and_congr_right $ assume hk, by rw [← not_imp_not]; simp [hk], by ext k; by_cases n ≤ k; simp [h, this] end Ico end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end end multiset namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h end list namespace lattice variables {ι : Sort*} [complete_lattice α] [decidable_eq ι] lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset (plift ι), ⨆i∈t, s (plift.down i)) := le_antisymm (supr_le $ assume b, le_supr_of_le {plift.up b} $ le_supr_of_le (plift.up b) $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset (plift ι), ⨅i∈t, s (plift.down i)) := le_antisymm (le_infi $ assume t, le_infi $ assume b, le_infi $ assume hb, infi_le _ _) (le_infi $ assume b, infi_le_of_le {plift.up b} $ infi_le_of_le (plift.up b) $ infi_le_of_le (by simp) $ le_refl _) end lattice namespace set variables {ι : Sort*} [decidable_eq ι] lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset (plift ι), ⋃i∈t, s (plift.down i)) := lattice.supr_eq_supr_finset s lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset (plift ι), ⋂i∈t, s (plift.down i)) := lattice.infi_eq_infi_finset s end set
9fdb17895ff7085a09d9ce2a3ffe580894ede38e
4fa118f6209450d4e8d058790e2967337811b2b5
/src/for_mathlib/ideal_operations.lean
a96e802549855914242624f5dc4629925ce7b821
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
1,224
lean
import ring_theory.ideal_operations -- PRs mostly go there -- PR directly to ring_theory.ideals lemma ideal.one_mem_of_unit_mem {R : Type*} [comm_ring R] {I : ideal R} {u : units R} (h : (u : R) ∈ I) : (1 : R) ∈ I := begin have : (u : R)*(u⁻¹ : units R) ∈ I, from I.mul_mem_right h, rwa u.mul_inv at this end lemma ideal.span_singleton_mul {R : Type*} [comm_ring R] (x y : R) : (ideal.span ({x} : set R)) * (ideal.span {y}) = ideal.span {x*y} := by simp [ideal.span_mul_span] lemma ideal.span_singleton_pow {R : Type*} [comm_ring R] (x : R) (n : ℕ) : (ideal.span ({x} : set R))^n = ideal.span {x^n} := begin induction n with n ih, { simp }, { rw [pow_succ, ih, ideal.span_singleton_mul, pow_succ] } end lemma ideal.eq_bot_iff_zero {R : Type*} [comm_ring R] {I : ideal R} : I = ⊥ ↔ (I : set R) = {0} := begin split ; intro h, { simp [h] }, { ext, change x ∈ (I : set R) ↔ _, simp [h] }, end @[simp] lemma ideal.span_empty {R : Type*} [comm_ring R] : ideal.span (∅ : set R) = ⊥ := ideal.span_eq_bot.mpr (λ x h, false.elim h) @[simp] lemma ideal.span_zero {R : Type*} [comm_ring R] : ideal.span ({0} : set R) = ⊥ := ideal.span_eq_bot.mpr $ λ x, set.mem_singleton_iff.mp
4f85f0520abea3d5f343537830a3ef56f8ad8892
9028d228ac200bbefe3a711342514dd4e4458bff
/src/ring_theory/adjoin.lean
6a994cb4278a4119d61c0a31114070681c20c464
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,882
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.polynomial.basic import algebra.algebra.subalgebra /-! # Adjoining elements to form subalgebras This file develops the basic theory of subalgebras of an R-algebra generated by a set of elements. A basic interface for `adjoin` is set up, and various results about finitely-generated subalgebras and submodules are proved. ## Definitions * `fg (S : subalgebra R A)` : A predicate saying that the subalgebra is finitely-generated as an A-algebra ## Tags adjoin, algebra, finitely-generated algebra -/ universes u v w open submodule namespace algebra variables {R : Type u} {A : Type v} {B : Type w} section semiring variables [comm_semiring R] [semiring A] [semiring B] variables [algebra R A] [algebra R B] {s t : set A} open subsemiring theorem subset_adjoin : s ⊆ adjoin R s := set.subset.trans (set.subset_union_right _ _) subset_closure theorem adjoin_le {S : subalgebra R A} (H : s ⊆ S) : adjoin R s ≤ S := closure_le.2 $ set.union_subset S.range_le H theorem adjoin_le_iff {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ S:= ⟨set.subset.trans subset_adjoin, adjoin_le⟩ theorem adjoin_mono (H : s ⊆ t) : adjoin R s ≤ adjoin R t := closure_le.2 (set.subset.trans (set.union_subset_union_right _ H) subset_closure) variables (R A) @[simp] theorem adjoin_empty : adjoin R (∅ : set A) = ⊥ := eq_bot_iff.2 $ adjoin_le $ set.empty_subset _ variables (R) {A} (s) theorem adjoin_eq_span : (adjoin R s : submodule R A) = span R (monoid.closure s) := begin apply le_antisymm, { intros r hr, rcases mem_closure_iff_exists_list.1 hr with ⟨L, HL, rfl⟩, clear hr, induction L with hd tl ih, { exact zero_mem _ }, rw list.forall_mem_cons at HL, rw [list.map_cons, list.sum_cons], refine submodule.add_mem _ _ (ih HL.2), replace HL := HL.1, clear ih tl, suffices : ∃ z r (hr : r ∈ monoid.closure s), has_scalar.smul.{u v} z r = list.prod hd, { rcases this with ⟨z, r, hr, hzr⟩, rw ← hzr, exact smul_mem _ _ (subset_span hr) }, induction hd with hd tl ih, { exact ⟨1, 1, is_submonoid.one_mem, one_smul _ _⟩ }, rw list.forall_mem_cons at HL, rcases (ih HL.2) with ⟨z, r, hr, hzr⟩, rw [list.prod_cons, ← hzr], rcases HL.1 with ⟨hd, rfl⟩ | hs, { refine ⟨hd * z, r, hr, _⟩, rw [smul_def, smul_def, (algebra_map _ _).map_mul, _root_.mul_assoc] }, { exact ⟨z, hd * r, is_submonoid.mul_mem (monoid.subset_closure hs) hr, (mul_smul_comm _ _ _).symm⟩ } }, exact span_le.2 (show monoid.closure s ⊆ adjoin R s, from monoid.closure_subset subset_adjoin) end lemma adjoin_image (f : A →ₐ[R] B) (s : set A) : adjoin R (f '' s) = (adjoin R s).map f := le_antisymm (adjoin_le $ set.image_subset _ subset_adjoin) $ subalgebra.map_le.2 $ adjoin_le $ set.image_subset_iff.1 subset_adjoin end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] variables [algebra R A] {s t : set A} open subsemiring variables (R s t) theorem adjoin_union : adjoin R (s ∪ t) = (adjoin R s).under (adjoin (adjoin R s) t) := le_antisymm (closure_mono $ set.union_subset (set.range_subset_iff.2 $ λ r, or.inl ⟨algebra_map R (adjoin R s) r, rfl⟩) (set.union_subset_union_left _ $ λ x hxs, ⟨⟨_, subset_adjoin hxs⟩, rfl⟩)) (closure_le.2 $ set.union_subset (set.range_subset_iff.2 $ λ x, adjoin_mono (set.subset_union_left _ _) x.2) (set.subset.trans (set.subset_union_right _ _) subset_adjoin)) theorem adjoin_eq_range : adjoin R s = (mv_polynomial.aeval (coe : s → A)).range := le_antisymm (adjoin_le $ λ x hx, ⟨mv_polynomial.X ⟨x, hx⟩, set.mem_univ _, mv_polynomial.eval₂_X _ _ _⟩) (λ x ⟨p, _, (hp : mv_polynomial.aeval coe p = x)⟩, hp ▸ mv_polynomial.induction_on p (λ r, by { rw [mv_polynomial.aeval_def, mv_polynomial.eval₂_C], exact (adjoin R s).algebra_map_mem r }) (λ p q hp hq, by rw alg_hom.map_add; exact is_add_submonoid.add_mem hp hq) (λ p ⟨n, hn⟩ hp, by rw [alg_hom.map_mul, mv_polynomial.aeval_def _ (mv_polynomial.X _), mv_polynomial.eval₂_X]; exact is_submonoid.mul_mem hp (subset_adjoin hn))) theorem adjoin_singleton_eq_range (x : A) : adjoin R {x} = (polynomial.aeval x).range := le_antisymm (adjoin_le $ set.singleton_subset_iff.2 ⟨polynomial.X, set.mem_univ _, polynomial.eval₂_X _ _⟩) (λ y ⟨p, _, (hp : polynomial.aeval x p = y)⟩, hp ▸ polynomial.induction_on p (λ r, by { rw [polynomial.aeval_def, polynomial.eval₂_C], exact (adjoin R _).algebra_map_mem r }) (λ p q hp hq, by rw alg_hom.map_add; exact is_add_submonoid.add_mem hp hq) (λ n r ih, by { rw [pow_succ', ← mul_assoc, alg_hom.map_mul, polynomial.aeval_def _ polynomial.X, polynomial.eval₂_X], exact is_submonoid.mul_mem ih (subset_adjoin rfl) })) theorem adjoin_union_coe_submodule : (adjoin R (s ∪ t) : submodule R A) = (adjoin R s) * (adjoin R t) := begin rw [adjoin_eq_span, adjoin_eq_span, adjoin_eq_span, span_mul_span], congr' 1 with z, simp [monoid.mem_closure_union_iff, set.mem_mul], end end comm_semiring section ring variables [comm_ring R] [ring A] variables [algebra R A] {s t : set A} variables {R s t} open ring theorem adjoin_int (s : set R) : adjoin ℤ s = subalgebra_of_is_subring (closure s) := le_antisymm (adjoin_le subset_closure) (closure_subset subset_adjoin) theorem mem_adjoin_iff {s : set A} {x : A} : x ∈ adjoin R s ↔ x ∈ closure (set.range (algebra_map R A) ∪ s) := ⟨λ hx, subsemiring.closure_induction hx subset_closure is_add_submonoid.zero_mem is_submonoid.one_mem (λ _ _, is_add_submonoid.add_mem) (λ _ _, is_submonoid.mul_mem), suffices closure (set.range ⇑(algebra_map R A) ∪ s) ⊆ adjoin R s, from @this x, closure_subset subsemiring.subset_closure⟩ theorem adjoin_eq_ring_closure (s : set A) : (adjoin R s : set A) = closure (set.range (algebra_map R A) ∪ s) := set.ext $ λ x, mem_adjoin_iff end ring section comm_ring variables [comm_ring R] [comm_ring A] variables [algebra R A] {s t : set A} variables {R s t} open ring theorem fg_trans (h1 : (adjoin R s : submodule R A).fg) (h2 : (adjoin (adjoin R s) t : submodule (adjoin R s) A).fg) : (adjoin R (s ∪ t) : submodule R A).fg := begin rcases fg_def.1 h1 with ⟨p, hp, hp'⟩, rcases fg_def.1 h2 with ⟨q, hq, hq'⟩, refine fg_def.2 ⟨p * q, hp.mul hq, le_antisymm _ _⟩, { rw [span_le], rintros _ ⟨x, y, hx, hy, rfl⟩, change x * y ∈ _, refine is_submonoid.mul_mem _ _, { have : x ∈ (adjoin R s : submodule R A), { rw ← hp', exact subset_span hx }, exact adjoin_mono (set.subset_union_left _ _) this }, have : y ∈ (adjoin (adjoin R s) t : submodule (adjoin R s) A), { rw ← hq', exact subset_span hy }, change y ∈ adjoin R (s ∪ t), rwa adjoin_union }, { intros r hr, change r ∈ adjoin R (s ∪ t) at hr, rw adjoin_union at hr, change r ∈ (adjoin (adjoin R s) t : submodule (adjoin R s) A) at hr, haveI := classical.dec_eq A, haveI := classical.dec_eq R, rw [← hq', ← set.image_id q, finsupp.mem_span_iff_total (adjoin R s)] at hr, rcases hr with ⟨l, hlq, rfl⟩, have := @finsupp.total_apply A A (adjoin R s), rw [this, finsupp.sum], refine sum_mem _ _, intros z hz, change (l z).1 * _ ∈ _, have : (l z).1 ∈ (adjoin R s : submodule R A) := (l z).2, rw [← hp', ← set.image_id p, finsupp.mem_span_iff_total R] at this, rcases this with ⟨l2, hlp, hl⟩, have := @finsupp.total_apply A A R, rw this at hl, rw [←hl, finsupp.sum_mul], refine sum_mem _ _, intros t ht, change _ * _ ∈ _, rw smul_mul_assoc, refine smul_mem _ _ _, exact subset_span ⟨t, z, hlp ht, hlq hz, rfl⟩ } end end comm_ring end algebra namespace subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] /-- A subalgebra `S` is finitely generated if there exists `t : finset A` such that `algebra.adjoin R t = S`. -/ def fg (S : subalgebra R A) : Prop := ∃ t : finset A, algebra.adjoin R ↑t = S lemma fg_adjoin_finset (s : finset A) : (algebra.adjoin R (↑s : set A)).fg := ⟨s, rfl⟩ theorem fg_def {S : subalgebra R A} : S.fg ↔ ∃ t : set A, set.finite t ∧ algebra.adjoin R t = S := ⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩, λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩ theorem fg_bot : (⊥ : subalgebra R A).fg := ⟨∅, algebra.adjoin_empty R A⟩ lemma fg_of_submodule_fg (h : (⊤ : submodule R A).fg) : (⊤ : subalgebra R A).fg := let ⟨s, hs⟩ := h in ⟨s, to_submodule_injective $ by { rw [algebra.coe_top, eq_top_iff, ← hs, span_le], exact algebra.subset_adjoin }⟩ section open_locale classical lemma fg_map (S : subalgebra R A) (f : A →ₐ[R] B) (hs : S.fg) : (S.map f).fg := let ⟨s, hs⟩ := hs in ⟨s.image f, by rw [finset.coe_image, algebra.adjoin_image, hs]⟩ end lemma fg_of_fg_map (S : subalgebra R A) (f : A →ₐ[R] B) (hf : function.injective f) (hs : (S.map f).fg) : S.fg := let ⟨s, hs⟩ := hs in ⟨s.preimage f $ λ _ _ _ _ h, hf h, map_injective f hf $ by { rw [← algebra.adjoin_image, finset.coe_preimage, set.image_preimage_eq_of_subset, hs], rw [← alg_hom.coe_range, ← algebra.adjoin_le_iff, hs, ← algebra.map_top], exact map_mono le_top }⟩ lemma fg_top (S : subalgebra R A) : (⊤ : subalgebra R S).fg ↔ S.fg := ⟨λ h, by { rw [← S.range_val, ← algebra.map_top], exact fg_map _ _ h }, λ h, fg_of_fg_map _ S.val subtype.val_injective $ by { rw [algebra.map_top, range_val], exact h }⟩ end subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] /-- The image of a Noetherian R-algebra under an R-algebra map is a Noetherian ring. -/ instance alg_hom.is_noetherian_ring_range (f : A →ₐ[R] B) [is_noetherian_ring A] : is_noetherian_ring f.range := is_noetherian_ring_range f.to_ring_hom theorem is_noetherian_ring_of_fg {S : subalgebra R A} (HS : S.fg) [is_noetherian_ring R] : is_noetherian_ring S := let ⟨t, ht⟩ := HS in ht ▸ (algebra.adjoin_eq_range R (↑t : set A)).symm ▸ by haveI : is_noetherian_ring (mv_polynomial (↑t : set A) R) := mv_polynomial.is_noetherian_ring; convert alg_hom.is_noetherian_ring_range _; apply_instance theorem is_noetherian_ring_closure (s : set R) (hs : s.finite) : is_noetherian_ring (ring.closure s) := show is_noetherian_ring (subalgebra_of_is_subring (ring.closure s)), from algebra.adjoin_int s ▸ is_noetherian_ring_of_fg (subalgebra.fg_def.2 ⟨s, hs, rfl⟩)
e0ceabc90231cb3c090eb8ceea961686ef927578
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Meta/ExprDefEq.lean
e4107ba760cf617be848261431a15df00d9b487b
[ "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
77,748
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ProjFns import Lean.Structure import Lean.Meta.WHNF import Lean.Meta.InferType import Lean.Meta.FunInfo import Lean.Meta.Check import Lean.Meta.Offset import Lean.Meta.ForEachExpr import Lean.Meta.UnificationHint namespace Lean.Meta /-- Return true if `b` is of the form `mk a.1 ... a.n`, and `a` is not a constructor application. If `a` and `b` are constructor applications, the method returns `false` to force `isDefEq` to use `isDefEqArgs`. For example, suppose we are trying to solve the constraint ``` Fin.mk ?n ?h =?= Fin.mk n h ``` If this method is applied, the constraints are reduced to ``` n =?= (Fin.mk ?n ?h).1 h =?= (Fin.mk ?n ?h).2 ``` The first constraint produces the assignment `?n := n`. Then, the second constraint is solved using proof irrelevance without assigning `?h`. TODO: investigate better solutions for the proof irrelevance issue. The problem above can happen is other scenarios. That is, proof irrelevance may prevent us from performing desired mvar assignments. -/ private def isDefEqEtaStruct (a b : Expr) : MetaM Bool := do matchConstCtor b.getAppFn (fun _ => return false) fun ctorVal us => do if (← useEtaStruct ctorVal.induct) then matchConstCtor a.getAppFn (fun _ => go ctorVal us) fun _ _ => return false else return false where go ctorVal us := do if ctorVal.numParams + ctorVal.numFields != b.getAppNumArgs then trace[Meta.isDefEq.eta.struct] "failed, insufficient number of arguments at{indentExpr b}" return false else if !isStructureLike (← getEnv) ctorVal.induct then trace[Meta.isDefEq.eta.struct] "failed, type is not a structure{indentExpr b}" return false else if (← isDefEq (← inferType a) (← inferType b)) then checkpointDefEq do let args := b.getAppArgs let params := args[:ctorVal.numParams].toArray for i in [ctorVal.numParams : args.size] do let j := i - ctorVal.numParams let proj ← mkProjFn ctorVal us params j a trace[Meta.isDefEq.eta.struct] "{a} =?= {b} @ [{j}], {proj} =?= {args[i]!}" unless (← isDefEq proj args[i]!) do trace[Meta.isDefEq.eta.struct] "failed, unexpect arg #{i}, projection{indentExpr proj}\nis not defeq to{indentExpr args[i]!}" return false return true else return false /-- Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`. Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean. Example: ``` (fun x : A => f ?m) =?= f ``` The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/ private def isDefEqEta (a b : Expr) : MetaM Bool := do if a.isLambda && !b.isLambda then let bType ← inferType b let bType ← whnfD bType match bType with | Expr.forallE n d _ c => let b' := mkLambda n c d (mkApp b (mkBVar 0)) checkpointDefEq <| Meta.isExprDefEqAux a b' | _ => pure false else return false /-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/ def isDefEqNative (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t let s? ← reduceNative? s let t? ← reduceNative? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for reducing Nat basic operations. -/ def isDefEqNat (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then pure LBool.undef else let s? ← reduceNat? s let t? ← reduceNat? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for constraints of the form `("..." =?= String.mk cs)` -/ def isDefEqStringLit (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.isStringLit && t.isAppOf ``String.mk then isDefEq s.toCtorIfLit t else if s.isAppOf `String.mk && t.isStringLit then isDefEq s t.toCtorIfLit else pure LBool.undef /-- Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned. Remark: `n` may be 0. -/ def isEtaUnassignedMVar (e : Expr) : MetaM Bool := do match e.etaExpanded? with | some (Expr.mvar mvarId) => if (← mvarId.isReadOnlyOrSyntheticOpaque) then pure false else if (← mvarId.isAssigned) then pure false else pure true | _ => pure false private def trySynthPending (e : Expr) : MetaM Bool := do let mvarId? ← getStuckMVar? e match mvarId? with | some mvarId => Meta.synthPending mvarId | none => pure false /-- Result type for `isDefEqArgsFirstPass`. -/ inductive DefEqArgsFirstPassResult where | /-- Failed to establish that explicit arguments are def-eq. Remark: higher output parameters, and parameters that depend on them are postponed. -/ failed | /-- Succeeded. The array `postponedImplicit` contains the position of the implicit arguments for which def-eq has been postponed. `postponedHO` contains the higher order output parameters, and parameters that depend on them. They should be processed after the implict ones. `postponedHO` is used to handle applications involving functions that contain higher order output parameters. Example: ```lean getElem : {cont : Type u_1} → {idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → (h : dom xs i) → elem ``` The argumengs `dom` and `h` must be processed after all implicit arguments otherwise higher-order unification problems are generated. See issue #1299, when trying to solve ``` getElem ?a ?i ?h =?= getElem a i (Fin.val_lt_of_le i ...) ``` we have to solve the constraint ``` ?dom a i.val =?= LT.lt i.val (Array.size a) ``` by solving after the instance has been synthesized, we reduce this constraint to a simple check. -/ ok (postponedImplicit : Array Nat) (postponedHO : Array Nat) /-- First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases Here, we say a case is easy if it is of the form ?m =?= t or t =?= ?m where `?m` is unassigned. These easy cases are not just an optimization. When `?m` is a function, by assigning it to t, we make sure a unification constraint (in the explicit part) ``` ?m t =?= f s ``` is not higher-order. We also handle the eta-expanded cases: ``` fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ ``` This is important because type inference often produces eta-expanded terms, and without this extra case, we could introduce counter intuitive behavior. Pre: `paramInfo.size <= args₁.size = args₂.size` See `DefEqArgsFirstPassResult` for additional information. -/ private def isDefEqArgsFirstPass (paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : MetaM DefEqArgsFirstPassResult := do let mut postponedImplicit := #[] let mut postponedHO := #[] for i in [:paramInfo.size] do let info := paramInfo[i]! let a₁ := args₁[i]! let a₂ := args₂[i]! if info.dependsOnHigherOrderOutParam || info.higherOrderOutParam then trace[Meta.isDefEq] "found messy {a₁} =?= {a₂}" postponedHO := postponedHO.push i else if info.isExplicit then unless (← Meta.isExprDefEqAux a₁ a₂) do return .failed else if (← isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) then unless (← Meta.isExprDefEqAux a₁ a₂) do return .failed else postponedImplicit := postponedImplicit.push i return .ok postponedImplicit postponedHO private partial def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do unless args₁.size == args₂.size do return false let finfo ← getFunInfoNArgs f args₁.size let .ok postponedImplicit postponedHO ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ | pure false -- finfo.paramInfo.size may be smaller than args₁.size for i in [finfo.paramInfo.size:args₁.size] do unless (← Meta.isExprDefEqAux args₁[i]! args₂[i]!) do return false for i in postponedImplicit do /- Second pass: unify implicit arguments. In the second pass, we make sure we are unfolding at least non reducible definitions (default setting). -/ let a₁ := args₁[i]! let a₂ := args₂[i]! let info := finfo.paramInfo[i]! if info.isInstImplicit then discard <| trySynthPending a₁ discard <| trySynthPending a₂ unless (← withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a₁ a₂) do return false for i in postponedHO do let a₁ := args₁[i]! let a₂ := args₂[i]! let info := finfo.paramInfo[i]! if info.isInstImplicit then unless (← withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a₁ a₂) do return false else unless (← Meta.isExprDefEqAux a₁ a₂) do return false return true /-- Check whether the types of the free variables at `fvars` are definitionally equal to the types at `ds₂`. Pre: `fvars.size == ds₂.size` This method also updates the set of local instances, and invokes the continuation `k` with the updated set. We can't use `withNewLocalInstances` because the `isDeq fvarType d₂` may use local instances. -/ @[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) (k : MetaM Bool) : MetaM Bool := let rec loop (i : Nat) := do if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩ let fvarDecl ← getFVarLocalDecl fvar let fvarType := fvarDecl.type let d₂ := ds₂[i]! if (← Meta.isExprDefEqAux fvarType d₂) then match (← isClass? fvarType) with | some className => withNewLocalInstance className fvar <| loop (i+1) | none => loop (i+1) else pure false else k loop 0 /-- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`. It accumulates the new free variables in `fvars`, and declare them at `lctx`. We use the domain types of `e₁` to create the new free variables. We store the domain types of `e₂` at `ds₂`. -/ private partial def isDefEqBindingAux (lctx : LocalContext) (fvars : Array Expr) (e₁ e₂ : Expr) (ds₂ : Array Expr) : MetaM Bool := let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : MetaM Bool := do let d₁ := d₁.instantiateRev fvars let d₂ := d₂.instantiateRev fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d₁ let fvars := fvars.push (mkFVar fvarId) isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂) match e₁, e₂ with | Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | _, _ => withReader (fun ctx => { ctx with lctx := lctx }) do isDefEqBindingDomain fvars ds₂ do Meta.isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars) @[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do let lctx ← getLCtx isDefEqBindingAux lctx #[] a b #[] private def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool := withTraceNode `Meta.isDefEq.assign.checkTypes (return m!"{exceptBoolEmoji ·} ({mvar} : {← inferType mvar}) := ({v} : {← inferType v})") do if !mvar.isMVar then trace[Meta.isDefEq.assign.checkTypes] "metavariable expected" return false else -- must check whether types are definitionally equal or not, before assigning and returning true let mvarType ← inferType mvar let vType ← inferType v if (← withTransparency TransparencyMode.default <| Meta.isExprDefEqAux mvarType vType) then mvar.mvarId!.assign v pure true else pure false /-- Auxiliary method for solving constraints of the form `?m xs := v`. It creates a lambda using `mkLambdaFVars ys v`, where `ys` is a superset of `xs`. `ys` is often equal to `xs`. It is a bigger when there are let-declaration dependencies in `xs`. For example, suppose we have `xs` of the form `#[a, c]` where ``` a : Nat b : Nat := f a c : b = a ``` In this scenario, the type of `?m` is `(x1 : Nat) -> (x2 : f x1 = x1) -> C[x1, x2]`, and type of `v` is `C[a, c]`. Note that, `?m a c` is type correct since `f a = a` is definitionally equal to the type of `c : b = a`, and the type of `?m a c` is equal to the type of `v`. Note that `fun xs => v` is the term `fun (x1 : Nat) (x2 : b = x1) => v` which has type `(x1 : Nat) -> (x2 : b = x1) -> C[x1, x2]` which is not definitionally equal to the type of `?m`, and may not even be type correct. The issue here is that we are not capturing the `let`-declarations. This method collects let-declarations `y` occurring between `xs[0]` and `xs.back` s.t. some `x` in `xs` depends on `y`. `ys` is the `xs` with these extra let-declarations included. In the example above, `ys` is `#[a, b, c]`, and `mkLambdaFVars ys v` produces `fun a => let b := f a; fun (c : b = a) => v` which has a type definitionally equal to the type of `?m`. Recall that the method `checkAssignment` ensures `v` does not contain offending `let`-declarations. This method assumes that for any `xs[i]` and `xs[j]` where `i < j`, we have that `index of xs[i]` < `index of xs[j]`. where the index is the position in the local context. -/ private partial def mkLambdaFVarsWithLetDeps (xs : Array Expr) (v : Expr) : MetaM (Option Expr) := do if not (← hasLetDeclsInBetween) then mkLambdaFVars xs v else let ys ← addLetDeps mkLambdaFVars ys v where /-- Return true if there are let-declarions between `xs[0]` and `xs[xs.size-1]`. We use it a quick-check to avoid the more expensive collection procedure. -/ hasLetDeclsInBetween : MetaM Bool := do let check (lctx : LocalContext) : Bool := Id.run do let start := lctx.getFVar! xs[0]! |>.index let stop := lctx.getFVar! xs.back |>.index for i in [start+1:stop] do match lctx.getAt? i with | some localDecl => if localDecl.isLet then return true | _ => pure () return false if xs.size <= 1 then return false else return check (← getLCtx) /-- Traverse `e` and stores in the state `NameHashSet` any let-declaration with index greater than `(← read)`. The context `Nat` is the position of `xs[0]` in the local context. -/ collectLetDeclsFrom (e : Expr) : ReaderT Nat (StateRefT FVarIdHashSet MetaM) Unit := do let rec visit (e : Expr) : MonadCacheT Expr Unit (ReaderT Nat (StateRefT FVarIdHashSet MetaM)) Unit := checkCache e fun _ => do match e with | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a => visit f; visit a | Expr.mdata _ b => visit b | Expr.proj _ _ b => visit b | Expr.fvar fvarId => let localDecl ← fvarId.getDecl if localDecl.isLet && localDecl.index > (← read) then modify fun s => s.insert localDecl.fvarId | _ => pure () visit (← instantiateMVars e) |>.run /-- Auxiliary definition for traversing all declarations between `xs[0]` ... `xs.back` backwards. The `Nat` argument is the current position in the local context being visited, and it is less than or equal to the position of `xs.back` in the local context. The `Nat` context `(← read)` is the position of `xs[0]` in the local context. -/ collectLetDepsAux : Nat → ReaderT Nat (StateRefT FVarIdHashSet MetaM) Unit | 0 => return () | i+1 => do if i+1 == (← read) then return () else match (← getLCtx).getAt? (i+1) with | none => collectLetDepsAux i | some localDecl => if (← get).contains localDecl.fvarId then collectLetDeclsFrom localDecl.type match localDecl.value? with | some val => collectLetDeclsFrom val | _ => pure () collectLetDepsAux i /-- Computes the set `ys`. It is a set of `FVarId`s, -/ collectLetDeps : MetaM FVarIdHashSet := do let lctx ← getLCtx let start := lctx.getFVar! xs[0]! |>.index let stop := lctx.getFVar! xs.back |>.index let s := xs.foldl (init := {}) fun s x => s.insert x.fvarId! let (_, s) ← collectLetDepsAux stop |>.run start |>.run s return s /-- Computes the array `ys` containing let-decls between `xs[0]` and `xs.back` that some `x` in `xs` depends on. -/ addLetDeps : MetaM (Array Expr) := do let lctx ← getLCtx let s ← collectLetDeps /- Convert `s` into the array `ys` -/ let start := lctx.getFVar! xs[0]! |>.index let stop := lctx.getFVar! xs.back |>.index let mut ys := #[] for i in [start:stop+1] do match lctx.getAt? i with | none => pure () | some localDecl => if s.contains localDecl.fvarId then ys := ys.push localDecl.toExpr return ys /-! Each metavariable is declared in a particular local context. We use the notation `C |- ?m : t` to denote a metavariable `?m` that was declared at the local context `C` with type `t` (see `MetavarDecl`). We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. The following method process the unification constraint ?m@C a₁ ... aₙ =?= t We say the unification constraint is a pattern IFF 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` Claim: we don't have to check free variable declarations. That is, if `t` contains a reference to `x : A := v`, we don't need to check `v`. Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3). If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`. So, condition 4 and 5 are satisfied. If the conditions above have been satisfied, then the solution for the unification constrain is ?m := fun a₁ ... aₙ => t Now, we consider some workarounds/approximations. A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3) (precise) solution: unfold `x` in `t`. A2) Suppose some `aᵢ` is in `C` (failed condition 2) (approximated) solution (when `config.quasiPatternApprox` is set to true) : ignore condition and also use ?m := fun a₁ ... aₙ => t Here is an example where this approximation fails: Given `C` containing `a : nat`, consider the following two constraints ?m@C a =?= a ?m@C b =?= a If we use the approximation in the first constraint, we get ?m := fun x => x when we apply this solution to the second one we get a failure. IMPORTANT: When applying this approximation we need to make sure the abstracted term `fun a₁ ... aₙ => t` is type correct. The check can only be skipped in the pattern case described above. Consider the following example. Given the local context (α : Type) (a : α) we try to solve ?m α =?= @id α a If we use the approximation above we obtain: ?m := (fun α' => @id α' a) which is a type incorrect term. `a` has type `α` but it is expected to have type `α'`. The problem occurs because the right hand side contains a free variable `a` that depends on the free variable `α` being abstracted. Note that this dependency cannot occur in patterns. We can address this by type checking the term after abstraction. This is not a significant performance bottleneck because this case doesn't happen very often in practice (262 times when compiling stdlib on Jan 2018). The second example is trickier, but it also occurs less frequently (8 times when compiling stdlib on Jan 2018, and all occurrences were at Init/Control when we define monads and auxiliary combinators for them). We considered three options for the addressing the issue on the second example: A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1). In Lean3, we would try to approximate this case using an approach similar to A2. However, this approximation complicates the code, and is never used in the Lean3 stdlib and mathlib. A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`. If `?m'` is assigned, we substitute. If not, we create an auxiliary metavariable with a smaller scope. Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step. A5) If some `aᵢ` is not a free variable, then we use first-order unification (if `config.foApprox` is set to true) ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k reduces to ?M a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k A6) If (m =?= v) is of the form ?m a_1 ... a_n =?= ?m b_1 ... b_k then we use first-order unification (if `config.foApprox` is set to true) A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form ``` ?m s₁ ... sₙ =?= t ``` where `s₁ ... sₙ` are arbitrary terms. We solve them by assigning the constant function to `?m`. ``` ?m := fun _ ... _ => t ``` In general, this approximation may produce bad solutions, and may prevent coercions from being tried. For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`. In this situation, the elaborator generates the unification constraint ``` ?m Prop =?= IO Bool ``` It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from the decidable proposition `x > 0` to `Bool`. On the other hand, the constant approximation is desirable for elaborating the term ``` let f (x : _) := pure "hello"; f () ``` with expected type `IO String`. In this example, the following unification contraint is generated. ``` ?m () String =?= IO String ``` It is not a higher-order pattern, first-order approximation reduces it to ``` ?m () =?= IO ``` which fails to be solved. However, constant approximation solves it by assigning ``` ?m := fun _ => IO ``` Note that `f`s type is `(x : ?α) -> ?m x String`. The metavariable `?m` may depend on `x`. If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide whether we should apply it or not. The heuristic is based on observing where the constraints above come from. In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f` does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected by any functional programmer used to non-dependently type languages (e.g., Haskell). We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks how many metavariable arguments are representing dependencies. -/ def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs namespace CheckAssignment builtin_initialize checkAssignmentExceptionId : InternalExceptionId ← registerInternalExceptionId `checkAssignment builtin_initialize outOfScopeExceptionId : InternalExceptionId ← registerInternalExceptionId `outOfScope structure State where cache : ExprStructMap Expr := {} structure Context where mvarId : MVarId mvarDecl : MetavarDecl fvars : Array Expr hasCtxLocals : Bool rhs : Expr abbrev CheckAssignmentM := ReaderT Context $ StateRefT State MetaM def throwCheckAssignmentFailure : CheckAssignmentM α := throw <| Exception.internal checkAssignmentExceptionId def throwOutOfScopeFVar : CheckAssignmentM α := throw <| Exception.internal outOfScopeExceptionId private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do return (← get).cache.find? e private def cache (e r : Expr) : CheckAssignmentM Unit := do modify fun s => { s with cache := s.cache.insert e r } instance : MonadCache Expr Expr CheckAssignmentM where findCached? := findCached? cache := cache @[inline] private def visit (f : Expr → CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr := if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e (fun _ => f e) private def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do let ctx ← read return m!"{msg} @ {mkMVar ctx.mvarId} {ctx.fvars} := {ctx.rhs}" @[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do let mvarDecl ← mvarId.getDecl let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context } let x : CheckAssignmentM (Option Expr) := catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId] (do let e ← x; return some e) (fun _ => pure none) x.run ctx |>.run' {} mutual partial def checkFVar (fvar : Expr) : CheckAssignmentM Expr := do let ctxMeta ← readThe Meta.Context let ctx ← read if ctx.mvarDecl.lctx.containsFVar fvar then pure fvar else let lctx := ctxMeta.lctx match lctx.findFVar? fvar with | some (.ldecl (value := v) ..) => visit check v | _ => if ctx.fvars.contains fvar then pure fvar else traceM `Meta.isDefEq.assign.outOfScopeFVar do addAssignmentInfo fvar throwOutOfScopeFVar partial def checkMVar (mvar : Expr) : CheckAssignmentM Expr := do let mvarId := mvar.mvarId! let ctx ← read if mvarId == ctx.mvarId then traceM `Meta.isDefEq.assign.occursCheck <| addAssignmentInfo "occurs check failed" throwCheckAssignmentFailure else match (← getExprMVarAssignment? mvarId) with | some v => check v | none => match (← mvarId.findDecl?) with | none => throwUnknownMVar mvarId | some mvarDecl => if ctx.hasCtxLocals then throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned. We "substract" variables being abstracted because we use `elimMVarDeps` -/ pure mvar else if mvarDecl.depth != (← getMCtx).depth || mvarDecl.kind.isSyntheticOpaque then traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure else let ctxMeta ← readThe Meta.Context if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then /- Create an auxiliary metavariable with a smaller context and "checked" type. Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains a metavariable that we also need to reduce the context. We remove from `ctx.mvarDecl.lctx` any variable that is not in `mvarDecl.lctx` or in `ctx.fvars`. We don't need to remove the ones in `ctx.fvars` because `elimMVarDeps` will take care of them. First, we collect `toErase` the variables that need to be erased. Notat that if a variable is `ctx.fvars`, but it depends on variable at `toErase`, we must also erase it. -/ let toErase ← mvarDecl.lctx.foldlM (init := #[]) fun toErase localDecl => do if ctx.mvarDecl.lctx.contains localDecl.fvarId then return toErase else if ctx.fvars.any fun fvar => fvar.fvarId! == localDecl.fvarId then if (← findLocalDeclDependsOn localDecl fun fvarId => toErase.contains fvarId) then -- localDecl depends on a variable that will be erased. So, we must add it to `toErase` too return toErase.push localDecl.fvarId else return toErase else return toErase.push localDecl.fvarId let lctx := toErase.foldl (init := mvarDecl.lctx) fun lctx toEraseFVar => lctx.erase toEraseFVar /- Compute new set of local instances. -/ let localInsts := mvarDecl.localInstances.filter fun localInst => toErase.contains localInst.fvar.fvarId! let mvarType ← check mvarDecl.type let newMVar ← mkAuxMVar lctx localInsts mvarType mvarDecl.numScopeArgs mvarId.assign newMVar pure newMVar else traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure /-- Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables, and one of them is out-of-scope. See `Expr.app` case at `check`. If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope, an assigning `?m := fun _ ... _ => ?n` -/ partial def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do let mvarType ← inferType mvar forallBoundedTelescope mvarType numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs newMVar | return false match (← checkAssignmentAux mvar.mvarId! #[] false v) with | some v => checkTypesAndAssign mvar v | none => return false -- See checkAssignment partial def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do run (check v) mvarId fvars hasCtxLocals v partial def checkApp (e : Expr) : CheckAssignmentM Expr := e.withApp fun f args => do let ctxMeta ← readThe Meta.Context if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then let f ← visit checkMVar f catchInternalId outOfScopeExceptionId (do let args ← args.mapM (visit check) return mkAppN f args) (fun ex => do if !f.isMVar then throw ex else if (← f.mvarId!.isDelayedAssigned) then throw ex else let eType ← inferType e let mvarType ← check eType /- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar` Note that `mvarType` may be different from `eType`. -/ let ctx ← read let newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType if (← assignToConstFun f args.size newMVar) then pure newMVar else throw ex) else let f ← visit check f let args ← args.mapM (visit check) return mkAppN f args partial def check (e : Expr) : CheckAssignmentM Expr := do match e with | Expr.mdata _ b => return e.updateMData! (← visit check b) | Expr.proj _ _ s => return e.updateProj! (← visit check s) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit check d) (← visit check b) | Expr.forallE _ d b _ => return e.updateForallE! (← visit check d) (← visit check b) | Expr.letE _ t v b _ => return e.updateLet! (← visit check t) (← visit check v) (← visit check b) | Expr.bvar .. => return e | Expr.sort .. => return e | Expr.const .. => return e | Expr.lit .. => return e | Expr.fvar .. => visit checkFVar e | Expr.mvar .. => visit checkMVar e | Expr.app .. => checkApp e -- TODO: investigate whether the following feature is too expensive or not /- catchInternalIds [checkAssignmentExceptionId, outOfScopeExceptionId] (checkApp e) fun ex => do let e' ← whnfR e if e != e' then check e' else throw ex -/ end end CheckAssignment namespace CheckAssignmentQuick partial def check (hasCtxLocals : Bool) (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) (e : Expr) : Bool := let rec visit (e : Expr) : Bool := if !e.hasExprMVar && !e.hasFVar then true else match e with | Expr.mdata _ b => visit b | Expr.proj _ _ s => visit s | Expr.app f a => visit f && visit a | Expr.lam _ d b _ => visit d && visit b | Expr.forallE _ d b _ => visit d && visit b | Expr.letE _ t v b _ => visit t && visit v && visit b | Expr.bvar .. => true | Expr.sort .. => true | Expr.const .. => true | Expr.lit .. => true | Expr.fvar fvarId .. => if mvarDecl.lctx.contains fvarId then true else match lctx.find? fvarId with | some (LocalDecl.ldecl ..) => false -- need expensive CheckAssignment.check | _ => if fvars.any fun x => x.fvarId! == fvarId then true else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it | Expr.mvar mvarId' => match mctx.getExprAssignmentCore? mvarId' with | some _ => false -- use CheckAssignment.check to instantiate | none => if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception else match mctx.findDecl? mvarId' with | none => false | some mvarDecl' => if hasCtxLocals then false -- use CheckAssignment.check else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true else false -- use CheckAssignment.check visit e end CheckAssignmentQuick /-- Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`. It will check whether we can perform the assignment ``` ?m := fun fvars => v ``` The result is `none` if the assignment can't be performed. The result is `some newV` where `newV` is a possibly updated `v`. This method may need to unfold let-declarations. -/ def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do /- Check whether `mvarId` occurs in the type of `fvars` or not. If it does, return `none` to prevent us from creating the cyclic assignment `?m := fun fvars => v` -/ for fvar in fvars do unless (← occursCheck mvarId (← inferType fvar)) do return none if !v.hasExprMVar && !v.hasFVar then pure (some v) else let mvarDecl ← mvarId.getDecl let hasCtxLocals := fvars.any fun fvar => mvarDecl.lctx.containsFVar fvar let ctx ← read let mctx ← getMCtx if CheckAssignmentQuick.check hasCtxLocals mctx ctx.lctx mvarDecl mvarId fvars v then pure (some v) else let v ← instantiateMVars v CheckAssignment.checkAssignmentAux mvarId fvars hasCtxLocals v private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := match v with | .mdata _ e => processAssignmentFOApproxAux mvar args e | Expr.app f a => if args.isEmpty then pure false else Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f | _ => pure false /-- Auxiliary method for applying first-order unification. It is an approximation. Remark: this method is trying to solve the unification constraint: ?m a₁ ... aₙ =?= v It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`. We have added support for unfolding here because we want to be able to solve unification problems such as ?m Unit =?= ITactic where `ITactic` is defined as def ITactic := Tactic Unit -/ private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := let rec loop (v : Expr) := do let cfg ← getConfig if !cfg.foApprox then pure false else trace[Meta.isDefEq.foApprox] "{mvar} {args} := {v}" let v := v.headBeta if (← checkpointDefEq <| processAssignmentFOApproxAux mvar args v) then pure true else match (← unfoldDefinition? v) with | none => pure false | some v => loop v loop v private partial def simpAssignmentArgAux (e : Expr) : MetaM Expr := do match e with | .mdata _ e => simpAssignmentArgAux e | .fvar fvarId => let some value ← fvarId.getValue? | return e simpAssignmentArgAux value | _ => return e /-- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`. We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`, and then removes metadata, and zeta-expand let-decls. -/ private def simpAssignmentArg (arg : Expr) : MetaM Expr := do let arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg simpAssignmentArgAux arg /-- Assign `mvar := fun a_1 ... a_{numArgs} => v`. We use it at `processConstApprox` and `isDefEqMVarSelf` -/ private def assignConst (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do let mvarDecl ← mvar.mvarId!.getDecl forallBoundedTelescope mvarDecl.type numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs v | pure false match (← checkAssignment mvar.mvarId! #[] v) with | none => pure false | some v => trace[Meta.isDefEq.constApprox] "{mvar} := {v}" checkTypesAndAssign mvar v /-- Auxiliary procedure for solving `?m args =?= v` when `args[:patternVarPrefix]` contains only pairwise distinct free variables. Let `args[:patternVarPrefix] = #[a₁, ..., aₙ]`, and `args[patternVarPrefix:] = #[b₁, ..., bᵢ]`, this procedure first reduces the constraint to ``` ?m a₁ ... aₙ =?= fun x₁ ... xᵢ => v ``` where the left-hand-side is a constant function. Then, it tries to find the longest prefix `#[a₁, ..., aⱼ]` of `#[a₁, ..., aₙ]` such that the following assignment is valid. ``` ?m := fun y₁ ... y‌ⱼ => (fun y_{j+1} ... yₙ x₁ ... xᵢ => v)[a₁/y₁, .., aⱼ/yⱼ] ``` That is, after the longest prefix is found, we solve the contraint as the lhs was a pattern. See the definition of "pattern" above. -/ private partial def processConstApprox (mvar : Expr) (args : Array Expr) (patternVarPrefix : Nat) (v : Expr) : MetaM Bool := do trace[Meta.isDefEq.constApprox] "{mvar} {args} := {v}" let rec defaultCase : MetaM Bool := assignConst mvar args.size v let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← mvarId.getDecl let numArgs := args.size if mvarDecl.numScopeArgs != numArgs && !cfg.constApprox then return false else if patternVarPrefix == 0 then defaultCase else let argsPrefix : Array Expr := args[:patternVarPrefix] let type ← instantiateForall mvarDecl.type argsPrefix let suffixSize := numArgs - argsPrefix.size forallBoundedTelescope type suffixSize fun xs _ => do if xs.size != suffixSize then defaultCase else let some v ← mkLambdaFVarsWithLetDeps xs v | defaultCase let rec go (argsPrefix : Array Expr) (v : Expr) : MetaM Bool := do trace[Meta.isDefEq] "processConstApprox.go {mvar} {argsPrefix} := {v}" let rec cont : MetaM Bool := do if argsPrefix.isEmpty then defaultCase else let some v ← mkLambdaFVarsWithLetDeps #[argsPrefix.back] v | defaultCase go argsPrefix.pop v match (← checkAssignment mvarId argsPrefix v) with | none => cont | some vNew => let some vNew ← mkLambdaFVarsWithLetDeps argsPrefix vNew | cont if argsPrefix.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `vNew` because abstraction using `mkLambdaFVars` may have produced a type incorrect term. See discussion at A2 -/ (isTypeCorrect vNew <&&> checkTypesAndAssign mvar vNew) <||> cont else checkTypesAndAssign mvar vNew <||> cont go argsPrefix v /-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`. It assumes `?m` is unassigned. -/ private partial def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool := withTraceNode `Meta.isDefEq.assign (return m!"{exceptBoolEmoji ·} {mvarApp} := {v}") do let mvar := mvarApp.getAppFn let mvarDecl ← mvar.mvarId!.getDecl let rec process (i : Nat) (args : Array Expr) (v : Expr) := do let cfg ← getConfig let useFOApprox (args : Array Expr) : MetaM Bool := processAssignmentFOApprox mvar args v <||> processConstApprox mvar args i v if h : i < args.size then let arg := args.get ⟨i, h⟩ let arg ← simpAssignmentArg arg let args := args.set ⟨i, h⟩ arg match arg with | Expr.fvar fvarId => if args[0:i].any fun prevArg => prevArg == arg then useFOApprox args else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then useFOApprox args else process (i+1) args v | _ => useFOApprox args else let v ← instantiateMVars v -- enforce A4 if v.getAppFn == mvar then -- using A6 useFOApprox args else let mvarId := mvar.mvarId! match (← checkAssignment mvarId args v) with | none => useFOApprox args | some v => do trace[Meta.isDefEq.assign.beforeMkLambda] "{mvar} {args} := {v}" let some v ← mkLambdaFVarsWithLetDeps args v | return false if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced a type incorrect term. See discussion at A2 -/ if (← isTypeCorrect v) then checkTypesAndAssign mvar v else trace[Meta.isDefEq.assign.typeError] "{mvar} := {v}" useFOApprox args else checkTypesAndAssign mvar v process 0 mvarApp.getAppArgs v /-- Similar to processAssignment, but if it fails, compute v's whnf and try again. This helps to solve constraints such as `?m =?= { α := ?m, ... }.α` Note this is not perfect solution since we still fail occurs check for constraints such as ```lean ?m =?= List { α := ?m, β := Nat }.β ``` -/ private def processAssignment' (mvarApp : Expr) (v : Expr) : MetaM Bool := do if (← processAssignment mvarApp v) then return true else let vNew ← whnf v if vNew != v then if mvarApp == vNew then return true else processAssignment mvarApp vNew else return false private def isDeltaCandidate? (t : Expr) : MetaM (Option ConstantInfo) := do match t.getAppFn with | Expr.const c _ => match (← getConst? c) with | r@(some info) => if info.hasValue then return r else return none | _ => return none | _ => pure none /-- Auxiliary method for isDefEqDelta -/ private def isListLevelDefEq (us vs : List Level) : MetaM LBool := toLBoolM <| isListLevelDefEqAux us vs /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeft] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeftRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`. Auxiliary method for isDefEqDelta -/ private def tryHeuristic (t s : Expr) : MetaM Bool := do let mut t := t let mut s := s let tFn := t.getAppFn let sFn := s.getAppFn let info ← getConstInfo tFn.constName! /- We only use the heuristic when `f` is a regular definition or an auxiliary `match` application. That is, it is not marked an abbreviation (e.g., a user-facing projection) or as opaque (e.g., proof). We check whether terms contain metavariables to make sure we can solve constraints such as `S.proj ?x =?= S.proj t` without performing delta-reduction. That is, we are assuming the heuristic implemented by this method is seldom effective when `t` and `s` do not have metavariables, are not structurally equal, and `f` is an abbreviation. On the other hand, by unfolding `f`, we often produce smaller terms. Recall that auxiliary `match` definitions are marked as abbreviations, but we must use the heuristic on them since they will not be unfolded when smartUnfolding is turned on. The abbreviation annotation in this case is used to help the kernel type checker. -/ unless info.hints.isRegular || isMatcherCore (← getEnv) tFn.constName! do unless t.hasExprMVar || s.hasExprMVar do return false withTraceNode `Meta.isDefEq.delta (return m!"{exceptBoolEmoji ·} {t} =?= {s}") do /- We process arguments before universe levels to reduce a source of brittleness in the TC procedure. In the TC procedure, we can solve problems containing metavariables. If the TC procedure tries to assign one of these metavariables, it interrupts the search using a "stuck" exception. The elaborator catches it, and "interprets" it as "we should try again later". Now suppose we have a TC problem, and there are two "local" candidate instances we can try: "bad" and "good". The "bad" candidate is stuck because of a universe metavariable in the TC problem. If we try "bad" first, the TC procedure is interrupted. Moreover, if we have ignored the exception, "bad" would fail anyway trying to assign two different free variables `α =?= β`. Example: `Preorder.{?u} α =?= Preorder.{?v} β`, where `?u` and `?v` are universe metavariables that were not created by the TC procedure. The key issue here is that we have an `isDefEq t s` invocation that is interrupted by the "stuck" exception, but it would have failed anyway if we had continued processing it. By solving the arguments first, we make the example above fail without throwing the "stuck" exception. TODO: instead of throwing an exception as soon as we get stuck, we should just set a flag. Then the entry-point for `isDefEq` checks the flag before returning `true`. -/ checkpointDefEq do isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels! /-- Auxiliary method for isDefEqDelta -/ private abbrev unfold (e : Expr) (failK : MetaM α) (successK : Expr → MetaM α) : MetaM α := do match (← unfoldDefinition? e) with | some e => successK e | none => failK /-- Auxiliary method for isDefEqDelta -/ private def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := do match t, s with | Expr.const _ ls₁, Expr.const _ ls₂ => isListLevelDefEq ls₁ ls₂ | Expr.app _ _, Expr.app _ _ => if (← tryHeuristic t s) then pure LBool.true else unfold t (unfold s (pure LBool.undef) (fun s => isDefEqRight fn t s)) (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s)) | _, _ => pure LBool.false private def sameHeadSymbol (t s : Expr) : Bool := match t.getAppFn, s.getAppFn with | Expr.const c₁ _, Expr.const c₂ _ => c₁ == c₂ | _, _ => false /-- - If headSymbol (unfold t) == headSymbol s, then unfold t - If headSymbol (unfold s) == headSymbol t, then unfold s - Otherwise unfold t and s if possible. Auxiliary method for isDefEqDelta -/ private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := unfold t (unfold s (pure LBool.undef) -- `t` and `s` failed to be unfolded (fun s => isDefEqRight sInfo.name t s)) (fun tNew => if sameHeadSymbol tNew s then isDefEqLeft tInfo.name tNew s else unfold s (isDefEqLeft tInfo.name tNew s) (fun sNew => if sameHeadSymbol t sNew then isDefEqRight sInfo.name t sNew else isDefEqLeftRight tInfo.name tNew sNew)) /-- If `t` and `s` do not contain metavariables, then use kernel definitional equality heuristics. Otherwise, use `unfoldComparingHeadsDefEq`. Auxiliary method for isDefEqDelta -/ private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := if !t.hasExprMVar && !s.hasExprMVar then /- If `t` and `s` do not contain metavariables, we simulate strategy used in the kernel. -/ if tInfo.hints.lt sInfo.hints then unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if sInfo.hints.lt tInfo.hints then unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldComparingHeadsDefEq tInfo sInfo t s else unfoldComparingHeadsDefEq tInfo sInfo t s /-- When `TransparencyMode` is set to `default` or `all`. If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s` If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)` Otherwise, use `unfoldDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do if (← shouldReduceReducibleOnly) then unfoldDefEq tInfo sInfo t s else let tReducible ← isReducible tInfo.name let sReducible ← isReducible sInfo.name if tReducible && !sReducible then unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if !tReducible && sReducible then unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldDefEq tInfo sInfo t s /-- This is an auxiliary method for isDefEqDelta. If `t` is a (non-class) projection function application and `s` is not ==> `isDefEqRight t (unfold s)` If `s` is a (non-class) projection function application and `t` is not ==> `isDefEqRight (unfold t) s` Otherwise, use `unfoldReducibeDefEq` One motivation for the heuristic above is unification problems such as ``` id (?m.1) =?= (a, b).1 ``` We want to reduce the lhs instead of the rhs, and eventually assign `?m := (a, b)`. Another motivation for the heuristic above is unification problems such as ``` List.length (a :: as) =?= HAdd.hAdd (List.length as) 1 ``` However, for class projections, we also unpack them and check whether the result function is the one on the other side. This is relevant for unification problems such as ``` Foo.pow x 256 =?= Pow.pow x 256 ``` where the the `Pow` instance is wrapping `Foo.pow` See issue #1419 for the complete example. -/ private partial def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do let tProjInfo? ← getProjectionFnInfo? tInfo.name let sProjInfo? ← getProjectionFnInfo? sInfo.name if let some tNew ← packedInstanceOf? tProjInfo? t sInfo.name then isDefEqLeft tInfo.name tNew s else if let some sNew ← packedInstanceOf? sProjInfo? s tInfo.name then isDefEqRight sInfo.name t sNew else match tProjInfo?, sProjInfo? with | some _, none => unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s | none, some _ => unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s | _, _ => unfoldReducibeDefEq tInfo sInfo t s where packedInstanceOf? (projInfo? : Option ProjectionFunctionInfo) (e : Expr) (declName : Name) : MetaM (Option Expr) := do let some { fromClass := true, .. } := projInfo? | return none -- It is not a class projection let some e ← unfoldDefinition? e | return none let e ← whnfCore e if e.isAppOf declName then return some e let .const name _ := e.getAppFn | return none -- Keep going if new `e` is also a class projection packedInstanceOf? (← getProjectionFnInfo? name) e declName /-- isDefEq by lazy delta reduction. This method implements many different heuristics: 1- If only `t` can be unfolded => then unfold `t` and continue 2- If only `s` can be unfolded => then unfold `s` and continue 3- If `t` and `s` can be unfolded and they have the same head symbol, then a) First try to solve unification by unifying arguments. b) If it fails, unfold both and continue. Implemented by `unfoldBothDefEq` 4- If `t` is a projection function application and `s` is not => then unfold `s` and continue. 5- If `s` is a projection function application and `t` is not => then unfold `t` and continue. Remark: 4&5 are implemented by `unfoldNonProjFnDefEq` 6- If `t` is reducible and `s` is not => then unfold `t` and continue. 7- If `s` is reducible and `t` is not => then unfold `s` and continue Remark: 6&7 are implemented by `unfoldReducibeDefEq` 8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel. Implemented by `unfoldDefEq` 9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue. 10- If `headSymbol (unfold s) == headSymbol t`, then unfold s 11- Otherwise, unfold `t` and `s` and continue. Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/ private def isDefEqDelta (t s : Expr) : MetaM LBool := do let tInfo? ← isDeltaCandidate? t let sInfo? ← isDeltaCandidate? s match tInfo?, sInfo? with | none, none => pure LBool.undef | some tInfo, none => unfold t (pure LBool.undef) fun t => isDefEqLeft tInfo.name t s | none, some sInfo => unfold s (pure LBool.undef) fun s => isDefEqRight sInfo.name t s | some tInfo, some sInfo => if tInfo.name == sInfo.name then unfoldBothDefEq tInfo.name t s else unfoldNonProjFnDefEq tInfo sInfo t s private def isAssigned : Expr → MetaM Bool | Expr.mvar mvarId => mvarId.isAssigned | _ => pure false private def expandDelayedAssigned? (t : Expr) : MetaM (Option Expr) := do let tFn := t.getAppFn if !tFn.isMVar then return none let some { fvars, mvarIdPending } ← getDelayedMVarAssignment? tFn.mvarId! | return none let tNew ← instantiateMVars t if tNew != t then return some tNew /- If `assignSyntheticOpaque` is true, we must follow the delayed assignment. Recall a delayed assignment `mvarId [xs] := mvarIdPending` is morally an assingment `mvarId := fun xs => mvarIdPending` where `xs` are free variables in the scope of `mvarIdPending`, but not in the scope of `mvarId`. We can only perform the abstraction when `mvarIdPending` has been fully synthesized. That is, `instantiateMVars (mkMVar mvarIdPending)` does not contain any expression metavariables. Here we just consume `fvar.size` arguments. That is, if `t` is of the form `mvarId as bs` where `as.size == fvars.size`, we return `mvarIdPending bs`. TODO: improve this transformation. Here is a possible improvement. Assume `t` is of the form `?m as` where `as` represent the arguments, and we are trying to solve `?m as =?= s[as]` where `s[as]` represents a term containing occurrences of `as`. We could try to compute the solution as usual `?m := fun ys => s[as/ys]` We also have the delayed assignment `?m [xs] := ?n`, where `xs` are variables in the scope of `?n`, and this delayed assignment is morally `?m := fun xs => ?n`. Thus, we can reduce `?m as =?= s[as]` to `?n =?= s[as/xs]`, and solve it using `?n`'s local context. This is more precise than simplying droping the arguments `as`. -/ unless (← getConfig).assignSyntheticOpaque do return none let tArgs := t.getAppArgs if tArgs.size < fvars.size then return none return some (mkAppRange (mkMVar mvarIdPending) fvars.size tArgs.size tArgs) private def isAssignable : Expr → MetaM Bool | Expr.mvar mvarId => do let b ← mvarId.isReadOnlyOrSyntheticOpaque; pure (!b) | _ => pure false private def etaEq (t s : Expr) : Bool := match t.etaExpanded? with | some t => t == s | none => false /-- Helper method for implementing `isDefEqProofIrrel`. Execute `k` with a transparency setting that is at least as strong as `.default`. This is important for modules that use the `.reducible` setting (e.g., `simp`, `rw`, etc). We added this feature to address issue #1302. ```lean @[simp] theorem get_cons_zero {as : List α} : (a :: as).get ⟨0, Nat.zero_lt_succ _⟩ = a := rfl example (a b c : α) : [a, b, c].get ⟨0, by simp⟩ = a := by simp ``` In the example above `simp` fails to use `get_cons_zero` because it fails to establish that the proof objects are definitionally equal using proof irrelevance. In this example, the propositions are ```lean 0 < Nat.succ (List.length [b, c]) =?= 0 < Nat.succ (Nat.succ (Nat.succ 0)) ``` So, unless we can unfold `List.length`, it fails. Remark: if this becomes a performance bottleneck, we should add a flag to control when it is used. Then, we can enable the flag only when applying `simp` and `rw` theorems. -/ private def withProofIrrelTransparency (k : MetaM α) : MetaM α := withAtLeastTransparency .default k private def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do if (← getConfig).proofIrrelevance then match (← isProofQuick t) with | LBool.false => pure LBool.undef | LBool.true => let tType ← inferType t let sType ← inferType s toLBoolM <| withProofIrrelTransparency <| Meta.isExprDefEqAux tType sType | LBool.undef => let tType ← inferType t if (← isProp tType) then let sType ← inferType s toLBoolM <| withProofIrrelTransparency <| Meta.isExprDefEqAux tType sType else pure LBool.undef else pure LBool.undef /-- Try to solve constraint of the form `?m args₁ =?= ?m args₂`. - First try to unify `args₁` and `args₂`, and return true if successful - Otherwise, try to assign `?m` to a constant function of the form `fun x_1 ... x_n => ?n` where `?n` is a fresh metavariable. See `assignConst`. -/ private def isDefEqMVarSelf (mvar : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do if args₁.size != args₂.size then pure false else if (← isDefEqArgs mvar args₁ args₂) then pure true else if !(← isAssignable mvar) then pure false else let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← mvarId.getDecl if mvarDecl.numScopeArgs == args₁.size || cfg.constApprox then let type ← inferType (mkAppN mvar args₁) let auxMVar ← mkAuxMVar mvarDecl.lctx mvarDecl.localInstances type assignConst mvar args₁.size auxMVar else pure false /-- Remove unnecessary let-decls -/ private def consumeLet : Expr → Expr | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b | e => e mutual private partial def isDefEqQuick (t s : Expr) : MetaM LBool := let t := consumeLet t let s := consumeLet s match t, s with | .lit l₁, .lit l₂ => return (l₁ == l₂).toLBool | .sort u, .sort v => toLBoolM <| isLevelDefEqAux u v | .lam .., .lam .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s | .forallE .., .forallE .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s -- | Expr.mdata _ t _, s => isDefEqQuick t s -- | t, Expr.mdata _ s _ => isDefEqQuick t s | .fvar fvarId₁, .fvar fvarId₂ => do if (← fvarId₁.isLetVar <||> fvarId₂.isLetVar) then return LBool.undef else if fvarId₁ == fvarId₂ then return LBool.true else isDefEqProofIrrel t s | t, s => isDefEqQuickOther t s private partial def isDefEqQuickOther (t s : Expr) : MetaM LBool := do /- We used to eagerly consume all metadata (see commented lines at `isDefEqQuick`), but it was unnecessarily removing helpful annotations for the pretty-printer. For example, consider the following example. ``` constant p : Nat → Prop constant q : Nat → Prop theorem p_of_q : q x → p x := sorry theorem pletfun : p (let_fun x := 0; x + 1) := by -- ⊢ p (let_fun x := 0; x + 1) apply p_of_q -- If we eagerly consume all metadata, the let_fun annotation is lost during `isDefEq` -- ⊢ q ((fun x => x + 1) 0) sorry ``` However, pattern annotations (`inaccessible?` and `patternWithRef?`) must be consumed. The frontend relies on the fact that is must not be propagated by `isDefEq`. Thus, we consume it here. This is a bit hackish since it is very adhoc. We might other annotations in the future that we should not preserve. Perhaps, we should mark the annotation we do want to preserve ones (e.g., hints for the pretty printer), and consume all other -/ if let some t := patternAnnotation? t then isDefEqQuick t s else if let some s := patternAnnotation? s then isDefEqQuick t s else if t == s then return LBool.true else if etaEq t s || etaEq s t then return LBool.true -- t =?= (fun xs => t xs) else let tFn := t.getAppFn let sFn := s.getAppFn if !tFn.isMVar && !sFn.isMVar then return LBool.undef else if (← isAssigned tFn) then let t ← instantiateMVars t isDefEqQuick t s else if (← isAssigned sFn) then let s ← instantiateMVars s isDefEqQuick t s else if let some t ← expandDelayedAssigned? t then isDefEqQuick t s else if let some s ← expandDelayedAssigned? s then isDefEqQuick t s /- Remark: we do not eagerly synthesize synthetic metavariables when the constraint is not stuck. Reason: we may fail to solve a constraint of the form `?x =?= A` when the synthesized instance is not definitionally equal to `A`. We left the code here as a remainder of this issue. -/ -- else if (← isSynthetic tFn <&&> trySynthPending tFn) then -- let t ← instantiateMVars t -- isDefEqQuick t s -- else if (← isSynthetic sFn <&&> trySynthPending sFn) then -- let s ← instantiateMVars s -- isDefEqQuick t s else if tFn.isMVar && sFn.isMVar && tFn == sFn then Bool.toLBool <$> isDefEqMVarSelf tFn t.getAppArgs s.getAppArgs else let tAssign? ← isAssignable tFn let sAssign? ← isAssignable sFn let assignableMsg (b : Bool) := if b then "[assignable]" else "[nonassignable]" trace[Meta.isDefEq] "{t} {assignableMsg tAssign?} =?= {s} {assignableMsg sAssign?}" if tAssign? && !sAssign? then toLBoolM <| processAssignment' t s else if !tAssign? && sAssign? then toLBoolM <| processAssignment' s t else if !tAssign? && !sAssign? then /- Trying to unify `?m ... =?= ?n ...` where both `?m` and `?n` cannot be assigned. This can happen when both of them are `syntheticOpaque` (e.g., metavars associated with tactics), or a metavariables from previous levels. If their types are propositions and are defeq, we can solve the constraint by proof irrelevance. This test is important for fixing a performance problem exposed by test `isDefEqPerfIssue.lean`. Without the proof irrelevance check, this example timeouts. Recall that: 1- The elaborator has a pending list of things to do: Tactics, TC, etc. 2- The elaborator only tries tactics after it tried to solve pending TC problems, delayed elaboratio, etc. The motivation: avoid unassigned metavariables in goals. 3- Each pending tactic goal is represented as a metavariable. It is marked as `synthethicOpaque` to make it clear that it should not be assigned by unification. 4- When we abstract a term containing metavariables, we often create new metavariables. Example: when abstracting `x` at `f ?m`, we obtain `fun x => f (?m' x)`. If `x` is in the scope of `?m`. If `?m` is `syntheticOpaque`, so is `?m'`, and we also have the delayed assignment `?m' x := ?m` 5- When checking a metavariable assignment, `?m := v` we check whether the type of `?m` is defeq to type of `v` with default reducibility setting. Now consider the following fragment ``` let a' := g 100 a ⟨i, h⟩ ⟨i - Nat.zero.succ, by exact Nat.lt_of_le_of_lt (Nat.pred_le i) h⟩ have : a'.size - i >= 0 := sorry f (i+1) a' ``` The elaborator tries to synthesize the instance `OfNat Nat 1` before we generate the tactic proof for `by exact ...` (remark 2). The solution `instOfNatNat 1` is synthesized. Let `m? a i h a' this` be the "hole" associated with the pending instance. Then, `isDefEq` tries to assign `m? a i h a' this := instOfNatNat 1` which is reduced to `m? := mkLambdaFVars #[a, i, h, a', this] (instOfNatNat 1)`. Note that, this is an abstraction step (remark 4), and the type contains the `syntheticOpaque` metavariable for the pending tactic proof (remark 3). Thus, a new `syntheticOpaque` opaque is created (remark 4). Then, `isDefEq` must check whether the type of `?m` is defeq to `mkLambdaFVars #[a, i, h, a', this] (instOfNatNat 1)` (remark 5). The two types are almost identical, but they contain different `syntheticOpaque` in the subterm corresponding to the `by exact ...` tactic proof. Without the following proof irrelevance test, the check will fail, and `isDefEq` timeouts unfolding `g` and its dependencies. Note that this test does not prevent a similar performance problem in a usecase where the tactic is used to synthesize a term that is not a proof. TODO: add better support for checking the delayed assignments. This is not high priority because tactics are usually only used for synthesizing proofs. -/ match (← isDefEqProofIrrel t s) with | LBool.true => return LBool.true | LBool.false => return LBool.false | _ => if tFn.isMVar || sFn.isMVar then let ctx ← read if ctx.config.isDefEqStuckEx then do trace[Meta.isDefEq.stuck] "{t} =?= {s}" Meta.throwIsDefEqStuck else return LBool.false else return LBool.undef else isDefEqQuickMVarMVar t s /-- Both `t` and `s` are terms of the form `?m ...` -/ private partial def isDefEqQuickMVarMVar (t s : Expr) : MetaM LBool := do if s.isMVar && !t.isMVar then /- Solve `?m t =?= ?n` by trying first `?n := ?m t`. Reason: this assignment is precise. -/ if (← checkpointDefEq (processAssignment s t)) then return LBool.true else toLBoolM <| processAssignment t s else if (← checkpointDefEq (processAssignment t s)) then return LBool.true else toLBoolM <| processAssignment s t end @[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do let status ← x match status with | LBool.true => pure true | LBool.false => pure false | LBool.undef => k @[specialize] private def unstuckMVar (e : Expr) (successK : Expr → MetaM Bool) (failK : MetaM Bool): MetaM Bool := do match (← getStuckMVar? e) with | some mvarId => trace[Meta.isDefEq.stuckMVar] "found stuck MVar {mkMVar mvarId} : {← inferType (mkMVar mvarId)}" if (← Meta.synthPending mvarId) then let e ← instantiateMVars e successK e else failK | none => failK private def isDefEqOnFailure (t s : Expr) : MetaM Bool := do trace[Meta.isDefEq.onFailure] "{t} =?= {s}" unstuckMVar t (fun t => Meta.isExprDefEqAux t s) <| unstuckMVar s (fun s => Meta.isExprDefEqAux t s) <| tryUnificationHints t s <||> tryUnificationHints s t private def isDefEqProj : Expr → Expr → MetaM Bool | Expr.proj _ i t, Expr.proj _ j s => pure (i == j) <&&> Meta.isExprDefEqAux t s | Expr.proj structName 0 s, v => isDefEqSingleton structName s v | v, Expr.proj structName 0 s => isDefEqSingleton structName s v | _, _ => pure false where /-- If `structName` is a structure with a single field and `(?m ...).1 =?= v`, then solve contraint as `?m ... =?= ⟨v⟩` -/ isDefEqSingleton (structName : Name) (s : Expr) (v : Expr) : MetaM Bool := do let ctorVal := getStructureCtor (← getEnv) structName if ctorVal.numFields != 1 then return false -- It is not a structure with a single field. let sType ← whnf (← inferType s) let sTypeFn := sType.getAppFn if !sTypeFn.isConstOf structName then return false let s ← whnf s let sFn := s.getAppFn if !sFn.isMVar then return false if (← isAssignable sFn) then let ctorApp := mkApp (mkAppN (mkConst ctorVal.name sTypeFn.constLevels!) sType.getAppArgs) v processAssignment' s ctorApp else return false /-- Given applications `t` and `s` that are in WHNF (modulo the current transparency setting), check whether they are definitionally equal or not. -/ private def isDefEqApp (t s : Expr) : MetaM Bool := do let tFn := t.getAppFn let sFn := s.getAppFn if tFn.isConst && sFn.isConst && tFn.constName! == sFn.constName! then /- See comment at `tryHeuristic` explaining why we processe arguments before universe levels. -/ if (← checkpointDefEq (isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!)) then return true else isDefEqOnFailure t s else if (← checkpointDefEq (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) then return true else isDefEqOnFailure t s /-- Return `true` if the types of the given expressions is an inductive datatype with an inductive datatype with a single constructor with no fields. -/ private def isDefEqUnitLike (t : Expr) (s : Expr) : MetaM Bool := do let tType ← whnf (← inferType t) matchConstStruct tType.getAppFn (fun _ => return false) fun _ _ ctorVal => do if ctorVal.numFields != 0 then return false else if (← useEtaStruct ctorVal.induct) then Meta.isExprDefEqAux tType (← inferType s) else return false /-- The `whnf` procedure has support for unfolding class projections when the transparency mode is set to `.instances`. This method ensures the behavior of `whnf` and `isDefEq` is consistent in this transparency mode. -/ private def isDefEqProjInst (t : Expr) (s : Expr) : MetaM LBool := do if (← getTransparency) != .instances then return .undef let t? ← unfoldProjInstWhenIntances? t let s? ← unfoldProjInstWhenIntances? s if t?.isSome || s?.isSome then toLBoolM <| Meta.isExprDefEqAux (t?.getD t) (s?.getD s) else return .undef private def isExprDefEqExpensive (t : Expr) (s : Expr) : MetaM Bool := do if (← (isDefEqEta t s <||> isDefEqEta s t)) then return true -- TODO: investigate whether this is the place for putting this check if (← (isDefEqEtaStruct t s <||> isDefEqEtaStruct s t)) then return true if (← isDefEqProj t s) then return true let t' ← whnfCore t let s' ← whnfCore s if t != t' || s != s' then Meta.isExprDefEqAux t' s' else whenUndefDo (isDefEqNative t s) do whenUndefDo (isDefEqNat t s) do whenUndefDo (isDefEqOffset t s) do whenUndefDo (isDefEqDelta t s) do if t.isConst && s.isConst then if t.constName! == s.constName! then isListLevelDefEqAux t.constLevels! s.constLevels! else return false else if (← pure t.isApp <&&> pure s.isApp <&&> isDefEqApp t s) then return true else whenUndefDo (isDefEqProjInst t s) do whenUndefDo (isDefEqStringLit t s) do if (← isDefEqUnitLike t s) then return true else isDefEqOnFailure t s private def mkCacheKey (t : Expr) (s : Expr) : Expr × Expr := if Expr.quickLt t s then (t, s) else (s, t) private def getCachedResult (key : Expr × Expr) : MetaM LBool := do match (← get).cache.defEq.find? key with | some val => return val.toLBool | none => return .undef private def cacheResult (key : Expr × Expr) (result : Bool) : MetaM Unit := do modifyDefEqCache fun c => c.insert key result @[export lean_is_expr_def_eq] partial def isExprDefEqAuxImpl (t : Expr) (s : Expr) : MetaM Bool := withIncRecDepth do withTraceNode `Meta.isDefEq (return m!"{exceptBoolEmoji ·} {t} =?= {s}") do checkMaxHeartbeats "isDefEq" whenUndefDo (isDefEqQuick t s) do whenUndefDo (isDefEqProofIrrel t s) do -- We perform `whnfCore` again with `deltaAtProj := true` at `isExprDefEqExpensive` after `isDefEqProj` let t' ← whnfCore t (deltaAtProj := false) let s' ← whnfCore s (deltaAtProj := false) if t != t' || s != s' then isExprDefEqAuxImpl t' s' else /- TODO: check whether the following `instantiateMVar`s are expensive or not in practice. Lean 3 does not use them, and may miss caching opportunities since it is not safe to cache when `t` and `s` may contain mvars. The unit test `tryHeuristicPerfIssue2.lean` cannot be solved without these two `instantiateMVar`s. If it becomes a problem, we may use store a flag in the context indicating whether we have already used `instantiateMVar` in outer invocations or not. It is not perfect (we may assign mvars in nested calls), but it should work well enough in practice, and prevent repeated traversals in nested calls. -/ let t ← instantiateMVars t let s ← instantiateMVars s let numPostponed ← getNumPostponed let k := mkCacheKey t s match (← getCachedResult k) with | .true => trace[Meta.isDefEq.cache] "cache hit 'true' for {t} =?= {s}" return true | .false => trace[Meta.isDefEq.cache] "cache hit 'false' for {t} =?= {s}" return false | .undef => let result ← isExprDefEqExpensive t s if numPostponed == (← getNumPostponed) then trace[Meta.isDefEq.cache] "cache {result} for {t} =?= {s}" cacheResult k result return result builtin_initialize registerTraceClass `Meta.isDefEq registerTraceClass `Meta.isDefEq.foApprox registerTraceClass `Meta.isDefEq.constApprox registerTraceClass `Meta.isDefEq.delta (inherited := true) registerTraceClass `Meta.isDefEq.assign registerTraceClass `Meta.isDefEq.assign.checkTypes (inherited := true) registerTraceClass `Meta.isDefEq.eta.struct end Lean.Meta
1a3651b90fbb34ff4f6febd330c5a3926d41e254
80746c6dba6a866de5431094bf9f8f841b043d77
/src/field_theory/splitting_field.lean
ca57a5426f2ef1b7cc49d062a407c004a6781610
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
7,819
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Definition of splitting fields, and definition of homomorphism into any field that splits -/ import ring_theory.adjoin_root ring_theory.unique_factorization_domain universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace polynomial noncomputable theory local attribute [instance, priority 0] classical.prop_decidable variables [discrete_field α] [discrete_field β] [discrete_field γ] open polynomial adjoin_root section splits variables (i : α → β) [is_field_hom i] /-- a polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1 -/ def splits (f : polynomial α) : Prop := f = 0 ∨ ∀ {g : polynomial β}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : polynomial α) := or.inl rfl @[simp] lemma splits_C (a : α) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 α _ _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((is_add_group_hom.injective_iff i).1 (is_field_hom.injective i) _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (classical.not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tautology)) lemma splits_of_degree_eq_one {f : polynomial α} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : polynomial α} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_mul {f g : polynomial α} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_domain.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : polynomial α} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_left _ _))⟩ lemma splits_map_iff (j : β → γ) [is_field_hom j] {f : polynomial α} : splits j (f.map i) ↔ splits (λ x, j (i x)) f := by simp [splits, polynomial.map_map] lemma exists_root_of_splits {f : polynomial α} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := is_noetherian_ring.exists_irreducible_factor principal_ideal_domain.is_noetherian_ring (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (by rw [ne.def, map_eq_zero]; exact hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : polynomial α} : splits i f → ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := suffices splits id (f.map i) → ∃ s : multiset β, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, is_noetherian_ring.irreducible_induction_on principal_ideal_domain.is_noetherian_ring (f.map i) (λ _, ⟨{37}, by simp [is_ring_hom.map_zero i]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero (nonzero_of_irreducible hp) hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 :: s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, domain.mul_right_inj hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit (nonzero_of_irreducible hp), mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 (nonzero_of_irreducible hp)), one_mul], end⟩) section UFD local attribute [instance, priority 0] principal_ideal_domain.to_unique_factorization_domain local infix ` ~ᵤ ` : 50 := associated open unique_factorization_domain associates lemma splits_of_exists_multiset {f : polynomial α} {s : multiset β} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (factors (f.map i)) (s.map (λ a : β, (X : polynomial β) - C a)) := unique (λ p hp, irreducible_factors (mt (map_eq_zero i).1 hf0) _ hp) (λ p, by simp [@eq_comm _ _ p, -sub_eq_add_neg, irreducible_of_degree_eq_one (degree_X_sub_C _)] {contextual := tt}) (associated.symm $ calc _ ~ᵤ f.map i : ⟨units.map C (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (mt (map_eq_zero i).1 hf0))), by conv_rhs {rw [hs, ← leading_coeff_map i, mul_comm]}; refl⟩ ... ~ᵤ _ : associated.symm (unique_factorization_domain.factors_prod (by simpa using hf0))), let ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : polynomial α} : splits id f → splits i f := unique_factorization_domain.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 (irreducible_of_prime hp) (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : polynomial α} : splits i f ↔ ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : β → γ) [is_field_hom j] {f : polynomial α} (h : splits i f) : splits (λ x, j (i x)) f := begin change i with (λ x, id (i x)) at h, rw [← splits_map_iff], rw [← splits_map_iff i id] at h, exact splits_of_splits_id _ h end end splits end polynomial
dce894c25c4d911a9bc4618fc24cefa40b67337a
a45212b1526d532e6e83c44ddca6a05795113ddc
/test/tidy.lean
4c46f6d47c7c4563fd483d571c7833d7f99c40ac
[ "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
1,150
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.tidy open tactic namespace tidy.test meta def interactive_simp := `[simp] def tidy_test_0 : ∀ x : unit, x = unit.star := begin success_if_fail { chain [ interactive_simp ] }, intro1, induction x, refl end def tidy_test_1 (a : string): ∀ x : unit, x = unit.star := begin tidy -- intros x, exact dec_trivial end structure A := (z : ℕ) structure B := (a : A) (aa : a.z = 0) structure C := (a : A) (b : B) (ab : a.z = b.a.z) structure D := (a : B) (b : C) (ab : a.a.z = b.a.z) open tactic def d : D := begin tidy, -- /- obviously says -/ fsplit, work_on_goal 0 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { refl } }, work_on_goal 0 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { refl } }, work_on_goal 1 { refl } }, refl end. def f : unit → unit → unit := by tidy -- intros a a_1, cases a_1, cases a, fsplit def g (P Q : Prop) (p : P) (h : P ↔ Q) : Q := by tidy end tidy.test
b9f2164a75fce229197739b7878a5c44499541d4
35960c5b117752aca7e3e7767c0b393e4dbd72a7
/src/exp/subst.lean
54def55ed230a6d3172ffee006980db59dc12253
[ "Apache-2.0" ]
permissive
spl/tts
461dc76b83df8db47e4660d0941dc97e6d4fd7d1
b65298fea68ce47c8ed3ba3dbce71c1a20dd3481
refs/heads/master
1,541,049,198,347
1,537,967,023,000
1,537,967,029,000
119,653,145
1
0
null
null
null
null
UTF-8
Lean
false
false
1,635
lean
import .fv namespace tts ------------------------------------------------------------------ namespace exp ------------------------------------------------------------------ variables {V : Type} -- Type of variable names variables {x y : tagged V} -- Variable names variables {e ex : exp V} -- Expressions variables [decidable_eq V] open occurs /-- Substitute a free variable for an expression in an expression -/ def subst (x : tagged V) (ex : exp V) : exp V → exp V | (var bound y) := var bound y | (var free y) := if x = y then ex else var free y | (app ef ea) := app (subst ef) (subst ea) | (lam v eb) := lam v (subst eb) | (let_ v ed eb) := let_ v (subst ed) (subst eb) @[simp] theorem subst_var_bound : subst x ex (var bound y) = var bound y := rfl @[simp] theorem subst_var_free_eq (h : x = y) : subst x ex (var free y) = ex := by simp [subst, h] @[simp] theorem subst_var_free_ne (h : x ≠ y) : subst x ex (var free y) = var free y := by simp [subst, h] @[simp] theorem subst_app {ef ea : exp V} : subst x ex (app ef ea) = app (subst x ex ef) (subst x ex ea) := rfl @[simp] theorem subst_lam {v} {eb : exp V} : subst x ex (lam v eb) = lam v (subst x ex eb) := rfl @[simp] theorem subst_let_ {v} {ed eb : exp V} : subst x ex (let_ v ed eb) = let_ v (subst x ex ed) (subst x ex eb) := rfl @[simp] theorem subst_fresh (h : x ∉ fv e) : subst x ex e = e := by induction e with o; try {cases o}; try {simp at h}; try {cases h}; simp * end /- namespace -/ exp -------------------------------------------------------- end /- namespace -/ tts --------------------------------------------------------
097cc81ba2aa574140aaa18b839e34cc2b623d0e
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Elab/Definition.lean
eeeccdf36a00c411fe8de34edca6c04c5aae12d1
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,117
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.ShareCommon import Init.Lean.Util.CollectLevelParams import Init.Lean.Util.FoldConsts import Init.Lean.Util.CollectFVars import Init.Lean.Elab.DeclModifiers import Init.Lean.Elab.Binders namespace Lean namespace Elab namespace Command inductive DefKind | «def» | «theorem» | «example» | «opaque» | «abbrev» def DefKind.isTheorem : DefKind → Bool | DefKind.theorem => true | _ => false def DefKind.isDefOrAbbrevOrOpaque : DefKind → Bool | DefKind.def => true | DefKind.opaque => true | DefKind.abbrev => true | _ => false def DefKind.isExample : DefKind → Bool | DefKind.example => true | _ => false structure DefView := (kind : DefKind) (ref : Syntax) (modifiers : Modifiers) (declId : Syntax) (binders : Syntax) (type? : Option Syntax) (val : Syntax) def collectUsedFVars (ref : Syntax) (used : CollectFVars.State) (e : Expr) : TermElabM CollectFVars.State := do e ← Term.instantiateMVars ref e; pure $ collectFVars used e def collectUsedFVarsAtFVars (ref : Syntax) (used : CollectFVars.State) (fvars : Array Expr) : TermElabM CollectFVars.State := fvars.foldlM (fun used fvar => do fvarType ← Term.inferType ref fvar; collectUsedFVars ref used fvarType) used def removeUnused (ref : Syntax) (vars : Array Expr) (xs : Array Expr) (e : Expr) (eType : Expr) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let used : CollectFVars.State := {}; used ← collectUsedFVars ref used eType; used ← collectUsedFVars ref used e; used ← collectUsedFVarsAtFVars ref used xs; localInsts ← Term.getLocalInsts; lctx ← Term.getLCtx; (lctx, localInsts, newVars, _) ← vars.foldrM (fun var (result : LocalContext × LocalInstances × Array Expr × CollectFVars.State) => let (lctx, localInsts, newVars, used) := result; if used.fvarSet.contains var.fvarId! then do varType ← Term.inferType ref var; used ← collectUsedFVars ref used varType; pure (lctx, localInsts, newVars.push var, used) else pure (lctx.erase var.fvarId!, localInsts.erase var.fvarId!, newVars, used)) (lctx, localInsts, #[], used); pure (lctx, localInsts, newVars.reverse) def withUsedWhen {α} (ref : Syntax) (vars : Array Expr) (xs : Array Expr) (e : Expr) (eType : Expr) (cond : Bool) (k : Array Expr → TermElabM α) : TermElabM α := if cond then do (lctx, localInsts, vars) ← removeUnused ref vars xs e eType; Term.withLCtx lctx localInsts $ k vars else k vars def withUsedWhen' {α} (ref : Syntax) (vars : Array Expr) (xs : Array Expr) (e : Expr) (cond : Bool) (k : Array Expr → TermElabM α) : TermElabM α := let dummyExpr := mkSort levelOne; withUsedWhen ref vars xs e dummyExpr cond k def mkDef (view : DefView) (declName : Name) (explictLevelNames : List Name) (vars : Array Expr) (xs : Array Expr) (type : Expr) (val : Expr) : TermElabM (Option Declaration) := do let ref := view.ref; Term.synthesizeSyntheticMVars; val ← Term.ensureHasType view.val type val; Term.synthesizeSyntheticMVars false; type ← Term.instantiateMVars ref type; val ← Term.instantiateMVars view.val val; if view.kind.isExample then pure none else withUsedWhen ref vars xs val type view.kind.isDefOrAbbrevOrOpaque $ fun vars => do type ← Term.mkForall ref xs type; type ← Term.mkForall ref vars type; val ← Term.mkLambda ref xs val; val ← Term.mkLambda ref vars val; type ← Term.levelMVarToParam type; val ← Term.levelMVarToParam val; type ← Term.instantiateMVars ref type; val ← Term.instantiateMVars view.val val; let shareCommonTypeVal : ShareCommonM (Expr × Expr) := do { type ← withShareCommon type; val ← withShareCommon val; pure (type, val) }; let (type, val) := shareCommonTypeVal.run; Term.trace `Elab.definition.body ref $ fun _ => declName ++ " : " ++ type ++ " :=" ++ Format.line ++ val; let usedParams : CollectLevelParams.State := {}; let usedParams := collectLevelParams usedParams type; let usedParams := collectLevelParams usedParams val; let levelParams := sortDeclLevelParams explictLevelNames usedParams.params; match view.kind with | DefKind.theorem => -- TODO theorem elaboration in parallel pure $ some $ Declaration.thmDecl { name := declName, lparams := levelParams, type := type, value := Task.pure val } | DefKind.opaque => pure $ some $ Declaration.opaqueDecl { name := declName, lparams := levelParams, type := type, value := val, isUnsafe := view.modifiers.isUnsafe } | DefKind.abbrev => pure $ some $ Declaration.defnDecl { name := declName, lparams := levelParams, type := type, value := val, hints := ReducibilityHints.abbrev, isUnsafe := view.modifiers.isUnsafe } | DefKind.def => do env ← Term.getEnv; pure $ some $ Declaration.defnDecl { name := declName, lparams := levelParams, type := type, value := val, hints := ReducibilityHints.regular (getMaxHeight env val + 1), isUnsafe := view.modifiers.isUnsafe } | _ => unreachable! def elabDefVal (defVal : Syntax) (expectedType : Expr) : TermElabM Expr := do let kind := defVal.getKind; if kind == `Lean.Parser.Command.declValSimple then -- parser! " := " >> termParser Term.elabTerm (defVal.getArg 1) expectedType else if kind == `Lean.Parser.Command.declValEqns then Term.throwError defVal "equations have not been implemented yet" else Term.throwUnsupportedSyntax def elabDefLike (view : DefView) : CommandElabM Unit := let ref := view.ref; withDeclId view.declId $ fun name => do declName ← mkDeclName view.modifiers name; checkNotAlreadyDeclared ref declName; applyAttributes ref declName view.modifiers.attrs AttributeApplicationTime.beforeElaboration; explictLevelNames ← getLevelNames; decl? ← runTermElabM declName $ fun vars => Term.elabBinders view.binders.getArgs $ fun xs => match view.type? with | some typeStx => do type ← Term.elabType typeStx; Term.synthesizeSyntheticMVars false; type ← Term.instantiateMVars typeStx type; withUsedWhen' ref vars xs type view.kind.isTheorem $ fun vars => do val ← elabDefVal view.val type; mkDef view declName explictLevelNames vars xs type val | none => do { type ← Term.mkFreshTypeMVar view.binders; val ← elabDefVal view.val type; mkDef view declName explictLevelNames vars xs type val }; match decl? with | none => pure () | some decl => do addDecl ref decl; applyAttributes ref declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking; compileDecl ref decl; applyAttributes ref declName view.modifiers.attrs AttributeApplicationTime.afterCompilation @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.definition; pure () end Command end Elab end Lean
909effd35582a1681041e2b08fb739bdee3bc7b3
2ee768fce4d0783536570385ee340d97e2411436
/src/u_prop.lean
5e4703e8c7cf0a007c1cd0901acd847b40846c96
[]
no_license
agjftucker/exists-unique
835cf0c0ec622d49dbceb84be37db62e6ab8a6d0
1fba6035a08347f424c765d8a1c56b1a15c8abbe
refs/heads/master
1,683,445,592,336
1,622,649,822,000
1,622,649,822,000
309,485,697
2
0
null
null
null
null
UTF-8
Lean
false
false
3,554
lean
import u_def v_prop q_prop local prefix `𝒫`:100 := fun {α : Type} (s : finset α), {t // t ≤ s} variables {𝒩 : Type} [decidable_eq 𝒩] {T : with_top ℝ} variables {ℋ : well_behaved_soln 𝒩 T} {ℰ : equity_function 𝒩 T} lemma U_empty_eq_univ : ∀ t, U ℋ ℰ ∅ t = set.univ := V_empty_eq_univ lemma u_match : ∀ A t y, u ℋ ℰ A t y = u ℋ ℰ (φ ℋ ℰ A t y) t y := v_match lemma u_eq_ite (A : finset 𝒩) (t : Tt T) (y : X 𝒩) (i : 𝒩) : u ℋ ℰ A t y i = ite (i ∈ A) (ℋ (fun s x (h : x ∉ U ℋ ℰ A s), u ℋ ℰ A s x i) t y) 0 := v_eq_ite A t y i namespace φp variables {A : finset 𝒩} (p_ : ∀ B < A, ∀ C ≤ B, u ℋ ℰ C ≤ u ℋ ℰ B) include p_ lemma uB_le_uA_of_uC_le_uA : ∀ B ≤ A, (∀ C < B, u ℋ ℰ C ≤ u ℋ ℰ A) → u ℋ ℰ B ≤ u ℋ ℰ A := begin intros B hB h, apply pos_op hB, intros t y hy, rw [←set.mem_compl_iff, set.compl_inter] at hy, cases hy, { rw [v_match B, v_match A], apply p_ _ ⟨(φ ℋ ℰ A t y).prop, hy⟩, apply φ_mono hB, }, { rw v_match B, apply h, exact ⟨(φ ℋ ℰ B t y).prop, hy⟩, }, end lemma uB_le_uA_of_uC_le_uA' : ∀ B, (∀ C < B, C ≤ A → u ℋ ℰ C ≤ u ℋ ℰ A) → B ≤ A → u ℋ ℰ B ≤ u ℋ ℰ A := begin intros B h hB, apply uB_le_uA_of_uC_le_uA p_ B hB, intros C hC, exact h C hC (trans (le_of_lt hC) hB), end variable (A) lemma uB_le_uA : ∀ B ≤ A, u ℋ ℰ B ≤ u ℋ ℰ A := finset.strong_induction (uB_le_uA_of_uC_le_uA' p_) end φp lemma u_mono : ∀ {A B : finset 𝒩}, B ≤ A → u ℋ ℰ B ≤ u ℋ ℰ A := finset.strong_induction φp.uB_le_uA lemma u_eq_sup' {A : finset 𝒩} {t : Tt T} {y : X 𝒩} (h : y ∉ U ℋ ℰ A t) : u ℋ ℰ A t y = A.ssubsets.sup' (ssubsets_nonempty h) (u ℋ ℰ) t y := begin apply le_antisymm, { rw u_match, apply finset.le_sup' (u ℋ ℰ), rw finset.mem_ssubsets, use [(φ ℋ ℰ A t y).prop, h], }, { apply finset.sup'_le _ (u ℋ ℰ), intros B hB y, apply u_mono, rw finset.mem_ssubsets at hB, exact hB.1, }, end lemma hr0 {t : Tt T} {y : X 𝒩} (B : finset 𝒩) : r ℋ ℰ t y B ∅ := begin intros i hi, exfalso, exact hi, end lemma hr1 {t : Tt T} {y : X 𝒩} (C D : finset 𝒩) (hle : D ≤ C) : ∀ B, r ℋ ℰ t y D B → r ℋ ℰ t y C B := begin intros B hr i hi, apply lt_of_lt_of_le (hr i hi), apply ℰ.mono_wrt_debt_valuation, apply u_mono hle, end lemma hr2 {t : Tt T} {y : X 𝒩} (B C D : finset 𝒩) : r ℋ ℰ t y D B → r ℋ ℰ t y D C → r ℋ ℰ t y D (B ⊔ C) := begin intros rDB rDC i hi, cases finset.mem_union.mp hi with hB hC, { exact rDB i hB, }, { exact rDC i hC, }, end instance (t : Tt T) (y : X 𝒩) : support_rel (r ℋ ℰ t y) := { bottom := hr0, sup := hr2, mono := hr1 } instance (A : finset 𝒩) (t : Tt T) (y : X 𝒩) : support_rel (r' ℋ ℰ A t y) := { bottom := fun B, hr0 ↑B, sup := fun B C D, hr2 ↑B ↑C ↑D, mono := fun C D hle B, hr1 ↑C ↑D hle ↑B } lemma q_φ {A : finset 𝒩} {t : Tt T} {y : X 𝒩} : q (r ℋ ℰ t y) (φ ℋ ℰ A t y) := begin rw q_iff (r_iff' A), rw φ_eq, exact si.q_φ, end lemma q_of_mem_U {A : finset 𝒩} {t : Tt T} {y : X 𝒩} : y ∈ U ℋ ℰ A t → q (r ℋ ℰ t y) A := begin intro h, rw ←le_antisymm (φ ℋ ℰ A t y).prop h, apply q_φ, end lemma mem_U_iff_q {A : finset 𝒩} {t : Tt T} {y : X 𝒩} : y ∈ U ℋ ℰ A t ↔ q (r ℋ ℰ t y) A := iff.intro q_of_mem_U mem_U_of_q
1a18b6f9de315871bafcc6bb17e9e768175712c8
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/Reparen.lean
fda36d9e155b8c9ad4eeaeb5609b13426319c544
[ "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,985
lean
/-! Reprint file after removing all parentheses and then passing it through the parenthesizer -/ import Lean.Parser open Lean open Lean.Format def unparenAux (parens body : Syntax) : Syntax := match parens.getHeadInfo, body.getHeadInfo, body.getTailInfo, parens.getTailInfo with | some bi', some bi, some ti, some ti' => (body.setHeadInfo { bi with leading := bi'.leading }).setTailInfo { ti with trailing := ti'.trailing } | _, _, _, _ => body partial def unparen : Syntax → Syntax -- don't remove parentheses in syntax quotations, they might be semantically significant | stx => if stx.isOfKind `Lean.Parser.Term.stxQuot then stx else match_syntax stx with | `(($stx')) => unparenAux stx $ unparen stx' | `(level|($stx')) => unparenAux stx $ unparen stx' | _ => stx.modifyArgs $ Array.map unparen unsafe def main (args : List String) : IO Unit := do let (debug, f) : Bool × String := match args with | [f, "-d"] => (true, f) | [f] => (false, f) | _ => panic! "usage: file [-d]"; env ← mkEmptyEnvironment; stx ← Lean.Parser.parseFile env args.head!; let header := stx.getArg 0; some s ← pure header.reprint | throw $ IO.userError "header reprint failed"; IO.print s; let cmds := (stx.getArg 1).getArgs; cmds.forM $ fun cmd => do let cmd := unparen cmd; (cmd, _) ← (finally (PrettyPrinter.parenthesizeCommand cmd) printTraces).toIO { options := Options.empty.setBool `trace.PrettyPrinter.parenthesize debug } { env := env }; some s ← pure cmd.reprint | throw $ IO.userError "cmd reprint failed"; IO.print s #eval main ["../../../src/Init/Core.lean"] def check (stx : Syntax) : CoreM Unit := do let stx' := unparen stx; stx' ← PrettyPrinter.parenthesizeTerm stx'; f ← PrettyPrinter.formatTerm stx'; IO.println f; when (stx != stx') $ throwError "reparenthesization failed" new_frontend open Lean syntax:80 term " ^~ " term:80 : term syntax:70 term " *~ " term:71 : term #eval check $ Unhygienic.run `(((1 + 2) *~ 3) ^~ 4)
b315cee3c95c5e79d13e5a3dfdccd0a70756b562
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/category_theory/limits/shapes/pullbacks.lean
dd53585f78906368f0aa68c5d401e9f8a049a292
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
20,479
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 data.fintype import category_theory.limits.limits import category_theory.limits.shapes.finite_limits import category_theory.sparse /-! # Pullbacks We define a category `walking_cospan` (resp. `walking_span`), which is the index category for the given data for a pullback (resp. pushout) diagram. Convenience methods `cospan f g` and `span f g` construct functors from the walking (co)span, hitting the given morphisms. We define `pullback f g` and `pushout f g` as limits and colimits of such functors. Typeclasses `has_pullbacks` and `has_pushouts` assert the existence of (co)limits shaped as walking (co)spans. -/ open category_theory namespace category_theory.limits universes v u local attribute [tidy] tactic.case_bash /-- The type of objects for the diagram indexing a pullback. -/ @[derive decidable_eq] inductive walking_cospan : Type v | left | right | one /-- The type of objects for the diagram indexing a pushout. -/ @[derive decidable_eq] inductive walking_span : Type v | zero | left | right instance fintype_walking_cospan : fintype walking_cospan := { elems := [walking_cospan.left, walking_cospan.right, walking_cospan.one].to_finset, complete := λ x, by { cases x; simp } } instance fintype_walking_span : fintype walking_span := { elems := [walking_span.zero, walking_span.left, walking_span.right].to_finset, complete := λ x, by { cases x; simp } } namespace walking_cospan /-- The arrows in a pullback diagram. -/ @[derive _root_.decidable_eq] inductive hom : walking_cospan → walking_cospan → Type v | inl : hom left one | inr : hom right one | id : Π X : walking_cospan.{v}, hom X X open hom instance fintype_walking_cospan_hom (j j' : walking_cospan) : fintype (hom j j') := { elems := walking_cospan.rec_on j (walking_cospan.rec_on j' [hom.id left].to_finset ∅ [inl].to_finset) (walking_cospan.rec_on j' ∅ [hom.id right].to_finset [inr].to_finset) (walking_cospan.rec_on j' ∅ ∅ [hom.id one].to_finset), complete := by tidy } def hom.comp : Π (X Y Z : walking_cospan) (f : hom X Y) (g : hom Y Z), hom X Z | _ _ _ (id _) h := h | _ _ _ inl (id one) := inl | _ _ _ inr (id one) := inr . instance category_struct : category_struct walking_cospan := { hom := hom, id := hom.id, comp := hom.comp, } instance (X Y : walking_cospan) : subsingleton (X ⟶ Y) := by tidy -- We make this a @[simp] lemma later; if we do it now there's a mysterious -- failure in `cospan`, below. lemma hom_id (X : walking_cospan.{v}) : hom.id X = 𝟙 X := rfl /-- The walking_cospan is the index diagram for a pullback. -/ instance : small_category.{v} walking_cospan.{v} := sparse_category instance : fin_category.{v} walking_cospan.{v} := { fintype_hom := walking_cospan.fintype_walking_cospan_hom } end walking_cospan namespace walking_span /-- The arrows in a pushout diagram. -/ @[derive _root_.decidable_eq] inductive hom : walking_span → walking_span → Type v | fst : hom zero left | snd : hom zero right | id : Π X : walking_span.{v}, hom X X open hom instance fintype_walking_span_hom (j j' : walking_span) : fintype (hom j j') := { elems := walking_span.rec_on j (walking_span.rec_on j' [hom.id zero].to_finset [fst].to_finset [snd].to_finset) (walking_span.rec_on j' ∅ [hom.id left].to_finset ∅) (walking_span.rec_on j' ∅ ∅ [hom.id right].to_finset), complete := by tidy } def hom.comp : Π (X Y Z : walking_span) (f : hom X Y) (g : hom Y Z), hom X Z | _ _ _ (id _) h := h | _ _ _ fst (id left) := fst | _ _ _ snd (id right) := snd . instance category_struct : category_struct walking_span := { hom := hom, id := hom.id, comp := hom.comp } instance (X Y : walking_span) : subsingleton (X ⟶ Y) := by tidy -- We make this a @[simp] lemma later; if we do it now there's a mysterious -- failure in `span`, below. lemma hom_id (X : walking_span.{v}) : hom.id X = 𝟙 X := rfl /-- The walking_span is the index diagram for a pushout. -/ instance : small_category.{v} walking_span.{v} := sparse_category instance : fin_category.{v} walking_span.{v} := { fintype_hom := walking_span.fintype_walking_span_hom } end walking_span open walking_span walking_cospan walking_span.hom walking_cospan.hom variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 /-- `cospan f g` is the functor from the walking cospan hitting `f` and `g`. -/ def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan.{v} ⥤ C := { obj := λ x, match x with | left := X | right := Y | one := Z end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, inl := f | _, _, inr := g end } /-- `span f g` is the functor from the walking span hitting `f` and `g`. -/ def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span.{v} ⥤ C := { obj := λ x, match x with | zero := X | left := Y | right := Z end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, fst := f | _, _, snd := g end } @[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.left = X := rfl @[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.left = Y := rfl @[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.right = Y := rfl @[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.right = Z := rfl @[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.one = Z := rfl @[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.zero = X := rfl @[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inl = f := rfl @[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.fst = f := rfl @[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inr = g := rfl @[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.snd = g := rfl lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) : (cospan f g).map (walking_cospan.hom.id w) = 𝟙 _ := rfl lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) : (span f g).map (walking_span.hom.id w) = 𝟙 _ := rfl /-- Every diagram indexing an equalizer is naturally isomorphic (actually, equal) to a `cospan` -/ def diagram_iso_cospan (F : walking_cospan ⥤ C) : F ≅ cospan (F.map inl) (F.map inr) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy /-- Every diagram indexing a coequalizer naturally isomorphic (actually, equal) to a `span` -/ def diagram_iso_span (F : walking_span ⥤ C) : F ≅ span (F.map fst) (F.map snd) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy variables {X Y Z : C} attribute [simp] walking_cospan.hom_id walking_span.hom_id abbreviation pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g) namespace pullback_cone variables {f : X ⟶ Z} {g : Y ⟶ Z} abbreviation fst (t : pullback_cone f g) : t.X ⟶ X := t.π.app left abbreviation snd (t : pullback_cone f g) : t.X ⟶ Y := t.π.app right def mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : pullback_cone f g := { X := W, π := { app := λ j, walking_cospan.cases_on j fst snd (fst ≫ f), naturality' := λ j j' f, by cases f; obviously } } @[simp] lemma mk_π_app_left {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app left = fst := rfl @[simp] lemma mk_π_app_right {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app right = snd := rfl @[simp] lemma mk_π_app_one {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app one = fst ≫ f := rfl @[reassoc] lemma condition (t : pullback_cone f g) : fst t ≫ f = snd t ≫ g := begin erw [t.w inl, ← t.w inr], refl end /-- To check whether a morphism is equalized by the maps of a pullback cone, it suffices to check it for `fst t` and `snd t` -/ lemma equalizer_ext (t : pullback_cone f g) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : ∀ (j : walking_cospan), k ≫ t.π.app j = l ≫ t.π.app j | left := h₀ | right := h₁ | one := calc k ≫ t.π.app one = k ≫ t.π.app left ≫ (cospan f g).map inl : by rw ←t.w ... = l ≫ t.π.app left ≫ (cospan f g).map inl : by rw [←category.assoc, h₀, category.assoc] ... = l ≫ t.π.app one : by rw t.w /-- This is a slightly more convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit.mk (t : pullback_cone f g) (lift : Π (s : cone (cospan f g)), s.X ⟶ t.X) (fac_left : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app left = s.π.app left) (fac_right : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app right = s.π.app right) (uniq : ∀ (s : cone (cospan f g)) (m : s.X ⟶ t.X) (w : ∀ j : walking_cospan, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, walking_cospan.cases_on j (fac_left s) (fac_right s) $ by rw [←t.w inl, ←s.w inl, ←fac_left s, category.assoc], uniq' := uniq } end pullback_cone abbreviation pushout_cocone (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g) namespace pushout_cocone variables {f : X ⟶ Y} {g : X ⟶ Z} abbreviation inl (t : pushout_cocone f g) : Y ⟶ t.X := t.ι.app left abbreviation inr (t : pushout_cocone f g) : Z ⟶ t.X := t.ι.app right def mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : pushout_cocone f g := { X := W, ι := { app := λ j, walking_span.cases_on j (f ≫ inl) inl inr, naturality' := λ j j' f, by cases f; obviously } } @[simp] lemma mk_ι_app_left {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app left = inl := rfl @[simp] lemma mk_ι_app_right {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app right = inr := rfl @[simp] lemma mk_ι_app_zero {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app zero = f ≫ inl := rfl @[reassoc] lemma condition (t : pushout_cocone f g) : f ≫ (inl t) = g ≫ (inr t) := begin erw [t.w fst, ← t.w snd], refl end /-- To check whether a morphism is coequalized by the maps of a pushout cocone, it suffices to check it for `inl t` and `inr t` -/ lemma coequalizer_ext (t : pushout_cocone f g) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : ∀ (j : walking_span), t.ι.app j ≫ k = t.ι.app j ≫ l | left := h₀ | right := h₁ | zero := calc t.ι.app zero ≫ k = ((span f g).map fst ≫ t.ι.app left) ≫ k : by rw ←t.w ... = ((span f g).map fst ≫ t.ι.app left) ≫ l : by rw [category.assoc, h₀, ←category.assoc] ... = t.ι.app zero ≫ l : by rw t.w /-- This is a slightly more convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit.mk (t : pushout_cocone f g) (desc : Π (s : cocone (span f g)), t.X ⟶ s.X) (fac_left : ∀ (s : cocone (span f g)), t.ι.app left ≫ desc s = s.ι.app left) (fac_right : ∀ (s : cocone (span f g)), t.ι.app right ≫ desc s = s.ι.app right) (uniq : ∀ (s : cocone (span f g)) (m : t.X ⟶ s.X) (w : ∀ j : walking_span, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, walking_span.cases_on j (by rw [←s.w fst, ←t.w fst, category.assoc, fac_left s]) (fac_left s) (fac_right s), uniq' := uniq } end pushout_cocone def cone.of_pullback_cone {F : walking_cospan.{v} ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy), naturality' := λ j j' g, begin cases j; cases j'; cases g; dsimp; simp, exact (t.w inl).symm, exact (t.w inr).symm end } }. @[simp] lemma cone.of_pullback_cone_π {F : walking_cospan.{v} ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) (j) : (cone.of_pullback_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl def cocone.of_pushout_cocone {F : walking_span.{v} ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := λ j j' g, begin cases j; cases j'; cases g; dsimp; simp, exact t.w fst, exact t.w snd end } }. @[simp] lemma cocone.of_pushout_cocone_ι {F : walking_span.{v} ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) (j) : (cocone.of_pushout_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl def pullback_cone.of_cone {F : walking_cospan.{v} ⥤ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) := { X := t.X, π := { app := λ j, t.π.app j ≫ eq_to_hom (by tidy) } } @[simp] lemma pullback_cone.of_cone_π {F : walking_cospan.{v} ⥤ C} (t : cone F) (j) : (pullback_cone.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl def pushout_cocone.of_cocone {F : walking_span.{v} ⥤ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) := { X := t.X, ι := { app := λ j, eq_to_hom (by tidy) ≫ t.ι.app j } } @[simp] lemma pushout_cocone.of_cocone_ι {F : walking_span.{v} ⥤ C} (t : cocone F) (j) : (pushout_cocone.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- `pullback f g` computes the pullback of a pair of morphisms with the same target. -/ abbreviation pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_limit (cospan f g)] := limit (cospan f g) /-- `pushout f g` computes the pushout of a pair of morphisms with the same source. -/ abbreviation pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_colimit (span f g)] := colimit (span f g) abbreviation pullback.fst {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : pullback f g ⟶ X := limit.π (cospan f g) walking_cospan.left abbreviation pullback.snd {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : pullback f g ⟶ Y := limit.π (cospan f g) walking_cospan.right abbreviation pushout.inl {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : Y ⟶ pushout f g := colimit.ι (span f g) walking_span.left abbreviation pushout.inr {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : Z ⟶ pushout f g := colimit.ι (span f g) walking_span.right abbreviation pullback.lift {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : W ⟶ pullback f g := limit.lift _ (pullback_cone.mk h k w) abbreviation pushout.desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout f g ⟶ W := colimit.desc _ (pushout_cocone.mk h k w) lemma pullback.condition {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : (pullback.fst : pullback f g ⟶ X) ≫ f = pullback.snd ≫ g := (limit.w (cospan f g) walking_cospan.hom.inl).trans (limit.w (cospan f g) walking_cospan.hom.inr).symm lemma pushout.condition {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : f ≫ (pushout.inl : Y ⟶ pushout f g) = g ≫ pushout.inr := (colimit.w (span f g) walking_span.hom.fst).trans (colimit.w (span f g) walking_span.hom.snd).symm /-- Two morphisms into a pullback are equal if their compositions with the pullback morphisms are equal -/ @[ext] lemma pullback.hom_ext {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] {W : C} {k l : W ⟶ pullback f g} (h₀ : k ≫ pullback.fst = l ≫ pullback.fst) (h₁ : k ≫ pullback.snd = l ≫ pullback.snd) : k = l := limit.hom_ext $ pullback_cone.equalizer_ext _ h₀ h₁ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono g] : mono (pullback.fst : pullback f g ⟶ X) := ⟨λ W u v h, pullback.hom_ext h $ (cancel_mono g).1 $ calc (u ≫ pullback.snd) ≫ g = u ≫ pullback.fst ≫ f : by rw [category.assoc, pullback.condition] ... = v ≫ pullback.fst ≫ f : by rw [←category.assoc, h, category.assoc] ... = (v ≫ pullback.snd) ≫ g : by rw [pullback.condition, ←category.assoc]⟩ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono f] : mono (pullback.snd : pullback f g ⟶ Y) := ⟨λ W u v h, pullback.hom_ext ((cancel_mono f).1 $ calc (u ≫ pullback.fst) ≫ f = u ≫ pullback.snd ≫ g : by rw [category.assoc, pullback.condition] ... = v ≫ pullback.snd ≫ g : by rw [←category.assoc, h, category.assoc] ... = (v ≫ pullback.fst) ≫ f : by rw [←pullback.condition, ←category.assoc]) h⟩ /-- Two morphisms out of a pushout are equal if their compositions with the pushout morphisms are equal -/ @[ext] lemma pushout.hom_ext {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] {W : C} {k l : pushout f g ⟶ W} (h₀ : pushout.inl ≫ k = pushout.inl ≫ l) (h₁ : pushout.inr ≫ k = pushout.inr ≫ l) : k = l := colimit.hom_ext $ pushout_cocone.coequalizer_ext _ h₀ h₁ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi g] : epi (pushout.inl : Y ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext h $ (cancel_epi g).1 $ calc g ≫ pushout.inr ≫ u = (f ≫ pushout.inl) ≫ u : by rw [←category.assoc, ←pushout.condition] ... = f ≫ pushout.inl ≫ v : by rw [category.assoc, h] ... = g ≫ pushout.inr ≫ v : by rw [←category.assoc, pushout.condition, category.assoc]⟩ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi f] : epi (pushout.inr : Z ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext ((cancel_epi f).1 $ calc f ≫ pushout.inl ≫ u = (g ≫ pushout.inr) ≫ u : by rw [←category.assoc, pushout.condition] ... = g ≫ pushout.inr ≫ v : by rw [category.assoc, h] ... = f ≫ pushout.inl ≫ v : by rw [←category.assoc, ←pushout.condition, category.assoc]) h⟩ variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms -/ class has_pullbacks := (has_limits_of_shape : has_limits_of_shape.{v} walking_cospan C) /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ class has_pushouts := (has_colimits_of_shape : has_colimits_of_shape.{v} walking_span C) attribute [instance] has_pullbacks.has_limits_of_shape has_pushouts.has_colimits_of_shape /-- Pullbacks are finite limits, so if `C` has all finite limits, it also has all pullbacks -/ def has_pullbacks_of_has_finite_limits [has_finite_limits.{v} C] : has_pullbacks.{v} C := { has_limits_of_shape := infer_instance } /-- Pushouts are finite colimits, so if `C` has all finite colimits, it also has all pushouts -/ def has_pushouts_of_has_finite_colimits [has_finite_colimits.{v} C] : has_pushouts.{v} C := { has_colimits_of_shape := infer_instance } /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ def has_pullbacks_of_has_limit_cospan [Π {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}, has_limit (cospan f g)] : has_pullbacks.{v} C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_cospan F).symm } } /-- If `C` has all colimits of diagrams `span f g`, then it has all pushouts -/ def has_pushouts_of_has_colimit_span [Π {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z}, has_colimit (span f g)] : has_pushouts.{v} C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_span F) } } end category_theory.limits
4a50dbeb611b39764d82dd405605ba699ce8abd4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/finset/default.lean
fbda9015955964dbf8042aa1a49198bb2696739a
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
230
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Finite sets. -/ import .basic .comb .to_set .card .bigops .partition
f48d7c8d83fd880896019fd9b2850f69b03b992b
ec62863c729b7eedee77b86d974f2c529fa79d25
/14/a.lean
7a17aeeaa56be80a656ab7f9fa35ee04c0f8d76d
[]
no_license
rwbarton/advent-of-lean-4
2ac9b17ba708f66051e3d8cd694b0249bc433b65
417c7e2718253ba7148c0279fcb251b6fc291477
refs/heads/main
1,675,917,092,057
1,609,864,581,000
1,609,864,581,000
317,700,289
24
0
null
null
null
null
UTF-8
Lean
false
false
1,316
lean
import Std.Data.HashMap inductive Command | setMask (mask : String) : Command | setMem (addr : Nat) (val : Nat) : Command open Command instance : Inhabited Command := ⟨setMask ""⟩ structure St : Type where mask : String mem : Std.HashMap Nat Nat def initSt : St := { mask := "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", mem := Std.HashMap.empty } def clearBit (i : Nat) (val : Nat) : Nat := (val / (2^(i+1))) * 2^(i+1) + (val % (2^i)) def setBit (i : Nat) (val : Nat) : Nat := clearBit i val + 2^i def maskedVal (mask : String) (val : Nat) : Nat := do let mut res := val for i in [0:36] do match mask.get i with | 'X' => () | '1' => res := setBit (35-i) res | '0' => res := clearBit (35-i) res | _ => panic! "bad mask" res def exec (st : St) : Command → St | setMask mask => { st with mask := mask } | setMem addr val => { st with mem := st.mem.insert addr (maskedVal st.mask val) } def parseCmd (str : String) : Command := match str.splitOn " " with | ["mask", "=", rhs] => setMask rhs | [lhs, "=", rhs] => setMem ((lhs.split (λ c => c == '[' || c == ']')).get! 1).toNat! rhs.toNat! | _ => panic! "invalid command" def main : IO Unit := do let lines ← IO.FS.lines "a.in" let st := (lines.map parseCmd).foldl exec initSt let sum := st.mem.fold (λ s k v => s + v) 0 IO.print s!"{sum}\n"
f67aaf6fc85ef11b2841232e9849a0946bb7fc51
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/isDefEqPerfIssue.lean
08a3b0cc997f5bf8624dfc44518656fce663a697
[ "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
370
lean
def g (n : Nat) (a : Array α) (i j : Fin a.size) : Array α := match n with | 0 => a.swap i j | n+1 => g n a j i partial def f (i : Nat) (a : Array α) : Array α := if h : i < a.size then let a' := g 100 a ⟨i, h⟩ ⟨i - Nat.zero.succ, by exact Nat.lt_of_le_of_lt (Nat.pred_le i) h⟩ have : a'.size - i >= 0 := sorry f (i+1) a' else a
151bbf4aad9458fe834be878b954878f59ef8cb0
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/algebra_attr.lean
a6c7cd01c6c4e7de479bd9c3f882d118cc5a9ba9
[ "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
266
lean
def f (a b : nat) := 0 def g (a b : nat) := 1 instance : is_commutative nat f := ⟨λ a b, rfl⟩ instance : is_commutative nat g := ⟨λ a b, rfl⟩ open tactic run_cmd do env ← get_env, s ← return $ env.get_class_attribute_symbols `algebra, trace s
de9b05d8952ca48209241c6775fa4814f20cc845
a19a4fce1e5677f4d20cbfdf60c04b6386ab8210
/library/init/nat.lean
3488756eb5f5e7acad1dc5b702ece0656061c881
[ "Apache-2.0" ]
permissive
nthomas103/lean
9c341a316e7d9faa00546462f90a8aa402e17eac
04eaf184a92606a56e54d0d6c8d59437557263fc
refs/heads/master
1,586,061,106,806
1,454,640,115,000
1,454,641,279,000
51,127,143
0
0
null
1,454,648,683,000
1,454,648,683,000
null
UTF-8
Lean
false
false
10,426
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import init.wf init.tactic init.num open eq.ops decidable or notation `ℕ` := nat namespace nat protected definition rec_on [reducible] [recursor] [unfold 2] {C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C a → C (succ a)) : C n := nat.rec H₁ H₂ n protected definition induction_on [recursor] {C : ℕ → Prop} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C a → C (succ a)) : C n := nat.rec H₁ H₂ n protected definition cases_on [reducible] [recursor] [unfold 2] {C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C (succ a)) : C n := nat.rec H₁ (λ a ih, H₂ a) n attribute nat.rec_on [recursor] -- Hack: force rec_on to be the first one. TODO(Leo): we should add priorities to recursors protected definition no_confusion_type [reducible] (P : Type) (v₁ v₂ : ℕ) : Type := nat.rec (nat.rec (P → P) (λ a₂ ih, P) v₂) (λ a₁ ih, nat.rec P (λ a₂ ih, (a₁ = a₂ → P) → P) v₂) v₁ protected definition no_confusion [reducible] [unfold 4] {P : Type} {v₁ v₂ : ℕ} (H : v₁ = v₂) : nat.no_confusion_type P v₁ v₂ := eq.rec (λ H₁ : v₁ = v₁, nat.rec (λ h, h) (λ a ih h, h (eq.refl a)) v₁) H H /- basic definitions on natural numbers -/ inductive le (a : ℕ) : ℕ → Prop := | nat_refl : le a a -- use nat_refl to avoid overloading le.refl | step : Π {b}, le a b → le a (succ b) definition nat_has_le [instance] [reducible] [priority nat.prio]: has_le nat := has_le.mk nat.le protected lemma le_refl [refl] : ∀ a : nat, a ≤ a := le.nat_refl protected definition lt [reducible] (n m : ℕ) := succ n ≤ m definition nat_has_lt [instance] [reducible] [priority nat.prio] : has_lt nat := has_lt.mk nat.lt definition pred [unfold 1] (a : nat) : nat := nat.cases_on a zero (λ a₁, a₁) -- add is defined in init.reserved_notation protected definition sub (a b : nat) : nat := nat.rec_on b a (λ b₁, pred) protected definition mul (a b : nat) : nat := nat.rec_on b zero (λ b₁ r, r + a) definition nat_has_sub [instance] [reducible] [priority nat.prio] : has_sub nat := has_sub.mk nat.sub definition nat_has_mul [instance] [reducible] [priority nat.prio] : has_mul nat := has_mul.mk nat.mul /- properties of ℕ -/ protected definition is_inhabited [instance] : inhabited nat := inhabited.mk zero protected definition has_decidable_eq [instance] [priority nat.prio] : ∀ x y : nat, decidable (x = y) | has_decidable_eq zero zero := inl rfl | has_decidable_eq (succ x) zero := inr (by contradiction) | has_decidable_eq zero (succ y) := inr (by contradiction) | has_decidable_eq (succ x) (succ y) := match has_decidable_eq x y with | inl xeqy := inl (by rewrite xeqy) | inr xney := inr (λ h : succ x = succ y, by injection h with xeqy; exact absurd xeqy xney) end /- properties of inequality -/ protected theorem le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := by simp theorem le_succ (n : ℕ) : n ≤ succ n := le.step !nat.le_refl theorem pred_le (n : ℕ) : pred n ≤ n := by cases n; repeat constructor theorem le_succ_iff_true [simp] (n : ℕ) : n ≤ succ n ↔ true := iff_true_intro (le_succ n) theorem pred_le_iff_true [simp] (n : ℕ) : pred n ≤ n ↔ true := iff_true_intro (pred_le n) protected theorem le_trans {n m k : ℕ} (H1 : n ≤ m) : m ≤ k → n ≤ k := le.rec H1 (λp H2, le.step) theorem le_succ_of_le {n m : ℕ} (H : n ≤ m) : n ≤ succ m := nat.le_trans H !le_succ theorem le_of_succ_le {n m : ℕ} (H : succ n ≤ m) : n ≤ m := nat.le_trans !le_succ H protected theorem le_of_lt {n m : ℕ} (H : n < m) : n ≤ m := le_of_succ_le H theorem succ_le_succ {n m : ℕ} : n ≤ m → succ n ≤ succ m := le.rec !nat.le_refl (λa b, le.step) theorem pred_le_pred {n m : ℕ} : n ≤ m → pred n ≤ pred m := le.rec !nat.le_refl (nat.rec (λa b, b) (λa b c, le.step)) theorem le_of_succ_le_succ {n m : ℕ} : succ n ≤ succ m → n ≤ m := pred_le_pred theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m := nat.cases_on n le.step (λa, succ_le_succ) theorem not_succ_le_zero (n : ℕ) : ¬succ n ≤ 0 := by intro H; cases H theorem succ_le_zero_iff_false (n : ℕ) : succ n ≤ 0 ↔ false := iff_false_intro !not_succ_le_zero theorem not_succ_le_self : Π {n : ℕ}, ¬succ n ≤ n := nat.rec !not_succ_le_zero (λa b c, b (le_of_succ_le_succ c)) theorem succ_le_self_iff_false [simp] (n : ℕ) : succ n ≤ n ↔ false := iff_false_intro not_succ_le_self theorem zero_le : ∀ (n : ℕ), 0 ≤ n := nat.rec !nat.le_refl (λa, le.step) theorem zero_le_iff_true [simp] (n : ℕ) : 0 ≤ n ↔ true := iff_true_intro !zero_le theorem lt.step {n m : ℕ} : n < m → n < succ m := le.step theorem zero_lt_succ (n : ℕ) : 0 < succ n := succ_le_succ !zero_le theorem zero_lt_succ_iff_true [simp] (n : ℕ) : 0 < succ n ↔ true := iff_true_intro (zero_lt_succ n) protected theorem lt_trans {n m k : ℕ} (H1 : n < m) : m < k → n < k := nat.le_trans (le.step H1) protected theorem lt_of_le_of_lt {n m k : ℕ} (H1 : n ≤ m) : m < k → n < k := nat.le_trans (succ_le_succ H1) protected theorem lt_of_lt_of_le {n m k : ℕ} : n < m → m ≤ k → n < k := nat.le_trans protected theorem lt_irrefl (n : ℕ) : ¬n < n := not_succ_le_self theorem lt_self_iff_false (n : ℕ) : n < n ↔ false := iff_false_intro (λ H, absurd H (nat.lt_irrefl n)) theorem self_lt_succ (n : ℕ) : n < succ n := !nat.le_refl theorem self_lt_succ_iff_true [simp] (n : ℕ) : n < succ n ↔ true := iff_true_intro (self_lt_succ n) theorem lt.base (n : ℕ) : n < succ n := !nat.le_refl theorem le_lt_antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m < n) : false := !nat.lt_irrefl (nat.lt_of_le_of_lt H1 H2) protected theorem le_antisymm {n m : ℕ} (H1 : n ≤ m) : m ≤ n → n = m := le.cases_on H1 (λa, rfl) (λa b c, absurd (nat.lt_of_le_of_lt b c) !nat.lt_irrefl) theorem lt_le_antisymm {n m : ℕ} (H1 : n < m) (H2 : m ≤ n) : false := le_lt_antisymm H2 H1 protected theorem nat.lt_asymm {n m : ℕ} (H1 : n < m) : ¬ m < n := le_lt_antisymm (nat.le_of_lt H1) theorem not_lt_zero (a : ℕ) : ¬ a < 0 := !not_succ_le_zero theorem lt_zero_iff_false [simp] (a : ℕ) : a < 0 ↔ false := iff_false_intro (not_lt_zero a) protected theorem eq_or_lt_of_le {a b : ℕ} (H : a ≤ b) : a = b ∨ a < b := le.cases_on H (inl rfl) (λn h, inr (succ_le_succ h)) protected theorem le_of_eq_or_lt {a b : ℕ} (H : a = b ∨ a < b) : a ≤ b := or.elim H !nat.le_of_eq !nat.le_of_lt -- less-than is well-founded definition lt.wf [instance] : well_founded lt := well_founded.intro (nat.rec (!acc.intro (λn H, absurd H (not_lt_zero n))) (λn IH, !acc.intro (λm H, or.elim (nat.eq_or_lt_of_le (le_of_succ_le_succ H)) (λe, eq.substr e IH) (acc.inv IH)))) definition measure {A : Type} : (A → ℕ) → A → A → Prop := inv_image lt definition measure.wf {A : Type} (f : A → ℕ) : well_founded (measure f) := inv_image.wf f lt.wf theorem succ_lt_succ {a b : ℕ} : a < b → succ a < succ b := succ_le_succ theorem lt_of_succ_lt {a b : ℕ} : succ a < b → a < b := le_of_succ_le theorem lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b := le_of_succ_le_succ definition decidable_le [instance] [priority nat.prio] : ∀ a b : nat, decidable (a ≤ b) := nat.rec (λm, (decidable.inl !zero_le)) (λn IH m, !nat.cases_on (decidable.inr (not_succ_le_zero n)) (λm, decidable.rec (λH, inl (succ_le_succ H)) (λH, inr (λa, H (le_of_succ_le_succ a))) (IH m))) definition decidable_lt [instance] [priority nat.prio] : ∀ a b : nat, decidable (a < b) := λ a b, decidable_le (succ a) b protected theorem lt_or_ge (a b : ℕ) : a < b ∨ a ≥ b := nat.rec (inr !zero_le) (λn, or.rec (λh, inl (le_succ_of_le h)) (λh, or.elim (nat.eq_or_lt_of_le h) (λe, inl (by simp)) inr)) b protected definition lt_ge_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a ≥ b → P) : P := by_cases H1 (λh, H2 (or.elim !nat.lt_or_ge (λa, absurd a h) (λa, a))) protected definition lt_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := nat.lt_ge_by_cases H1 (λh₁, nat.lt_ge_by_cases H3 (λh₂, H2 (nat.le_antisymm h₂ h₁))) protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a := nat.lt_by_cases (λH, inl H) (λH, inr (inl H)) (λH, inr (inr H)) protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a := or.rec_on (nat.lt_trichotomy a b) (λ hlt, absurd hlt hnlt) (λ h, h) theorem lt_succ_of_le {a b : ℕ} : a ≤ b → a < succ b := succ_le_succ theorem lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h theorem succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h theorem succ_sub_succ_eq_sub [simp] (a b : ℕ) : succ a - succ b = a - b := nat.rec (by esimp) (λ b, congr_arg pred) b theorem sub_eq_succ_sub_succ (a b : ℕ) : a - b = succ a - succ b := eq.symm !succ_sub_succ_eq_sub theorem zero_sub_eq_zero [simp] (a : ℕ) : 0 - a = 0 := nat.rec rfl (λ a, congr_arg pred) a theorem zero_eq_zero_sub (a : ℕ) : 0 = 0 - a := by simp theorem sub_le (a b : ℕ) : a - b ≤ a := nat.rec_on b !nat.le_refl (λ b₁, nat.le_trans !pred_le) theorem sub_le_iff_true [simp] (a b : ℕ) : a - b ≤ a ↔ true := iff_true_intro (sub_le a b) theorem sub_lt {a b : ℕ} (H1 : 0 < a) (H2 : 0 < b) : a - b < a := !nat.cases_on (λh, absurd h !nat.lt_irrefl) (λa h, succ_le_succ (!nat.cases_on (λh, absurd h !nat.lt_irrefl) (λb c, eq.substr !succ_sub_succ_eq_sub !sub_le) H2)) H1 theorem sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le !sub_le theorem sub_lt_succ_iff_true [simp] (a b : ℕ) : a - b < succ a ↔ true := iff_true_intro !sub_lt_succ end nat
860f2cbbd790c836b7c005ab5143146bdabdc4f8
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/category_theory/limits/functor_category.lean
1c01da3d6a64f43d2174b6813597500974b84413
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,208
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.limits.preserves.limits import category_theory.currying import category_theory.products open category_theory category_theory.category namespace category_theory.limits universes v v₂ u u₂ -- morphism levels before object levels. See note [category_theory universes]. variables {C : Type u} [category.{v} C] {D : Type u₂} [category.{v} D] variables {J K : Type v} [small_category J] [category.{v₂} K] @[simp, reassoc] lemma limit.lift_π_app (H : J ⥤ K ⥤ C) [has_limit H] (c : cone H) (j : J) (k : K) : (limit.lift H c).app k ≫ (limit.π H j).app k = (c.π.app j).app k := congr_app (limit.lift_π c j) k @[simp, reassoc] lemma colimit.ι_desc_app (H : J ⥤ K ⥤ C) [has_colimit H] (c : cocone H) (j : J) (k : K) : (colimit.ι H j).app k ≫ (colimit.desc H c).app k = (c.ι.app j).app k := congr_app (colimit.ι_desc c j) k /-- The evaluation functors jointly reflect limits: that is, to show a cone is a limit of `F` it suffices to show that each evaluation cone is a limit. In other words, to prove a cone is limiting you can show it's pointwise limiting. -/ def evaluation_jointly_reflects_limits {F : J ⥤ K ⥤ C} (c : cone F) (t : Π (k : K), is_limit (((evaluation K C).obj k).map_cone c)) : is_limit c := { lift := λ s, { app := λ k, (t k).lift ⟨s.X.obj k, whisker_right s.π ((evaluation K C).obj k)⟩, naturality' := λ X Y f, (t Y).hom_ext $ λ j, begin rw [assoc, (t Y).fac _ j], simpa using ((t X).fac_assoc ⟨s.X.obj X, whisker_right s.π ((evaluation K C).obj X)⟩ j _).symm, end }, fac' := λ s j, nat_trans.ext _ _ $ funext $ λ k, (t k).fac _ j, uniq' := λ s m w, nat_trans.ext _ _ $ funext $ λ x, (t x).hom_ext $ λ j, (congr_app (w j) x).trans ((t x).fac ⟨s.X.obj _, whisker_right s.π ((evaluation K C).obj _)⟩ j).symm } /-- Given a functor `F` and a collection of limit cones for each diagram `X ↦ F X k`, we can stitch them together to give a cone for the diagram `F`. `combined_is_limit` shows that the new cone is limiting, and `eval_combined` shows it is (essentially) made up of the original cones. -/ @[simps] def combine_cones (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) : cone F := { X := { obj := λ k, (c k).cone.X, map := λ k₁ k₂ f, (c k₂).is_limit.lift ⟨_, (c k₁).cone.π ≫ F.flip.map f⟩, map_id' := λ k, (c k).is_limit.hom_ext (λ j, by { dsimp, simp }), map_comp' := λ k₁ k₂ k₃ f₁ f₂, (c k₃).is_limit.hom_ext (λ j, by simp) }, π := { app := λ j, { app := λ k, (c k).cone.π.app j }, naturality' := λ j₁ j₂ g, nat_trans.ext _ _ $ funext $ λ k, (c k).cone.π.naturality g } } /-- The stitched together cones each project down to the original given cones (up to iso). -/ def evaluate_combined_cones (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) (k : K) : ((evaluation K C).obj k).map_cone (combine_cones F c) ≅ (c k).cone := cones.ext (iso.refl _) (by tidy) /-- Stitching together limiting cones gives a limiting cone. -/ def combined_is_limit (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) : is_limit (combine_cones F c) := evaluation_jointly_reflects_limits _ (λ k, (c k).is_limit.of_iso_limit (evaluate_combined_cones F c k).symm) /-- The evaluation functors jointly reflect colimits: that is, to show a cocone is a colimit of `F` it suffices to show that each evaluation cocone is a colimit. In other words, to prove a cocone is colimiting you can show it's pointwise colimiting. -/ def evaluation_jointly_reflects_colimits {F : J ⥤ K ⥤ C} (c : cocone F) (t : Π (k : K), is_colimit (((evaluation K C).obj k).map_cocone c)) : is_colimit c := { desc := λ s, { app := λ k, (t k).desc ⟨s.X.obj k, whisker_right s.ι ((evaluation K C).obj k)⟩, naturality' := λ X Y f, (t X).hom_ext $ λ j, begin rw [(t X).fac_assoc _ j], erw ← (c.ι.app j).naturality_assoc f, erw (t Y).fac ⟨s.X.obj _, whisker_right s.ι _⟩ j, dsimp, simp, end }, fac' := λ s j, nat_trans.ext _ _ $ funext $ λ k, (t k).fac _ j, uniq' := λ s m w, nat_trans.ext _ _ $ funext $ λ x, (t x).hom_ext $ λ j, (congr_app (w j) x).trans ((t x).fac ⟨s.X.obj _, whisker_right s.ι ((evaluation K C).obj _)⟩ j).symm } /-- Given a functor `F` and a collection of colimit cocones for each diagram `X ↦ F X k`, we can stitch them together to give a cocone for the diagram `F`. `combined_is_colimit` shows that the new cocone is colimiting, and `eval_combined` shows it is (essentially) made up of the original cocones. -/ @[simps] def combine_cocones (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) : cocone F := { X := { obj := λ k, (c k).cocone.X, map := λ k₁ k₂ f, (c k₁).is_colimit.desc ⟨_, F.flip.map f ≫ (c k₂).cocone.ι⟩, map_id' := λ k, (c k).is_colimit.hom_ext (λ j, by { dsimp, simp }), map_comp' := λ k₁ k₂ k₃ f₁ f₂, (c k₁).is_colimit.hom_ext (λ j, by simp) }, ι := { app := λ j, { app := λ k, (c k).cocone.ι.app j }, naturality' := λ j₁ j₂ g, nat_trans.ext _ _ $ funext $ λ k, (c k).cocone.ι.naturality g } } /-- The stitched together cocones each project down to the original given cocones (up to iso). -/ def evaluate_combined_cocones (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) (k : K) : ((evaluation K C).obj k).map_cocone (combine_cocones F c) ≅ (c k).cocone := cocones.ext (iso.refl _) (by tidy) /-- Stitching together colimiting cocones gives a colimiting cocone. -/ def combined_is_colimit (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) : is_colimit (combine_cocones F c) := evaluation_jointly_reflects_colimits _ (λ k, (c k).is_colimit.of_iso_colimit (evaluate_combined_cocones F c k).symm) noncomputable theory instance functor_category_has_limits_of_shape [has_limits_of_shape J C] : has_limits_of_shape J (K ⥤ C) := { has_limit := λ F, has_limit.mk { cone := combine_cones F (λ k, get_limit_cone _), is_limit := combined_is_limit _ _ } } instance functor_category_has_colimits_of_shape [has_colimits_of_shape J C] : has_colimits_of_shape J (K ⥤ C) := { has_colimit := λ F, has_colimit.mk { cocone := combine_cocones _ (λ k, get_colimit_cocone _), is_colimit := combined_is_colimit _ _ } } instance functor_category_has_limits [has_limits C] : has_limits (K ⥤ C) := {} instance functor_category_has_colimits [has_colimits C] : has_colimits (K ⥤ C) := {} instance evaluation_preserves_limits_of_shape [has_limits_of_shape J C] (k : K) : preserves_limits_of_shape J ((evaluation K C).obj k) := { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (combined_is_limit _ _) $ is_limit.of_iso_limit (limit.is_limit _) (evaluate_combined_cones F _ k).symm } /-- If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a limit, then the evaluation of that limit at `k` is the limit of the evaluations of `F.obj j` at `k`. -/ def limit_obj_iso_limit_comp_evaluation [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : (limit F).obj k ≅ limit (F ⋙ ((evaluation K C).obj k)) := preserves_limit_iso ((evaluation K C).obj k) F @[simp, reassoc] lemma limit_obj_iso_limit_comp_evaluation_hom_π [has_limits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) : (limit_obj_iso_limit_comp_evaluation F k).hom ≫ limit.π (F ⋙ ((evaluation K C).obj k)) j = (limit.π F j).app k := begin dsimp [limit_obj_iso_limit_comp_evaluation], simp, end @[simp, reassoc] lemma limit_obj_iso_limit_comp_evaluation_inv_π_app [has_limits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K): (limit_obj_iso_limit_comp_evaluation F k).inv ≫ (limit.π F j).app k = limit.π (F ⋙ ((evaluation K C).obj k)) j := begin dsimp [limit_obj_iso_limit_comp_evaluation], rw iso.inv_comp_eq, simp, end @[ext] lemma limit_obj_ext {H : J ⥤ K ⥤ C} [has_limits_of_shape J C] {k : K} {W : C} {f g : W ⟶ (limit H).obj k} (w : ∀ j, f ≫ (limits.limit.π H j).app k = g ≫ (limits.limit.π H j).app k) : f = g := begin apply (cancel_mono (limit_obj_iso_limit_comp_evaluation H k).hom).1, ext, simpa using w j, end instance evaluation_preserves_colimits_of_shape [has_colimits_of_shape J C] (k : K) : preserves_colimits_of_shape J ((evaluation K C).obj k) := { preserves_colimit := λ F, preserves_colimit_of_preserves_colimit_cocone (combined_is_colimit _ _) $ is_colimit.of_iso_colimit (colimit.is_colimit _) (evaluate_combined_cocones F _ k).symm } /-- If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a colimit, then the evaluation of that colimit at `k` is the colimit of the evaluations of `F.obj j` at `k`. -/ def colimit_obj_iso_colimit_comp_evaluation [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : (colimit F).obj k ≅ colimit (F ⋙ ((evaluation K C).obj k)) := preserves_colimit_iso ((evaluation K C).obj k) F @[simp, reassoc] lemma colimit_obj_iso_colimit_comp_evaluation_ι_inv [has_colimits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) : colimit.ι (F ⋙ ((evaluation K C).obj k)) j ≫ (colimit_obj_iso_colimit_comp_evaluation F k).inv = (colimit.ι F j).app k := begin dsimp [colimit_obj_iso_colimit_comp_evaluation], simp, end @[simp, reassoc] lemma colimit_obj_iso_colimit_comp_evaluation_ι_app_hom [has_colimits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) : (colimit.ι F j).app k ≫ (colimit_obj_iso_colimit_comp_evaluation F k).hom = colimit.ι (F ⋙ ((evaluation K C).obj k)) j := begin dsimp [colimit_obj_iso_colimit_comp_evaluation], rw ←iso.eq_comp_inv, simp, end @[ext] lemma colimit_obj_ext {H : J ⥤ K ⥤ C} [has_colimits_of_shape J C] {k : K} {W : C} {f g : (colimit H).obj k ⟶ W} (w : ∀ j, (colimit.ι H j).app k ≫ f = (colimit.ι H j).app k ≫ g) : f = g := begin apply (cancel_epi (colimit_obj_iso_colimit_comp_evaluation H k).inv).1, ext, simpa using w j, end instance evaluation_preserves_limits [has_limits C] (k : K) : preserves_limits ((evaluation K C).obj k) := { preserves_limits_of_shape := λ J 𝒥, by resetI; apply_instance } /-- `F : D ⥤ K ⥤ C` preserves limit if it does for each `k : K`. -/ def preserves_limit_of_evaluation (F : D ⥤ K ⥤ C) (G : J ⥤ D) (H : Π (k : K), preserves_limit G (F ⋙ (evaluation K C).obj k : D ⥤ C)) : preserves_limit G F := ⟨λ c hc, begin apply evaluation_jointly_reflects_limits, intro X, haveI := H X, change is_limit ((F ⋙ (evaluation K C).obj X).map_cone c), exact preserves_limit.preserves hc, end⟩ /-- `F : D ⥤ K ⥤ C` preserves limits of shape `J` if it does for each `k : K`. -/ def preserves_limits_of_shape_of_evaluation (F : D ⥤ K ⥤ C) (J : Type v) [small_category J] (H : Π (k : K), preserves_limits_of_shape J (F ⋙ (evaluation K C).obj k)) : preserves_limits_of_shape J F := ⟨λ G, preserves_limit_of_evaluation F G (λ k, preserves_limits_of_shape.preserves_limit)⟩ /-- `F : D ⥤ K ⥤ C` preserves all limits if it does for each `k : K`. -/ def preserves_limits_of_evaluation (F : D ⥤ K ⥤ C) (H : Π (k : K), preserves_limits (F ⋙ (evaluation K C).obj k)) : preserves_limits F := ⟨λ L hL, by exactI preserves_limits_of_shape_of_evaluation F L (λ k, preserves_limits.preserves_limits_of_shape)⟩ instance evaluation_preserves_colimits [has_colimits C] (k : K) : preserves_colimits ((evaluation K C).obj k) := { preserves_colimits_of_shape := λ J 𝒥, by resetI; apply_instance } /-- `F : D ⥤ K ⥤ C` preserves limit if it does for each `k : K`. -/ def preserves_colimit_of_evaluation (F : D ⥤ K ⥤ C) (G : J ⥤ D) (H : Π (k), preserves_colimit G (F ⋙ (evaluation K C).obj k)) : preserves_colimit G F := ⟨λ c hc, begin apply evaluation_jointly_reflects_colimits, intro X, haveI := H X, change is_colimit ((F ⋙ (evaluation K C).obj X).map_cocone c), exact preserves_colimit.preserves hc, end⟩ /-- `F : D ⥤ K ⥤ C` preserves all colimits of shape `J` if it does for each `k : K`. -/ def preserves_colimits_of_shape_of_evaluation (F : D ⥤ K ⥤ C) (J : Type v) [small_category J] (H : Π (k : K), preserves_colimits_of_shape J (F ⋙ (evaluation K C).obj k)) : preserves_colimits_of_shape J F := ⟨λ G, preserves_colimit_of_evaluation F G (λ k, preserves_colimits_of_shape.preserves_colimit)⟩ /-- `F : D ⥤ K ⥤ C` preserves all colimits if it does for each `k : K`. -/ def preserves_colimits_of_evaluation (F : D ⥤ K ⥤ C) (H : Π (k : K), preserves_colimits (F ⋙ (evaluation K C).obj k)) : preserves_colimits F := ⟨λ L hL, by exactI preserves_colimits_of_shape_of_evaluation F L (λ k, preserves_colimits.preserves_colimits_of_shape)⟩ open category_theory.prod /-- For a functor `G : J ⥤ K ⥤ C`, its limit `K ⥤ C` is given by `(G' : K ⥤ J ⥤ C) ⋙ lim`. Note that this does not require `K` to be small. -/ @[simps] def limit_iso_swap_comp_lim [has_limits_of_shape J C] (G : J ⥤ K ⥤ C) [has_limit G] : limit G ≅ curry.obj (swap K J ⋙ uncurry.obj G) ⋙ lim := nat_iso.of_components (λ Y, limit_obj_iso_limit_comp_evaluation G Y ≪≫ (lim.map_iso (eq_to_iso (by { apply functor.hext, { intro X, simp }, { intros X₁ X₂ f, dsimp only [swap], simp }})))) begin intros Y₁ Y₂ f, ext1 x, dsimp only [swap], simp only [limit_obj_iso_limit_comp_evaluation_hom_π_assoc, category.comp_id, limit_obj_iso_limit_comp_evaluation_hom_π, eq_to_iso.hom, curry.obj_map_app, nat_trans.naturality, category.id_comp, eq_to_hom_refl, functor.comp_map, eq_to_hom_app, lim_map_π_assoc, lim_map_π, category.assoc, uncurry.obj_map, lim_map_eq_lim_map, iso.trans_hom, nat_trans.id_app, category_theory.functor.map_id, functor.map_iso_hom], erw category.id_comp, end /-- For a functor `G : J ⥤ K ⥤ C`, its colimit `K ⥤ C` is given by `(G' : K ⥤ J ⥤ C) ⋙ colim`. Note that this does not require `K` to be small. -/ @[simps] def colimit_iso_swap_comp_colim [has_colimits_of_shape J C] (G : J ⥤ K ⥤ C) [has_colimit G] : colimit G ≅ curry.obj (swap K J ⋙ uncurry.obj G) ⋙ colim := nat_iso.of_components (λ Y, colimit_obj_iso_colimit_comp_evaluation G Y ≪≫ (colim.map_iso (eq_to_iso (by { apply functor.hext, { intro X, simp }, { intros X Y f, dsimp only [swap], simp, } })))) begin intros Y₁ Y₂ f, ext1 x, rw ← (colimit.ι G x).naturality_assoc f, dsimp only [swap], simp only [eq_to_iso.hom, colimit_obj_iso_colimit_comp_evaluation_ι_app_hom_assoc, curry.obj_map_app, colimit.ι_map, category.id_comp, eq_to_hom_refl, iso.trans_hom, functor.comp_map, eq_to_hom_app, colimit.ι_map_assoc, functor.map_iso_hom, category.assoc, uncurry.obj_map, nat_trans.id_app, category_theory.functor.map_id], erw category.id_comp, end end category_theory.limits
910004d985569656e07ba7f7a810afa29ce4ad02
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/inner_product_space/l2_space.lean
93269208a249819686445cd2ffe70d46994d2e2f
[ "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
19,069
lean
/- Copyright (c) 2022 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.inner_product_space.projection import analysis.normed_space.lp_space /-! # Hilbert sum of a family of inner product spaces Given a family `(G : ι → Type*) [Π i, inner_product_space 𝕜 (G i)]` of inner product spaces, this file equips `lp G 2` with an inner product space structure, where `lp G 2` consists of those dependent functions `f : Π i, G i` for which `∑' i, ∥f i∥ ^ 2`, the sum of the norms-squared, is summable. This construction is sometimes called the *Hilbert sum* of the family `G`. By choosing `G` to be `ι → 𝕜`, the Hilbert space `ℓ²(ι, 𝕜)` may be seen as a special case of this construction. ## Main definitions * `orthogonal_family.linear_isometry`: Given a Hilbert space `E`, a family `G` of inner product spaces and a family `V : Π i, G i →ₗᵢ[𝕜] E` of isometric embeddings of the `G i` into `E` with mutually-orthogonal images, there is an induced isometric embedding of the Hilbert sum of `G` into `E`. * `orthogonal_family.linear_isometry_equiv`: Given a Hilbert space `E`, a family `G` of inner product spaces and a family `V : Π i, G i →ₗᵢ[𝕜] E` of isometric embeddings of the `G i` into `E` with mutually-orthogonal images whose span is dense in `E`, there is an induced isometric isomorphism of the Hilbert sum of `G` with `E`. * `hilbert_basis`: We define a *Hilbert basis* of a Hilbert space `E` to be a structure whose single field `hilbert_basis.repr` is an isometric isomorphism of `E` with `ℓ²(ι, 𝕜)` (i.e., the Hilbert sum of `ι` copies of `𝕜`). This parallels the definition of `basis`, in `linear_algebra.basis`, as an isomorphism of an `R`-module with `ι →₀ R`. * `hilbert_basis.has_coe_to_fun`: More conventionally a Hilbert basis is thought of as a family `ι → E` of vectors in `E` satisfying certain properties (orthonormality, completeness). We obtain this interpretation of a Hilbert basis `b` by defining `⇑b`, of type `ι → E`, to be the image under `b.repr` of `lp.single 2 i (1:𝕜)`. This parallels the definition `basis.has_coe_to_fun` in `linear_algebra.basis`. * `hilbert_basis.mk`: Make a Hilbert basis of `E` from an orthonormal family `v : ι → E` of vectors in `E` whose span is dense. This parallels the definition `basis.mk` in `linear_algebra.basis`. * `hilbert_basis.mk_of_orthogonal_eq_bot`: Make a Hilbert basis of `E` from an orthonormal family `v : ι → E` of vectors in `E` whose span has trivial orthogonal complement. ## Main results * `lp.inner_product_space`: Construction of the inner product space instance on the Hilbert sum `lp G 2`. Note that from the file `analysis.normed_space.lp_space`, the space `lp G 2` already held a normed space instance (`lp.normed_space`), and if each `G i` is a Hilbert space (i.e., complete), then `lp G 2` was already known to be complete (`lp.complete_space`). So the work here is to define the inner product and show it is compatible. * `orthogonal_family.range_linear_isometry`: Given a family `G` of inner product spaces and a family `V : Π i, G i →ₗᵢ[𝕜] E` of isometric embeddings of the `G i` into `E` with mutually-orthogonal images, the image of the embedding `orthogonal_family.linear_isometry` of the Hilbert sum of `G` into `E` is the closure of the span of the images of the `G i`. * `hilbert_basis.repr_apply_apply`: Given a Hilbert basis `b` of `E`, the entry `b.repr x i` of `x`'s representation in `ℓ²(ι, 𝕜)` is the inner product `⟪b i, x⟫`. * `hilbert_basis.has_sum_repr`: Given a Hilbert basis `b` of `E`, a vector `x` in `E` can be expressed as the "infinite linear combination" `∑' i, b.repr x i • b i` of the basis vectors `b i`, with coefficients given by the entries `b.repr x i` of `x`'s representation in `ℓ²(ι, 𝕜)`. * `exists_hilbert_basis`: A Hilbert space admits a Hilbert basis. ## Keywords Hilbert space, Hilbert sum, l2, Hilbert basis, unitary equivalence, isometric isomorphism -/ open is_R_or_C submodule filter open_locale big_operators nnreal ennreal classical complex_conjugate noncomputable theory variables {ι : Type*} variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [inner_product_space 𝕜 E] [cplt : complete_space E] variables {G : ι → Type*} [Π i, inner_product_space 𝕜 (G i)] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y notation `ℓ²(` ι `,` 𝕜 `)` := lp (λ i : ι, 𝕜) 2 /-! ### Inner product space structure on `lp G 2` -/ namespace lp lemma summable_inner (f g : lp G 2) : summable (λ i, ⟪f i, g i⟫) := begin -- Apply the Direct Comparison Test, comparing with ∑' i, ∥f i∥ * ∥g i∥ (summable by Hölder) refine summable_of_norm_bounded (λ i, ∥f i∥ * ∥g i∥) (lp.summable_mul _ f g) _, { rw real.is_conjugate_exponent_iff; norm_num }, intros i, -- Then apply Cauchy-Schwarz pointwise exact norm_inner_le_norm _ _, end instance : inner_product_space 𝕜 (lp G 2) := { inner := λ f g, ∑' i, ⟪f i, g i⟫, norm_sq_eq_inner := λ f, begin calc ∥f∥ ^ 2 = ∥f∥ ^ (2:ℝ≥0∞).to_real : by norm_cast ... = ∑' i, ∥f i∥ ^ (2:ℝ≥0∞).to_real : lp.norm_rpow_eq_tsum _ f ... = ∑' i, ∥f i∥ ^ 2 : by norm_cast ... = ∑' i, re ⟪f i, f i⟫ : by simp only [norm_sq_eq_inner] ... = re (∑' i, ⟪f i, f i⟫) : (is_R_or_C.re_clm.map_tsum _).symm ... = _ : by congr, { norm_num }, { exact summable_inner f f }, end, conj_sym := λ f g, begin calc conj _ = conj ∑' i, ⟪g i, f i⟫ : by congr ... = ∑' i, conj ⟪g i, f i⟫ : is_R_or_C.conj_cle.map_tsum ... = ∑' i, ⟪f i, g i⟫ : by simp only [inner_conj_sym] ... = _ : by congr, end, add_left := λ f₁ f₂ g, begin calc _ = ∑' i, ⟪(f₁ + f₂) i, g i⟫ : _ ... = ∑' i, (⟪f₁ i, g i⟫ + ⟪f₂ i, g i⟫) : by simp only [inner_add_left, pi.add_apply, coe_fn_add] ... = (∑' i, ⟪f₁ i, g i⟫) + ∑' i, ⟪f₂ i, g i⟫ : tsum_add _ _ ... = _ : by congr, { congr, }, { exact summable_inner f₁ g }, { exact summable_inner f₂ g } end, smul_left := λ f g c, begin calc _ = ∑' i, ⟪c • f i, g i⟫ : _ ... = ∑' i, conj c * ⟪f i, g i⟫ : by simp only [inner_smul_left] ... = conj c * ∑' i, ⟪f i, g i⟫ : tsum_mul_left ... = _ : _, { simp only [coe_fn_smul, pi.smul_apply] }, { congr }, end, .. lp.normed_space } lemma inner_eq_tsum (f g : lp G 2) : ⟪f, g⟫ = ∑' i, ⟪f i, g i⟫ := rfl lemma has_sum_inner (f g : lp G 2) : has_sum (λ i, ⟪f i, g i⟫) ⟪f, g⟫ := (summable_inner f g).has_sum lemma inner_single_left (i : ι) (a : G i) (f : lp G 2) : ⟪lp.single 2 i a, f⟫ = ⟪a, f i⟫ := begin refine (has_sum_inner (lp.single 2 i a) f).unique _, convert has_sum_ite_eq i ⟪a, f i⟫, ext j, rw lp.single_apply, split_ifs, { subst h }, { simp } end lemma inner_single_right (i : ι) (a : G i) (f : lp G 2) : ⟪f, lp.single 2 i a⟫ = ⟪f i, a⟫ := by simpa [inner_conj_sym] using congr_arg conj (inner_single_left i a f) end lp /-! ### Identification of a general Hilbert space `E` with a Hilbert sum -/ namespace orthogonal_family variables {V : Π i, G i →ₗᵢ[𝕜] E} (hV : orthogonal_family 𝕜 V) include cplt hV protected lemma summable_of_lp (f : lp G 2) : summable (λ i, V i (f i)) := begin rw hV.summable_iff_norm_sq_summable, convert (lp.mem_ℓp f).summable _, { norm_cast }, { norm_num } end /-- A mutually orthogonal family of subspaces of `E` induce a linear isometry from `lp 2` of the subspaces into `E`. -/ protected def linear_isometry : lp G 2 →ₗᵢ[𝕜] E := { to_fun := λ f, ∑' i, V i (f i), map_add' := λ f g, by simp only [tsum_add (hV.summable_of_lp f) (hV.summable_of_lp g), lp.coe_fn_add, pi.add_apply, linear_isometry.map_add], map_smul' := λ c f, by simpa only [linear_isometry.map_smul, pi.smul_apply, lp.coe_fn_smul] using tsum_const_smul (hV.summable_of_lp f), norm_map' := λ f, begin classical, -- needed for lattice instance on `finset ι`, for `filter.at_top_ne_bot` have H : 0 < (2:ℝ≥0∞).to_real := by norm_num, suffices : ∥∑' (i : ι), V i (f i)∥ ^ ((2:ℝ≥0∞).to_real) = ∥f∥ ^ ((2:ℝ≥0∞).to_real), { exact real.rpow_left_inj_on H.ne' (norm_nonneg _) (norm_nonneg _) this }, refine tendsto_nhds_unique _ (lp.has_sum_norm H f), convert (hV.summable_of_lp f).has_sum.norm.rpow_const (or.inr H.le), ext s, exact_mod_cast (hV.norm_sum f s).symm, end } protected lemma linear_isometry_apply (f : lp G 2) : hV.linear_isometry f = ∑' i, V i (f i) := rfl protected lemma has_sum_linear_isometry (f : lp G 2) : has_sum (λ i, V i (f i)) (hV.linear_isometry f) := (hV.summable_of_lp f).has_sum @[simp] protected lemma linear_isometry_apply_single {i : ι} (x : G i) : hV.linear_isometry (lp.single 2 i x) = V i x := begin rw [hV.linear_isometry_apply, ← tsum_ite_eq i (V i x)], congr, ext j, rw [lp.single_apply], split_ifs, { subst h }, { simp } end @[simp] protected lemma linear_isometry_apply_dfinsupp_sum_single (W₀ : Π₀ (i : ι), G i) : hV.linear_isometry (W₀.sum (lp.single 2)) = W₀.sum (λ i, V i) := begin have : hV.linear_isometry (∑ i in W₀.support, lp.single 2 i (W₀ i)) = ∑ i in W₀.support, hV.linear_isometry (lp.single 2 i (W₀ i)), { exact hV.linear_isometry.to_linear_map.map_sum }, simp [dfinsupp.sum, this] {contextual := tt}, end /-- The canonical linear isometry from the `lp 2` of a mutually orthogonal family of subspaces of `E` into E, has range the closure of the span of the subspaces. -/ protected lemma range_linear_isometry [Π i, complete_space (G i)] : hV.linear_isometry.to_linear_map.range = (⨆ i, (V i).to_linear_map.range).topological_closure := begin refine le_antisymm _ _, { rintros x ⟨f, rfl⟩, refine mem_closure_of_tendsto (hV.has_sum_linear_isometry f) (eventually_of_forall _), intros s, rw set_like.mem_coe, refine sum_mem _, intros i hi, refine mem_supr_of_mem i _, exact linear_map.mem_range_self _ (f i) }, { apply topological_closure_minimal, { refine supr_le _, rintros i x ⟨x, rfl⟩, use lp.single 2 i x, exact hV.linear_isometry_apply_single x }, exact hV.linear_isometry.isometry.uniform_inducing.is_complete_range.is_closed } end /-- A mutually orthogonal family of complete subspaces of `E`, whose range is dense in `E`, induces a isometric isomorphism from E to `lp 2` of the subspaces. Note that this goes in the opposite direction from `orthogonal_family.linear_isometry`. -/ noncomputable def linear_isometry_equiv [Π i, complete_space (G i)] (hV' : (⨆ i, (V i).to_linear_map.range).topological_closure = ⊤) : E ≃ₗᵢ[𝕜] lp G 2 := linear_isometry_equiv.symm $ linear_isometry_equiv.of_surjective hV.linear_isometry begin refine linear_map.range_eq_top.mp _, rw ← hV', rw hV.range_linear_isometry, end /-- In the canonical isometric isomorphism `E ≃ₗᵢ[𝕜] lp G 2` induced by an orthogonal family `G`, a vector `w : lp G 2` is the image of the infinite sum of the associated elements in `E`. -/ protected lemma linear_isometry_equiv_symm_apply [Π i, complete_space (G i)] (hV' : (⨆ i, (V i).to_linear_map.range).topological_closure = ⊤) (w : lp G 2) : (hV.linear_isometry_equiv hV').symm w = ∑' i, V i (w i) := by simp [orthogonal_family.linear_isometry_equiv, orthogonal_family.linear_isometry_apply] /-- In the canonical isometric isomorphism `E ≃ₗᵢ[𝕜] lp G 2` induced by an orthogonal family `G`, a vector `w : lp G 2` is the image of the infinite sum of the associated elements in `E`, and this sum indeed converges. -/ protected lemma has_sum_linear_isometry_equiv_symm [Π i, complete_space (G i)] (hV' : (⨆ i, (V i).to_linear_map.range).topological_closure = ⊤) (w : lp G 2) : has_sum (λ i, V i (w i)) ((hV.linear_isometry_equiv hV').symm w) := by simp [orthogonal_family.linear_isometry_equiv, orthogonal_family.has_sum_linear_isometry] /-- In the canonical isometric isomorphism `E ≃ₗᵢ[𝕜] lp G 2` induced by an `ι`-indexed orthogonal family `G`, an "elementary basis vector" in `lp G 2` supported at `i : ι` is the image of the associated element in `E`. -/ @[simp] protected lemma linear_isometry_equiv_symm_apply_single [Π i, complete_space (G i)] (hV' : (⨆ i, (V i).to_linear_map.range).topological_closure = ⊤) {i : ι} (x : G i) : (hV.linear_isometry_equiv hV').symm (lp.single 2 i x) = V i x := by simp [orthogonal_family.linear_isometry_equiv, orthogonal_family.linear_isometry_apply_single] /-- In the canonical isometric isomorphism `E ≃ₗᵢ[𝕜] lp G 2` induced by an `ι`-indexed orthogonal family `G`, a finitely-supported vector in `lp G 2` is the image of the associated finite sum of elements of `E`. -/ @[simp] protected lemma linear_isometry_equiv_symm_apply_dfinsupp_sum_single [Π i, complete_space (G i)] (hV' : (⨆ i, (V i).to_linear_map.range).topological_closure = ⊤) (W₀ : Π₀ (i : ι), G i) : (hV.linear_isometry_equiv hV').symm (W₀.sum (lp.single 2)) = (W₀.sum (λ i, V i)) := by simp [orthogonal_family.linear_isometry_equiv, orthogonal_family.linear_isometry_apply_dfinsupp_sum_single] /-- In the canonical isometric isomorphism `E ≃ₗᵢ[𝕜] lp G 2` induced by an `ι`-indexed orthogonal family `G`, a finitely-supported vector in `lp G 2` is the image of the associated finite sum of elements of `E`. -/ @[simp] protected lemma linear_isometry_equiv_apply_dfinsupp_sum_single [Π i, complete_space (G i)] (hV' : (⨆ i, (V i).to_linear_map.range).topological_closure = ⊤) (W₀ : Π₀ (i : ι), G i) : (hV.linear_isometry_equiv hV' (W₀.sum (λ i, V i)) : Π i, G i) = W₀ := begin rw ← hV.linear_isometry_equiv_symm_apply_dfinsupp_sum_single hV', rw linear_isometry_equiv.apply_symm_apply, ext i, simp [dfinsupp.sum, lp.single_apply] {contextual := tt}, end end orthogonal_family /-! ### Hilbert bases -/ section variables (ι) (𝕜) (E) /-- A Hilbert basis on `ι` for an inner product space `E` is an identification of `E` with the `lp` space `ℓ²(ι, 𝕜)`. -/ structure hilbert_basis := of_repr :: (repr : E ≃ₗᵢ[𝕜] ℓ²(ι, 𝕜)) end namespace hilbert_basis instance {ι : Type*} : inhabited (hilbert_basis ι 𝕜 ℓ²(ι, 𝕜)) := ⟨of_repr (linear_isometry_equiv.refl 𝕜 _)⟩ /-- `b i` is the `i`th basis vector. -/ instance : has_coe_to_fun (hilbert_basis ι 𝕜 E) (λ _, ι → E) := { coe := λ b i, b.repr.symm (lp.single 2 i (1:𝕜)) } @[simp] protected lemma repr_symm_single (b : hilbert_basis ι 𝕜 E) (i : ι) : b.repr.symm (lp.single 2 i (1:𝕜)) = b i := rfl @[simp] protected lemma repr_self (b : hilbert_basis ι 𝕜 E) (i : ι) : b.repr (b i) = lp.single 2 i (1:𝕜) := by rw [← b.repr_symm_single, linear_isometry_equiv.apply_symm_apply] protected lemma repr_apply_apply (b : hilbert_basis ι 𝕜 E) (v : E) (i : ι) : b.repr v i = ⟪b i, v⟫ := begin rw [← b.repr.inner_map_map (b i) v, b.repr_self, lp.inner_single_left], simp, end @[simp] protected lemma orthonormal (b : hilbert_basis ι 𝕜 E) : orthonormal 𝕜 b := begin rw orthonormal_iff_ite, intros i j, rw [← b.repr.inner_map_map (b i) (b j), b.repr_self, b.repr_self, lp.inner_single_left, lp.single_apply], simp, end protected lemma has_sum_repr_symm (b : hilbert_basis ι 𝕜 E) (f : ℓ²(ι, 𝕜)) : has_sum (λ i, f i • b i) (b.repr.symm f) := begin suffices H : (λ (i : ι), f i • b i) = (λ (b_1 : ι), (b.repr.symm.to_continuous_linear_equiv) ((λ (i : ι), lp.single 2 i (f i)) b_1)), { rw H, have : has_sum (λ (i : ι), lp.single 2 i (f i)) f := lp.has_sum_single ennreal.two_ne_top f, exact (↑(b.repr.symm.to_continuous_linear_equiv) : ℓ²(ι, 𝕜) →L[𝕜] E).has_sum this }, ext i, apply b.repr.injective, have : lp.single 2 i (f i * 1) = f i • lp.single 2 i 1 := lp.single_smul 2 i (1:𝕜) (f i), rw mul_one at this, rw [linear_isometry_equiv.map_smul, b.repr_self, ← this, linear_isometry_equiv.coe_to_continuous_linear_equiv], exact (b.repr.apply_symm_apply (lp.single 2 i (f i))).symm, end protected lemma has_sum_repr (b : hilbert_basis ι 𝕜 E) (x : E) : has_sum (λ i, b.repr x i • b i) x := by simpa using b.has_sum_repr_symm (b.repr x) @[simp] protected lemma dense_span (b : hilbert_basis ι 𝕜 E) : (span 𝕜 (set.range b)).topological_closure = ⊤ := begin classical, rw eq_top_iff, rintros x -, refine mem_closure_of_tendsto (b.has_sum_repr x) (eventually_of_forall _), intros s, simp only [set_like.mem_coe], refine sum_mem _, rintros i -, refine smul_mem _ _ _, exact subset_span ⟨i, rfl⟩ end variables {v : ι → E} (hv : orthonormal 𝕜 v) include hv cplt /-- An orthonormal family of vectors whose span is dense in the whole module is a Hilbert basis. -/ protected def mk (hsp : (span 𝕜 (set.range v)).topological_closure = ⊤) : hilbert_basis ι 𝕜 E := hilbert_basis.of_repr $ hv.orthogonal_family.linear_isometry_equiv begin convert hsp, simp [← linear_map.span_singleton_eq_range, ← submodule.span_Union], end @[simp] protected lemma coe_mk (hsp : (span 𝕜 (set.range v)).topological_closure = ⊤) : ⇑(hilbert_basis.mk hv hsp) = v := begin ext i, show (hilbert_basis.mk hv hsp).repr.symm _ = v i, simp [hilbert_basis.mk] end /-- An orthonormal family of vectors whose span has trivial orthogonal complement is a Hilbert basis. -/ protected def mk_of_orthogonal_eq_bot (hsp : (span 𝕜 (set.range v))ᗮ = ⊥) : hilbert_basis ι 𝕜 E := hilbert_basis.mk hv (by rw [← orthogonal_orthogonal_eq_closure, orthogonal_eq_top_iff, hsp]) @[simp] protected lemma coe_of_orthogonal_eq_bot_mk (hsp : (span 𝕜 (set.range v))ᗮ = ⊥) : ⇑(hilbert_basis.mk_of_orthogonal_eq_bot hv hsp) = v := hilbert_basis.coe_mk hv _ omit hv /-- A Hilbert space admits a Hilbert basis extending a given orthonormal subset. -/ lemma _root_.orthonormal.exists_hilbert_basis_extension {s : set E} (hs : orthonormal 𝕜 (coe : s → E)) : ∃ (w : set E) (b : hilbert_basis w 𝕜 E), s ⊆ w ∧ ⇑b = (coe : w → E) := let ⟨w, hws, hw_ortho, hw_max⟩ := exists_maximal_orthonormal hs in ⟨ w, hilbert_basis.mk_of_orthogonal_eq_bot hw_ortho (by simpa [maximal_orthonormal_iff_orthogonal_complement_eq_bot hw_ortho] using hw_max), hws, hilbert_basis.coe_of_orthogonal_eq_bot_mk _ _ ⟩ variables (𝕜 E) /-- A Hilbert space admits a Hilbert basis. -/ lemma _root_.exists_hilbert_basis : ∃ (w : set E) (b : hilbert_basis w 𝕜 E), ⇑b = (coe : w → E) := let ⟨w, hw, hw', hw''⟩ := (orthonormal_empty 𝕜 E).exists_hilbert_basis_extension in ⟨w, hw, hw''⟩ end hilbert_basis
52289cce13d6cc2b55671a2cbd700aad5ffe8dc1
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/meta/task.lean
5f2466139834b16ef4ec5499445527c509d0147f
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
635
lean
prelude import init.logic meta constant {u} task : Type u → Type u namespace task meta constant {u} get {α : Type u} (t : task α) : α protected meta constant {u} pure {α : Type u} (t : α) : task α protected meta constant {u v} map {α : Type u} {β : Type v} (f : α → β) (t : task α) : task β protected meta constant {u} flatten {α : Type u} : task (task α) → task α protected meta def {u v} bind {α : Type u} {β : Type v} (t : task α) (f : α → task β) : task β := task.flatten (task.map f t) @[inline] meta def {u} delay {α : Type u} (f : unit → α) : task α := task.map f (task.pure ()) end task
ed2e435d783f32accc4be3cb26a72d03ce4cf049
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/class4.lean
a08ef8b4a7e4c9ca1d74d3372a3512da89dce440
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
2,415
lean
import standard inductive nat : Type := | zero : nat | succ : nat → nat definition add (x y : nat) := nat_rec x (λ n r, succ r) y infixl `+`:65 := add theorem add_zero_left (x : nat) : x + zero = x := refl _ theorem add_succ_left (x y : nat) : x + (succ y) = succ (x + y) := refl _ definition is_zero (x : nat) := nat_rec true (λ n r, false) x theorem is_zero_zero : is_zero zero := eqt_elim (refl _) theorem not_is_zero_succ (x : nat) : ¬ is_zero (succ x) := eqf_elim (refl _) theorem dichotomy (m : nat) : m = zero ∨ (∃ n, m = succ n) := nat_rec (or_intro_left _ (refl zero)) (λ m H, or_intro_right _ (exists_intro m (refl (succ m)))) m theorem is_zero_to_eq (x : nat) (H : is_zero x) : x = zero := or_elim (dichotomy x) (assume Hz : x = zero, Hz) (assume Hs : (∃ n, x = succ n), exists_elim Hs (λ (w : nat) (Hw : x = succ w), absurd_elim _ H (subst (symm Hw) (not_is_zero_succ w)))) theorem is_not_zero_to_eq {x : nat} (H : ¬ is_zero x) : ∃ n, x = succ n := or_elim (dichotomy x) (assume Hz : x = zero, absurd_elim _ (subst (symm Hz) is_zero_zero) H) (assume Hs, Hs) theorem not_zero_add (x y : nat) (H : ¬ is_zero y) : ¬ is_zero (x + y) := exists_elim (is_not_zero_to_eq H) (λ (w : nat) (Hw : y = succ w), have H1 : x + y = succ (x + w), from calc x + y = x + succ w : {Hw} ... = succ (x + w) : refl _, have H2 : ¬ is_zero (succ (x + w)), from not_is_zero_succ (x+w), subst (symm H1) H2) inductive not_zero (x : nat) : Prop := | not_zero_intro : ¬ is_zero x → not_zero x theorem not_zero_not_is_zero {x : nat} (H : not_zero x) : ¬ is_zero x := not_zero_rec (λ H1, H1) H theorem not_zero_add_right [instance] (x y : nat) (H : not_zero y) : not_zero (x + y) := not_zero_intro (not_zero_add x y (not_zero_not_is_zero H)) theorem not_zero_succ [instance] (x : nat) : not_zero (succ x) := not_zero_intro (not_is_zero_succ x) variable div : Π (x y : nat) {H : not_zero y}, nat variables a b : nat set_option pp.implicit true opaque_hint (hiding [module]) check div a (succ b) check (λ H : not_zero b, div a b) check (succ zero) check a + (succ zero) check div a (a + (succ b)) opaque_hint (exposing [module]) check div a (a + (succ b)) opaque_hint (hiding add) check div a (a + (succ b)) opaque_hint (exposing add) check div a (a + (succ b))
0db39268fa584220dd1432172ee67eee49610e53
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/440.lean
4c8d33878a12ca5f2a10f47a398e3bc72b19fabd
[ "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
138
lean
theorem t1 : True := _ theorem t2 : True := t1 def f (x : Nat) : Nat := x + _ #check f def g (x : Nat) : Nat := f (x + x) #eval g 0
fb257972b0f5e05ff8fd4762c7ec9fb3ce1b0992
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/determinant.lean
6ecad0466635009b0ee1005ce94665ba9c509515
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,387
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, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.free_module.pid import linear_algebra.matrix.basis import linear_algebra.matrix.diagonal import linear_algebra.matrix.to_linear_equiv import linear_algebra.matrix.reindex import linear_algebra.multilinear.basis import linear_algebra.dual import ring_theory.algebra_tower /-! # Determinant of families of vectors This file defines the determinant of an endomorphism, and of a family of vectors with respect to some basis. For the determinant of a matrix, see the file `linear_algebra.matrix.determinant`. ## Main definitions In the list below, and in all this file, `R` is a commutative ring (semiring is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite types used for indexing. * `basis.det`: the determinant of a family of vectors with respect to a basis, as a multilinear map * `linear_map.det`: the determinant of an endomorphism `f : End R M` as a multiplicative homomorphism (if `M` does not have a finite `R`-basis, the result is `1` instead) ## Tags basis, det, determinant -/ noncomputable theory open_locale big_operators open_locale matrix open linear_map open submodule universes u v w open linear_map matrix variables {R : Type*} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {M' : Type*} [add_comm_group M'] [module R M'] variables {ι : Type*} [decidable_eq ι] [fintype ι] variables (e : basis ι R M) section conjugate variables {A : Type*} [comm_ring A] variables {m n : Type*} [fintype m] [fintype n] /-- If `R^m` and `R^n` are linearly equivalent, then `m` and `n` are also equivalent. -/ def equiv_of_pi_lequiv_pi {R : Type*} [comm_ring R] [is_domain R] (e : (m → R) ≃ₗ[R] (n → R)) : m ≃ n := basis.index_equiv (basis.of_equiv_fun e.symm) (pi.basis_fun _ _) namespace matrix /-- If `M` and `M'` are each other's inverse matrices, they are square matrices up to equivalence of types. -/ def index_equiv_of_inv [is_domain A] [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : m ≃ n := equiv_of_pi_lequiv_pi (to_lin'_of_inv hMM' hM'M) lemma det_comm [decidable_eq n] (M N : matrix n n A) : det (M ⬝ N) = det (N ⬝ M) := by rw [det_mul, det_mul, mul_comm] /-- If there exists a two-sided inverse `M'` for `M` (indexed differently), then `det (N ⬝ M) = det (M ⬝ N)`. -/ lemma det_comm' [is_domain A] [decidable_eq m] [decidable_eq n] {M : matrix n m A} {N : matrix m n A} {M' : matrix m n A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : det (M ⬝ N) = det (N ⬝ M) := -- Although `m` and `n` are different a priori, we will show they have the same cardinality. -- This turns the problem into one for square matrices, which is easy. let e := index_equiv_of_inv hMM' hM'M in by rw [← det_minor_equiv_self e, minor_mul_equiv _ _ _ (equiv.refl n) _, det_comm, ← minor_mul_equiv, equiv.coe_refl, minor_id_id] /-- If `M'` is a two-sided inverse for `M` (indexed differently), `det (M ⬝ N ⬝ M') = det N`. -/ lemma det_conj [is_domain A] [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} {N : matrix n n A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : det (M ⬝ N ⬝ M') = det N := by rw [← det_comm' hM'M hMM', ← matrix.mul_assoc, hM'M, matrix.one_mul] end matrix end conjugate namespace linear_map /-! ### Determinant of a linear map -/ variables {A : Type*} [comm_ring A] [is_domain A] [module A M] variables {κ : Type*} [fintype κ] /-- The determinant of `linear_map.to_matrix` does not depend on the choice of basis. -/ lemma det_to_matrix_eq_det_to_matrix [decidable_eq κ] (b : basis ι A M) (c : basis κ A M) (f : M →ₗ[A] M) : det (linear_map.to_matrix b b f) = det (linear_map.to_matrix c c f) := by rw [← linear_map_to_matrix_mul_basis_to_matrix c b c, ← basis_to_matrix_mul_linear_map_to_matrix b c b, matrix.det_conj]; rw [basis.to_matrix_mul_to_matrix, basis.to_matrix_self] /-- The determinant of an endomorphism given a basis. See `linear_map.det` for a version that populates the basis non-computably. Although the `trunc (basis ι A M)` parameter makes it slightly more convenient to switch bases, there is no good way to generalize over universe parameters, so we can't fully state in `det_aux`'s type that it does not depend on the choice of basis. Instead you can use the `det_aux_def'` lemma, or avoid mentioning a basis at all using `linear_map.det`. -/ def det_aux : trunc (basis ι A M) → (M →ₗ[A] M) →* A := trunc.lift (λ b : basis ι A M, (det_monoid_hom).comp (to_matrix_alg_equiv b : (M →ₗ[A] M) →* matrix ι ι A)) (λ b c, monoid_hom.ext $ det_to_matrix_eq_det_to_matrix b c) /-- Unfold lemma for `det_aux`. See also `det_aux_def'` which allows you to vary the basis. -/ lemma det_aux_def (b : basis ι A M) (f : M →ₗ[A] M) : linear_map.det_aux (trunc.mk b) f = matrix.det (linear_map.to_matrix b b f) := rfl -- Discourage the elaborator from unfolding `det_aux` and producing a huge term. attribute [irreducible] linear_map.det_aux lemma det_aux_def' {ι' : Type*} [fintype ι'] [decidable_eq ι'] (tb : trunc $ basis ι A M) (b' : basis ι' A M) (f : M →ₗ[A] M) : linear_map.det_aux tb f = matrix.det (linear_map.to_matrix b' b' f) := by { apply trunc.induction_on tb, intro b, rw [det_aux_def, det_to_matrix_eq_det_to_matrix b b'] } @[simp] lemma det_aux_id (b : trunc $ basis ι A M) : linear_map.det_aux b (linear_map.id) = 1 := (linear_map.det_aux b).map_one @[simp] lemma det_aux_comp (b : trunc $ basis ι A M) (f g : M →ₗ[A] M) : linear_map.det_aux b (f.comp g) = linear_map.det_aux b f * linear_map.det_aux b g := (linear_map.det_aux b).map_mul f g section open_locale classical -- Discourage the elaborator from unfolding `det` and producing a huge term by marking it -- as irreducible. /-- The determinant of an endomorphism independent of basis. If there is no finite basis on `M`, the result is `1` instead. -/ @[irreducible] protected def det : (M →ₗ[A] M) →* A := if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 lemma coe_det [decidable_eq M] : ⇑(linear_map.det : (M →ₗ[A] M) →* A) = if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 := by { ext, unfold linear_map.det, split_ifs, { congr }, -- use the correct `decidable_eq` instance refl } end -- Auxiliary lemma, the `simp` normal form goes in the other direction -- (using `linear_map.det_to_matrix`) lemma det_eq_det_to_matrix_of_finset [decidable_eq M] {s : finset M} (b : basis s A M) (f : M →ₗ[A] M) : f.det = matrix.det (linear_map.to_matrix b b f) := have ∃ (s : finset M), nonempty (basis s A M), from ⟨s, ⟨b⟩⟩, by rw [linear_map.coe_det, dif_pos, det_aux_def' _ b]; assumption @[simp] lemma det_to_matrix (b : basis ι A M) (f : M →ₗ[A] M) : matrix.det (to_matrix b b f) = f.det := by { haveI := classical.dec_eq M, rw [det_eq_det_to_matrix_of_finset b.reindex_finset_range, det_to_matrix_eq_det_to_matrix b] } @[simp] lemma det_to_matrix' {ι : Type*} [fintype ι] [decidable_eq ι] (f : (ι → A) →ₗ[A] (ι → A)) : det f.to_matrix' = f.det := by simp [← to_matrix_eq_to_matrix'] /-- To show `P f.det` it suffices to consider `P (to_matrix _ _ f).det` and `P 1`. -/ @[elab_as_eliminator] lemma det_cases [decidable_eq M] {P : A → Prop} (f : M →ₗ[A] M) (hb : ∀ (s : finset M) (b : basis s A M), P (to_matrix b b f).det) (h1 : P 1) : P f.det := begin unfold linear_map.det, split_ifs with h, { convert hb _ h.some_spec.some, apply det_aux_def' }, { exact h1 } end @[simp] lemma det_comp (f g : M →ₗ[A] M) : (f.comp g).det = f.det * g.det := linear_map.det.map_mul f g @[simp] lemma det_id : (linear_map.id : M →ₗ[A] M).det = 1 := linear_map.det.map_one /-- Multiplying a map by a scalar `c` multiplies its determinant by `c ^ dim M`. -/ @[simp] lemma det_smul {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] (c : 𝕜) (f : M →ₗ[𝕜] M) : linear_map.det (c • f) = c ^ (finite_dimensional.finrank 𝕜 M) * linear_map.det f := begin by_cases H : ∃ (s : finset M), nonempty (basis s 𝕜 M), { haveI : finite_dimensional 𝕜 M, { rcases H with ⟨s, ⟨hs⟩⟩, exact finite_dimensional.of_finset_basis hs }, simp only [← det_to_matrix (finite_dimensional.fin_basis 𝕜 M), linear_equiv.map_smul, fintype.card_fin, det_smul] }, { classical, have : finite_dimensional.finrank 𝕜 M = 0 := finrank_eq_zero_of_not_exists_basis H, simp [coe_det, H, this] } end lemma det_zero' {ι : Type*} [fintype ι] [nonempty ι] (b : basis ι A M) : linear_map.det (0 : M →ₗ[A] M) = 0 := by { haveI := classical.dec_eq ι, rw [← det_to_matrix b, linear_equiv.map_zero, det_zero], assumption } /-- In a finite-dimensional vector space, the zero map has determinant `1` in dimension `0`, and `0` otherwise. -/ @[simp] lemma det_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] : linear_map.det (0 : M →ₗ[𝕜] M) = (0 : 𝕜) ^ (finite_dimensional.finrank 𝕜 M) := by simp only [← zero_smul 𝕜 (1 : M →ₗ[𝕜] M), det_smul, mul_one, monoid_hom.map_one] /-- Conjugating a linear map by a linear equiv does not change its determinant. -/ @[simp] lemma det_conj {N : Type*} [add_comm_group N] [module A N] (f : M →ₗ[A] M) (e : M ≃ₗ[A] N) : linear_map.det ((e : M →ₗ[A] N) ∘ₗ (f ∘ₗ (e.symm : N →ₗ[A] M))) = linear_map.det f := begin classical, by_cases H : ∃ (s : finset M), nonempty (basis s A M), { rcases H with ⟨s, ⟨b⟩⟩, rw [← det_to_matrix b f, ← det_to_matrix (b.map e), to_matrix_comp (b.map e) b (b.map e), to_matrix_comp (b.map e) b b, ← matrix.mul_assoc, matrix.det_conj], { rw [← to_matrix_comp, linear_equiv.comp_coe, e.symm_trans, linear_equiv.refl_to_linear_map, to_matrix_id] }, { rw [← to_matrix_comp, linear_equiv.comp_coe, e.trans_symm, linear_equiv.refl_to_linear_map, to_matrix_id] } }, { have H' : ¬ (∃ (t : finset N), nonempty (basis t A N)), { contrapose! H, rcases H with ⟨s, ⟨b⟩⟩, exact ⟨_, ⟨(b.map e.symm).reindex_finset_range⟩⟩ }, simp only [coe_det, H, H', pi.one_apply, dif_neg, not_false_iff] } end end linear_map -- Cannot be stated using `linear_map.det` because `f` is not an endomorphism. lemma linear_equiv.is_unit_det (f : M ≃ₗ[R] M') (v : basis ι R M) (v' : basis ι R M') : is_unit (linear_map.to_matrix v v' f).det := begin apply is_unit_det_of_left_inverse, simpa using (linear_map.to_matrix_comp v v' v f.symm f).symm end /-- Specialization of `linear_equiv.is_unit_det` -/ lemma linear_equiv.is_unit_det' {A : Type*} [comm_ring A] [is_domain A] [module A M] (f : M ≃ₗ[A] M) : is_unit (linear_map.det (f : M →ₗ[A] M)) := by haveI := classical.dec_eq M; exact (f : M →ₗ[A] M).det_cases (λ s b, f.is_unit_det _ _) is_unit_one /-- Builds a linear equivalence from a linear map whose determinant in some bases is a unit. -/ @[simps] def linear_equiv.of_is_unit_det {f : M →ₗ[R] M'} {v : basis ι R M} {v' : basis ι R M'} (h : is_unit (linear_map.to_matrix v v' f).det) : M ≃ₗ[R] M' := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul, inv_fun := to_lin v' v (to_matrix v v' f)⁻¹, left_inv := λ x, calc to_lin v' v (to_matrix v v' f)⁻¹ (f x) = to_lin v v ((to_matrix v v' f)⁻¹ ⬝ to_matrix v v' f) x : by { rw [to_lin_mul v v' v, to_lin_to_matrix, linear_map.comp_apply] } ... = x : by simp [h], right_inv := λ x, calc f (to_lin v' v (to_matrix v v' f)⁻¹ x) = to_lin v' v' (to_matrix v v' f ⬝ (to_matrix v v' f)⁻¹) x : by { rw [to_lin_mul v' v v', linear_map.comp_apply, to_lin_to_matrix v v'] } ... = x : by simp [h] } /-- Builds a linear equivalence from a linear map on a finite-dimensional vector space whose determinant is nonzero. -/ @[reducible] def linear_map.equiv_of_det_ne_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] [finite_dimensional 𝕜 M] (f : M →ₗ[𝕜] M) (hf : linear_map.det f ≠ 0) : M ≃ₗ[𝕜] M := have is_unit (linear_map.to_matrix (finite_dimensional.fin_basis 𝕜 M) (finite_dimensional.fin_basis 𝕜 M) f).det := by simp only [linear_map.det_to_matrix, is_unit_iff_ne_zero.2 hf], linear_equiv.of_is_unit_det this /-- The determinant of a family of vectors with respect to some basis, as an alternating multilinear map. -/ def basis.det : alternating_map R M R ι := { to_fun := λ v, det (e.to_matrix v), map_add' := begin intros v i x y, simp only [e.to_matrix_update, linear_equiv.map_add], apply det_update_column_add end, map_smul' := begin intros u i c x, simp only [e.to_matrix_update, algebra.id.smul_eq_mul, linear_equiv.map_smul], apply det_update_column_smul end, map_eq_zero_of_eq' := begin intros v i j h hij, rw [←function.update_eq_self i v, h, ←det_transpose, e.to_matrix_update, ←update_row_transpose, ←e.to_matrix_transpose_apply], apply det_zero_of_row_eq hij, rw [update_row_ne hij.symm, update_row_self], end } lemma basis.det_apply (v : ι → M) : e.det v = det (e.to_matrix v) := rfl lemma basis.det_self : e.det e = 1 := by simp [e.det_apply] /-- `basis.det` is not the zero map. -/ lemma basis.det_ne_zero [nontrivial R] : e.det ≠ 0 := λ h, by simpa [h] using e.det_self lemma is_basis_iff_det {v : ι → M} : linear_independent R v ∧ span R (set.range v) = ⊤ ↔ is_unit (e.det v) := begin split, { rintro ⟨hli, hspan⟩, set v' := basis.mk hli hspan with v'_eq, rw e.det_apply, convert linear_equiv.is_unit_det (linear_equiv.refl _ _) v' e using 2, ext i j, simp }, { intro h, rw [basis.det_apply, basis.to_matrix_eq_to_matrix_constr] at h, set v' := basis.map e (linear_equiv.of_is_unit_det h) with v'_def, have : ⇑ v' = v, { ext i, rw [v'_def, basis.map_apply, linear_equiv.of_is_unit_det_apply, e.constr_basis] }, rw ← this, exact ⟨v'.linear_independent, v'.span_eq⟩ }, end lemma basis.is_unit_det (e' : basis ι R M) : is_unit (e.det e') := (is_basis_iff_det e).mp ⟨e'.linear_independent, e'.span_eq⟩ /-- Any alternating map to `R` where `ι` has the cardinality of a basis equals the determinant map with respect to that basis, multiplied by the value of that alternating map on that basis. -/ lemma alternating_map.eq_smul_basis_det (f : alternating_map R M R ι) : f = f e • e.det := begin refine basis.ext_alternating e (λ i h, _), let σ : equiv.perm ι := equiv.of_bijective i (fintype.injective_iff_bijective.1 h), change f (e ∘ σ) = (f e • e.det) (e ∘ σ), simp [alternating_map.map_perm, basis.det_self] end variables {A : Type*} [comm_ring A] [is_domain A] [module A M] @[simp] lemma basis.det_comp (e : basis ι A M) (f : M →ₗ[A] M) (v : ι → M) : e.det (f ∘ v) = f.det * e.det v := by { rw [basis.det_apply, basis.det_apply, ← f.det_to_matrix e, ← matrix.det_mul, e.to_matrix_eq_to_matrix_constr (f ∘ v), e.to_matrix_eq_to_matrix_constr v, ← to_matrix_comp, e.constr_comp] } lemma basis.det_reindex {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι' → M) (e : ι ≃ ι') : (b.reindex e).det v = b.det (v ∘ e) := by rw [basis.det_apply, basis.to_matrix_reindex', det_reindex_alg_equiv, basis.det_apply] lemma basis.det_reindex_symm {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι → M) (e : ι' ≃ ι) : (b.reindex e.symm).det (v ∘ e) = b.det v := by rw [basis.det_reindex, function.comp.assoc, e.self_comp_symm, function.comp.right_id] @[simp] lemma basis.det_map (b : basis ι R M) (f : M ≃ₗ[R] M') (v : ι → M') : (b.map f).det v = b.det (f.symm ∘ v) := by { rw [basis.det_apply, basis.to_matrix_map, basis.det_apply] }
0798810cced33256371e981311a3abfe080601bc
92b50235facfbc08dfe7f334827d47281471333b
/hott/types/pointed.hlean
c3e13f64542d1b64a098746b3c9c5150b22847e4
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
9,378
hlean
/- Copyright (c) 2014 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 Ported from Coq HoTT -/ import arity .eq .bool .unit .sigma open is_trunc eq prod sigma nat equiv option is_equiv bool unit structure pointed [class] (A : Type) := (point : A) structure Pointed := {carrier : Type} (Point : carrier) open Pointed namespace pointed attribute Pointed.carrier [coercion] variables {A B : Type} definition pt [unfold 2] [H : pointed A] := point A protected abbreviation Mk [constructor] := @Pointed.mk protected definition mk' [constructor] (A : Type) [H : pointed A] : Pointed := Pointed.mk (point A) definition pointed_carrier [instance] [constructor] (A : Pointed) : pointed A := pointed.mk (Point A) -- Any contractible type is pointed definition pointed_of_is_contr [instance] [priority 800] [constructor] (A : Type) [H : is_contr A] : pointed A := pointed.mk !center -- A pi type with a pointed target is pointed definition pointed_pi [instance] [constructor] (P : A → Type) [H : Πx, pointed (P x)] : pointed (Πx, P x) := pointed.mk (λx, pt) -- A sigma type of pointed components is pointed definition pointed_sigma [instance] [constructor] (P : A → Type) [G : pointed A] [H : pointed (P pt)] : pointed (Σx, P x) := pointed.mk ⟨pt,pt⟩ definition pointed_prod [instance] [constructor] (A B : Type) [H1 : pointed A] [H2 : pointed B] : pointed (A × B) := pointed.mk (pt,pt) definition pointed_loop [instance] [constructor] (a : A) : pointed (a = a) := pointed.mk idp definition pointed_bool [instance] [constructor] : pointed bool := pointed.mk ff definition Bool [constructor] : Pointed := pointed.mk' bool definition pointed_fun_closed [constructor] (f : A → B) [H : pointed A] : pointed B := pointed.mk (f pt) definition Loop_space [reducible] [constructor] (A : Pointed) : Pointed := pointed.mk' (point A = point A) -- definition Iterated_loop_space : Pointed → ℕ → Pointed -- | Iterated_loop_space A 0 := A -- | Iterated_loop_space A (n+1) := Iterated_loop_space (Loop_space A) n definition Iterated_loop_space [reducible] (n : ℕ) (A : Pointed) : Pointed := nat.rec_on n (λA, A) (λn IH A, IH (Loop_space A)) A prefix `Ω`:(max+5) := Loop_space notation `Ω[`:95 n:0 `]`:0 A:95 := Iterated_loop_space n A definition iterated_loop_space (A : Type) [H : pointed A] (n : ℕ) : Type := Ω[n] (pointed.mk' A) open equiv.ops definition Pointed_eq {A B : Pointed} (f : A ≃ B) (p : f pt = pt) : A = B := begin cases A with A a, cases B with B b, esimp at *, fapply apd011 @Pointed.mk, { apply ua f}, { rewrite [cast_ua,p]}, end definition add_point [constructor] (A : Type) : Pointed := Pointed.mk (none : option A) postfix `₊`:(max+1) := add_point -- the inclusion A → A₊ is called "some", the extra point "pt" or "none" ("@none A") end pointed open pointed structure pmap (A B : Pointed) := (map : A → B) (resp_pt : map (Point A) = Point B) open pmap namespace pointed abbreviation respect_pt [unfold 3] := @pmap.resp_pt notation `map₊` := pmap infix `→*`:30 := pmap attribute pmap.map [coercion] variables {A B C D : Pointed} {f g h : A →* B} definition pmap_eq (r : Πa, f a = g a) (s : respect_pt f = (r pt) ⬝ respect_pt g) : f = g := begin cases f with f p, cases g with g q, esimp at *, fapply apo011 pmap.mk, { exact eq_of_homotopy r}, { apply concato_eq, apply pathover_eq_Fl, apply inv_con_eq_of_eq_con, rewrite [ap_eq_ap10,↑ap10,apd10_eq_of_homotopy,s]} end definition pid [constructor] (A : Pointed) : A →* A := pmap.mk function.id idp definition pcompose [constructor] (g : B →* C) (f : A →* B) : A →* C := pmap.mk (λa, g (f a)) (ap g (respect_pt f) ⬝ respect_pt g) infixr `∘*`:60 := pcompose structure phomotopy (f g : A →* B) := (homotopy : f ~ g) (homotopy_pt : homotopy pt ⬝ respect_pt g = respect_pt f) infix `~*`:50 := phomotopy abbreviation to_homotopy_pt [unfold 5] := @phomotopy.homotopy_pt abbreviation to_homotopy [coercion] [unfold 5] (p : f ~* g) : Πa, f a = g a := phomotopy.homotopy p definition passoc (h : C →* D) (g : B →* C) (f : A →* B) : (h ∘* g) ∘* f ~* h ∘* (g ∘* f) := begin fconstructor, intro a, reflexivity, cases A, cases B, cases C, cases D, cases f with f pf, cases g with g pg, cases h with h ph, esimp at *, induction pf, induction pg, induction ph, reflexivity end definition pid_comp (f : A →* B) : pid B ∘* f ~* f := begin fconstructor, { intro a, reflexivity}, { esimp, exact !idp_con ⬝ !ap_id⁻¹} end definition comp_pid (f : A →* B) : f ∘* pid A ~* f := begin fconstructor, { intro a, reflexivity}, { reflexivity} end definition pmap_equiv_left (A : Type) (B : Pointed) : A₊ →* B ≃ (A → B) := begin fapply equiv.MK, { intro f a, cases f with f p, exact f (some a)}, { intro f, fconstructor, intro a, cases a, exact pt, exact f a, reflexivity}, { intro f, reflexivity}, { intro f, cases f with f p, esimp, fapply pmap_eq, { intro a, cases a; all_goals (esimp at *), exact p⁻¹}, { esimp, exact !con.left_inv⁻¹}}, end -- definition Loop_space_functor (f : A →* B) : Ω A →* Ω B := -- begin -- fapply pmap.mk, -- { intro p, exact ap f p}, -- end -- set_option pp.notation false -- definition pmap_equiv_right (A : Pointed) (B : Type) -- : (Σ(b : B), map₊ A (pointed.Mk b)) ≃ (A → B) := -- begin -- fapply equiv.MK, -- { intro u a, cases u with b f, cases f with f p, esimp at f, exact f a}, -- { intro f, refine ⟨f pt, _⟩, fapply pmap.mk, -- intro a, esimp, exact f a, -- reflexivity}, -- { intro f, reflexivity}, -- { intro u, cases u with b f, cases f with f p, esimp at *, apply sigma_eq p, -- esimp, apply sorry -- } -- end definition pmap_bool_equiv (B : Pointed) : map₊ Bool B ≃ B := begin fapply equiv.MK, { intro f, cases f with f p, exact f tt}, { intro b, fconstructor, intro u, cases u, exact pt, exact b, reflexivity}, { intro b, reflexivity}, { intro f, cases f with f p, esimp, fapply pmap_eq, { intro a, cases a; all_goals (esimp at *), exact p⁻¹}, { esimp, exact !con.left_inv⁻¹}}, end definition apn [constructor] (n : ℕ) (f : map₊ A B) : Ω[n] A →* Ω[n] B := begin revert A B f, induction n with n IH, { intros A B f, exact f}, { intros A B f, esimp [Iterated_loop_space], apply IH (Ω A), { esimp, fconstructor, intro q, refine !respect_pt⁻¹ ⬝ ap f q ⬝ !respect_pt, esimp, apply con.left_inv}} end definition ap1 [constructor] (f : A →* B) : Ω A →* Ω B := apn (succ 0) f definition ap1_compose (g : B →* C) (f : A →* B) : ap1 (g ∘* f) ~* ap1 g ∘* ap1 f := begin induction B, induction C, induction g with g pg, induction f with f pf, esimp at *, induction pg, induction pf, fconstructor, { intro p, esimp, apply whisker_left, exact ap_compose g f p ⬝ ap (ap g) !idp_con⁻¹}, { reflexivity} end protected definition phomotopy.refl [refl] (f : A →* B) : f ~* f := begin fconstructor, { intro a, exact idp}, { apply idp_con} end protected definition phomotopy.trans [trans] (p : f ~* g) (q : g ~* h) : f ~* h := begin fconstructor, { intro a, exact p a ⬝ q a}, { induction f, induction g, induction p with p p', induction q with q q', esimp at *, induction p', induction q', esimp, apply con.assoc} end protected definition phomotopy.symm [symm] (p : f ~* g) : g ~* f := begin fconstructor, { intro a, exact (p a)⁻¹}, { induction f, induction p with p p', esimp at *, induction p', esimp, apply inv_con_cancel_left} end infix `⬝*`:75 := phomotopy.trans postfix `⁻¹*`:(max+1) := phomotopy.symm definition eq_of_phomotopy (p : f ~* g) : f = g := begin fapply pmap_eq, { intro a, exact p a}, { exact !to_homotopy_pt⁻¹} end definition pwhisker_left (h : B →* C) (p : f ~* g) : h ∘* f ~* h ∘* g := begin fconstructor, { intro a, exact ap h (p a)}, { induction A, induction B, induction C, induction f with f pf, induction g with g pg, induction h with h ph, induction p with p p', esimp at *, induction ph, induction pg, induction p', reflexivity} end definition pwhisker_right (h : C →* A) (p : f ~* g) : f ∘* h ~* g ∘* h := begin fconstructor, { intro a, exact p (h a)}, { induction A, induction B, induction C, induction f with f pf, induction g with g pg, induction h with h ph, induction p with p p', esimp at *, induction ph, induction pg, induction p', esimp, exact !idp_con⁻¹} end structure pequiv (A B : Pointed) := (to_pmap : A →* B) (is_equiv_to_pmap : is_equiv to_pmap) infix `≃*`:25 := pequiv attribute pequiv.to_pmap [coercion] attribute pequiv.is_equiv_to_pmap [instance] definition equiv_of_pequiv [constructor] (f : A ≃* B) : A ≃ B := equiv.mk f _ end pointed
d031eafbf9dd8b4f455484fa7365d6dc9434d51e
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Server/FileWorker/WidgetRequests.lean
d4124510999fbbda3b00730c8c36ea5ea7ddab9b
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
2,421
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Widget.InteractiveCode import Lean.Widget.InteractiveGoal import Lean.Widget.InteractiveDiagnostic import Lean.Server.Rpc.RequestHandling import Lean.Server.FileWorker.RequestHandling /-! Registers all widget-related RPC procedures. -/ namespace Lean.Widget open Server structure MsgToInteractive where msg : WithRpcRef MessageData indent : Nat deriving Inhabited, RpcEncoding builtin_initialize registerRpcCallHandler `Lean.Widget.InteractiveDiagnostics.msgToInteractive MsgToInteractive (TaggedText MsgEmbed) fun ⟨⟨m⟩, i⟩ => RequestM.asTask do msgToInteractive m i structure InfoPopup where type : Option CodeWithInfos exprExplicit : Option CodeWithInfos doc : Option String deriving Inhabited, RpcEncoding builtin_initialize registerRpcCallHandler `Lean.Widget.InteractiveDiagnostics.infoToInteractive (WithRpcRef InfoWithCtx) InfoPopup fun ⟨i⟩ => RequestM.asTask do i.ctx.runMetaM i.lctx do let type? ← match (← i.info.type?) with | some type => some <$> exprToInteractive type | none => none let exprExplicit? ← match i.info with | Elab.Info.ofTermInfo ti => some <$> exprToInteractiveExplicit ti.expr | Elab.Info.ofFieldInfo fi => some (TaggedText.text fi.fieldName.toString) | _ => none return { type := type? exprExplicit := exprExplicit? doc := ← i.info.docString? : InfoPopup } builtin_initialize registerRpcCallHandler `Lean.Widget.getInteractiveGoals Lsp.PlainGoalParams (Option InteractiveGoals) FileWorker.getInteractiveGoals registerRpcCallHandler `Lean.Widget.getInteractiveTermGoal Lsp.PlainTermGoalParams (Option InteractiveTermGoal) FileWorker.getInteractiveTermGoal open RequestM in def getInteractiveDiagnostics (_ : Json) : RequestM (RequestTask (Array InteractiveDiagnostic)) := do let doc ← readDoc let t₁ ← doc.cmdSnaps.waitAll t₁.map fun (snaps, _) => snaps.getLast!.interactiveDiags.toArray builtin_initialize registerRpcCallHandler `Lean.Widget.getInteractiveDiagnostics Json (Array InteractiveDiagnostic) getInteractiveDiagnostics end Lean.Widget
b35f57041d0c1813b3a3e11b3cb5d5b904eaadd5
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/local_extr.lean
339de81f73af8e319c92334bb83f73491ee75dcf
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,875
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import order.filter.extr import topology.continuous_on /-! # Local extrema of functions on topological spaces ## Main definitions This file defines special versions of `is_*_filter f a l`, `*=min/max/extr`, from `order/filter/extr` for two kinds of filters: `nhds_within` and `nhds`. These versions are called `is_local_*_on` and `is_local_*`, respectively. ## Main statements Many lemmas in this file restate those from `order/filter/extr`, and you can find a detailed documentation there. These convenience lemmas are provided only to make the dot notation return propositions of expected types, not just `is_*_filter`. Here is the list of statements specific to these two types of filters: * `is_local_*.on`, `is_local_*_on.on_subset`: restrict to a subset; * `is_local_*_on.inter` : intersect the set with another one; * `is_*_on.localize` : a global extremum is a local extremum too. * `is_[local_]*_on.is_local_*` : if we have `is_local_*_on f s a` and `s ∈ 𝓝 a`, then we have `is_local_* f a`. -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [topological_space α] open set filter open_locale topological_space filter section preorder variables [preorder β] [preorder γ] (f : α → β) (s : set α) (a : α) /-- `is_local_min_on f s a` means that `f a ≤ f x` for all `x ∈ s` in some neighborhood of `a`. -/ def is_local_min_on := is_min_filter f (𝓝[s] a) a /-- `is_local_max_on f s a` means that `f x ≤ f a` for all `x ∈ s` in some neighborhood of `a`. -/ def is_local_max_on := is_max_filter f (𝓝[s] a) a /-- `is_local_extr_on f s a` means `is_local_min_on f s a ∨ is_local_max_on f s a`. -/ def is_local_extr_on := is_extr_filter f (𝓝[s] a) a /-- `is_local_min f a` means that `f a ≤ f x` for all `x` in some neighborhood of `a`. -/ def is_local_min := is_min_filter f (𝓝 a) a /-- `is_local_max f a` means that `f x ≤ f a` for all `x ∈ s` in some neighborhood of `a`. -/ def is_local_max := is_max_filter f (𝓝 a) a /-- `is_local_extr_on f s a` means `is_local_min_on f s a ∨ is_local_max_on f s a`. -/ def is_local_extr := is_extr_filter f (𝓝 a) a variables {f s a} lemma is_local_extr_on.elim {p : Prop} : is_local_extr_on f s a → (is_local_min_on f s a → p) → (is_local_max_on f s a → p) → p := or.elim lemma is_local_extr.elim {p : Prop} : is_local_extr f a → (is_local_min f a → p) → (is_local_max f a → p) → p := or.elim /-! ### Restriction to (sub)sets -/ lemma is_local_min.on (h : is_local_min f a) (s) : is_local_min_on f s a := h.filter_inf _ lemma is_local_max.on (h : is_local_max f a) (s) : is_local_max_on f s a := h.filter_inf _ lemma is_local_extr.on (h : is_local_extr f a) (s) : is_local_extr_on f s a := h.filter_inf _ lemma is_local_min_on.on_subset {t : set α} (hf : is_local_min_on f t a) (h : s ⊆ t) : is_local_min_on f s a := hf.filter_mono $ nhds_within_mono a h lemma is_local_max_on.on_subset {t : set α} (hf : is_local_max_on f t a) (h : s ⊆ t) : is_local_max_on f s a := hf.filter_mono $ nhds_within_mono a h lemma is_local_extr_on.on_subset {t : set α} (hf : is_local_extr_on f t a) (h : s ⊆ t) : is_local_extr_on f s a := hf.filter_mono $ nhds_within_mono a h lemma is_local_min_on.inter (hf : is_local_min_on f s a) (t) : is_local_min_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) lemma is_local_max_on.inter (hf : is_local_max_on f s a) (t) : is_local_max_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) lemma is_local_extr_on.inter (hf : is_local_extr_on f s a) (t) : is_local_extr_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) lemma is_min_on.localize (hf : is_min_on f s a) : is_local_min_on f s a := hf.filter_mono $ inf_le_right lemma is_max_on.localize (hf : is_max_on f s a) : is_local_max_on f s a := hf.filter_mono $ inf_le_right lemma is_extr_on.localize (hf : is_extr_on f s a) : is_local_extr_on f s a := hf.filter_mono $ inf_le_right lemma is_local_min_on.is_local_min (hf : is_local_min_on f s a) (hs : s ∈ 𝓝 a) : is_local_min f a := have 𝓝 a ≤ 𝓟 s, from le_principal_iff.2 hs, hf.filter_mono $ le_inf (le_refl _) this lemma is_local_max_on.is_local_max (hf : is_local_max_on f s a) (hs : s ∈ 𝓝 a) : is_local_max f a := have 𝓝 a ≤ 𝓟 s, from le_principal_iff.2 hs, hf.filter_mono $ le_inf (le_refl _) this lemma is_local_extr_on.is_local_extr (hf : is_local_extr_on f s a) (hs : s ∈ 𝓝 a) : is_local_extr f a := hf.elim (λ hf, (hf.is_local_min hs).is_extr) (λ hf, (hf.is_local_max hs).is_extr) lemma is_min_on.is_local_min (hf : is_min_on f s a) (hs : s ∈ 𝓝 a) : is_local_min f a := hf.localize.is_local_min hs lemma is_max_on.is_local_max (hf : is_max_on f s a) (hs : s ∈ 𝓝 a) : is_local_max f a := hf.localize.is_local_max hs lemma is_extr_on.is_local_extr (hf : is_extr_on f s a) (hs : s ∈ 𝓝 a) : is_local_extr f a := hf.localize.is_local_extr hs lemma is_local_min_on.not_nhds_le_map [topological_space β] (hf : is_local_min_on f s a) [ne_bot (𝓝[Iio (f a)] (f a))] : ¬𝓝 (f a) ≤ map f (𝓝[s] a) := λ hle, have ∀ᶠ y in 𝓝[Iio (f a)] (f a), f a ≤ y, from (eventually_map.2 hf).filter_mono (inf_le_left.trans hle), let ⟨y, hy⟩ := (this.and self_mem_nhds_within).exists in hy.1.not_lt hy.2 lemma is_local_max_on.not_nhds_le_map [topological_space β] (hf : is_local_max_on f s a) [ne_bot (𝓝[Ioi (f a)] (f a))] : ¬𝓝 (f a) ≤ map f (𝓝[s] a) := @is_local_min_on.not_nhds_le_map α (order_dual β) _ _ _ _ _ ‹_› hf ‹_› lemma is_local_extr_on.not_nhds_le_map [topological_space β] (hf : is_local_extr_on f s a) [ne_bot (𝓝[Iio (f a)] (f a))] [ne_bot (𝓝[Ioi (f a)] (f a))] : ¬𝓝 (f a) ≤ map f (𝓝[s] a) := hf.elim (λ h, h.not_nhds_le_map) (λ h, h.not_nhds_le_map) /-! ### Constant -/ lemma is_local_min_on_const {b : β} : is_local_min_on (λ _, b) s a := is_min_filter_const lemma is_local_max_on_const {b : β} : is_local_max_on (λ _, b) s a := is_max_filter_const lemma is_local_extr_on_const {b : β} : is_local_extr_on (λ _, b) s a := is_extr_filter_const lemma is_local_min_const {b : β} : is_local_min (λ _, b) a := is_min_filter_const lemma is_local_max_const {b : β} : is_local_max (λ _, b) a := is_max_filter_const lemma is_local_extr_const {b : β} : is_local_extr (λ _, b) a := is_extr_filter_const /-! ### Composition with (anti)monotone functions -/ lemma is_local_min.comp_mono (hf : is_local_min f a) {g : β → γ} (hg : monotone g) : is_local_min (g ∘ f) a := hf.comp_mono hg lemma is_local_max.comp_mono (hf : is_local_max f a) {g : β → γ} (hg : monotone g) : is_local_max (g ∘ f) a := hf.comp_mono hg lemma is_local_extr.comp_mono (hf : is_local_extr f a) {g : β → γ} (hg : monotone g) : is_local_extr (g ∘ f) a := hf.comp_mono hg lemma is_local_min.comp_antitone (hf : is_local_min f a) {g : β → γ} (hg : antitone g) : is_local_max (g ∘ f) a := hf.comp_antitone hg lemma is_local_max.comp_antitone (hf : is_local_max f a) {g : β → γ} (hg : antitone g) : is_local_min (g ∘ f) a := hf.comp_antitone hg lemma is_local_extr.comp_antitone (hf : is_local_extr f a) {g : β → γ} (hg : antitone g) : is_local_extr (g ∘ f) a := hf.comp_antitone hg lemma is_local_min_on.comp_mono (hf : is_local_min_on f s a) {g : β → γ} (hg : monotone g) : is_local_min_on (g ∘ f) s a := hf.comp_mono hg lemma is_local_max_on.comp_mono (hf : is_local_max_on f s a) {g : β → γ} (hg : monotone g) : is_local_max_on (g ∘ f) s a := hf.comp_mono hg lemma is_local_extr_on.comp_mono (hf : is_local_extr_on f s a) {g : β → γ} (hg : monotone g) : is_local_extr_on (g ∘ f) s a := hf.comp_mono hg lemma is_local_min_on.comp_antitone (hf : is_local_min_on f s a) {g : β → γ} (hg : antitone g) : is_local_max_on (g ∘ f) s a := hf.comp_antitone hg lemma is_local_max_on.comp_antitone (hf : is_local_max_on f s a) {g : β → γ} (hg : antitone g) : is_local_min_on (g ∘ f) s a := hf.comp_antitone hg lemma is_local_extr_on.comp_antitone (hf : is_local_extr_on f s a) {g : β → γ} (hg : antitone g) : is_local_extr_on (g ∘ f) s a := hf.comp_antitone hg lemma is_local_min.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_local_min f a) {g : α → γ} (hg : is_local_min g a) : is_local_min (λ x, op (f x) (g x)) a := hf.bicomp_mono hop hg lemma is_local_max.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_local_max f a) {g : α → γ} (hg : is_local_max g a) : is_local_max (λ x, op (f x) (g x)) a := hf.bicomp_mono hop hg -- No `extr` version because we need `hf` and `hg` to be of the same kind lemma is_local_min_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_local_min_on f s a) {g : α → γ} (hg : is_local_min_on g s a) : is_local_min_on (λ x, op (f x) (g x)) s a := hf.bicomp_mono hop hg lemma is_local_max_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_local_max_on f s a) {g : α → γ} (hg : is_local_max_on g s a) : is_local_max_on (λ x, op (f x) (g x)) s a := hf.bicomp_mono hop hg /-! ### Composition with `continuous_at` -/ lemma is_local_min.comp_continuous [topological_space δ] {g : δ → α} {b : δ} (hf : is_local_min f (g b)) (hg : continuous_at g b) : is_local_min (f ∘ g) b := hg hf lemma is_local_max.comp_continuous [topological_space δ] {g : δ → α} {b : δ} (hf : is_local_max f (g b)) (hg : continuous_at g b) : is_local_max (f ∘ g) b := hg hf lemma is_local_extr.comp_continuous [topological_space δ] {g : δ → α} {b : δ} (hf : is_local_extr f (g b)) (hg : continuous_at g b) : is_local_extr (f ∘ g) b := hf.comp_tendsto hg lemma is_local_min.comp_continuous_on [topological_space δ] {s : set δ} {g : δ → α} {b : δ} (hf : is_local_min f (g b)) (hg : continuous_on g s) (hb : b ∈ s) : is_local_min_on (f ∘ g) s b := hf.comp_tendsto (hg b hb) lemma is_local_max.comp_continuous_on [topological_space δ] {s : set δ} {g : δ → α} {b : δ} (hf : is_local_max f (g b)) (hg : continuous_on g s) (hb : b ∈ s) : is_local_max_on (f ∘ g) s b := hf.comp_tendsto (hg b hb) lemma is_local_extr.comp_continuous_on [topological_space δ] {s : set δ} (g : δ → α) {b : δ} (hf : is_local_extr f (g b)) (hg : continuous_on g s) (hb : b ∈ s) : is_local_extr_on (f ∘ g) s b := hf.elim (λ hf, (hf.comp_continuous_on hg hb).is_extr) (λ hf, (is_local_max.comp_continuous_on hf hg hb).is_extr) lemma is_local_min_on.comp_continuous_on [topological_space δ] {t : set α} {s : set δ} {g : δ → α} {b : δ} (hf : is_local_min_on f t (g b)) (hst : s ⊆ g ⁻¹' t) (hg : continuous_on g s) (hb : b ∈ s) : is_local_min_on (f ∘ g) s b := hf.comp_tendsto (tendsto_nhds_within_mono_right (image_subset_iff.mpr hst) (continuous_within_at.tendsto_nhds_within_image (hg b hb))) lemma is_local_max_on.comp_continuous_on [topological_space δ] {t : set α} {s : set δ} {g : δ → α} {b : δ} (hf : is_local_max_on f t (g b)) (hst : s ⊆ g ⁻¹' t) (hg : continuous_on g s) (hb : b ∈ s) : is_local_max_on (f ∘ g) s b := hf.comp_tendsto (tendsto_nhds_within_mono_right (image_subset_iff.mpr hst) (continuous_within_at.tendsto_nhds_within_image (hg b hb))) lemma is_local_extr_on.comp_continuous_on [topological_space δ] {t : set α} {s : set δ} (g : δ → α) {b : δ} (hf : is_local_extr_on f t (g b)) (hst : s ⊆ g ⁻¹' t) (hg : continuous_on g s) (hb : b ∈ s) : is_local_extr_on (f ∘ g) s b := hf.elim (λ hf, (hf.comp_continuous_on hst hg hb).is_extr) (λ hf, (is_local_max_on.comp_continuous_on hf hst hg hb).is_extr) end preorder /-! ### Pointwise addition -/ section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_local_min.add (hf : is_local_min f a) (hg : is_local_min g a) : is_local_min (λ x, f x + g x) a := hf.add hg lemma is_local_max.add (hf : is_local_max f a) (hg : is_local_max g a) : is_local_max (λ x, f x + g x) a := hf.add hg lemma is_local_min_on.add (hf : is_local_min_on f s a) (hg : is_local_min_on g s a) : is_local_min_on (λ x, f x + g x) s a := hf.add hg lemma is_local_max_on.add (hf : is_local_max_on f s a) (hg : is_local_max_on g s a) : is_local_max_on (λ x, f x + g x) s a := hf.add hg end ordered_add_comm_monoid /-! ### Pointwise negation and subtraction -/ section ordered_add_comm_group variables [ordered_add_comm_group β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_local_min.neg (hf : is_local_min f a) : is_local_max (λ x, -f x) a := hf.neg lemma is_local_max.neg (hf : is_local_max f a) : is_local_min (λ x, -f x) a := hf.neg lemma is_local_extr.neg (hf : is_local_extr f a) : is_local_extr (λ x, -f x) a := hf.neg lemma is_local_min_on.neg (hf : is_local_min_on f s a) : is_local_max_on (λ x, -f x) s a := hf.neg lemma is_local_max_on.neg (hf : is_local_max_on f s a) : is_local_min_on (λ x, -f x) s a := hf.neg lemma is_local_extr_on.neg (hf : is_local_extr_on f s a) : is_local_extr_on (λ x, -f x) s a := hf.neg lemma is_local_min.sub (hf : is_local_min f a) (hg : is_local_max g a) : is_local_min (λ x, f x - g x) a := hf.sub hg lemma is_local_max.sub (hf : is_local_max f a) (hg : is_local_min g a) : is_local_max (λ x, f x - g x) a := hf.sub hg lemma is_local_min_on.sub (hf : is_local_min_on f s a) (hg : is_local_max_on g s a) : is_local_min_on (λ x, f x - g x) s a := hf.sub hg lemma is_local_max_on.sub (hf : is_local_max_on f s a) (hg : is_local_min_on g s a) : is_local_max_on (λ x, f x - g x) s a := hf.sub hg end ordered_add_comm_group /-! ### Pointwise `sup`/`inf` -/ section semilattice_sup variables [semilattice_sup β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_local_min.sup (hf : is_local_min f a) (hg : is_local_min g a) : is_local_min (λ x, f x ⊔ g x) a := hf.sup hg lemma is_local_max.sup (hf : is_local_max f a) (hg : is_local_max g a) : is_local_max (λ x, f x ⊔ g x) a := hf.sup hg lemma is_local_min_on.sup (hf : is_local_min_on f s a) (hg : is_local_min_on g s a) : is_local_min_on (λ x, f x ⊔ g x) s a := hf.sup hg lemma is_local_max_on.sup (hf : is_local_max_on f s a) (hg : is_local_max_on g s a) : is_local_max_on (λ x, f x ⊔ g x) s a := hf.sup hg end semilattice_sup section semilattice_inf variables [semilattice_inf β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_local_min.inf (hf : is_local_min f a) (hg : is_local_min g a) : is_local_min (λ x, f x ⊓ g x) a := hf.inf hg lemma is_local_max.inf (hf : is_local_max f a) (hg : is_local_max g a) : is_local_max (λ x, f x ⊓ g x) a := hf.inf hg lemma is_local_min_on.inf (hf : is_local_min_on f s a) (hg : is_local_min_on g s a) : is_local_min_on (λ x, f x ⊓ g x) s a := hf.inf hg lemma is_local_max_on.inf (hf : is_local_max_on f s a) (hg : is_local_max_on g s a) : is_local_max_on (λ x, f x ⊓ g x) s a := hf.inf hg end semilattice_inf /-! ### Pointwise `min`/`max` -/ section linear_order variables [linear_order β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_local_min.min (hf : is_local_min f a) (hg : is_local_min g a) : is_local_min (λ x, min (f x) (g x)) a := hf.min hg lemma is_local_max.min (hf : is_local_max f a) (hg : is_local_max g a) : is_local_max (λ x, min (f x) (g x)) a := hf.min hg lemma is_local_min_on.min (hf : is_local_min_on f s a) (hg : is_local_min_on g s a) : is_local_min_on (λ x, min (f x) (g x)) s a := hf.min hg lemma is_local_max_on.min (hf : is_local_max_on f s a) (hg : is_local_max_on g s a) : is_local_max_on (λ x, min (f x) (g x)) s a := hf.min hg lemma is_local_min.max (hf : is_local_min f a) (hg : is_local_min g a) : is_local_min (λ x, max (f x) (g x)) a := hf.max hg lemma is_local_max.max (hf : is_local_max f a) (hg : is_local_max g a) : is_local_max (λ x, max (f x) (g x)) a := hf.max hg lemma is_local_min_on.max (hf : is_local_min_on f s a) (hg : is_local_min_on g s a) : is_local_min_on (λ x, max (f x) (g x)) s a := hf.max hg lemma is_local_max_on.max (hf : is_local_max_on f s a) (hg : is_local_max_on g s a) : is_local_max_on (λ x, max (f x) (g x)) s a := hf.max hg end linear_order section eventually /-! ### Relation with `eventually` comparisons of two functions -/ variables [preorder β] {s : set α} lemma filter.eventually_le.is_local_max_on {f g : α → β} {a : α} (hle : g ≤ᶠ[𝓝[s] a] f) (hfga : f a = g a) (h : is_local_max_on f s a) : is_local_max_on g s a := hle.is_max_filter hfga h lemma is_local_max_on.congr {f g : α → β} {a : α} (h : is_local_max_on f s a) (heq : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : is_local_max_on g s a := h.congr heq $ heq.eq_of_nhds_within hmem lemma filter.eventually_eq.is_local_max_on_iff {f g : α → β} {a : α} (heq : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : is_local_max_on f s a ↔ is_local_max_on g s a := heq.is_max_filter_iff $ heq.eq_of_nhds_within hmem lemma filter.eventually_le.is_local_min_on {f g : α → β} {a : α} (hle : f ≤ᶠ[𝓝[s] a] g) (hfga : f a = g a) (h : is_local_min_on f s a) : is_local_min_on g s a := hle.is_min_filter hfga h lemma is_local_min_on.congr {f g : α → β} {a : α} (h : is_local_min_on f s a) (heq : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : is_local_min_on g s a := h.congr heq $ heq.eq_of_nhds_within hmem lemma filter.eventually_eq.is_local_min_on_iff {f g : α → β} {a : α} (heq : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : is_local_min_on f s a ↔ is_local_min_on g s a := heq.is_min_filter_iff $ heq.eq_of_nhds_within hmem lemma is_local_extr_on.congr {f g : α → β} {a : α} (h : is_local_extr_on f s a) (heq : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : is_local_extr_on g s a := h.congr heq $ heq.eq_of_nhds_within hmem lemma filter.eventually_eq.is_local_extr_on_iff {f g : α → β} {a : α} (heq : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : is_local_extr_on f s a ↔ is_local_extr_on g s a := heq.is_extr_filter_iff $ heq.eq_of_nhds_within hmem lemma filter.eventually_le.is_local_max {f g : α → β} {a : α} (hle : g ≤ᶠ[𝓝 a] f) (hfga : f a = g a) (h : is_local_max f a) : is_local_max g a := hle.is_max_filter hfga h lemma is_local_max.congr {f g : α → β} {a : α} (h : is_local_max f a) (heq : f =ᶠ[𝓝 a] g) : is_local_max g a := h.congr heq heq.eq_of_nhds lemma filter.eventually_eq.is_local_max_iff {f g : α → β} {a : α} (heq : f =ᶠ[𝓝 a] g) : is_local_max f a ↔ is_local_max g a := heq.is_max_filter_iff heq.eq_of_nhds lemma filter.eventually_le.is_local_min {f g : α → β} {a : α} (hle : f ≤ᶠ[𝓝 a] g) (hfga : f a = g a) (h : is_local_min f a) : is_local_min g a := hle.is_min_filter hfga h lemma is_local_min.congr {f g : α → β} {a : α} (h : is_local_min f a) (heq : f =ᶠ[𝓝 a] g) : is_local_min g a := h.congr heq heq.eq_of_nhds lemma filter.eventually_eq.is_local_min_iff {f g : α → β} {a : α} (heq : f =ᶠ[𝓝 a] g) : is_local_min f a ↔ is_local_min g a := heq.is_min_filter_iff heq.eq_of_nhds lemma is_local_extr.congr {f g : α → β} {a : α} (h : is_local_extr f a) (heq : f =ᶠ[𝓝 a] g) : is_local_extr g a := h.congr heq heq.eq_of_nhds lemma filter.eventually_eq.is_local_extr_iff {f g : α → β} {a : α} (heq : f =ᶠ[𝓝 a] g) : is_local_extr f a ↔ is_local_extr g a := heq.is_extr_filter_iff heq.eq_of_nhds end eventually
0bf3b76f2cced4038fee507b628c2ca5826d96df
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/category/Profinite/basic.lean
91a665bc034c6c8fea4457268ca0247f76da59c1
[ "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
11,305
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Calle Sönne -/ import topology.category.CompHaus.basic import topology.connected import topology.subset_properties import topology.locally_constant.basic import category_theory.adjunction.reflective import category_theory.monad.limits import category_theory.Fintype /-! # The category of Profinite Types We construct the category of profinite topological spaces, often called profinite sets -- perhaps they could be called profinite types in Lean. The type of profinite topological spaces is called `Profinite`. It has a category instance and is a fully faithful subcategory of `Top`. The fully faithful functor is called `Profinite_to_Top`. ## Implementation notes A profinite type is defined to be a topological space which is compact, Hausdorff and totally disconnected. ## TODO 0. Link to category of projective limits of finite discrete sets. 1. finite coproducts 2. Clausen/Scholze topology on the category `Profinite`. ## Tags profinite -/ universe u open category_theory /-- The type of profinite topological spaces. -/ structure Profinite := (to_CompHaus : CompHaus) [is_totally_disconnected : totally_disconnected_space to_CompHaus] namespace Profinite /-- Construct a term of `Profinite` from a type endowed with the structure of a compact, Hausdorff and totally disconnected topological space. -/ def of (X : Type*) [topological_space X] [compact_space X] [t2_space X] [totally_disconnected_space X] : Profinite := ⟨⟨⟨X⟩⟩⟩ instance : inhabited Profinite := ⟨Profinite.of pempty⟩ instance category : category Profinite := induced_category.category to_CompHaus instance concrete_category : concrete_category Profinite := induced_category.concrete_category _ instance has_forget₂ : has_forget₂ Profinite Top := induced_category.has_forget₂ _ instance : has_coe_to_sort Profinite Type* := ⟨λ X, X.to_CompHaus⟩ instance {X : Profinite} : totally_disconnected_space X := X.is_totally_disconnected -- We check that we automatically infer that Profinite sets are compact and Hausdorff. example {X : Profinite} : compact_space X := infer_instance example {X : Profinite} : t2_space X := infer_instance @[simp] lemma coe_to_CompHaus {X : Profinite} : (X.to_CompHaus : Type*) = X := rfl @[simp] lemma coe_id (X : Profinite) : (𝟙 X : X → X) = id := rfl @[simp] lemma coe_comp {X Y Z : Profinite} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g : X → Z) = g ∘ f := rfl end Profinite /-- The fully faithful embedding of `Profinite` in `CompHaus`. -/ @[simps, derive [full, faithful]] def Profinite_to_CompHaus : Profinite ⥤ CompHaus := induced_functor _ /-- The fully faithful embedding of `Profinite` in `Top`. This is definitionally the same as the obvious composite. -/ @[simps, derive [full, faithful]] def Profinite.to_Top : Profinite ⥤ Top := forget₂ _ _ @[simp] lemma Profinite.to_CompHaus_to_Top : Profinite_to_CompHaus ⋙ CompHaus_to_Top = Profinite.to_Top := rfl section Profinite /-- (Implementation) The object part of the connected_components functor from compact Hausdorff spaces to Profinite spaces, given by quotienting a space by its connected components. See: https://stacks.math.columbia.edu/tag/0900 -/ -- Without explicit universe annotations here, Lean introduces two universe variables and -- unhelpfully defines a function `CompHaus.{max u₁ u₂} → Profinite.{max u₁ u₂}`. def CompHaus.to_Profinite_obj (X : CompHaus.{u}) : Profinite.{u} := { to_CompHaus := { to_Top := Top.of (connected_components X), is_compact := quotient.compact_space, is_hausdorff := connected_components.t2 }, is_totally_disconnected := connected_components.totally_disconnected_space } /-- (Implementation) The bijection of homsets to establish the reflective adjunction of Profinite spaces in compact Hausdorff spaces. -/ def Profinite.to_CompHaus_equivalence (X : CompHaus.{u}) (Y : Profinite.{u}) : (CompHaus.to_Profinite_obj X ⟶ Y) ≃ (X ⟶ Profinite_to_CompHaus.obj Y) := { to_fun := λ f, f.comp ⟨quotient.mk', continuous_quotient_mk⟩, inv_fun := λ g, { to_fun := continuous.connected_components_lift g.2, continuous_to_fun := continuous.connected_components_lift_continuous g.2}, left_inv := λ f, continuous_map.ext $ connected_components.surjective_coe.forall.2 $ λ a, rfl, right_inv := λ f, continuous_map.ext $ λ x, rfl } /-- The connected_components functor from compact Hausdorff spaces to profinite spaces, left adjoint to the inclusion functor. -/ def CompHaus.to_Profinite : CompHaus ⥤ Profinite := adjunction.left_adjoint_of_equiv Profinite.to_CompHaus_equivalence (λ _ _ _ _ _, rfl) lemma CompHaus.to_Profinite_obj' (X : CompHaus) : ↥(CompHaus.to_Profinite.obj X) = connected_components X := rfl /-- Finite types are given the discrete topology. -/ def Fintype.discrete_topology (A : Fintype) : topological_space A := ⊥ section discrete_topology local attribute [instance] Fintype.discrete_topology /-- The natural functor from `Fintype` to `Profinite`, endowing a finite type with the discrete topology. -/ @[simps] def Fintype.to_Profinite : Fintype ⥤ Profinite := { obj := λ A, Profinite.of A, map := λ _ _ f, ⟨f⟩ } end discrete_topology end Profinite namespace Profinite -- TODO the following construction of limits could be generalised -- to allow diagrams in lower universes. /-- An explicit limit cone for a functor `F : J ⥤ Profinite`, defined in terms of `Top.limit_cone`. -/ def limit_cone {J : Type u} [small_category J] (F : J ⥤ Profinite.{u}) : limits.cone F := { X := { to_CompHaus := (CompHaus.limit_cone.{u u} (F ⋙ Profinite_to_CompHaus)).X, is_totally_disconnected := begin change totally_disconnected_space ↥{u : Π (j : J), (F.obj j) | _}, exact subtype.totally_disconnected_space, end }, π := { app := (CompHaus.limit_cone.{u u} (F ⋙ Profinite_to_CompHaus)).π.app } } /-- The limit cone `Profinite.limit_cone F` is indeed a limit cone. -/ def limit_cone_is_limit {J : Type u} [small_category J] (F : J ⥤ Profinite.{u}) : limits.is_limit (limit_cone F) := { lift := λ S, (CompHaus.limit_cone_is_limit.{u u} (F ⋙ Profinite_to_CompHaus)).lift (Profinite_to_CompHaus.map_cone S), uniq' := λ S m h, (CompHaus.limit_cone_is_limit.{u u} _).uniq (Profinite_to_CompHaus.map_cone S) _ h } /-- The adjunction between CompHaus.to_Profinite and Profinite.to_CompHaus -/ def to_Profinite_adj_to_CompHaus : CompHaus.to_Profinite ⊣ Profinite_to_CompHaus := adjunction.adjunction_of_equiv_left _ _ /-- The category of profinite sets is reflective in the category of compact hausdroff spaces -/ instance to_CompHaus.reflective : reflective Profinite_to_CompHaus := { to_is_right_adjoint := ⟨CompHaus.to_Profinite, Profinite.to_Profinite_adj_to_CompHaus⟩ } noncomputable instance to_CompHaus.creates_limits : creates_limits Profinite_to_CompHaus := monadic_creates_limits _ noncomputable instance to_Top.reflective : reflective Profinite.to_Top := reflective.comp Profinite_to_CompHaus CompHaus_to_Top noncomputable instance to_Top.creates_limits : creates_limits Profinite.to_Top := monadic_creates_limits _ instance has_limits : limits.has_limits Profinite := has_limits_of_has_limits_creates_limits Profinite.to_Top instance has_colimits : limits.has_colimits Profinite := has_colimits_of_reflective Profinite_to_CompHaus noncomputable instance forget_preserves_limits : limits.preserves_limits (forget Profinite) := by apply limits.comp_preserves_limits Profinite.to_Top (forget Top) variables {X Y : Profinite.{u}} (f : X ⟶ Y) /-- Any morphism of profinite spaces is a closed map. -/ lemma is_closed_map : is_closed_map f := CompHaus.is_closed_map _ /-- Any continuous bijection of profinite spaces induces an isomorphism. -/ lemma is_iso_of_bijective (bij : function.bijective f) : is_iso f := begin haveI := CompHaus.is_iso_of_bijective (Profinite_to_CompHaus.map f) bij, exact is_iso_of_fully_faithful Profinite_to_CompHaus _ end /-- Any continuous bijection of profinite spaces induces an isomorphism. -/ noncomputable def iso_of_bijective (bij : function.bijective f) : X ≅ Y := by letI := Profinite.is_iso_of_bijective f bij; exact as_iso f instance forget_reflects_isomorphisms : reflects_isomorphisms (forget Profinite) := ⟨by introsI A B f hf; exact Profinite.is_iso_of_bijective _ ((is_iso_iff_bijective f).mp hf)⟩ /-- Construct an isomorphism from a homeomorphism. -/ @[simps hom inv] def iso_of_homeo (f : X ≃ₜ Y) : X ≅ Y := { hom := ⟨f, f.continuous⟩, inv := ⟨f.symm, f.symm.continuous⟩, hom_inv_id' := by { ext x, exact f.symm_apply_apply x }, inv_hom_id' := by { ext x, exact f.apply_symm_apply x } } /-- Construct a homeomorphism from an isomorphism. -/ @[simps] def homeo_of_iso (f : X ≅ Y) : X ≃ₜ Y := { to_fun := f.hom, inv_fun := f.inv, left_inv := λ x, by { change (f.hom ≫ f.inv) x = x, rw [iso.hom_inv_id, coe_id, id.def] }, right_inv := λ x, by { change (f.inv ≫ f.hom) x = x, rw [iso.inv_hom_id, coe_id, id.def] }, continuous_to_fun := f.hom.continuous, continuous_inv_fun := f.inv.continuous } /-- The equivalence between isomorphisms in `Profinite` and homeomorphisms of topological spaces. -/ @[simps] def iso_equiv_homeo : (X ≅ Y) ≃ (X ≃ₜ Y) := { to_fun := homeo_of_iso, inv_fun := iso_of_homeo, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } lemma epi_iff_surjective {X Y : Profinite.{u}} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin split, { contrapose!, rintros ⟨y, hy⟩ hf, let C := set.range f, have hC : is_closed C := (is_compact_range f.continuous).is_closed, let U := Cᶜ, have hU : is_open U := is_open_compl_iff.mpr hC, have hyU : y ∈ U, { refine set.mem_compl _, rintro ⟨y', hy'⟩, exact hy y' hy' }, have hUy : U ∈ nhds y := hU.mem_nhds hyU, obtain ⟨V, hV, hyV, hVU⟩ := is_topological_basis_clopen.mem_nhds_iff.mp hUy, classical, letI : topological_space (ulift.{u} $ fin 2) := ⊥, let Z := of (ulift.{u} $ fin 2), let g : Y ⟶ Z := ⟨(locally_constant.of_clopen hV).map ulift.up, locally_constant.continuous _⟩, let h : Y ⟶ Z := ⟨λ _, ⟨1⟩, continuous_const⟩, have H : h = g, { rw ← cancel_epi f, ext x, dsimp [locally_constant.of_clopen], rw if_neg, { refl }, refine mt (λ α, hVU α) _, simp only [set.mem_range_self, not_true, not_false_iff, set.mem_compl_iff], }, apply_fun (λ e, (e y).down) at H, dsimp [locally_constant.of_clopen] at H, rw if_pos hyV at H, exact top_ne_bot H }, { rw ← category_theory.epi_iff_surjective, apply (forget Profinite).epi_of_epi_map } end lemma mono_iff_injective {X Y : Profinite.{u}} (f : X ⟶ Y) : mono f ↔ function.injective f := begin split, { intro h, haveI : limits.preserves_limits Profinite_to_CompHaus := infer_instance, haveI : mono (Profinite_to_CompHaus.map f) := infer_instance, rwa ← CompHaus.mono_iff_injective }, { rw ← category_theory.mono_iff_injective, apply (forget Profinite).mono_of_mono_map } end end Profinite
4ca82f1c13751761b6f82565bffd1c1955e2ecdc
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/linear_algebra/ray.lean
8ff35ef3b4b8bee9c9f1e938eabcfa4dc3c1169e
[ "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
24,226
lean
/- Copyright (c) 2021 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.linear_independent /-! # Rays in modules This file defines rays in modules. ## Main definitions * `same_ray`: two vectors belong to the same ray if they are proportional with a nonnegative coefficient. * `module.ray` is a type for the equivalence class of nonzero vectors in a module with some common positive multiple. -/ noncomputable theory open_locale big_operators section ordered_comm_semiring variables (R : Type*) [ordered_comm_semiring R] variables {M : Type*} [add_comm_monoid M] [module R M] variables {N : Type*} [add_comm_monoid N] [module R N] variables (ι : Type*) [decidable_eq ι] /-- Two vectors are in the same ray if either one of them is zero or some positive multiples of them are equal (in the typical case over a field, this means one of them is a nonnegative multiple of the other). -/ def same_ray (v₁ v₂ : M) : Prop := v₁ = 0 ∨ v₂ = 0 ∨ ∃ (r₁ r₂ : R), 0 < r₁ ∧ 0 < r₂ ∧ r₁ • v₁ = r₂ • v₂ variables {R} namespace same_ray variables {x y z : M} @[simp] lemma zero_left (y : M) : same_ray R 0 y := or.inl rfl @[simp] lemma zero_right (x : M) : same_ray R x 0 := or.inr $ or.inl rfl @[nontriviality] lemma of_subsingleton [subsingleton M] (x y : M) : same_ray R x y := by { rw [subsingleton.elim x 0], exact zero_left _ } @[nontriviality] lemma of_subsingleton' [subsingleton R] (x y : M) : same_ray R x y := by { haveI := module.subsingleton R M, exact of_subsingleton x y } /-- `same_ray` is reflexive. -/ @[refl] lemma refl (x : M) : same_ray R x x := begin nontriviality R, exact or.inr (or.inr $ ⟨1, 1, zero_lt_one, zero_lt_one, rfl⟩) end protected lemma rfl : same_ray R x x := refl _ /-- `same_ray` is symmetric. -/ @[symm] lemma symm (h : same_ray R x y) : same_ray R y x := (or.left_comm.1 h).imp_right $ or.imp_right $ λ ⟨r₁, r₂, h₁, h₂, h⟩, ⟨r₂, r₁, h₂, h₁, h.symm⟩ /-- If `x` and `y` are nonzero vectors on the same ray, then there exist positive numbers `r₁ r₂` such that `r₁ • x = r₂ • y`. -/ lemma exists_pos (h : same_ray R x y) (hx : x ≠ 0) (hy : y ≠ 0) : ∃ r₁ r₂ : R, 0 < r₁ ∧ 0 < r₂ ∧ r₁ • x = r₂ • y := (h.resolve_left hx).resolve_left hy lemma _root_.same_ray_comm : same_ray R x y ↔ same_ray R y x := ⟨same_ray.symm, same_ray.symm⟩ /-- `same_ray` is transitive unless the vector in the middle is zero and both other vectors are nonzero. -/ lemma trans (hxy : same_ray R x y) (hyz : same_ray R y z) (hy : y = 0 → x = 0 ∨ z = 0) : same_ray R x z := begin rcases eq_or_ne x 0 with rfl|hx, { exact zero_left z }, rcases eq_or_ne z 0 with rfl|hz, { exact zero_right x }, rcases eq_or_ne y 0 with rfl|hy, { exact (hy rfl).elim (λ h, (hx h).elim) (λ h, (hz h).elim) }, rcases hxy.exists_pos hx hy with ⟨r₁, r₂, hr₁, hr₂, h₁⟩, rcases hyz.exists_pos hy hz with ⟨r₃, r₄, hr₃, hr₄, h₂⟩, refine or.inr (or.inr $ ⟨r₃ * r₁, r₂ * r₄, mul_pos hr₃ hr₁, mul_pos hr₂ hr₄, _⟩), rw [mul_smul, mul_smul, h₁, ← h₂, smul_comm] end /-- A vector is in the same ray as a nonnegative multiple of itself. -/ lemma _root_.same_ray_nonneg_smul_right (v : M) {r : R} (h : 0 ≤ r) : same_ray R v (r • v) := or.inr $ h.eq_or_lt.imp (λ h, h ▸ zero_smul R v) $ λ h, ⟨r, 1, h, by { nontriviality R, exact zero_lt_one }, (one_smul _ _).symm⟩ /-- A vector is in the same ray as a positive multiple of itself. -/ lemma _root_.same_ray_pos_smul_right (v : M) {r : R} (h : 0 < r) : same_ray R v (r • v) := same_ray_nonneg_smul_right v h.le /-- A vector is in the same ray as a nonnegative multiple of one it is in the same ray as. -/ lemma nonneg_smul_right {r : R} (h : same_ray R x y) (hr : 0 ≤ r) : same_ray R x (r • y) := h.trans (same_ray_nonneg_smul_right y hr) $ λ hy, or.inr $ by rw [hy, smul_zero] /-- A vector is in the same ray as a positive multiple of one it is in the same ray as. -/ lemma pos_smul_right {r : R} (h : same_ray R x y) (hr : 0 < r) : same_ray R x (r • y) := h.nonneg_smul_right hr.le /-- A nonnegative multiple of a vector is in the same ray as that vector. -/ lemma _root_.same_ray_nonneg_smul_left (v : M) {r : R} (h : 0 ≤ r) : same_ray R (r • v) v := (same_ray_nonneg_smul_right v h).symm /-- A positive multiple of a vector is in the same ray as that vector. -/ lemma _root_.same_ray_pos_smul_left (v : M) {r : R} (h : 0 < r) : same_ray R (r • v) v := same_ray_nonneg_smul_left v h.le /-- A nonnegative multiple of a vector is in the same ray as one it is in the same ray as. -/ lemma nonneg_smul_left {r : R} (h : same_ray R x y) (hr : 0 ≤ r) : same_ray R (r • x) y := (h.symm.nonneg_smul_right hr).symm /-- A positive multiple of a vector is in the same ray as one it is in the same ray as. -/ lemma pos_smul_left {r : R} (h : same_ray R x y) (hr : 0 < r) : same_ray R (r • x) y := h.nonneg_smul_left hr.le /-- If two vectors are on the same ray then they remain so after applying a linear map. -/ lemma map (f : M →ₗ[R] N) (h : same_ray R x y) : same_ray R (f x) (f y) := h.imp (λ hx, by rw [hx, map_zero]) $ or.imp (λ hy, by rw [hy, map_zero]) $ λ ⟨r₁, r₂, hr₁, hr₂, h⟩, ⟨r₁, r₂, hr₁, hr₂, by rw [←f.map_smul, ←f.map_smul, h]⟩ /-- The images of two vectors under a linear equivalence are on the same ray if and only if the original vectors are on the same ray. -/ @[simp] lemma _root_.same_ray_map_iff (e : M ≃ₗ[R] N) : same_ray R (e x) (e y) ↔ same_ray R x y := ⟨λ h, by simpa using same_ray.map e.symm.to_linear_map h, same_ray.map e.to_linear_map⟩ /-- If two vectors are on the same ray then both scaled by the same action are also on the same ray. -/ lemma smul {S : Type*} [monoid S] [distrib_mul_action S M] [smul_comm_class R S M] (h : same_ray R x y) (s : S) : same_ray R (s • x) (s • y) := h.map (s • (linear_map.id : M →ₗ[R] M)) /-- If `x` and `y` are on the same ray as `z`, then so is `x + y`. -/ lemma add_left (hx : same_ray R x z) (hy : same_ray R y z) : same_ray R (x + y) z := begin rcases eq_or_ne x 0 with rfl|hx₀, { rwa zero_add }, rcases eq_or_ne y 0 with rfl|hy₀, { rwa add_zero }, rcases eq_or_ne z 0 with rfl|hz₀, { apply zero_right }, rcases hx.exists_pos hx₀ hz₀ with ⟨rx, rz₁, hrx, hrz₁, Hx⟩, rcases hy.exists_pos hy₀ hz₀ with ⟨ry, rz₂, hry, hrz₂, Hy⟩, refine or.inr (or.inr ⟨rx * ry, ry * rz₁ + rx * rz₂, mul_pos hrx hry, _, _⟩), { apply_rules [add_pos, mul_pos] }, { simp only [mul_smul, smul_add, add_smul, ← Hx, ← Hy], rw smul_comm } end /-- If `y` and `z` are on the same ray as `x`, then so is `y + z`. -/ lemma add_right (hy : same_ray R x y) (hz : same_ray R x z) : same_ray R x (y + z) := (hy.symm.add_left hz.symm).symm end same_ray /-- Nonzero vectors, as used to define rays. This type depends on an unused argument `R` so that `ray_vector.setoid` can be an instance. -/ @[nolint unused_arguments has_nonempty_instance] def ray_vector (R M : Type*) [has_zero M] := {v : M // v ≠ 0} instance ray_vector.has_coe {R M : Type*} [has_zero M] : has_coe (ray_vector R M) M := coe_subtype instance {R M : Type*} [has_zero M] [nontrivial M] : nonempty (ray_vector R M) := let ⟨x, hx⟩ := exists_ne (0 : M) in ⟨⟨x, hx⟩⟩ variables (R M) /-- The setoid of the `same_ray` relation for the subtype of nonzero vectors. -/ instance : setoid (ray_vector R M) := { r := λ x y, same_ray R (x : M) y, iseqv := ⟨λ x, same_ray.refl _, λ x y h, h.symm, λ x y z hxy hyz, hxy.trans hyz $ λ hy, (y.2 hy).elim⟩ } /-- A ray (equivalence class of nonzero vectors with common positive multiples) in a module. -/ @[nolint has_nonempty_instance] def module.ray := quotient (ray_vector.setoid R M) variables {R M} /-- Equivalence of nonzero vectors, in terms of same_ray. -/ lemma equiv_iff_same_ray {v₁ v₂ : ray_vector R M} : v₁ ≈ v₂ ↔ same_ray R (v₁ : M) v₂ := iff.rfl variables (R) /-- The ray given by a nonzero vector. -/ protected def ray_of_ne_zero (v : M) (h : v ≠ 0) : module.ray R M := ⟦⟨v, h⟩⟧ /-- An induction principle for `module.ray`, used as `induction x using module.ray.ind`. -/ lemma module.ray.ind {C : module.ray R M → Prop} (h : ∀ v (hv : v ≠ 0), C (ray_of_ne_zero R v hv)) (x : module.ray R M) : C x := quotient.ind (subtype.rec $ by exact h) x variable {R} instance [nontrivial M] : nonempty (module.ray R M) := nonempty.map quotient.mk infer_instance /-- The rays given by two nonzero vectors are equal if and only if those vectors satisfy `same_ray`. -/ lemma ray_eq_iff {v₁ v₂ : M} (hv₁ : v₁ ≠ 0) (hv₂ : v₂ ≠ 0) : ray_of_ne_zero R _ hv₁ = ray_of_ne_zero R _ hv₂ ↔ same_ray R v₁ v₂ := quotient.eq /-- The ray given by a positive multiple of a nonzero vector. -/ @[simp] lemma ray_pos_smul {v : M} (h : v ≠ 0) {r : R} (hr : 0 < r) (hrv : r • v ≠ 0) : ray_of_ne_zero R (r • v) hrv = ray_of_ne_zero R v h := (ray_eq_iff _ _).2 $ same_ray_pos_smul_left v hr /-- An equivalence between modules implies an equivalence between ray vectors. -/ def ray_vector.map_linear_equiv (e : M ≃ₗ[R] N) : ray_vector R M ≃ ray_vector R N := equiv.subtype_equiv e.to_equiv $ λ _, e.map_ne_zero_iff.symm /-- An equivalence between modules implies an equivalence between rays. -/ def module.ray.map (e : M ≃ₗ[R] N) : module.ray R M ≃ module.ray R N := quotient.congr (ray_vector.map_linear_equiv e) $ λ ⟨a, ha⟩ ⟨b, hb⟩, (same_ray_map_iff _).symm @[simp] lemma module.ray.map_apply (e : M ≃ₗ[R] N) (v : M) (hv : v ≠ 0) : module.ray.map e (ray_of_ne_zero _ v hv) = ray_of_ne_zero _ (e v) (e.map_ne_zero_iff.2 hv) := rfl @[simp] lemma module.ray.map_refl : (module.ray.map $ linear_equiv.refl R M) = equiv.refl _ := equiv.ext $ module.ray.ind R $ λ _ _, rfl @[simp] lemma module.ray.map_symm (e : M ≃ₗ[R] N) : (module.ray.map e).symm = module.ray.map e.symm := rfl section action variables {G : Type*} [group G] [distrib_mul_action G M] /-- Any invertible action preserves the non-zeroness of ray vectors. This is primarily of interest when `G = Rˣ` -/ instance {R : Type*} : mul_action G (ray_vector R M) := { smul := λ r, (subtype.map ((•) r) $ λ a, (smul_ne_zero_iff_ne _).2), mul_smul := λ a b m, subtype.ext $ mul_smul a b _, one_smul := λ m, subtype.ext $ one_smul _ _ } variables [smul_comm_class R G M] /-- Any invertible action preserves the non-zeroness of rays. This is primarily of interest when `G = Rˣ` -/ instance : mul_action G (module.ray R M) := { smul := λ r, quotient.map ((•) r) (λ a b h, h.smul _), mul_smul := λ a b, quotient.ind $ by exact(λ m, congr_arg quotient.mk $ mul_smul a b _), one_smul := quotient.ind $ by exact (λ m, congr_arg quotient.mk $ one_smul _ _), } /-- The action via `linear_equiv.apply_distrib_mul_action` corresponds to `module.ray.map`. -/ @[simp] lemma module.ray.linear_equiv_smul_eq_map (e : M ≃ₗ[R] M) (v : module.ray R M) : e • v = module.ray.map e v := rfl @[simp] lemma smul_ray_of_ne_zero (g : G) (v : M) (hv) : g • ray_of_ne_zero R v hv = ray_of_ne_zero R (g • v) ((smul_ne_zero_iff_ne _).2 hv) := rfl end action namespace module.ray /-- Scaling by a positive unit is a no-op. -/ lemma units_smul_of_pos (u : Rˣ) (hu : 0 < (u : R)) (v : module.ray R M) : u • v = v := begin induction v using module.ray.ind, rw [smul_ray_of_ne_zero, ray_eq_iff], exact same_ray_pos_smul_left _ hu end /-- An arbitrary `ray_vector` giving a ray. -/ def some_ray_vector (x : module.ray R M) : ray_vector R M := quotient.out x /-- The ray of `some_ray_vector`. -/ @[simp] lemma some_ray_vector_ray (x : module.ray R M) : (⟦x.some_ray_vector⟧ : module.ray R M) = x := quotient.out_eq _ /-- An arbitrary nonzero vector giving a ray. -/ def some_vector (x : module.ray R M) : M := x.some_ray_vector /-- `some_vector` is nonzero. -/ @[simp] lemma some_vector_ne_zero (x : module.ray R M) : x.some_vector ≠ 0 := x.some_ray_vector.property /-- The ray of `some_vector`. -/ @[simp] lemma some_vector_ray (x : module.ray R M) : ray_of_ne_zero R _ x.some_vector_ne_zero = x := (congr_arg _ (subtype.coe_eta _ _) : _).trans x.out_eq end module.ray end ordered_comm_semiring section ordered_comm_ring variables {R : Type*} [ordered_comm_ring R] variables {M N : Type*} [add_comm_group M] [add_comm_group N] [module R M] [module R N] {x y : M} /-- `same_ray.neg` as an `iff`. -/ @[simp] lemma same_ray_neg_iff : same_ray R (-x) (-y) ↔ same_ray R x y := by simp only [same_ray, neg_eq_zero, smul_neg, neg_inj] alias same_ray_neg_iff ↔ same_ray.of_neg same_ray.neg lemma same_ray_neg_swap : same_ray R (-x) y ↔ same_ray R x (-y) := by rw [← same_ray_neg_iff, neg_neg] lemma eq_zero_of_same_ray_neg_smul_right [no_zero_smul_divisors R M] {r : R} (hr : r < 0) (h : same_ray R x (r • x)) : x = 0 := begin rcases h with rfl|h₀|⟨r₁, r₂, hr₁, hr₂, h⟩, { refl }, { simpa [hr.ne] using h₀ }, { rw [← sub_eq_zero, smul_smul, ← sub_smul, smul_eq_zero] at h, refine h.resolve_left (ne_of_gt $ sub_pos.2 _), exact (mul_neg_of_pos_of_neg hr₂ hr).trans hr₁ } end /-- If a vector is in the same ray as its negation, that vector is zero. -/ lemma eq_zero_of_same_ray_self_neg [no_zero_smul_divisors R M] (h : same_ray R x (-x)) : x = 0 := begin nontriviality M, haveI : nontrivial R := module.nontrivial R M, refine eq_zero_of_same_ray_neg_smul_right (neg_lt_zero.2 (@one_pos R _ _)) _, rwa [neg_one_smul] end namespace ray_vector /-- Negating a nonzero vector. -/ instance {R : Type*} : has_neg (ray_vector R M) := ⟨λ v, ⟨-v, neg_ne_zero.2 v.prop⟩⟩ /-- Negating a nonzero vector commutes with coercion to the underlying module. -/ @[simp, norm_cast] lemma coe_neg {R : Type*} (v : ray_vector R M) : ↑(-v) = -(v : M) := rfl /-- Negating a nonzero vector twice produces the original vector. -/ instance {R : Type*} : has_involutive_neg (ray_vector R M) := { neg := has_neg.neg, neg_neg := λ v, by rw [subtype.ext_iff, coe_neg, coe_neg, neg_neg] } /-- If two nonzero vectors are equivalent, so are their negations. -/ @[simp] lemma equiv_neg_iff {v₁ v₂ : ray_vector R M} : -v₁ ≈ -v₂ ↔ v₁ ≈ v₂ := same_ray_neg_iff end ray_vector variables (R) /-- Negating a ray. -/ instance : has_neg (module.ray R M) := ⟨quotient.map (λ v, -v) (λ v₁ v₂, ray_vector.equiv_neg_iff.2)⟩ /-- The ray given by the negation of a nonzero vector. -/ @[simp] lemma neg_ray_of_ne_zero (v : M) (h : v ≠ 0) : -(ray_of_ne_zero R _ h) = ray_of_ne_zero R (-v) (neg_ne_zero.2 h) := rfl namespace module.ray variables {R} /-- Negating a ray twice produces the original ray. -/ instance : has_involutive_neg (module.ray R M) := { neg := has_neg.neg, neg_neg := λ x, quotient.ind (λ a, congr_arg quotient.mk $ neg_neg _) x } variables {R M} /-- A ray does not equal its own negation. -/ lemma ne_neg_self [no_zero_smul_divisors R M] (x : module.ray R M) : x ≠ -x := begin induction x using module.ray.ind with x hx, rw [neg_ray_of_ne_zero, ne.def, ray_eq_iff], exact mt eq_zero_of_same_ray_self_neg hx end lemma neg_units_smul (u : Rˣ) (v : module.ray R M) : (-u) • v = - (u • v) := begin induction v using module.ray.ind, simp only [smul_ray_of_ne_zero, units.smul_def, units.coe_neg, neg_smul, neg_ray_of_ne_zero] end /-- Scaling by a negative unit is negation. -/ lemma units_smul_of_neg (u : Rˣ) (hu : (u : R) < 0) (v : module.ray R M) : u • v = -v := begin rw [← neg_inj, neg_neg, ← neg_units_smul, units_smul_of_pos], rwa [units.coe_neg, right.neg_pos_iff] end end module.ray end ordered_comm_ring section linear_ordered_comm_ring variables {R : Type*} [linear_ordered_comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] /-- `same_ray` follows from membership of `mul_action.orbit` for the `units.pos_subgroup`. -/ lemma same_ray_of_mem_orbit {v₁ v₂ : M} (h : v₁ ∈ mul_action.orbit (units.pos_subgroup R) v₂) : same_ray R v₁ v₂ := begin rcases h with ⟨⟨r, hr : 0 < (r : R)⟩, (rfl : r • v₂ = v₁)⟩, exact same_ray_pos_smul_left _ hr end /-- Scaling by an inverse unit is the same as scaling by itself. -/ @[simp] lemma units_inv_smul (u : Rˣ) (v : module.ray R M) : u⁻¹ • v = u • v := calc u⁻¹ • v = (u * u) • u⁻¹ • v : eq.symm $ (u⁻¹ • v).units_smul_of_pos _ $ mul_self_pos.2 u.ne_zero ... = u • v : by rw [mul_smul, smul_inv_smul] section variables [no_zero_smul_divisors R M] @[simp] lemma same_ray_smul_right_iff {v : M} {r : R} : same_ray R v (r • v) ↔ 0 ≤ r ∨ v = 0 := ⟨λ hrv, or_iff_not_imp_left.2 $ λ hr, eq_zero_of_same_ray_neg_smul_right (not_le.1 hr) hrv, or_imp_distrib.2 ⟨same_ray_nonneg_smul_right v, λ h, h.symm ▸ same_ray.zero_left _⟩⟩ /-- A nonzero vector is in the same ray as a multiple of itself if and only if that multiple is positive. -/ lemma same_ray_smul_right_iff_of_ne {v : M} (hv : v ≠ 0) {r : R} (hr : r ≠ 0) : same_ray R v (r • v) ↔ 0 < r := by simp only [same_ray_smul_right_iff, hv, or_false, hr.symm.le_iff_lt] @[simp] lemma same_ray_smul_left_iff {v : M} {r : R} : same_ray R (r • v) v ↔ 0 ≤ r ∨ v = 0 := same_ray_comm.trans same_ray_smul_right_iff /-- A multiple of a nonzero vector is in the same ray as that vector if and only if that multiple is positive. -/ lemma same_ray_smul_left_iff_of_ne {v : M} (hv : v ≠ 0) {r : R} (hr : r ≠ 0) : same_ray R (r • v) v ↔ 0 < r := same_ray_comm.trans (same_ray_smul_right_iff_of_ne hv hr) @[simp] lemma same_ray_neg_smul_right_iff {v : M} {r : R} : same_ray R (-v) (r • v) ↔ r ≤ 0 ∨ v = 0 := by rw [← same_ray_neg_iff, neg_neg, ← neg_smul, same_ray_smul_right_iff, neg_nonneg] lemma same_ray_neg_smul_right_iff_of_ne {v : M} {r : R} (hv : v ≠ 0) (hr : r ≠ 0) : same_ray R (-v) (r • v) ↔ r < 0 := by simp only [same_ray_neg_smul_right_iff, hv, or_false, hr.le_iff_lt] @[simp] lemma same_ray_neg_smul_left_iff {v : M} {r : R} : same_ray R (r • v) (-v) ↔ r ≤ 0 ∨ v = 0 := same_ray_comm.trans same_ray_neg_smul_right_iff lemma same_ray_neg_smul_left_iff_of_ne {v : M} {r : R} (hv : v ≠ 0) (hr : r ≠ 0) : same_ray R (r • v) (-v) ↔ r < 0 := same_ray_comm.trans $ same_ray_neg_smul_right_iff_of_ne hv hr @[simp] lemma units_smul_eq_self_iff {u : Rˣ} {v : module.ray R M} : u • v = v ↔ (0 : R) < u := begin induction v using module.ray.ind with v hv, simp only [smul_ray_of_ne_zero, ray_eq_iff, units.smul_def, same_ray_smul_left_iff_of_ne hv u.ne_zero] end @[simp] lemma units_smul_eq_neg_iff {u : Rˣ} {v : module.ray R M} : u • v = -v ↔ ↑u < (0 : R) := by rw [← neg_inj, neg_neg, ← module.ray.neg_units_smul, units_smul_eq_self_iff, units.coe_neg, neg_pos] /-- Two vectors are in the same ray, or the first is in the same ray as the negation of the second, if and only if they are not linearly independent. -/ lemma same_ray_or_same_ray_neg_iff_not_linear_independent {x y : M} : (same_ray R x y ∨ same_ray R x (-y)) ↔ ¬ linear_independent R ![x, y] := begin by_cases hx : x = 0, { simp [hx, λ h : linear_independent R ![0, y], h.ne_zero 0 rfl] }, by_cases hy : y = 0, { simp [hy, λ h : linear_independent R ![x, 0], h.ne_zero 1 rfl] }, simp_rw [fintype.not_linear_independent_iff, fin.sum_univ_two, fin.exists_fin_two], refine ⟨λ h, _, λ h, _⟩, { rcases h with (hx0|hy0|⟨r₁, r₂, hr₁, hr₂, h⟩)|(hx0|hy0|⟨r₁, r₂, hr₁, hr₂, h⟩), { exact false.elim (hx hx0) }, { exact false.elim (hy hy0) }, { refine ⟨![r₁, -r₂], _⟩, simp [h, hr₁.ne.symm] }, { exact false.elim (hx hx0) }, { exact false.elim (hy (neg_eq_zero.1 hy0)) }, { refine ⟨![r₁, r₂], _⟩, simp [h, hr₁.ne.symm] } }, { rcases h with ⟨m, hm, hmne⟩, change m 0 • x + m 1 • y = 0 at hm, rw add_eq_zero_iff_eq_neg at hm, rcases lt_trichotomy (m 0) 0 with hm0|hm0|hm0; rcases lt_trichotomy (m 1) 0 with hm1|hm1|hm1, { refine or.inr (or.inr (or.inr ⟨-(m 0), -(m 1), left.neg_pos_iff.2 hm0, left.neg_pos_iff.2 hm1, _⟩)), simp [hm] }, { exfalso, simpa [hm1, hx, hm0.ne] using hm }, { refine or.inl (or.inr (or.inr ⟨-(m 0), m 1, left.neg_pos_iff.2 hm0, hm1, _⟩)), simp [hm] }, { exfalso, simpa [hm0, hy, hm1.ne] using hm }, { refine false.elim (not_and_distrib.2 hmne ⟨hm0, hm1⟩) }, { exfalso, simpa [hm0, hy, hm1.ne.symm] using hm }, { refine or.inl (or.inr (or.inr ⟨m 0, -(m 1), hm0, left.neg_pos_iff.2 hm1, _⟩)), simp [hm] }, { exfalso, simpa [hm1, hx, hm0.ne.symm] using hm }, { refine or.inr (or.inr (or.inr ⟨m 0, m 1, hm0, hm1, _⟩)), simp [hm] } } end /-- Two vectors are in the same ray, or they are nonzero and the first is in the same ray as the negation of the second, if and only if they are not linearly independent. -/ lemma same_ray_or_ne_zero_and_same_ray_neg_iff_not_linear_independent {x y : M} : (same_ray R x y ∨ x ≠ 0 ∧ y ≠ 0 ∧ same_ray R x (-y)) ↔ ¬ linear_independent R ![x, y] := begin rw ←same_ray_or_same_ray_neg_iff_not_linear_independent, by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0; simp [hx, hy] end end end linear_ordered_comm_ring namespace same_ray variables {R : Type*} [linear_ordered_field R] variables {M : Type*} [add_comm_group M] [module R M] {x y v₁ v₂ : M} lemma exists_pos_left (h : same_ray R x y) (hx : x ≠ 0) (hy : y ≠ 0) : ∃ r : R, 0 < r ∧ r • x = y := let ⟨r₁, r₂, hr₁, hr₂, h⟩ := h.exists_pos hx hy in ⟨r₂⁻¹ * r₁, mul_pos (inv_pos.2 hr₂) hr₁, by rw [mul_smul, h, inv_smul_smul₀ hr₂.ne']⟩ lemma exists_pos_right (h : same_ray R x y) (hx : x ≠ 0) (hy : y ≠ 0) : ∃ r : R, 0 < r ∧ x = r • y := (h.symm.exists_pos_left hy hx).imp $ λ _, and.imp_right eq.symm /-- If a vector `v₂` is on the same ray as a nonzero vector `v₁`, then it is equal to `c • v₁` for some nonnegative `c`. -/ lemma exists_nonneg_left (h : same_ray R x y) (hx : x ≠ 0) : ∃ r : R, 0 ≤ r ∧ r • x = y := begin obtain rfl | hy := eq_or_ne y 0, { exact ⟨0, le_rfl, zero_smul _ _⟩ }, { exact (h.exists_pos_left hx hy).imp (λ _, and.imp_left le_of_lt) } end /-- If a vector `v₁` is on the same ray as a nonzero vector `v₂`, then it is equal to `c • v₂` for some nonnegative `c`. -/ lemma exists_nonneg_right (h : same_ray R x y) (hy : y ≠ 0) : ∃ r : R, 0 ≤ r ∧ x = r • y := (h.symm.exists_nonneg_left hy).imp $ λ _, and.imp_right eq.symm /-- If vectors `v₁` and `v₂` are on the same ray, then for some nonnegative `a b`, `a + b = 1`, we have `v₁ = a • (v₁ + v₂)` and `v₂ = b • (v₁ + v₂)`. -/ lemma exists_eq_smul_add (h : same_ray R v₁ v₂) : ∃ a b : R, 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ v₁ = a • (v₁ + v₂) ∧ v₂ = b • (v₁ + v₂) := begin rcases h with rfl|rfl|⟨r₁, r₂, h₁, h₂, H⟩, { use [0, 1], simp }, { use [1, 0], simp }, { have h₁₂ : 0 < r₁ + r₂, from add_pos h₁ h₂, refine ⟨r₂ / (r₁ + r₂), r₁ / (r₁ + r₂), div_nonneg h₂.le h₁₂.le, div_nonneg h₁.le h₁₂.le, _, _, _⟩, { rw [← add_div, add_comm, div_self h₁₂.ne'] }, { rw [div_eq_inv_mul, mul_smul, smul_add, ← H, ← add_smul, add_comm r₂, inv_smul_smul₀ h₁₂.ne'] }, { rw [div_eq_inv_mul, mul_smul, smul_add, H, ← add_smul, add_comm r₂, inv_smul_smul₀ h₁₂.ne'] } } end /-- If vectors `v₁` and `v₂` are on the same ray, then they are nonnegative multiples of the same vector. Actually, this vector can be assumed to be `v₁ + v₂`, see `same_ray.exists_eq_smul_add`. -/ lemma exists_eq_smul (h : same_ray R v₁ v₂) : ∃ (u : M) (a b : R), 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ v₁ = a • u ∧ v₂ = b • u := ⟨v₁ + v₂, h.exists_eq_smul_add⟩ end same_ray
a5d31ea6cd556d2b531bfef1bf023a5f6938ca9b
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Declaration.lean
caaa27fdf3894cf060dec28caac98fb8ccf88f8e
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,483
lean
/- Copyright (c) 2018 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 /-- Reducibility hints are used in the convertibility checker. When trying to solve a constraint such a (f ...) =?= (g ...) where f and g are definitions, the checker has to decide which one will be unfolded. If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque, Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev, Else if f and g are regular, then we unfold the one with the biggest definitional height. Otherwise both are unfolded. The arguments of the `regular` Constructor are: the definitional height and the flag `selfOpt`. The definitional height is by default computed by the kernel. It only takes into account other regular definitions used in a definition. When creating declarations using meta-programming, we can specify the definitional depth manually. Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a declaration during Type checking. Remark: the ReducibilityHints are not related to the attributes: reducible/irrelevance/semireducible. These attributes are used by the Elaborator. The ReducibilityHints are used by the kernel (and Elaborator). Moreover, the ReducibilityHints cannot be changed after a declaration is added to the kernel. -/ inductive ReducibilityHints | opaque : ReducibilityHints | «abbrev» : ReducibilityHints | regular : UInt32 → ReducibilityHints @[export lean_mk_reducibility_hints_regular] def mkReducibilityHintsRegularEx (h : UInt32) : ReducibilityHints := ReducibilityHints.regular h @[export lean_reducibility_hints_get_height] def ReducibilityHints.getHeightEx (h : ReducibilityHints) : UInt32 := match h with | ReducibilityHints.regular h => h | _ => 0 namespace ReducibilityHints instance : Inhabited ReducibilityHints := ⟨opaque⟩ def lt : ReducibilityHints → ReducibilityHints → Bool | «abbrev», «abbrev» => false | «abbrev», _ => true | regular d₁, regular d₂ => d₁ < d₂ | regular _, opaque => true | _, _ => false end ReducibilityHints /-- Base structure for `AxiomVal`, `DefinitionVal`, `TheoremVal`, `InductiveVal`, `ConstructorVal`, `RecursorVal` and `QuotVal`. -/ structure ConstantVal := (name : Name) (lparams : List Name) (type : Expr) instance : Inhabited ConstantVal := ⟨{ name := arbitrary _, lparams := arbitrary _, type := arbitrary _ }⟩ structure AxiomVal extends ConstantVal := (isUnsafe : Bool) @[export lean_mk_axiom_val] def mkAxiomValEx (name : Name) (lparams : List Name) (type : Expr) (isUnsafe : Bool) : AxiomVal := { name := name, lparams := lparams, type := type, isUnsafe := isUnsafe } @[export lean_axiom_val_is_unsafe] def AxiomVal.isUnsafeEx (v : AxiomVal) : Bool := v.isUnsafe structure DefinitionVal extends ConstantVal := (value : Expr) (hints : ReducibilityHints) (isUnsafe : Bool) @[export lean_mk_definition_val] def mkDefinitionValEx (name : Name) (lparams : List Name) (type : Expr) (val : Expr) (hints : ReducibilityHints) (isUnsafe : Bool) : DefinitionVal := { name := name, lparams := lparams, type := type, value := val, hints := hints, isUnsafe := isUnsafe } @[export lean_definition_val_is_unsafe] def DefinitionVal.isUnsafeEx (v : DefinitionVal) : Bool := v.isUnsafe structure TheoremVal extends ConstantVal := (value : Expr) /- Value for an opaque constant declaration `constant x : t := e` -/ structure OpaqueVal extends ConstantVal := (value : Expr) (isUnsafe : Bool) @[export lean_mk_opaque_val] def mkOpaqueValEx (name : Name) (lparams : List Name) (type : Expr) (val : Expr) (isUnsafe : Bool) : OpaqueVal := { name := name, lparams := lparams, type := type, value := val, isUnsafe := isUnsafe } @[export lean_opaque_val_is_unsafe] def OpaqueVal.isUnsafeEx (v : OpaqueVal) : Bool := v.isUnsafe structure Constructor := (name : Name) (type : Expr) structure InductiveType := (name : Name) (type : Expr) (ctors : List Constructor) /-- Declaration object that can be sent to the kernel. -/ inductive Declaration | axiomDecl (val : AxiomVal) | defnDecl (val : DefinitionVal) | thmDecl (val : TheoremVal) | opaqueDecl (val : OpaqueVal) | quotDecl | mutualDefnDecl (defns : List DefinitionVal) -- All definitions must be marked as `unsafe` | inductDecl (lparams : List Name) (nparams : Nat) (types : List InductiveType) (isUnsafe : Bool) instance : Inhabited Declaration := ⟨Declaration.quotDecl⟩ @[export lean_mk_inductive_decl] def mkInductiveDeclEs (lparams : List Name) (nparams : Nat) (types : List InductiveType) (isUnsafe : Bool) : Declaration := Declaration.inductDecl lparams nparams types isUnsafe @[export lean_is_unsafe_inductive_decl] def Declaration.isUnsafeInductiveDeclEx : Declaration → Bool | Declaration.inductDecl _ _ _ isUnsafe => isUnsafe | _ => false @[specialize] def Declaration.foldExprM {α} {m : Type → Type} [Monad m] (d : Declaration) (f : α → Expr → m α) (a : α) : m α := match d with | Declaration.quotDecl => pure a | Declaration.axiomDecl { type := type, .. } => f a type | Declaration.defnDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.opaqueDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.thmDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.mutualDefnDecl vals => vals.foldlM (fun a v => do let a ← f a v.type; f a v.value) a | Declaration.inductDecl _ _ inductTypes _ => inductTypes.foldlM (fun a inductType => do let a ← f a inductType.type inductType.ctors.foldlM (fun a ctor => f a ctor.type) a) a @[inline] def Declaration.forExprM {m : Type → Type} [Monad m] (d : Declaration) (f : Expr → m Unit) : m Unit := d.foldExprM (fun _ a => f a) () /-- The kernel compiles (mutual) inductive declarations (see `inductiveDecls`) into a set of - `Declaration.inductDecl` (for each inductive datatype in the mutual Declaration), - `Declaration.ctorDecl` (for each Constructor in the mutual Declaration), - `Declaration.recDecl` (automatically generated recursors). This data is used to implement iota-reduction efficiently and compile nested inductive declarations. A series of checks are performed by the kernel to check whether a `inductiveDecls` is valid or not. -/ structure InductiveVal extends ConstantVal := (nparams : Nat) -- Number of parameters (nindices : Nat) -- Number of indices (all : List Name) -- List of all (including this one) inductive datatypes in the mutual declaration containing this one (ctors : List Name) -- List of all constructors for this inductive datatype (isRec : Bool) -- `true` Iff it is recursive (isUnsafe : Bool) (isReflexive : Bool) @[export lean_mk_inductive_val] def mkInductiveValEx (name : Name) (lparams : List Name) (type : Expr) (nparams nindices : Nat) (all ctors : List Name) (isRec isUnsafe isReflexive : Bool) : InductiveVal := { name := name, lparams := lparams, type := type, nparams := nparams, nindices := nindices, all := all, ctors := ctors, isRec := isRec, isUnsafe := isUnsafe, isReflexive := isReflexive } @[export lean_inductive_val_is_rec] def InductiveVal.isRecEx (v : InductiveVal) : Bool := v.isRec @[export lean_inductive_val_is_unsafe] def InductiveVal.isUnsafeEx (v : InductiveVal) : Bool := v.isUnsafe @[export lean_inductive_val_is_reflexive] def InductiveVal.isReflexiveEx (v : InductiveVal) : Bool := v.isReflexive def InductiveVal.nctors (v : InductiveVal) : Nat := v.ctors.length structure ConstructorVal extends ConstantVal := (induct : Name) -- Inductive Type this Constructor is a member of (cidx : Nat) -- Constructor index (i.e., Position in the inductive declaration) (nparams : Nat) -- Number of parameters in inductive datatype `induct` (nfields : Nat) -- Number of fields (i.e., arity - nparams) (isUnsafe : Bool) @[export lean_mk_constructor_val] def mkConstructorValEx (name : Name) (lparams : List Name) (type : Expr) (induct : Name) (cidx nparams nfields : Nat) (isUnsafe : Bool) : ConstructorVal := { name := name, lparams := lparams, type := type, induct := induct, cidx := cidx, nparams := nparams, nfields := nfields, isUnsafe := isUnsafe } @[export lean_constructor_val_is_unsafe] def ConstructorVal.isUnsafeEx (v : ConstructorVal) : Bool := v.isUnsafe instance : Inhabited ConstructorVal := ⟨{ toConstantVal := arbitrary _, induct := arbitrary _, cidx := 0, nparams := 0, nfields := 0, isUnsafe := true }⟩ /-- Information for reducing a recursor -/ structure RecursorRule := (ctor : Name) -- Reduction rule for this Constructor (nfields : Nat) -- Number of fields (i.e., without counting inductive datatype parameters) (rhs : Expr) -- Right hand side of the reduction rule structure RecursorVal extends ConstantVal := (all : List Name) -- List of all inductive datatypes in the mutual declaration that generated this recursor (nparams : Nat) -- Number of parameters (nindices : Nat) -- Number of indices (nmotives : Nat) -- Number of motives (nminors : Nat) -- Number of minor premises (rules : List RecursorRule) -- A reduction for each Constructor (k : Bool) -- It supports K-like reduction (isUnsafe : Bool) @[export lean_mk_recursor_val] def mkRecursorValEx (name : Name) (lparams : List Name) (type : Expr) (all : List Name) (nparams nindices nmotives nminors : Nat) (rules : List RecursorRule) (k isUnsafe : Bool) : RecursorVal := { name := name, lparams := lparams, type := type, all := all, nparams := nparams, nindices := nindices, nmotives := nmotives, nminors := nminors, rules := rules, k := k, isUnsafe := isUnsafe } @[export lean_recursor_k] def RecursorVal.kEx (v : RecursorVal) : Bool := v.k @[export lean_recursor_is_unsafe] def RecursorVal.isUnsafeEx (v : RecursorVal) : Bool := v.isUnsafe def RecursorVal.getMajorIdx (v : RecursorVal) : Nat := v.nparams + v.nmotives + v.nminors + v.nindices def RecursorVal.getInduct (v : RecursorVal) : Name := v.name.getPrefix inductive QuotKind | type -- `Quot` | ctor -- `Quot.mk` | lift -- `Quot.lift` | ind -- `Quot.ind` structure QuotVal extends ConstantVal := (kind : QuotKind) @[export lean_mk_quot_val] def mkQuotValEx (name : Name) (lparams : List Name) (type : Expr) (kind : QuotKind) : QuotVal := { name := name, lparams := lparams, type := type, kind := kind } @[export lean_quot_val_kind] def QuotVal.kindEx (v : QuotVal) : QuotKind := v.kind /-- Information associated with constant declarations. -/ inductive ConstantInfo | axiomInfo (val : AxiomVal) | defnInfo (val : DefinitionVal) | thmInfo (val : TheoremVal) | opaqueInfo (val : OpaqueVal) | quotInfo (val : QuotVal) | inductInfo (val : InductiveVal) | ctorInfo (val : ConstructorVal) | recInfo (val : RecursorVal) namespace ConstantInfo def toConstantVal : ConstantInfo → ConstantVal | defnInfo {toConstantVal := d, ..} => d | axiomInfo {toConstantVal := d, ..} => d | thmInfo {toConstantVal := d, ..} => d | opaqueInfo {toConstantVal := d, ..} => d | quotInfo {toConstantVal := d, ..} => d | inductInfo {toConstantVal := d, ..} => d | ctorInfo {toConstantVal := d, ..} => d | recInfo {toConstantVal := d, ..} => d def isUnsafe : ConstantInfo → Bool | defnInfo v => v.isUnsafe | axiomInfo v => v.isUnsafe | thmInfo v => false | opaqueInfo v => v.isUnsafe | quotInfo v => false | inductInfo v => v.isUnsafe | ctorInfo v => v.isUnsafe | recInfo v => v.isUnsafe def name (d : ConstantInfo) : Name := d.toConstantVal.name def lparams (d : ConstantInfo) : List Name := d.toConstantVal.lparams def type (d : ConstantInfo) : Expr := d.toConstantVal.type def value? : ConstantInfo → Option Expr | defnInfo {value := r, ..} => some r | thmInfo {value := r, ..} => some r | _ => none def hasValue : ConstantInfo → Bool | defnInfo {value := r, ..} => true | thmInfo {value := r, ..} => true | _ => false def value! : ConstantInfo → Expr | defnInfo {value := r, ..} => r | thmInfo {value := r, ..} => r | _ => panic! "declaration with value expected" def hints : ConstantInfo → ReducibilityHints | defnInfo {hints := r, ..} => r | _ => ReducibilityHints.opaque def isCtor : ConstantInfo → Bool | ctorInfo _ => true | _ => false @[extern "lean_instantiate_type_lparams"] constant instantiateTypeLevelParams (c : @& ConstantInfo) (ls : @& List Level) : Expr @[extern "lean_instantiate_value_lparams"] constant instantiateValueLevelParams (c : @& ConstantInfo) (ls : @& List Level) : Expr end ConstantInfo def mkRecName (declName : Name) : Name := Name.mkStr declName "rec" end Lean
70b1e7e70e0a21c717b07efca42e8a6895a32266
63abd62053d479eae5abf4951554e1064a4c45b4
/src/meta/expr.lean
5802eec19d9793172e80073805cd3848b95ff29a
[ "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
39,809
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs import tactic.derive_inhabited /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind @[priority 100] meta instance has_reflect.has_to_pexpr {α} [has_reflect α] : has_to_pexpr α := ⟨λ b, pexpr.of_expr (reflect b)⟩ namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) /-- `last_string n` returns the rightmost component of `n`, ignoring numeral components. For example, ``last_string `a.b.c.33`` will return `` `c ``. -/ def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ meta def from_string (s : string) : name := from_components $ s.split (= '.') /-- In surface Lean, we can write anonymous Π binders (i.e. binders where the argument is not named) using the function arrow notation: ```lean inductive test : Type := | intro : unit → test ``` After elaboration, however, every binder must have a name, so Lean generates one. In the example, the binder in the type of `intro` is anonymous, so Lean gives it the name `a`: ```lean test.intro : ∀ (a : unit), test ``` When there are multiple anonymous binders, they are named `a_1`, `a_2` etc. Thus, when we want to know whether the user named a binder, we can check whether the name follows this scheme. Note, however, that this is not reliable. When the user writes (for whatever reason) ```lean inductive test : Type := | intro : ∀ (a : unit), test ``` we cannot tell that the binder was, in fact, named. The function `name.is_likely_generated_binder_name` checks if a name is of the form `a`, `a_1`, etc. -/ library_note "likely generated binder names" /-- Check whether a simple name was likely generated by Lean to name an anonymous binder. Such names are either `a` or `a_n` for some natural `n`. See note [likely generated binder names]. -/ meta def is_likely_generated_binder_simple_name : string → bool | "a" := tt | n := match n.get_rest "a_" with | none := ff | some suffix := suffix.is_nat end /-- Check whether a name was likely generated by Lean to name an anonymous binder. Such names are either `a` or `a_n` for some natural `n`. See note [likely generated binder names]. -/ meta def is_likely_generated_binder_name (n : name) : bool := match n with | mk_string s anonymous := is_likely_generated_binder_simple_name s | _ := ff end end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff /-- `l.fold_mvar f` folds a function `f : name → α → α` over each `n : name` appearing in a `level.mvar n` in `l`. -/ meta def fold_mvar {α} : level → (name → α → α) → α → α | zero f := id | (succ a) f := fold_mvar a f | (param a) f := id | (mvar a) f := f a | (max a b) f := fold_mvar a f ∘ fold_mvar b f | (imax a b) f := fold_mvar a f ∘ fold_mvar b f end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq, derive inhabited] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) /-- `nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`. The `pexpr` does not hold any typing information: `to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`. -/ meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) namespace expr /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero) := some 0 | `(has_one.one) := some 1 | `(bit0 %%e) := bit0 <$> e.to_nat | `(bit1 %%e) := bit1 <$> e.to_nat | `(nat.succ %%e) := (+1) <$> e.to_nat | `(nat.zero) := some 0 | _ := none /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- `is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `expr` -/ namespace expr open tactic /-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/ meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Clean an expression by removing `id`s listed in `clean_ids`. -/ meta def clean (e : expr) : expr := e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Match a variable. -/ meta def match_var {elab} : expr elab → option ℕ | (var n) := some n | _ := none /-- Match a sort. -/ meta def match_sort {elab} : expr elab → option level | (sort u) := some u | _ := none /-- Match a constant. -/ meta def match_const {elab} : expr elab → option (name × list level) | (const n lvls) := some (n, lvls) | _ := none /-- Match a metavariable. -/ meta def match_mvar {elab} : expr elab → option (name × name × expr elab) | (mvar unique pretty type) := some (unique, pretty, type) | _ := none /-- Match a local constant. -/ meta def match_local_const {elab} : expr elab → option (name × name × binder_info × expr elab) | (local_const unique pretty bi type) := some (unique, pretty, bi, type) | _ := none /-- Match an application. -/ meta def match_app {elab} : expr elab → option (expr elab × expr elab) | (app t u) := some (t, u) | _ := none /-- Match an abstraction. -/ meta def match_lam {elab} : expr elab → option (name × binder_info × expr elab × expr elab) | (lam var_name bi type body) := some (var_name, bi, type, body) | _ := none /-- Match a Π type. -/ meta def match_pi {elab} : expr elab → option (name × binder_info × expr elab × expr elab) | (pi var_name bi type body) := some (var_name, bi, type, body) | _ := none /-- Match a let. -/ meta def match_elet {elab} : expr elab → option (name × expr elab × expr elab × expr elab) | (elet var_name type assignment body) := some (var_name, type, assignment, body) | _ := none /-- Match a macro. -/ meta def match_macro {elab} : expr elab → option (macro_def × list (expr elab)) | (macro df args) := some (df, args) | _ := none /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- Get the universe levels of a `const` expression -/ meta def univ_levels : expr → list level | (const n ls) := ls | _ := [] /-- Replace any metavariables in the expression with underscores, in preparation for printing `refine ...` statements. -/ meta def replace_mvars (e : expr) : expr := e.replace (λ e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none) /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns the set of all local constants in an expression. -/ meta def list_local_consts' (e : expr) : expr_set := e.fold mk_expr_set (λ e' _ es, if e'.is_local_constant then es.insert e' else es) /-- Returns the unique names of all local constants in an expression. -/ meta def list_local_const_unique_names (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_local_constant then es.insert e'.local_uniq_name else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns the set of all meta-variables in an expression. -/ meta def list_meta_vars' (e : expr) : expr_set := e.fold mk_expr_set (λ e' _ es, if e'.is_mvar then es.insert e' else es) /-- Returns a list of all universe meta-variables in an expression (without duplicates). -/ meta def list_univ_meta_vars (e : expr) : list name := native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s, match e' with | (sort u) := u.fold_mvar (flip native.rb_set.insert) s | (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s | _ := s end /-- Test `t` contains the specified subexpression `e`, or a metavariable. This represents the notion that `e` "may occur" in `t`, possibly after subsequent unification. -/ meta def contains_expr_or_mvar (t : expr) (e : expr) : bool := -- We can't use `t.has_meta_var` here, as that detects universe metavariables, too. ¬ t.list_meta_vars.empty ∨ e.occurs t /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true. -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- Returns true if `e` contains a `sorry`. -/ meta def contains_sorry (e : expr) : bool := e.fold ff (λ e' _ b, if (is_sorry e').is_some then tt else b) /-- `app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`. -/ meta def app_symbol_in (e : expr) (l : list name) : bool := match e.get_app_fn with | (expr.const n _) := n ∈ l | _ := ff end /-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/ meta def get_simp_args (e : expr) : tactic (list expr) := -- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app if ¬ e.is_app then pure [] else do cgr ← mk_specialized_congr_lemma_simp e, pure $ do (arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args, guard $ arg_kind = congr_arg_kind.eq, pure arg /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- Repeatedly apply `expr.subst`. -/ meta def substs : expr → list expr → expr | e es := es.foldl expr.subst e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. This is very similar to `expr.substs`, but this also reduces head let-expressions. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def pi_codomain : expr → expr | (pi n bi d b) := pi_codomain b | e := e /-- Get the body/value of a lambda-expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def lambda_body : expr → expr | (lam n bi d b) := lambda_body b | e := e /-- Auxilliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxilliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default binder /-- Strip-away the context-dependent unique id for the given local const and return: its friendly `name`, its `binder_info`, and its `type : expr`. -/ meta def get_local_const_kind : expr → name × binder_info × expr | (expr.local_const _ n bi e) := (n, bi, e) | _ := (name.anonymous, binder_info.default, expr.const name.anonymous []) /-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/ meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab | (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t | e new_t := e /-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to `expr tt` at the site of definition unnecessarily. DANGER: Unless you know exactly what you are doing, this is probably not the function you are looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/ meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast /-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever `f` is encountered in `e` verbatim, replace it with `t`". -/ meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) : expr elab := unsafe_cast $ e.unsafe_cast.replace $ λ e n, (mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd /-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of other `expr.local_const`s. It determines whether `e` should be considered "available in context" as a variable by virtue of the fact that the variables `vs` have been deemed such. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. DANGER: It is possible that for `f : expr` another `expr.local_const`, we have `is_implicitly_included_variable f vs = ff` but `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to iteratively add a list of local constants (usually, the `variables` declared in the local scope) which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables were added in a particular iteration. The function `all_implicitly_included_variables` below implements this behaviour. Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/ meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool := if ¬(e.local_pp_name.to_string.starts_with "_") then e ∈ vs else e.local_type.fold tt $ λ se _ b, if ¬b then ff else if ¬se.is_local_constant then tt else se ∈ vs /-- Private work function for `all_implicitly_included_variables`, performing the actual series of iterations, tracking with a boolean whether any updates occured this iteration. -/ private meta def all_implicitly_included_variables_aux : list expr → list expr → list expr → bool → list expr | [] vs rs tt := all_implicitly_included_variables_aux rs vs [] ff | [] vs rs ff := vs | (e :: rest) vs rs b := let (vs, rs, b) := if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in all_implicitly_included_variables_aux rest vs rs b /-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`, another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion of the variables in `vs` into the local context implies that `e` should also be included. See `is_implicitly_included_variable e vs` for the details. In particular, those elements of `vs` are included automatically. -/ meta def all_implicitly_included_variables (es vs : list expr) : list expr := all_implicitly_included_variables_aux es vs [] ff end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def filter (e : environment) (test : declaration → bool) : list declaration := e.fold [] $ λ d ds, if test d then d::ds else ds /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the resulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration open tactic /-- `declaration.update_with_fun f tgt decl` sets the name of the given `decl : declaration` to `tgt`, and applies `f` to the names of all `expr.const`s which appear in the value or type of `decl`. -/ protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file` Use `environment.in_current_file` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns true iff `d` is an automatically-generated or internal declaration. -/ meta def is_auto_or_internal (env : environment) (d : declaration) : bool := d.to_name.is_internal || d.is_auto_generated env /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param /-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/ protected meta def reducibility_hints : declaration → reducibility_hints | (declaration.defn _ _ _ _ red _) := red | _ := _root_.reducibility_hints.opaque /-- formats the arguments of a `declaration.thm` -/ private meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format := do tp ← pp tp, body ← pp body.get, return $ "<theorem " ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.defn` -/ private meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, body ← pp body, return $ "<" ++ (if is_trusted then "def " else "meta def ") ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.cnst` -/ private meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, return $ "<" ++ (if is_trusted then "constant " else "meta constant ") ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- formats the arguments of a `declaration.ax` -/ private meta def print_ax (nm : name) (tp : expr) : tactic format := do tp ← pp tp, return $ "<axiom " ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- pretty-prints a `declaration` object. -/ meta def to_tactic_format : declaration → tactic format | (declaration.thm nm _ tp bd) := print_thm nm tp bd | (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted | (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted | (declaration.ax nm _ tp) := print_ax nm tp meta instance : has_to_tactic_format declaration := ⟨to_tactic_format⟩ end declaration meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) := unchecked_cast expr.has_decidable_eq
4e74599a65a96de788ccf64bd886dc4c3d3b7157
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/assert_exists/test2.lean
1e3453a11c3d97d8b6a8d9c500bbc0322fbe9fc0
[ "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
184
lean
import tactic.assert_exists import algebra.order.ring.defs import data.int.basic assert_exists int assert_not_exists rat assert_instance ring ℤ assert_no_instance ordered_ring ℤ
853ff3326243b82ccd74f55ddd47c26b194a52f5
aa2345b30d710f7e75f13157a35845ee6d48c017
/analysis/topology/uniform_space.lean
90307eb2f12de3c4caade8dafb6a610815386d63
[ "Apache-2.0" ]
permissive
CohenCyril/mathlib
5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe
a12d5a192f5923016752f638d19fc1a51610f163
refs/heads/master
1,586,031,957,957
1,541,432,824,000
1,541,432,824,000
156,246,337
0
0
Apache-2.0
1,541,434,514,000
1,541,434,513,000
null
UTF-8
Lean
false
false
72,532
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 Theory of uniform spaces. Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * completeness * extension of uniform continuous functions to complete spaces * uniform contiunuity & embedding * totally bounded * totally bounded ∧ complete → compact One reason to directly formalize uniform spaces is foundational: we define ℝ as a completion of ℚ. The central concept of uniform spaces is its uniformity: a filter relating two elements of the space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the `triangular` rule holds. The formalization is mostly based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter data.quot analysis.topology.topological_space analysis.topology.continuity open set lattice filter classical local attribute [instance] prop_decidable set_option eqn_compiler.zeta true universes u section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) := by ext p; cases p; simp only [mem_comp_rel]; tauto /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity) def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U.sets) x, (x, x) ∈ r) (symm : ∀ r ∈ U.sets, {p | prod.swap p ∈ r} ∈ U.sets) (comp : ∀ r ∈ U.sets, ∃ t ∈ U.sets, comp_rel t t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity.sets, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity.sets)) @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity.sets)) : uniform_space α := ⟨c, is_open_uniformity⟩ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.refl _ } def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.refl _ } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[extensionality] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity : filter (α × α) := (@uniform_space.to_core α _).uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ (@uniformity α _).sets) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ @uniformity α _ := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ (@uniformity α _).sets) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) uniformity ≤ uniformity := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : uniformity.lift' (λs:set (α×α), comp_rel s s) ≤ uniformity := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto prod.swap (@uniformity α _) uniformity := symm_le_uniformity lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ_, (a, a)) f uniformity := assume s hs, show {x | (a, a) ∈ s} ∈ f.sets, from univ_mem_sets' $ assume b, refl_mem_uniformity hs lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, comp_rel t t ⊆ s := have s ∈ (uniformity.lift' (λt:set (α×α), comp_rel t t)).sets, from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : uniformity ≤ (@prod.swap α α) <$> uniformity := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : uniformity = (@prod.swap α α) <$> uniformity := le_antisymm uniformity_le_symm symm_le_uniformity theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : uniformity.lift (λs, g (preimage prod.swap s)) ≤ f) : uniformity.lift g ≤ f := calc uniformity.lift g ≤ (filter.map prod.swap (@uniformity α _)).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f): uniformity.lift (λs, f (comp_rel s s)) ≤ uniformity.lift f := calc uniformity.lift (λs, f (comp_rel s s)) = (uniformity.lift' (λs:set (α×α), comp_rel s s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ uniformity.lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ uniformity := calc uniformity.lift' (λd, comp_rel d (comp_rel d d)) = uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_comp (monotone_comp_rel monotone_const monotone_id) monotone_principal ... = uniformity.lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ uniformity : comp_le_uniformity lemma mem_nhds_uniformity_iff {x : α} {s : set α} : (s ∈ (nhds x).sets) ↔ ({p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets) := ⟨ begin simp [mem_nhds_sets_iff, is_open_uniformity], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_comap_uniformity {x : α} : nhds x = uniformity.comap (prod.mk x) := by ext s; rw [mem_nhds_uniformity_iff, mem_comap_sets]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, uniformity.sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_uniformity {x : α} : nhds x = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) := begin ext s, rw [mem_lift'_sets], tactic.swap, apply monotone_preimage, simp [mem_nhds_uniformity_iff], exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩, assume ⟨t, h₁, h₂⟩, uniformity.sets_of_superset h₁ $ assume ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {y : α | (x, y) ∈ s} ∈ (nhds x).sets := have nhds x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), by simp at this; assumption lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {x : α | (x, y) ∈ s} ∈ (nhds y).sets := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (nhds a) uniformity := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (nhds a) uniformity := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_comp monotone_preimage $ monotone_comp monotone_preimage monotone_principal) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> uniformity).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ monotone_comp monotone_preimage hg ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (nhds a) (nhds b) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (nhds a).lift (λs:set α, (nhds b).lift (λt:set α, principal (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_comp (monotone_prod monotone_const monotone_id) monotone_principal, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : nhds (a, b) = uniformity.lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ (@uniformity α _).sets) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ (nhds (x, y)).sets, begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d∈(@uniformity α _).sets, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ (uniformity.lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s∈(@uniformity α _).sets, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀s∈(@uniformity α _).sets, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : (@uniformity α _) = uniformity.lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc uniformity.lift' closure ≤ uniformity.lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ uniformity : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : (@uniformity α _) = uniformity.lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ (@uniformity α _).sets, by filter_upwards [hs] this, by simp [this]) (assume s hs, (uniformity.lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : interior s ∈ (@uniformity α _).sets := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed [uniform_space α] {s : set (α×α)} (h : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, is_closed t ∧ t ⊆ s := have s ∈ ((@uniformity α _).lift' closure).sets, by rwa [uniformity_eq_uniformity_closure] at h, have ∃t∈(@uniformity α _).sets, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, uniformity.sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /- uniform continuity -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) uniformity uniformity theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ (@uniformity β _).sets, {x : α × α | (f x.1, f x.2) ∈ r} ∈ (@uniformity α _).sets := iff.rfl lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem_sets]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := @tendsto_const_uniformity _ _ _ b uniformity lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (g ∘ f) := hf.comp hg def uniform_embedding [uniform_space β] (f : α → β) := function.injective f ∧ comap (λx:α×α, (f x.1, f x.2)) uniformity = uniformity theorem uniform_embedding_def [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ ∀ s, s ∈ (@uniformity α _).sets ↔ ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by rw [uniform_embedding, eq_comm, filter.ext_iff]; simp [subset_def] theorem uniform_embedding_def' [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ s, s ∈ (@uniformity α _).sets → ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by simp [uniform_embedding_def, uniform_continuous_def]; exact ⟨λ ⟨I, H⟩, ⟨I, λ s su, (H _).2 ⟨s, su, λ x y, id⟩, λ s, (H s).1⟩, λ ⟨I, H₁, H₂⟩, ⟨I, λ s, ⟨H₂ s, λ ⟨t, tu, h⟩, sets_of_superset _ (H₁ t tu) (λ ⟨a, b⟩, h a b)⟩⟩⟩ lemma uniform_embedding.uniform_continuous [uniform_space β] {f : α → β} (hf : uniform_embedding f) : uniform_continuous f := (uniform_embedding_def'.1 hf).2.1 lemma uniform_embedding.uniform_continuous_iff [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hg : uniform_embedding g) : uniform_continuous f ↔ uniform_continuous (g ∘ f) := by simp [uniform_continuous, tendsto]; rw [← hg.2, ← map_le_iff_le_comap, filter.map_map] lemma uniform_embedding.embedding [uniform_space β] {f : α → β} (h : uniform_embedding f) : embedding f := begin refine ⟨h.left, eq_of_nhds_eq_nhds $ assume a, _⟩, rw [nhds_induced_eq_comap, nhds_eq_uniformity, nhds_eq_uniformity, ← h.right, comap_lift'_eq, comap_lift'_eq2]; { refl <|> exact monotone_preimage } end lemma uniform_embedding.dense_embedding [uniform_space β] {f : α → β} (h : uniform_embedding f) (hd : ∀x, x ∈ closure (range f)) : dense_embedding f := { dense := hd, inj := h.left, induced := assume a, by rw [h.embedding.2, nhds_induced_eq_comap] } lemma uniform_continuous.continuous [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_tendsto.mpr $ assume a, calc map f (nhds a) ≤ (map (λp:α×α, (f p.1, f p.2)) uniformity).lift' (λs:set (β×β), {y | (f a, y) ∈ s}) : begin rw [nhds_eq_uniformity, map_lift'_eq, map_lift'_eq2], exact (lift'_mono' $ assume s hs b ⟨a', (ha' : (_, a') ∈ s), a'_eq⟩, ⟨(a, a'), ha', show (f a, f a') = (f a, b), from a'_eq ▸ rfl⟩), exact monotone_preimage, exact monotone_preimage end ... ≤ nhds (f a) : by rw [nhds_eq_uniformity]; exact lift'_mono hf (le_refl _) lemma closure_image_mem_nhds_of_uniform_embedding [uniform_space α] [uniform_space β] {s : set (α×α)} {e : α → β} (b : β) (he₁ : uniform_embedding e) (he₂ : dense_embedding e) (hs : s ∈ (@uniformity α _).sets) : ∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ (nhds b).sets := have s ∈ (comap (λp:α×α, (e p.1, e p.2)) $ uniformity).sets, from he₁.right.symm ▸ hs, let ⟨t₁, ht₁u, ht₁⟩ := this in have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁, let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in have preimage e {b' | (b, b') ∈ t₂} ∈ (comap e $ nhds b).sets, from preimage_mem_comap $ mem_nhds_left b ht₂u, let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := inhabited_of_mem_sets (he₂.comap_nhds_neq_bot) this in have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ (@uniformity β _).sets → {y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s} ≠ ∅, from assume b' s' hb' hs', have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ (comap e $ nhds b').sets, from preimage_mem_comap $ mem_nhds_left b' $ inter_mem_sets hs' htu, let ⟨a₂, ha₂s', ha₂t⟩ := inhabited_of_mem_sets (he₂.comap_nhds_neq_bot) this in have (e a, e a₂) ∈ t₁, from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t, have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s}, from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩, ne_empty_of_mem this, have ∀b', (b, b') ∈ t → nhds b' ⊓ principal (e '' {a' | (a, a') ∈ s}) ≠ ⊥, begin intros b' hb', rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_neq_bot_iff], exact assume s, this b' s hb', exact monotone_inter monotone_preimage monotone_const end, have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}), from assume b' hb', by rw [closure_eq_nhds]; exact this b' hb', ⟨a, (nhds b).sets_of_superset (mem_nhds_left b htu) this⟩ /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ uniformity lemma cauchy_iff [uniform_space α] {f : filter α} : cauchy f ↔ (f ≠ ⊥ ∧ (∀s∈(@uniformity α _).sets, ∃t∈f.sets, set.prod t t ⊆ s)) := and_congr (iff.refl _) $ forall_congr $ assume s, forall_congr $ assume hs, mem_prod_same_iff lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy_nhds {a : α} : cauchy (nhds a) := ⟨nhds_neq_bot, calc filter.prod (nhds a) (nhds a) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ uniformity.lift' (λs:set (α×α), comp_rel s s) : le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ uniformity : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_downwards cauchy_nhds (show principal {a} ≠ ⊥, by simp) (pure_le_nhds a) lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : f ⊓ nhds x ≠ ⊥) : f ≤ nhds x := have ∀s∈f.sets, x ∈ closure s, begin intros s hs, simp [closure_eq_nhds, inf_comm], exact assume h', adhs $ bot_unique $ h' ▸ inf_le_inf (by simp; exact hs) (le_refl _) end, calc f ≤ f.lift' (λs:set α, {y | x ∈ closure s ∧ y ∈ closure s}) : le_infi $ assume s, le_infi $ assume hs, begin rw [←forall_sets_neq_empty_iff_neq_bot] at adhs, simp [this s hs], exact mem_sets_of_superset hs subset_closure end ... ≤ f.lift' (λs:set α, {y | (x, y) ∈ closure (set.prod s s)}) : by simp [closure_prod_eq]; exact le_refl _ ... = (filter.prod f f).lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : begin rw [prod_same_eq], rw [lift'_lift'_assoc], exact monotone_prod monotone_id monotone_id, exact monotone_comp (assume s t h x h', closure_mono h h') monotone_preimage end ... ≤ uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : lift'_mono hf.right (le_refl _) ... = (uniformity.lift' closure).lift' (λs:set (α×α), {y | (x, y) ∈ s}) : begin rw [lift'_lift'_assoc], exact assume s t h, closure_mono h, exact monotone_preimage end ... = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) : by rw [←uniformity_eq_uniformity_closure] ... = nhds x : by rw [nhds_eq_uniformity] lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ nhds x ↔ f ⊓ nhds x ≠ ⊥ := ⟨assume h, (inf_of_le_left h).symm ▸ hf.left, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β} (hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) := ⟨have f ≠ ⊥, from hf.left, by simp; assumption, calc filter.prod (map m f) (map m f) = map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) uniformity : map_mono hf.right ... ≤ uniformity : hm⟩ lemma cauchy_comap [uniform_space β] {f : filter β} {m : α → β} (hm : comap (λp:α×α, (m p.1, m p.2)) uniformity ≤ uniformity) (hf : cauchy f) (hb : comap m f ≠ ⊥) : cauchy (comap m f) := ⟨hb, calc filter.prod (comap m f) (comap m f) = comap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_comap_comap_eq ... ≤ comap (λp:α×α, (m p.1, m p.2)) uniformity : comap_mono hf.right ... ≤ uniformity : hm⟩ /- separated uniformity -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (@uniformity α _).sets lemma separated_equiv : equivalence (λx y, (x, y) ∈ separation_rel α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α) s (hs : s ∈ (@uniformity α _).sets), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ @[class] def separated (α : Type u) [uniform_space α] := separation_rel α = id_rel theorem separated_def {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, (∀ r ∈ (@uniformity α _).sets, (x, y) ∈ r) → x = y := by simp [separated, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, x ≠ y → ∃ r ∈ (@uniformity α _).sets, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [classical.not_forall] instance separated_t2 [s : separated α] : t2_space α := ⟨assume x y, assume h : x ≠ y, let ⟨d, hd, (hxy : (x, y) ∉ d)⟩ := separated_def'.1 s x y h in let ⟨d', hd', (hd'd' : comp_rel d' d' ⊆ d)⟩ := comp_mem_uniformity_sets hd in have {y | (x, y) ∈ d'} ∈ (nhds x).sets, from mem_nhds_left x hd', let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in have {x | (x, y) ∈ d'} ∈ (nhds y).sets, from mem_nhds_right y hd', let ⟨v, hv₁, hv₂, hv₃⟩ := mem_nhds_sets_iff.mp this in have u ∩ v = ∅, from eq_empty_of_subset_empty $ assume z ⟨(h₁ : z ∈ u), (h₂ : z ∈ v)⟩, have (x, y) ∈ comp_rel d' d', from ⟨z, hu₁ h₁, hv₁ h₂⟩, hxy $ hd'd' this, ⟨u, v, hu₂, hv₂, hu₃, hv₃, this⟩⟩ instance separated_regular [separated α] : regular_space α := { regular := λs a hs ha, have -s ∈ (nhds a).sets, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ -s} ∈ uniformity.sets, from mem_nhds_uniformity_iff.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ uniformity.sets, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ -s, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ (nhds a).sets, from (nhds a).sets_of_superset (mem_nhds_left a hd) subset_closure, have nhds a ⊓ principal (-closure e) = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (principal (- closure e)) (principal (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨- closure e, is_closed_closure, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..separated_t2 } /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def totally_bounded (s : set α) : Prop := ∀d ∈ (@uniformity α _).sets, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔ ∀d ∈ (@uniformity α _).sets, ∃t ⊆ s, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) := ⟨λ H d hd, begin rcases comp_symm_of_uniformity hd with ⟨r, hr, rs, rd⟩, rcases H r hr with ⟨k, fk, ks⟩, let u := {y ∈ k | ∃ x, x ∈ s ∧ (x, y) ∈ r}, let f : u → α := λ x, classical.some x.2.2, have : ∀ x : u, f x ∈ s ∧ (f x, x.1) ∈ r := λ x, classical.some_spec x.2.2, refine ⟨range f, _, _, _⟩, { exact range_subset_iff.2 (λ x, (this x).1) }, { have : finite u := finite_subset fk (λ x h, h.1), exact ⟨@set.fintype_range _ _ _ _ this.fintype⟩ }, { intros x xs, have := ks xs, simp at this, rcases this with ⟨y, hy, xy⟩, let z : coe_sort u := ⟨y, hy, x, xs, xy⟩, exact mem_bUnion_iff.2 ⟨_, ⟨z, rfl⟩, rd $ mem_comp_rel.2 ⟨_, xy, rs (this z).2⟩⟩ } end, λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩ lemma totally_bounded_subset [uniform_space α] {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) (h : totally_bounded s₂) : totally_bounded s₁ := assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩ lemma totally_bounded_closure [uniform_space α] {s : set α} (h : totally_bounded s) : totally_bounded (closure s) := assume t ht, let ⟨t', ht', hct', htt'⟩ := mem_uniformity_is_closed ht, ⟨c, hcf, hc⟩ := h t' ht' in ⟨c, hcf, calc closure s ⊆ closure (⋃ (y : α) (H : y ∈ c), {x : α | (x, y) ∈ t'}) : closure_mono hc ... = _ : closure_eq_of_is_closed $ is_closed_Union hcf $ assume i hi, continuous_iff_is_closed.mp (continuous_id.prod_mk continuous_const) _ hct' ... ⊆ _ : bUnion_subset $ assume i hi, subset.trans (assume x, @htt' (x, i)) (subset_bUnion_of_mem hi)⟩ lemma totally_bounded_image [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (hf : uniform_continuous f) (hs : totally_bounded s) : totally_bounded (f '' s) := assume t ht, have {p:α×α | (f p.1, f p.2) ∈ t} ∈ (@uniformity α _).sets, from hf ht, let ⟨c, hfc, hct⟩ := hs _ this in ⟨f '' c, finite_image f hfc, begin simp [image_subset_iff], simp [subset_def] at hct, intros x hx, simp [-mem_image], exact let ⟨i, hi, ht⟩ := hct x hx in ⟨f i, mem_image_of_mem f hi, ht⟩ end⟩ lemma totally_bounded_preimage [uniform_space α] [uniform_space β] {f : α → β} {s : set β} (hf : uniform_embedding f) (hs : totally_bounded s) : totally_bounded (f ⁻¹' s) := λ t ht, begin rw ← hf.2 at ht, rcases mem_comap_sets.2 ht with ⟨t', ht', ts⟩, rcases totally_bounded_iff_subset.1 (totally_bounded_subset (image_preimage_subset f s) hs) _ ht' with ⟨c, cs, hfc, hct⟩, refine ⟨f ⁻¹' c, finite_preimage hf.1 hfc, λ x h, _⟩, have := hct (mem_image_of_mem f h), simp at this ⊢, rcases this with ⟨z, zc, zt⟩, rcases cs zc with ⟨y, yc, rfl⟩, exact ⟨y, zc, ts (by exact zt)⟩ end lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α} (hs : totally_bounded s) (hf : is_ultrafilter f) (h : f ≤ principal s) : cauchy f := ⟨hf.left, assume t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets, from mem_sets_of_superset (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets, from mem_of_finite_Union_ultrafilter hf hi this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, (filter.prod f f).sets_of_superset (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) := ⟨assume : totally_bounded s, assume f hf hs, ⟨ultrafilter_of f, ultrafilter_of_le, cauchy_of_totally_bounded_of_ultrafilter this (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩, assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, assume d hd, classical.by_contradiction $ assume hs, have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}), by simpa using hs, let f := ⨅t:{t : set α // finite t}, principal (s \ (⋃y∈t.val, {x | (x,y) ∈ d})), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h, hd_cover finite_empty $ h.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inr⟩) (assume ⟨t, ht⟩, by simp [diff_eq_empty]; exact hd_cover ht), have f ≤ principal s, from infi_le_of_le ⟨∅, finite_empty⟩ $ by simp; exact subset.refl s, let ⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this, ⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α c d).mp $ hc₂.right hd in have c ≤ principal s, from le_trans ‹c ≤ f› this, have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this, let ⟨y, hym, hys⟩ := inhabited_of_mem_sets hc₂.left this in let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in have m ⊆ ys, from assume y' hy', show y' ∈ (⋃y'∈({y}:set α), {x | (x, y') ∈ d}), by simp; exact @hmd (y', y) ⟨hy', hym⟩, have c ≤ principal (s - ys), from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_singleton _⟩ $ le_refl _, have (s - ys) ∩ (m ∩ s) ∈ c.sets, from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›, have ∅ ∈ c.sets, from c.sets_of_superset this $ assume x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm, hc₂.left $ empty_in_sets_eq_bot.mp this⟩ lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f, is_ultrafilter f → f ≤ principal s → cauchy f) := ⟨assume hs f, cauchy_of_totally_bounded_of_ultrafilter hs, assume h, totally_bounded_iff_filter.mpr $ assume f hf hfs, have cauchy (ultrafilter_of f), from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs), ⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩ lemma compact_of_totally_bounded_complete {s : set α} (ht : totally_bounded s) (hc : ∀{f:filter α}, cauchy f → f ≤ principal s → ∃x∈s, f ≤ nhds x) : compact s := begin rw [compact_iff_ultrafilter_le_nhds], rw [totally_bounded_iff_ultrafilter] at ht, exact assume f hf hfs, hc (ht _ hf hfs) hfs end /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ nhds x) theorem le_nhds_lim_of_cauchy {α} [uniform_space α] [complete_space α] [inhabited α] {f : filter α} (hf : cauchy f) : f ≤ nhds (lim f) := lim_spec (complete_space.complete hf) lemma complete_of_is_closed [complete_space α] {s : set α} {f : filter α} (h : is_closed s) (hf : cauchy f) (hfs : f ≤ principal s) : ∃x∈s, f ≤ nhds x := let ⟨x, hx⟩ := complete_space.complete hf in have x ∈ s, from is_closed_iff_nhds.mp h x $ neq_bot_of_le_neq_bot hf.left $ le_inf hx hfs, ⟨x, this, hx⟩ instance complete_of_compact {α : Type u} [uniform_space α] [compact_space α] : complete_space α := ⟨begin intros f hf, have A : ∃a∈univ, f ⊓ nhds a ≠ ⊥ := compact_univ f hf.1 (le_principal_iff.2 univ_mem_sets), rcases A with ⟨a, _ , fa⟩, existsi a, exact le_nhds_of_cauchy_adhp hf fa end⟩ lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : compact s := @compact_of_totally_bounded_complete α _ s ht $ assume f, complete_of_is_closed hc lemma complete_space_extension [uniform_space β] {m : β → α} (hm : uniform_embedding m) (dense : ∀x, x ∈ closure (range m)) (h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ nhds x) : complete_space α := ⟨assume (f : filter α), assume hf : cauchy f, let p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s}, g := uniformity.lift (λs, f.lift' (p s)) in have mp₀ : monotone p, from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩, have mp₁ : ∀{s}, monotone (p s), from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩, have f ≤ g, from le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, le_principal_iff.mpr $ mem_sets_of_superset ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩, have g ≠ ⊥, from neq_bot_of_le_neq_bot hf.left this, have comap m g ≠ ⊥, from comap_neq_bot $ assume t ht, let ⟨t', ht', ht_mem⟩ := (mem_lift_sets $ monotone_lift' monotone_const mp₀).mp ht in let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_sets mp₁).mp ht_mem in let ⟨x, (hx : x ∈ t'')⟩ := inhabited_of_mem_sets hf.left ht'' in have h₀ : nhds x ⊓ principal (range m) ≠ ⊥, by simp [closure_eq_nhds] at dense; exact dense x, have h₁ : {y | (x, y) ∈ t'} ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_left α (nhds x) (principal (range m)) _ $ mem_nhds_left x ht', have h₂ : range m ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_right α (nhds x) (principal (range m)) _ $ subset.refl _, have {y | (x, y) ∈ t'} ∩ range m ∈ (nhds x ⊓ principal (range m)).sets, from @inter_mem_sets α (nhds x ⊓ principal (range m)) _ _ h₁ h₂, let ⟨y, xyt', b, b_eq⟩ := inhabited_of_mem_sets h₀ this in ⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩, have cauchy g, from ⟨‹g ≠ ⊥›, assume s hs, let ⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs, ⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁, ⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂) in have hg₁ : p (preimage prod.swap s₁) t ∈ g.sets, from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht, have hg₂ : p s₂ t ∈ g.sets, from mem_lift hs₂ $ @mem_lift' α α f _ t ht, have hg : set.prod (p (preimage prod.swap s₁) t) (p s₂ t) ∈ (filter.prod g g).sets, from @prod_mem_prod α α _ _ g g hg₁ hg₂, (filter.prod g g).sets_of_superset hg (assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩, have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩, comp_s₁ $ prod_mk_mem_comp_rel hc₁ $ comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩, have cauchy (filter.comap m g), from cauchy_comap (le_of_eq hm.right) ‹cauchy g› (by assumption), let ⟨x, (hx : map m (filter.comap m g) ≤ nhds x)⟩ := h _ this in have map m (filter.comap m g) ⊓ nhds x ≠ ⊥, from (le_nhds_iff_adhp_of_cauchy (cauchy_map hm.uniform_continuous this)).mp hx, have g ⊓ nhds x ≠ ⊥, from neq_bot_of_le_neq_bot this (inf_le_inf (assume s hs, ⟨s, hs, subset.refl _⟩) (le_refl _)), ⟨x, calc f ≤ g : by assumption ... ≤ nhds x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩ section uniform_extension variables [uniform_space β] [uniform_space γ] {e : β → α} (h_e : uniform_embedding e) (h_dense : ∀x, x ∈ closure (range e)) {f : β → γ} (h_f : uniform_continuous f) local notation `ψ` := (h_e.dense_embedding h_dense).extend f lemma uniformly_extend_of_emb (b : β) : ψ (e b) = f b := dense_embedding.extend_e_eq _ b lemma uniformly_extend_exists [complete_space γ] (a : α) : ∃c, tendsto f (comap e (nhds a)) (nhds c) := let de := (h_e.dense_embedding h_dense) in have cauchy (nhds a), from cauchy_nhds, have cauchy (comap e (nhds a)), from cauchy_comap (le_of_eq h_e.right) this de.comap_nhds_neq_bot, have cauchy (map f (comap e (nhds a))), from cauchy_map h_f this, complete_space.complete this lemma uniformly_extend_spec [complete_space γ] (h_f : uniform_continuous f) (a : α) : tendsto f (comap e (nhds a)) (nhds (ψ a)) := let de := (h_e.dense_embedding h_dense) in begin by_cases ha : a ∈ range e, { rcases ha with ⟨b, rfl⟩, rw [uniformly_extend_of_emb, de.induced], exact h_f.continuous.tendsto _ }, { simp only [dense_embedding.extend, dif_neg ha], exact (@lim_spec _ (id _) _ _ $ uniformly_extend_exists h_e h_dense h_f _) } end lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] : uniform_continuous ψ := assume d hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in have h_pnt : ∀{a m}, m ∈ (nhds a).sets → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s, from assume a m hm, have nb : map f (comap e (nhds a)) ≠ ⊥, from map_ne_bot (h_e.dense_embedding h_dense).comap_nhds_neq_bot, have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ (map f (comap e (nhds a))).sets, from inter_mem_sets (image_mem_map $ preimage_mem_comap $ hm) (uniformly_extend_spec h_e h_dense h_f _ (inter_mem_sets (mem_nhds_right _ hs) (mem_nhds_left _ hs))), inhabited_of_mem_sets nb this, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (@uniformity β _).sets, from h_f hs, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (comap (λx:β×β, (e x.1, e x.2)) uniformity).sets, by rwa [h_e.right.symm] at this, let ⟨t, ht, ts⟩ := this in show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ uniformity.sets, from (@uniformity α _).sets_of_superset (interior_mem_uniformity ht) $ assume ⟨x₁, x₂⟩ hx_t, have nhds (x₁, x₂) ≤ principal (interior t), from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t, have interior t ∈ (filter.prod (nhds x₁) (nhds x₂)).sets, by rwa [nhds_prod_eq, le_principal_iff] at this, let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in have set.prod (preimage e m₁) (preimage e m₂) ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s, from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm ... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset ... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts, have set.prod (f '' preimage e m₁) (f '' preimage e m₂) ⊆ s, from calc set.prod (f '' preimage e m₁) (f '' preimage e m₂) = (λp:(β×β), (f p.1, f p.2)) '' (set.prod (preimage e m₁) (preimage e m₂)) : prod_image_image_eq ... ⊆ (λp:(β×β), (f p.1, f p.2)) '' preimage (λp:(β×β), (f p.1, f p.2)) s : mono_image this ... ⊆ s : image_subset_iff.mpr $ subset.refl _, have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩, hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s), from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩ end uniform_extension end uniform_space end section constructions variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} instance : partial_order (uniform_space α) := { le := λt s, s.uniformity ≤ t.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, @le_trans _ _ c.uniformity b.uniformity a.uniformity h₂ h₁ } instance : has_Sup (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma le_Sup {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : t ≤ Sup tt := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma Sup_le {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t' ≤ t) : Sup tt ≤ t := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_bot (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_top (uniform_space α) := ⟨{ to_topological_space := ⊤, uniformity := principal id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Sup {a, b}, le_sup_left := assume a b, le_Sup $ by simp, le_sup_right := assume a b, le_Sup $ by simp, sup_le := assume a b c h₁ h₂, Sup_le $ assume t', begin simp, intro h, cases h with h h, repeat { subst h; assumption } end, inf := λa b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := assume a b c h₁ h₂, le_Sup ⟨h₁, h₂⟩, inf_le_left := assume a b, Sup_le $ assume x ⟨ha, hb⟩, ha, inf_le_right := assume a b, Sup_le $ assume x ⟨ha, hb⟩, hb, top := ⊤, le_top := assume u, u.refl, bot := ⊥, bot_le := assume a, show a.uniformity ≤ ⊤, from le_top, Sup := Sup, le_Sup := assume s u, le_Sup, Sup_le := assume s u, Sup_le, Inf := λtt, Sup {t | ∀t'∈tt, t ≤ t'}, le_Inf := assume s a hs, le_Sup hs, Inf_le := assume s a ha, Sup_le $ assume u hs, hs _ ha, ..uniform_space.partial_order } lemma supr_uniformity {ι : Sort*} {u : ι → uniform_space α} : (supr u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, a = u i), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : a = u i)⟩, ha.symm ▸ infi_le _ _) lemma sup_uniformity {u v : uniform_space α} : (u ⊔ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊔ v) = (⨆i (h : i = u ∨ i = v), i), by simp [supr_or, supr_sup_eq], calc (u ⊔ v).uniformity = ((⨆i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [supr_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊤⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_comap.comp tendsto_swap_uniformity, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced_eq_comap, mem_nhds_uniformity_iff, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff.1 $ mem_nhds_left _ ht⟩ } end } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap_comp {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap_comp lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] (f : α → β) : uniform_continuous f ↔ uβ.comap f ≤ uα := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := eq_of_nhds_eq_nhds $ assume a, begin simp [nhds_induced_eq_comap, nhds_eq_uniformity, nhds_eq_uniformity], change comap f (uniformity.lift' (preimage (λb, (f a, b)))) = (u.uniformity.comap (λp:α×α, (f p.1, f p.2))).lift' (preimage (λa', (a, a'))), rw [comap_lift'_eq monotone_preimage, comap_lift'_eq2 monotone_preimage], exact rfl end lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := rfl lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := bot_unique $ assume s hs, classical.by_cases (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊥) (assume : s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊥) lemma to_topological_space_supr {ι : Sort*} {u : ι → uniform_space α} : @uniform_space.to_topological_space α (supr u) = (⨆i, @uniform_space.to_topological_space α (u i)) := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_supr, nhds_eq_uniformity], change _ = (supr u).uniformity.lift' (preimage $ prod.mk a), begin rw [supr_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, @nhds_eq_uniformity α (u i) a), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (have supr u = ⊥, from bot_unique $ supr_le $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (supr u) = ⊥, from this.symm ▸ to_topological_space_bot, this.symm ▸ bot_le) (supr_le $ assume i, to_topological_space_mono $ le_supr _ _)) lemma to_topological_space_Sup {s : set (uniform_space α)} : @uniform_space.to_topological_space α (Sup s) = (⨆i∈s, @uniform_space.to_topological_space α i) := begin rw [Sup_eq_supr, to_topological_space_supr], apply congr rfl, funext x, exact to_topological_space_supr end lemma to_topological_space_sup {u v : uniform_space α} : @uniform_space.to_topological_space α (u ⊔ v) = @uniform_space.to_topological_space α u ⊔ @uniform_space.to_topological_space α v := ord_continuous_sup $ assume s, to_topological_space_Sup instance : uniform_space empty := ⊤ instance : uniform_space unit := ⊤ instance : uniform_space bool := ⊤ instance : uniform_space ℕ := ⊤ instance : uniform_space ℤ := ⊤ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : (@uniformity (subtype p) _) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) uniformity := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ (nhds a).sets) : tendsto f (nhds a) (nhds (f a)) := by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_tendsto.mp hf.continuous _) lemma uniform_embedding_subtype_emb {α : Type*} {β : Type*} [uniform_space α] [uniform_space β] (p : α → Prop) {e : α → β} (ue : uniform_embedding e) (de : dense_embedding e) : uniform_embedding (de.subtype_emb p) := ⟨(de.subtype p).inj, by simp [comap_comap_comp, (∘), dense_embedding.subtype_emb, uniformity_subtype, ue.right.symm]⟩ lemma uniform_extend_subtype {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [complete_space γ] {p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α} (hf : uniform_continuous (λx:subtype p, f x.val)) (he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (range e)) (hb : closure (e '' s) ∈ (nhds b).sets) (hs : is_closed s) (hp : ∀x∈s, p x) : ∃c, tendsto f (comap e (nhds b)) (nhds c) := have de : dense_embedding e, from he.dense_embedding hd, have de' : dense_embedding (de.subtype_emb p), by exact de.subtype p, have ue' : uniform_embedding (de.subtype_emb p), from uniform_embedding_subtype_emb _ he de, have b ∈ closure (e '' {x | p x}), from (closure_mono $ mono_image $ hp) (mem_of_nhds hb), let ⟨c, (hc : tendsto (f ∘ subtype.val) (comap (de.subtype_emb p) (nhds ⟨b, this⟩)) (nhds c))⟩ := uniformly_extend_exists ue' de'.dense hf _ in begin rw [nhds_subtype_eq_comap] at hc, simp [comap_comap_comp] at hc, change (tendsto (f ∘ @subtype.val α p) (comap (e ∘ @subtype.val α p) (nhds b)) (nhds c)) at hc, rw [←comap_comap_comp] at hc, existsi c, apply tendsto_comap'' s _ _ hc, exact ⟨_, hb, assume x, begin change e x ∈ (closure (e '' s)) → x ∈ s, rw [←closure_induced, closure_eq_nhds], dsimp, rw [nhds_induced_eq_comap, de.induced], change x ∈ {x | nhds x ⊓ principal s ≠ ⊥} → x ∈ s, rw [←closure_eq_nhds, closure_eq_of_is_closed hs], exact id, exact de.inj end⟩, exact (assume x hx, ⟨⟨x, hp x hx⟩, rfl⟩) end /--If a Cauchy filter contains a compact set, then it is converging. The proof is done by restricting to the compact set, and then lifting everything back. The same would work if the filter contained a complete set, but complete sets are not defined, and this would be less useful anyway.-/ lemma complete_of_compact_set {α : Type u} [uniform_space α] {f : filter α} (h : cauchy f) {t : set α} (tf : t ∈ f.sets) (ht : compact t) : ∃x, f ≤ nhds x := begin let ft := ((comap subtype.val f) : filter t), haveI : compact_space t := ⟨by rw [←compact_iff_compact_univ]; apply ht⟩, have B : ft ≠ ⊥ := comap_neq_bot begin intros u u_fset, have : u ∩ t ∈ f.sets := f.inter_sets u_fset tf, rcases inhabited_of_mem_sets h.1 this with ⟨y, yut⟩, exact ⟨⟨y, yut.2⟩, yut.1⟩, end, have : cauchy ft := cauchy_comap (le_refl _) h B, /-We have proved that the restricted filter is Cauchy. By compactness, it converges-/ rcases complete_space.complete this with ⟨⟨y, yt⟩, hy⟩, existsi y, rw nhds_subtype_eq_comap at hy, calc f ≤ map subtype.val (comap subtype.val f) : le_map_comap' tf (by simp) ... ≤ map subtype.val (comap subtype.val (nhds y)) : map_mono hy ... ≤ nhds y : map_comap_le end /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊔ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊔ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_sup, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : @uniformity (α × β) _ = uniformity.comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ uniformity.comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := sup_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : @uniformity (α×β) _ = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod uniformity uniformity) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap_comp, comap_comap_comp] lemma mem_uniformity_of_uniform_continuous_invarant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ (@uniformity α _).sets) : ∃u∈(@uniformity α _).sets, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_sets_iff.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ (@uniformity α _).sets) (hb : b ∈ (@uniformity β _).sets) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _).sets := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) uniformity uniformity := le_trans (map_mono (@le_sup_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) uniformity uniformity := le_trans (map_mono (@le_sup_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := uniform_continuous.comp (uniform_continuous.prod_mk uniform_continuous_id uniform_continuous_const) h lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := uniform_continuous.comp (uniform_continuous.prod_mk uniform_continuous_const uniform_continuous_id) h lemma cauchy_prod [uniform_space β] {f : filter α} {g : filter β} : cauchy f → cauchy g → cauchy (filter.prod f g) | ⟨f_proper, hf⟩ ⟨g_proper, hg⟩ := ⟨filter.prod_neq_bot.2 ⟨f_proper, g_proper⟩, let p_α := λp:(α×β)×(α×β), (p.1.1, p.2.1), p_β := λp:(α×β)×(α×β), (p.1.2, p.2.2) in suffices (f.prod f).comap p_α ⊓ (g.prod g).comap p_β ≤ uniformity.comap p_α ⊓ uniformity.comap p_β, by simpa [uniformity_prod, filter.prod, filter.comap_inf, filter.comap_comap_comp, (∘), lattice.inf_assoc, lattice.inf_comm, lattice.inf_left_comm], lattice.inf_le_inf (filter.comap_mono hf) (filter.comap_mono hg)⟩ instance complete_space.prod [complete_space α] [complete_space β] : complete_space (α × β) := { complete := λ f hf, let ⟨x1, hx1⟩ := complete_space.complete $ cauchy_map uniform_continuous_fst hf in let ⟨x2, hx2⟩ := complete_space.complete $ cauchy_map uniform_continuous_snd hf in ⟨(x1, x2), by rw [nhds_prod_eq, filter.prod_def]; from filter.le_lift (λ s hs, filter.le_lift' $ λ t ht, have H1 : prod.fst ⁻¹' s ∈ f.sets := hx1 hs, have H2 : prod.snd ⁻¹' t ∈ f.sets := hx2 ht, filter.inter_mem_sets H1 H2)⟩ } lemma uniform_embedding.prod {α' : Type*} {β' : Type*} [uniform_space α] [uniform_space β] [uniform_space α'] [uniform_space β'] {e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) : uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) := ⟨assume ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, by simp [prod.mk.inj_iff]; exact assume eq₁ eq₂, ⟨h₁.left eq₁, h₂.left eq₂⟩, by simp [(∘), uniformity_prod, h₁.right.symm, h₂.right.symm, comap_inf, comap_comap_comp]⟩ lemma to_topological_space_prod [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl end constructions lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ (@uniformity α _).sets, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ (@uniformity α _).sets), {y | (x, y) ∈ comp_rel m n} ⊆ c i}, have hu₁ : ∀ n ∈ (@uniformity α _).sets, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply uniformity.sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ (@uniformity α _).sets, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases compact_elim_finite_subcover_image hs hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ (@uniformity α _).sets, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂ namespace dense_embedding open filter variables {α : Type*} [topological_space α] variables {β : Type*} [topological_space β] variables {γ : Type*} [uniform_space γ] [complete_space γ] [separated γ] lemma continuous_extend_of_cauchy {e : α → β} {f : α → γ} (de : dense_embedding e) (h : ∀ b : β, cauchy (map f (comap e $ nhds b))) : continuous (de.extend f) := continuous_extend de $ λ b, complete_space.complete (h b) end dense_embedding
ae8d9e531dc238f1749410e097bcec4f26762fbe
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/vector_bundle/prod.lean
a7486d3642dc5828dc2bbbc1fdf28ab70eb314c9
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
11,436
lean
/- Copyright © 2022 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Floris van Doorn -/ import topology.vector_bundle.basic /-! # Direct sum of two vector bundles If `E₁ : B → Type*` and `E₂ : B → Type*` define two topological vector bundles over `R` with fiber models `F₁` and `F₂`, we define the bundle of direct sums `E₁ ×ᵇ E₂ := λ x, E₁ x × E₂ x`. We can endow `E₁ ×ᵇ E₂` with a topological vector bundle structure: `bundle.prod.topological_vector_bundle`. A similar construction (which is yet to be formalized) can be done for the vector bundle of continuous linear maps from `E₁ x` to `E₂ x` with fiber a type synonym `vector_bundle_continuous_linear_map R F₁ E₁ F₂ E₂ x := (E₁ x →L[R] E₂ x)` (and with the topology inherited from the norm-topology on `F₁ →L[R] F₂`, without the need to define the strong topology on continuous linear maps between general topological vector spaces). Likewise for tensor products of topological vector bundles, exterior algebras, and so on, where the topology can be defined using a norm on the fiber model if this helps. ## Tags Vector bundle -/ noncomputable theory open bundle set open_locale classical variables (R 𝕜 : Type*) {B : Type*} (F : Type*) (E : B → Type*) namespace topological_vector_bundle section defs variables (E₁ : B → Type*) (E₂ : B → Type*) variables [topological_space (total_space E₁)] [topological_space (total_space E₂)] /-- Equip the total space of the fibrewise product of two topological vector bundles `E₁`, `E₂` with the induced topology from the diagonal embedding into `total_space E₁ × total_space E₂`. -/ instance prod.topological_space : topological_space (total_space (E₁ ×ᵇ E₂)) := topological_space.induced (λ p, ((⟨p.1, p.2.1⟩ : total_space E₁), (⟨p.1, p.2.2⟩ : total_space E₂))) (by apply_instance : topological_space (total_space E₁ × total_space E₂)) /-- The diagonal map from the total space of the fibrewise product of two topological vector bundles `E₁`, `E₂` into `total_space E₁ × total_space E₂` is `inducing`. -/ lemma prod.inducing_diag : inducing (λ p, (⟨p.1, p.2.1⟩, ⟨p.1, p.2.2⟩) : total_space (E₁ ×ᵇ E₂) → total_space E₁ × total_space E₂) := ⟨rfl⟩ end defs variables [nontrivially_normed_field R] [topological_space B] variables (F₁ : Type*) [normed_add_comm_group F₁] [normed_space R F₁] (E₁ : B → Type*) [topological_space (total_space E₁)] [Π x, add_comm_monoid (E₁ x)] [Π x, module R (E₁ x)] variables (F₂ : Type*) [normed_add_comm_group F₂] [normed_space R F₂] (E₂ : B → Type*) [topological_space (total_space E₂)] [Π x, add_comm_monoid (E₂ x)] [Π x, module R (E₂ x)] namespace trivialization variables (e₁ : trivialization R F₁ E₁) (e₂ : trivialization R F₂ E₂) include e₁ e₂ variables {R F₁ E₁ F₂ E₂} /-- Given trivializations `e₁`, `e₂` for vector bundles `E₁`, `E₂` over a base `B`, the forward function for the construction `topological_vector_bundle.trivialization.prod`, the induced trivialization for the direct sum of `E₁` and `E₂`. -/ def prod.to_fun' : total_space (E₁ ×ᵇ E₂) → B × (F₁ × F₂) := λ p, ⟨p.1, (e₁ ⟨p.1, p.2.1⟩).2, (e₂ ⟨p.1, p.2.2⟩).2⟩ variables {e₁ e₂} lemma prod.continuous_to_fun : continuous_on (prod.to_fun' e₁ e₂) (@total_space.proj B (E₁ ×ᵇ E₂) ⁻¹' (e₁.base_set ∩ e₂.base_set)) := begin let f₁ : total_space (E₁ ×ᵇ E₂) → total_space E₁ × total_space E₂ := λ p, ((⟨p.1, p.2.1⟩ : total_space E₁), (⟨p.1, p.2.2⟩ : total_space E₂)), let f₂ : total_space E₁ × total_space E₂ → (B × F₁) × (B × F₂) := λ p, ⟨e₁ p.1, e₂ p.2⟩, let f₃ : (B × F₁) × (B × F₂) → B × F₁ × F₂ := λ p, ⟨p.1.1, p.1.2, p.2.2⟩, have hf₁ : continuous f₁ := (prod.inducing_diag E₁ E₂).continuous, have hf₂ : continuous_on f₂ (e₁.source ×ˢ e₂.source) := e₁.to_local_homeomorph.continuous_on.prod_map e₂.to_local_homeomorph.continuous_on, have hf₃ : continuous f₃ := (continuous_fst.comp continuous_fst).prod_mk (continuous_snd.prod_map continuous_snd), refine ((hf₃.comp_continuous_on hf₂).comp hf₁.continuous_on _).congr _, { rw [e₁.source_eq, e₂.source_eq], exact maps_to_preimage _ _ }, rintros ⟨b, v₁, v₂⟩ ⟨hb₁, hb₂⟩, simp only [prod.to_fun', prod.mk.inj_iff, eq_self_iff_true, and_true], rw e₁.coe_fst, rw [e₁.source_eq, mem_preimage], exact hb₁, end variables (e₁ e₂) /-- Given trivializations `e₁`, `e₂` for vector bundles `E₁`, `E₂` over a base `B`, the inverse function for the construction `topological_vector_bundle.trivialization.prod`, the induced trivialization for the direct sum of `E₁` and `E₂`. -/ def prod.inv_fun' (p : B × (F₁ × F₂)) : total_space (E₁ ×ᵇ E₂) := ⟨p.1, e₁.symm p.1 p.2.1, e₂.symm p.1 p.2.2⟩ variables {e₁ e₂} lemma prod.left_inv {x : total_space (E₁ ×ᵇ E₂)} (h : x ∈ @total_space.proj B (E₁ ×ᵇ E₂) ⁻¹' (e₁.base_set ∩ e₂.base_set)) : prod.inv_fun' e₁ e₂ (prod.to_fun' e₁ e₂ x) = x := begin obtain ⟨x, v₁, v₂⟩ := x, obtain ⟨h₁ : x ∈ e₁.base_set, h₂ : x ∈ e₂.base_set⟩ := h, simp only [prod.to_fun', prod.inv_fun', symm_apply_apply_mk, h₁, h₂] end lemma prod.right_inv {x : B × F₁ × F₂} (h : x ∈ (e₁.base_set ∩ e₂.base_set) ×ˢ (univ : set (F₁ × F₂))) : prod.to_fun' e₁ e₂ (prod.inv_fun' e₁ e₂ x) = x := begin obtain ⟨x, w₁, w₂⟩ := x, obtain ⟨⟨h₁ : x ∈ e₁.base_set, h₂ : x ∈ e₂.base_set⟩, -⟩ := h, simp only [prod.to_fun', prod.inv_fun', apply_mk_symm, h₁, h₂] end lemma prod.continuous_inv_fun : continuous_on (prod.inv_fun' e₁ e₂) ((e₁.base_set ∩ e₂.base_set) ×ˢ univ) := begin rw (prod.inducing_diag E₁ E₂).continuous_on_iff, have H₁ : continuous (λ p : B × F₁ × F₂, ((p.1, p.2.1), (p.1, p.2.2))) := (continuous_id.prod_map continuous_fst).prod_mk (continuous_id.prod_map continuous_snd), refine (e₁.continuous_on_symm.prod_map e₂.continuous_on_symm).comp H₁.continuous_on _, exact λ x h, ⟨⟨h.1.1, mem_univ _⟩, ⟨h.1.2, mem_univ _⟩⟩ end variables (e₁ e₂) variables [Π x : B, topological_space (E₁ x)] [Π x : B, topological_space (E₂ x)] [topological_vector_bundle R F₁ E₁] [topological_vector_bundle R F₂ E₂] /-- Given trivializations `e₁`, `e₂` for vector bundles `E₁`, `E₂` over a base `B`, the induced trivialization for the direct sum of `E₁` and `E₂`, whose base set is `e₁.base_set ∩ e₂.base_set`. -/ @[nolint unused_arguments] def prod : trivialization R (F₁ × F₂) (E₁ ×ᵇ E₂) := { to_fun := prod.to_fun' e₁ e₂, inv_fun := prod.inv_fun' e₁ e₂, source := (@total_space.proj B (E₁ ×ᵇ E₂)) ⁻¹' (e₁.base_set ∩ e₂.base_set), target := (e₁.base_set ∩ e₂.base_set) ×ˢ set.univ, map_source' := λ x h, ⟨h, set.mem_univ _⟩, map_target' := λ x h, h.1, left_inv' := λ x, prod.left_inv, right_inv' := λ x, prod.right_inv, open_source := begin refine (e₁.open_base_set.inter e₂.open_base_set).preimage _, have : continuous (@total_space.proj B E₁) := continuous_proj R B F₁, exact this.comp (prod.inducing_diag E₁ E₂).continuous.fst, end, open_target := (e₁.open_base_set.inter e₂.open_base_set).prod is_open_univ, continuous_to_fun := prod.continuous_to_fun, continuous_inv_fun := prod.continuous_inv_fun, base_set := e₁.base_set ∩ e₂.base_set, open_base_set := e₁.open_base_set.inter e₂.open_base_set, source_eq := rfl, target_eq := rfl, proj_to_fun := λ x h, rfl, linear' := λ x ⟨h₁, h₂⟩, (((e₁.linear h₁).mk' _).prod_map ((e₂.linear h₂).mk' _)).is_linear } @[simp] lemma base_set_prod : (prod e₁ e₂).base_set = e₁.base_set ∩ e₂.base_set := rfl variables {e₁ e₂} lemma prod_apply {x : B} (hx₁ : x ∈ e₁.base_set) (hx₂ : x ∈ e₂.base_set) (v₁ : E₁ x) (v₂ : E₂ x) : prod e₁ e₂ ⟨x, (v₁, v₂)⟩ = ⟨x, e₁.continuous_linear_equiv_at x hx₁ v₁, e₂.continuous_linear_equiv_at x hx₂ v₂⟩ := rfl lemma prod_symm_apply (x : B) (w₁ : F₁) (w₂ : F₂) : (prod e₁ e₂).to_local_equiv.symm (x, w₁, w₂) = ⟨x, e₁.symm x w₁, e₂.symm x w₂⟩ := rfl end trivialization open trivialization variables [Π x : B, topological_space (E₁ x)] [Π x : B, topological_space (E₂ x)] [topological_vector_bundle R F₁ E₁] [topological_vector_bundle R F₂ E₂] /-- The product of two vector bundles is a vector bundle. -/ instance _root_.bundle.prod.topological_vector_bundle : topological_vector_bundle R (F₁ × F₂) (E₁ ×ᵇ E₂) := { total_space_mk_inducing := λ b, begin rw (prod.inducing_diag E₁ E₂).inducing_iff, exact (total_space_mk_inducing R F₁ E₁ b).prod_mk (total_space_mk_inducing R F₂ E₂ b), end, trivialization_atlas := (λ (p : trivialization R F₁ E₁ × trivialization R F₂ E₂), p.1.prod p.2) '' (trivialization_atlas R F₁ E₁ ×ˢ trivialization_atlas R F₂ E₂), trivialization_at := λ b, (trivialization_at R F₁ E₁ b).prod (trivialization_at R F₂ E₂ b), mem_base_set_trivialization_at := λ b, ⟨mem_base_set_trivialization_at R F₁ E₁ b, mem_base_set_trivialization_at R F₂ E₂ b⟩, trivialization_mem_atlas := λ b, ⟨(_, _), ⟨trivialization_mem_atlas R F₁ E₁ b, trivialization_mem_atlas R F₂ E₂ b⟩, rfl⟩, continuous_on_coord_change := begin rintros _ ⟨⟨e₁, e₂⟩, ⟨he₁, he₂⟩, rfl⟩ _ ⟨⟨e₁', e₂'⟩, ⟨he₁', he₂'⟩, rfl⟩, have := continuous_on_coord_change e₁ he₁ e₁' he₁', have := continuous_on_coord_change e₂ he₂ e₂' he₂', refine (((continuous_on_coord_change e₁ he₁ e₁' he₁').mono _).prod_mapL R ((continuous_on_coord_change e₂ he₂ e₂' he₂').mono _)).congr _; dsimp only [base_set_prod] with mfld_simps, { mfld_set_tac }, { mfld_set_tac }, { rintro b hb, rw [continuous_linear_map.ext_iff], rintro ⟨v₁, v₂⟩, show (e₁.prod e₂).coord_change (e₁'.prod e₂') b (v₁, v₂) = (e₁.coord_change e₁' b v₁, e₂.coord_change e₂' b v₂), rw [e₁.coord_change_apply e₁', e₂.coord_change_apply e₂', (e₁.prod e₂).coord_change_apply'], exacts [rfl, hb, ⟨hb.1.2, hb.2.2⟩, ⟨hb.1.1, hb.2.1⟩] } end } variables {R F₁ E₁ F₂ E₂} @[simp] lemma trivialization.continuous_linear_equiv_at_prod {e₁ : trivialization R F₁ E₁} {e₂ : trivialization R F₂ E₂} {x : B} (hx₁ : x ∈ e₁.base_set) (hx₂ : x ∈ e₂.base_set) : (e₁.prod e₂).continuous_linear_equiv_at x ⟨hx₁, hx₂⟩ = (e₁.continuous_linear_equiv_at x hx₁).prod (e₂.continuous_linear_equiv_at x hx₂) := begin ext1, funext v, obtain ⟨v₁, v₂⟩ := v, rw [(e₁.prod e₂).continuous_linear_equiv_at_apply, trivialization.prod], exact (congr_arg prod.snd (prod_apply hx₁ hx₂ v₁ v₂) : _) end end topological_vector_bundle
b87df1f9f12304f731fd8cf4a00cfc9e527e1ef3
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/von_neumann_algebra/basic.lean
657402fed8c7510ae1d97cc9469ba420c21b5f85
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,682
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import analysis.normed_space.dual import analysis.normed_space.star.basic import analysis.complex.basic import analysis.inner_product_space.adjoint import algebra.star.subalgebra /-! # Von Neumann algebras We give the "abstract" and "concrete" definitions of a von Neumann algebra. We still have a major project ahead of us to show the equivalence between these definitions! An abstract von Neumann algebra `wstar_algebra M` is a C^* algebra with a Banach space predual, per Sakai (1971). A concrete von Neumann algebra `von_neumann_algebra H` (where `H` is a Hilbert space) is a *-closed subalgebra of bounded operators on `H` which is equal to its double commutant. We'll also need to prove the von Neumann double commutant theorem, that the concrete definition is equivalent to a *-closed subalgebra which is weakly closed. -/ universes u v /-- Sakai's definition of a von Neumann algebra as a C^* algebra with a Banach space predual. So that we can unambiguously talk about these "abstract" von Neumann algebras in parallel with the "concrete" ones (weakly closed *-subalgebras of B(H)), we name this definition `wstar_algebra`. Note that for now we only assert the mere existence of predual, rather than picking one. This may later prove problematic, and need to be revisited. Picking one may cause problems with definitional unification of different instances. One the other hand, not picking one means that the weak-* topology (which depends on a choice of predual) must be defined using the choice, and we may be unhappy with the resulting opaqueness of the definition. -/ class wstar_algebra (M : Type u) [normed_ring M] [star_ring M] [cstar_ring M] [module ℂ M] [normed_algebra ℂ M] [star_module ℂ M] := (exists_predual : ∃ (X : Type u) [normed_group X] [normed_space ℂ X] [complete_space X], nonempty (normed_space.dual ℂ X ≃ₗᵢ⋆[ℂ] M)) -- TODO: Without this, `von_neumann_algebra` times out. Why? set_option old_structure_cmd true /-- The double commutant definition of a von Neumann algebra, as a *-closed subalgebra of bounded operators on a Hilbert space, which is equal to its double commutant. Note that this definition is parameterised by the Hilbert space on which the algebra faithfully acts, as is standard in the literature. See `wstar_algebra` for the abstract notion (a C^*-algebra with Banach space predual). Note this is a bundled structure, parameterised by the Hilbert space `H`, rather than a typeclass on the type of elements. Thus we can't say that the bounded operators `H →L[ℂ] H` form a `von_neumann_algebra` (although we will later construct the instance `wstar_algebra (H →L[ℂ] H)`), and instead will use `⊤ : von_neumann_algebra H`. -/ @[nolint has_inhabited_instance] structure von_neumann_algebra (H : Type u) [inner_product_space ℂ H] [complete_space H] extends star_subalgebra ℂ (H →L[ℂ] H) := (double_commutant : set.centralizer (set.centralizer carrier) = carrier) /-- Consider a von Neumann algebra acting on a Hilbert space `H` as a *-subalgebra of `H →L[ℂ] H`. (That is, we forget that it is equal to its double commutant or equivalently that it is closed in the weak and strong operator topologies.) -/ add_decl_doc von_neumann_algebra.to_star_subalgebra namespace von_neumann_algebra variables (H : Type u) [inner_product_space ℂ H] [complete_space H] instance : set_like (von_neumann_algebra H) (H →L[ℂ] H) := ⟨von_neumann_algebra.carrier, λ p q h, by cases p; cases q; congr'⟩ end von_neumann_algebra
7f5e000a136f81e4c6a3a2b90a8031efb9b4db50
a8ca99e8fae20e1383a6a786312b9f44f7dfdb42
/coq/2.1 simple type theory.lean
b60157ce3c6df15483279166f3c7def8f4f6a3f8
[ "MIT" ]
permissive
nolmeunion/learn
b715a4e9560101275c9c418d191cc198c905d189
482f4b8a5de81375e5663ea0b065d25f2f7da4b6
refs/heads/master
1,671,751,332,943
1,601,261,285,000
1,601,261,285,000
287,418,011
0
0
null
null
null
null
UTF-8
Lean
false
false
700
lean
/- declare some constants -/ constant m : nat -- m is a natural number constant n : nat constants b1 b2 : bool -- declare two constants at once /- check their types -/ #check m -- output: nat #check n #check n + 0 -- nat #check m * (n + 0) -- nat #check b1 -- bool #check b1 && b2 -- "&&" is boolean and #check b1 || b2 -- boolean or #check tt -- boolean "true" constant f : nat → nat constant f' : nat → nat constant p : nat × nat constant f'' : ℕ → ℕ #check f #check f'' constant F : (ℕ → ℕ ) → ℕ #check F #check (m, n).fst -- every expression has a type -- we can build more types on simple types
94237a6aa4b9487d4e6a0de6096099a96ab9e3d3
84c325c9a58de83324b777adc78ac188ecdbceae
/src/repl.lean
474b14751ca576f5e98b3ee32c8d74b06319a389
[ "Apache-2.0" ]
permissive
brando90/lean-gym
0c3b433dac9c1a1079623721cdb3307a0981d86b
f4a94fcf54f8729be416ebdca82097d95a6f1c39
refs/heads/main
1,683,583,589,195
1,622,558,076,000
1,622,558,076,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,400
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Stanislas Polu, Jesse Michael Han REPL implementation to interact with Lean through stdio at a specific declaration. -/ import tactic import data.string.basic import all import util.io import util.tactic import tactic.gptf.utils.util import basic.table import tactic.gptf.basic section main setup_tactic_parser meta structure LeanREPLRequest : Type := (cmd : string) (sid: string) (tsid: string) (tac: string) (name: string) (open_ns: string) meta structure LeanREPLResponse : Type := (sid : option string) (tsid : option string) (tactic_state : option string) (error: option string) meta structure LeanREPLState : Type := (state : dict string (dict string tactic_state)) (next_sid : ℕ) namespace LeanREPLState meta def insert_ts (σ : LeanREPLState) (sid) (tsid) (ts) : LeanREPLState := ⟨dict.insert sid (dict.insert tsid ts (σ.1.get_default (dict.empty) sid)) σ.1, σ.2⟩ meta def get_ts (σ : LeanREPLState) (sid) (tsid) : option tactic_state := (σ.1.get_default (dict.empty) sid).get tsid meta def get_next_tsid (σ : LeanREPLState) (sid) : string := (format! "{(σ.1.get_default (dict.empty) sid).size}").to_string meta def erase_search (σ : LeanREPLState) (sid) : LeanREPLState := ⟨σ.1.erase sid, σ.2⟩ meta def get_next_sid (σ : LeanREPLState) : string := (format! "{σ.2}").to_string meta def incr_next_sid (σ : LeanREPLState) : LeanREPLState := ⟨σ.1, σ.2+1⟩ end LeanREPLState meta instance : has_from_json LeanREPLRequest := ⟨λ msg, match msg with | (json.array [json.of_string cmd, json.array args]) := match cmd with | "run_tac" := match json.array args with | (json.array [json.of_string sid, json.of_string tsid, json.of_string tac]) := pure ⟨cmd, sid, tsid, tac, "", ""⟩ | exc := tactic.fail format!"[fatal] request_parsing_error: cmd=run_tac data={exc}" end | "init_search" := match json.array args with | (json.array [json.of_string name, json.of_string open_ns]) := pure ⟨cmd, "", "", "", name, open_ns⟩ | exc := tactic.fail format!"[fatal] request_parsing_error: cmd=init_theorem data={exc}" end | "clear_search" := match json.array args with | (json.array [json.of_string sid]) := pure ⟨cmd, sid, "" , "", "", ""⟩ | exc := tactic.fail format!"[fatal] request_parsing_error: cmd=init_theorem data={exc}" end | exc := tactic.fail format!"[fatal] request_parsing_error: data={exc}" end | exc := tactic.fail format!"[fatal] request_parsing_error: data={exc}" end ⟩ @[reducible] meta def LeanREPL := state_t LeanREPLState io meta def LeanREPL.forever (x : LeanREPL unit) : LeanREPL unit := do σ₀ ← get, state_t.lift $ io.iterate σ₀ $ λ σ, do { (_, σ') ← x.run σ, return (some σ') }, state_t.lift $ io.fail' $ format! "[LeanREPL.forever] unreachable code" meta def record_ts {m} [monad m] (sid: string) (ts : tactic_state) : (state_t LeanREPLState m) string := do { σ ← get, let tsid := σ.get_next_tsid sid, modify $ λ σ, σ.insert_ts sid tsid ts, pure tsid } meta def LeanREPLResponse.to_json: LeanREPLResponse → json | ⟨sid, tsid, ts, err⟩ := json.object [ ⟨"search_id", match sid with | none := json.null | some sid := json.of_string sid end⟩, ⟨"tactic_state_id", match tsid with | none := json.null | some tsid := json.of_string tsid end⟩, ⟨"tactic_state", match ts with | none := json.null | some ts := json.of_string ts end⟩, ⟨"error", match err with | none := json.null | some err := json.of_string err end⟩ ] meta instance : has_to_format LeanREPLResponse := ⟨has_to_format.to_format ∘ LeanREPLResponse.to_json⟩ meta def parse_theorem_name (nm: string) : tactic name := do lean.parser.run_with_input ident nm meta def parse_open_namespace (open_ns: string) : tactic (list name) := do lean.parser.run_with_input (many ident) open_ns meta def handle_init_search (req : LeanREPLRequest) : LeanREPL LeanREPLResponse := do { σ ← get, -- Parse declaration name. decl_name ← state_t.lift $ io.run_tactic'' $ do { parse_theorem_name req.name }, -- Parse open namespaces. decl_open_ns ← state_t.lift $ io.run_tactic'' $ do { parse_open_namespace req.open_ns }, -- Check that the declaration is a theorem. is_theorem ← state_t.lift $ io.run_tactic'' $ do { tactic.is_theorem decl_name } <|> pure ff, match is_theorem with -- The declaration is not a theorem, return an error. | ff := do { let err := format! "not_a_theorem: name={req.name} open_ns={req.open_ns}", pure ⟨none, none, none, some err.to_string⟩ } -- The declaration is a theorem, set the env with open namespaces to it and -- generate a new tactic state. | tt := do { ts ← state_t.lift $ io.run_tactic'' $ do { env ← tactic.get_env, decl ← env.get decl_name, let g := decl.type, tactic.set_goal_to g, lean_file ← env.decl_olean decl_name, tactic.set_env_core $ environment.for_decl_of_imported_module lean_file decl_name, add_open_namespaces decl_open_ns, tactic.read }, let sid := σ.get_next_sid, modify $ λ σ, σ.incr_next_sid, tsid ← record_ts sid ts, ts_str ← (state_t.lift ∘ io.run_tactic'') $ ts.fully_qualified >>= postprocess_tactic_state, pure $ ⟨sid, tsid, ts_str, none⟩ } end } meta def handle_clear_search (req : LeanREPLRequest) : LeanREPL LeanREPLResponse := do { -- Simply remove the table associated with the provided search id from the state. modify $ λ σ, σ.erase_search req.sid, pure $ ⟨req.sid, none, none, none⟩ } meta def handle_run_tac (req : LeanREPLRequest) : LeanREPL LeanREPLResponse := do { σ ← get, match (σ.get_ts req.sid req.tsid) with -- Received an unknown search id, return an error. | none := do { let err := format! "unknown_id: search_id={req.sid} tactic_state_id={req.tsid}", pure ⟨none, none, none, some err.to_string⟩ } -- The tactic state was retrieved from the state. | (some ts) := do { -- Set the tactic state and try to apply the tactic. result_with_string ← state_t.lift $ io.run_tactic'' $ do { tactic.write ts, get_tac_and_capture_result req.tac 5000 <|> do { let msg : format := format!"parse_itactic failed on `{req.tac}`", interaction_monad.mk_exception msg none <$> tactic.read } }, match result_with_string with -- The tactic application was successful. | interaction_monad.result.success s ts' := do { -- h ← (state_t.lift ∘ io.run_tactic'') $ tactic.write ts' *> tactic_hash, tsid ← record_ts req.sid ts', ts_str ← (state_t.lift ∘ io.run_tactic'') $ ts'.fully_qualified >>= postprocess_tactic_state, pure $ ⟨req.sid, tsid, ts_str, none⟩ } -- The tactic application failed, return an error with the failure message. | interaction_monad.result.exception fn pos old := state_t.lift $ do { let msg := (fn.get_or_else (λ _, format.of_string "n/a")) (), let err := format! "gen_tac_and_capture_res_failed: pos={pos} msg={msg}", pure ⟨none, none, none, some err.to_string ⟩ } end } end } meta def handle_request (req : LeanREPLRequest) : LeanREPL LeanREPLResponse := match req.cmd with | "run_tac" := handle_run_tac req | "init_search" := handle_init_search req | "clear_search" := handle_clear_search req | exc := state_t.lift $ io.fail' format! "[fatal] unknown_command: cmd={exc}" end meta def parse_request (msg : string) : io LeanREPLRequest := do { match json.parse msg with | (some json_msg) := io.run_tactic'' $ has_from_json.from_json json_msg | none := io.fail' format! "[fatal] parse_failed: data={msg}" end } meta def loop : LeanREPL unit := do { req ← (state_t.lift $ io.get_line >>= parse_request), res ← handle_request req, state_t.lift $ io.put_str_ln' $ format! "{(json.unparse ∘ LeanREPLResponse.to_json) res}" } meta def main : io unit := do { state_t.run loop.forever ⟨dict.empty, 0⟩ $> () } end main
2a0c03552dbcbf46ae8892dca8431f25d26dbd18
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/concrete_category/bundled_hom_auto.lean
dfbe4540c2ba6424b6dcee073b85990bafc12783
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,824
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.concrete_category.basic import Mathlib.category_theory.concrete_category.bundled import Mathlib.PostPort universes u l namespace Mathlib /-! # Category instances for algebraic structures that use bundled homs. Many algebraic structures in Lean initially used unbundled homs (e.g. a bare function between types, along with an `is_monoid_hom` typeclass), but the general trend is towards using bundled homs. This file provides a basic infrastructure to define concrete categories using bundled homs, and define forgetful functors between them. -/ namespace category_theory /-- Class for bundled homs. Note that the arguments order follows that of lemmas for `monoid_hom`. This way we can use `⟨@monoid_hom.to_fun, @monoid_hom.id ...⟩` in an instance. -/ class bundled_hom {c : Type u → Type u} (hom : {α β : Type u} → c α → c β → Type u) where to_fun : {α β : Type u} → (Iα : c α) → (Iβ : c β) → hom Iα Iβ → α → β id : {α : Type u} → (I : c α) → hom I I comp : {α β γ : Type u} → (Iα : c α) → (Iβ : c β) → (Iγ : c γ) → hom Iβ Iγ → hom Iα Iβ → hom Iα Iγ hom_ext : autoParam (∀ {α β : Type u} (Iα : c α) (Iβ : c β), function.injective (to_fun Iα Iβ)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) id_to_fun : autoParam (∀ {α : Type u} (I : c α), to_fun I I (id I) = id) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) comp_to_fun : autoParam (∀ {α β γ : Type u} (Iα : c α) (Iβ : c β) (Iγ : c γ) (f : hom Iα Iβ) (g : hom Iβ Iγ), to_fun Iα Iγ (comp Iα Iβ Iγ g f) = to_fun Iβ Iγ g ∘ to_fun Iα Iβ f) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) namespace bundled_hom /-- Every `@bundled_hom c _` defines a category with objects in `bundled c`. This instance generates the type-class problem `bundled_hom ?m` (which is why this is marked as `[nolint]`). Currently that is not a problem, as there are almost no instances of `bundled_hom`. -/ protected instance category {c : Type u → Type u} (hom : {α β : Type u} → c α → c β → Type u) [𝒞 : bundled_hom hom] : category (bundled c) := category.mk /-- A category given by `bundled_hom` is a concrete category. This instance generates the type-class problem `bundled_hom ?m` (which is why this is marked as `[nolint]`). Currently that is not a problem, as there are almost no instances of `bundled_hom`. -/ protected instance category_theory.bundled.category_theory.concrete_category {c : Type u → Type u} (hom : {α β : Type u} → c α → c β → Type u) [𝒞 : bundled_hom hom] : concrete_category (bundled c) := concrete_category.mk (functor.mk (fun (X : bundled c) => ↥X) fun (X Y : bundled c) (f : X ⟶ Y) => to_fun 𝒞 (bundled.str X) (bundled.str Y) f) /-- A version of `has_forget₂.mk'` for categories defined using `@bundled_hom`. -/ def mk_has_forget₂ {c : Type u → Type u} {hom : {α β : Type u} → c α → c β → Type u} [𝒞 : bundled_hom hom] {d : Type u → Type u} {hom_d : {α β : Type u} → d α → d β → Type u} [bundled_hom hom_d] (obj : {α : Type u} → c α → d α) (map : {X Y : bundled c} → (X ⟶ Y) → (bundled.map obj X ⟶ bundled.map obj Y)) (h_map : ∀ {X Y : bundled c} (f : X ⟶ Y), ⇑(map f) = ⇑f) : has_forget₂ (bundled c) (bundled d) := has_forget₂.mk' (bundled.map obj) sorry map sorry /-- The `hom` corresponding to first forgetting along `F`, then taking the `hom` associated to `c`. For typical usage, see the construction of `CommMon` from `Mon`. -/ def map_hom {c : Type u → Type u} (hom : {α β : Type u} → c α → c β → Type u) {d : Type u → Type u} (F : {α : Type u} → d α → c α) {α : Type u} {β : Type u} (Iα : d α) (Iβ : d β) := hom (F iα) (F iβ) /-- Construct the `bundled_hom` induced by a map between type classes. This is useful for building categories such as `CommMon` from `Mon`. -/ def map {c : Type u → Type u} (hom : {α β : Type u} → c α → c β → Type u) [𝒞 : bundled_hom hom] {d : Type u → Type u} (F : {α : Type u} → d α → c α) : bundled_hom (map_hom hom F) := mk (fun (α β : Type u) (iα : d α) (iβ : d β) (f : map_hom hom F iα iβ) => to_fun 𝒞 (F iα) (F iβ) f) (fun (α : Type u) (iα : d α) => id 𝒞 (F iα)) fun (α β γ : Type u) (iα : d α) (iβ : d β) (iγ : d γ) (f : map_hom hom F iβ iγ) (g : map_hom hom F iα iβ) => comp 𝒞 (F iα) (F iβ) (F iγ) f g /-- We use the empty `parent_projection` class to label functions like `comm_monoid.to_monoid`, which we would like to use to automatically construct `bundled_hom` instances from. Once we've set up `Mon` as the category of bundled monoids, this allows us to set up `CommMon` by defining an instance ```instance : parent_projection (comm_monoid.to_monoid) := ⟨⟩``` -/ class parent_projection {c : Type u → Type u} {d : Type u → Type u} (F : {α : Type u} → d α → c α) where protected instance bundled_hom_of_parent_projection {c : Type u → Type u} (hom : {α β : Type u} → c α → c β → Type u) [𝒞 : bundled_hom hom] {d : Type u → Type u} (F : {α : Type u} → d α → c α) [parent_projection F] : bundled_hom (map_hom hom F) := map hom F protected instance forget₂ {c : Type u → Type u} (hom : {α β : Type u} → c α → c β → Type u) [𝒞 : bundled_hom hom] {d : Type u → Type u} (F : {α : Type u} → d α → c α) [parent_projection F] : has_forget₂ (bundled d) (bundled c) := has_forget₂.mk (functor.mk (fun (X : bundled d) => bundled.mk ↥X) fun (X Y : bundled d) (f : X ⟶ Y) => f) protected instance forget₂_full {c : Type u → Type u} (hom : {α β : Type u} → c α → c β → Type u) [𝒞 : bundled_hom hom] {d : Type u → Type u} (F : {α : Type u} → d α → c α) [parent_projection F] : full (forget₂ (bundled d) (bundled c)) := full.mk fun (X Y : bundled d) (f : functor.obj (forget₂ (bundled d) (bundled c)) X ⟶ functor.obj (forget₂ (bundled d) (bundled c)) Y) => f end Mathlib
040212a99e9aecb7e26cfeffd5710494995b8a84
8e691ffe296a38e3e9dc95845e5b607422c3c973
/src/order/filter/basic.lean
b3e40840f20ce8e8eb98629ab668ad80909de5f6
[ "Apache-2.0" ]
permissive
jmvlangen/mathlib
8d847f7831f0e8ddebc99568704530af7c9e1a50
82f79a58df3047b8002bbaf90ce50da2a978e114
refs/heads/master
1,588,094,154,678
1,552,412,266,000
1,552,412,266,000
175,439,673
0
0
null
null
null
null
UTF-8
Lean
false
false
80,340
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad Theory of filters on sets. -/ import order.galois_connection order.zorn import data.set.finite data.list data.pfun import algebra.pi_instances import category.applicative open lattice set universes u v w x y local attribute [instance] classical.prop_decidable namespace lattice variables {α : Type u} {ι : Sort v} def complete_lattice.copy (c : complete_lattice α) (le : α → α → Prop) (eq_le : le = @complete_lattice.le α c) (top : α) (eq_top : top = @complete_lattice.top α c) (bot : α) (eq_bot : bot = @complete_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) : complete_lattice α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..}; subst_vars, exact @complete_lattice.le_refl α c, exact @complete_lattice.le_trans α c, exact @complete_lattice.le_antisymm α c, exact @complete_lattice.le_sup_left α c, exact @complete_lattice.le_sup_right α c, exact @complete_lattice.sup_le α c, exact @complete_lattice.inf_le_left α c, exact @complete_lattice.inf_le_right α c, exact @complete_lattice.le_inf α c, exact @complete_lattice.le_top α c, exact @complete_lattice.bot_le α c, exact @complete_lattice.le_Sup α c, exact @complete_lattice.Sup_le α c, exact @complete_lattice.Inf_le α c, exact @complete_lattice.le_Inf α c end end lattice open set lattice section order variables {α : Type u} (r : α → α → Prop) local infix `≼` : 50 := r lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact assume a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ end order theorem directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α} (h : zorn.chain (f ⁻¹'o r) c) : directed r (λx:{a:α // a ∈ c}, f (x.val)) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists]; exact ⟨b, hb, refl _⟩) (assume : a ≠ b, (h a ha b hb this).elim (λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩) (λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩)) structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by rw [filter_eq_iff, ext_iff] @[extensionality] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 lemma univ_mem_sets : univ ∈ f := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets lemma univ_mem_sets' (h : ∀ a, a ∈ s): s ∈ f := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)), λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩ lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (∀i∈is, s i ∈ f) → (⋂i∈is, s i) ∈ f := finite.induction_on hf (assume hs, by simp only [univ_mem_sets, mem_empty_eq, Inter_neg, Inter_univ, not_false_iff]) (assume i is _ hf hi hs, have h₁ : s i ∈ f, from hs i (by simp), have h₂ : (⋂x∈is, s x) ∈ f, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true], by simp [inter_mem_sets h₁ h₂]) lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e), eapplyc `filter.univ_mem_sets', match e' with | some e := interactive.exact e | none := skip end end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := assume x y hx hy, subset.trans hx hy, inter_sets := assume x y, subset_inter } instance : inhabited (filter α) := ⟨principal ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ principal t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ principal s := subset.refl _ end principal section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [univ_mem_sets, mem_set_of_eq]; exact univ_mem_sets, sets_of_superset := assume x y hx xy, mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy, inter_sets := assume x y hx hy, mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ } @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ filter.sets t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, g.sets ⊆ f.sets, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ {} : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := {s | generate_sets g s}, univ_sets := generate_sets.univ, sets_of_superset := assume x y, generate_sets.superset, inter_sets := assume s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (assume h u hu, h $ generate_sets.basic $ hu) (assume h u hu, hu.rec_on h univ_mem_sets (assume x y _ hxy hx, mem_sets_of_superset hx hxy) (assume x y _ _ hx hy, inter_mem_sets hx hy)) protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s), sets_of_superset := assume x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := assume x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ assume u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.refl _ /- Galois insertion from sets of sets into a filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := assume s f, sets_iff_generate, le_l_u := assume f u, generate_sets.basic, choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), a ∩ b ⊆ s }, univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩, sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩, ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd, calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩ @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃t₁∈f.sets, ∃t₂∈g.sets, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩ lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht) instance : has_top (filter α) := ⟨{ sets := {s | ∀x, x ∈ s}, univ_sets := assume x, mem_univ x, sets_of_superset := assume x y hx hxy a, hxy (hx a), inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀x, x ∈ s) := iff.refl _ @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_sets_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.lattice.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.lattice.has_top).1 (top_unique $ assume s hs, by have := univ_mem_sets ; finish) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.lattice.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right)) (assume s ⟨a, ha, b, hb, hs⟩, show s ∈ complete_lattice.inf f g, from mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ principal) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀i, x ∈ f i) := by simp only [supr_sets_eq, iff_self, mem_Inter] @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f := show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal_sets] lemma monotone_principal : monotone (principal : set α → filter α) := by simp only [monotone, principal_mono]; exact assume a b h, h @[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl /- lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f) : ∃x, x ∈ s := have ∅ ∉ f.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h, have s ≠ ∅, from assume h, this (h ▸ hs), exists_mem_of_ne_empty this lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩) lemma forall_sets_neq_empty_iff_neq_bot {f : filter α} : (∀ (s : set α), s ∈ f → s ≠ ∅) ↔ f ≠ ⊥ := by simp only [(@empty_in_sets_eq_bot α f).symm, ne.def]; exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩ lemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f := have ∅ ∈ f ⊓ principal (- s), from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩ lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], assume x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩ end } in subset.antisymm (show u ≤ infi f, from le_infi $ assume i, le_supr (λi, (f i).sets) i) (Union_subset $ assume i, infi_le f i) lemma mem_infi {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) (s): s ∈ infi f ↔ s ∈ ⋃ i, (f i).sets := show s ∈ (infi f).sets ↔ s ∈ ⋃ i, (f i).sets, by rw infi_sets_eq h ne lemma infi_sets_eq' {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : ∃i, i ∈ s) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := let ⟨i, hi⟩ := ne in calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by rw [infi_subtype]; refl ... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by rw [supr_subtype]; refl lemma infi_sets_eq_finite (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h), apply_instance end lemma mem_infi_finite {f : ι → filter α} (s): s ∈ infi f ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets := show s ∈ (infi f).sets ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets, by rw infi_sets_eq_finite @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, mem_sup_sets, iff_self, mem_set_of_eq] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, iff_self, mem_Inter, mem_set_of_eq] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin assume x y z s, simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp], intros hs t₁ ht₁ t₂ ht₂ hts, exact ⟨s ∪ t₁, x.sets_of_superset hs $ subset_union_left _ _, y.sets_of_superset ht₁ $ subset_union_right _ _, s ∪ t₂, x.sets_of_superset hs $ subset_union_left _ _, z.sets_of_superset ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.lattice.complete_lattice } /- the complementary version with ⨆i, f ⊓ g i does not hold! -/ lemma infi_sup_eq {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ assume i, sup_le_sup (le_refl f) $ infi_le _ _), rintros t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_right_of_le le_top }, { rintros ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅a∈s, p a) ≤ t), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top_sets, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { intros t₁ ht₁ t₂ p hp ht₂ ht, existsi function.update p a t₁, have : ∀a'∈s, function.update p a t₁ a' = p a', from assume a' ha', have a' ≠ a, from assume h, has $ h ▸ ha', function.update_noteq this, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht }, assume p hpa hp ht, exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) := filter_eq $ set.ext $ by simp only [union_subset_iff, union_subset_iff, mem_sup_sets, forall_const, iff_self, mem_principal_sets] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, mem_principal_sets, mem_Inter]; exact (@supr_le_iff (set α) _ _ _ _).symm lemma principal_univ : principal (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true] lemma principal_empty : principal (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ @[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ := ⟨assume h, principal_eq_iff_eq.mp $ by simp only [principal_empty, h, eq_self_iff_true], assume h, by simp only [h, principal_empty, eq_self_iff_true]⟩ lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : -s ∈ f) : f ⊓ principal s = ⊥ := empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩ theorem mem_inf_principal (f : filter α) (s t : set α) : s ∈ f ⊓ principal t ↔ { x | x ∈ t → x ∈ s } ∈ f := begin simp only [mem_inf_sets, mem_principal_sets, exists_prop], split, { rintros ⟨u, ul, v, tsubv, uvinter⟩, apply filter.mem_sets_of_superset ul, intros x xu xt, exact uvinter ⟨xu, tsubv xt⟩ }, intro h, refine ⟨_, h, t, set.subset.refl t, _⟩, rintros x ⟨hx, xt⟩, exact hx xt end end lattice section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem_sets, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st, inter_sets := assume s t hs ht, inter_mem_sets hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (principal s) = principal (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma range_mem_map : range m ∈ map m f := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, m '' s ⊆ t) := iff.intro (assume ht, ⟨set.preimage m t, ht, image_preimage_subset _ _⟩) (assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht) @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } end comap /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite (- s)}, univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq], sets_of_superset := assume s t (hs : finite (-s)) (st: s ⊆ t), finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st, inter_sets := assume s t (hs : finite (-s)) (ht : finite (-t)), by simp only [compl_inter, finite_union, ht, hs, mem_set_of_eq] } /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃u∈ f, ∃t∈ g, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩, assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁, assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ instance : has_pure filter := ⟨λ(α : Type u) x, principal {x}⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } section -- this section needs to be before applicative, otherwise the wrong instance will be chosen protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected def is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β a f, by simp only [bind, Sup_image, image_singleton, join_principal_eq_Sup, lattice.Sup_singleton, map_principal, eq_self_iff_true], bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter_eq $ by simp only [bind, join, map, preimage, principal, set.subset_univ, eq_self_iff_true, function.comp_app, mem_set_of_eq, singleton_subset_iff] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } @[simp] lemma pure_def (x : α) : pure x = principal {x} := rfl @[simp] lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α) := by simp only [imp_self, pure_def, mem_principal_sets, singleton_subset_iff]; exact id @[simp] lemma mem_pure_iff {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := by rw [pure_def, mem_principal_sets, set.singleton_subset_iff] @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /- map and comap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap_sets : s ∈ comap m g ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.refl _⟩ lemma comap_id : comap id f = f := le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst) lemma comap_comap_comp {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩) @[simp] theorem comap_principal {t : set β} : comap m (principal t) = principal (m ⁻¹' t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b, assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := assume f g, map_le_iff_le_comap lemma map_mono (h : f₁ ≤ f₂) : map m f₁ ≤ map m f₂ := (gc_map_comap m).monotone_l h lemma monotone_map : monotone (map m) | a b := map_mono lemma comap_mono (h : g₁ ≤ g₂) : comap m g₁ ≤ comap m g₂ := (gc_map_comap m).monotone_u h lemma monotone_comap : monotone (comap m) | a b := comap_mono @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by rw [comap_top]; exact le_top lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ assume s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆i, comap m (f i)) := le_antisymm (assume s hs, have ∀i, ∃t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], assume i, exact (ht i).2 end⟩) (supr_le $ assume i, monotone_comap $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) (sup_le (comap_mono le_sup_left) (comap_mono le_sup_right)) lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := le_antisymm map_comap_le (assume t' ⟨t, ht, sub⟩, by filter_upwards [ht, hf]; rintros x hxt ⟨y, rfl⟩; exact sub hxt) lemma comap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : comap m (map m f) = f := have ∀s, preimage m (image m s) = s, from assume s, preimage_image_eq s h, le_antisymm (assume s hs, ⟨ image m s, f.sets_of_superset hs $ by simp only [this, subset.refl], by simp only [this, subset.refl]⟩) le_comap_map lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)] assume a has ⟨b, ⟨hbs, hb⟩, h⟩, have b = a, from hm _ hbs _ has h, this ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) map_mono lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this theorem le_map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : l ≤ map f (comap f l) := assume s ⟨t, tl, ht⟩, have t ∩ u ⊆ s, from assume x ⟨xt, xu⟩, exists.elim (hf x xu) $ λ a faeq, by { rw ←faeq, apply ht, change f a ∈ t, rw faeq, exact xt }, mem_sets_of_superset (inter_mem_sets tl ul) this theorem map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective' ul hf) theorem le_map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : l ≤ map f (comap f l) := le_map_comap_of_surjective' univ_mem_sets (λ y _, hf y) theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective hf l) lemma comap_neq_bot {f : filter β} {m : α → β} (hm : ∀t∈ f, ∃a, m a ∈ t) : comap m f ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, t_s⟩, let ⟨a, (ha : a ∈ preimage m t)⟩ := hm t ht in neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s lemma comap_neq_bot_of_surj {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : comap m f ≠ ⊥ := comap_neq_bot $ assume t ht, let ⟨b, (hx : b ∈ t)⟩ := inhabited_of_mem_sets hf ht, ⟨a, (ha : m a = b)⟩ := hm b in ⟨a, ha.symm ▸ hx⟩ @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ := assume h, hf $ by rwa [map_eq_bot_iff] at h lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀(comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter, iff_self, mem_Inter, mem_preimage_eq, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage_eq] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map lemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f) : map m₁ f = map m₂ f := have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f), map m₁ f ≤ map m₂ f, begin intros m₁ m₂ h s hs, show {x | m₁ x ∈ s} ∈ f, filter_upwards [h, hs], simp only [subset_def, mem_preimage_eq, mem_set_of_eq, forall_true_iff] {contextual := tt} end, le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ mem_sets_of_superset h $ assume x, eq.symm) -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) (hι : nonempty ι) : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ infi f), have ∃i, preimage m s ∈ f i, by simp only [infi_sets_eq hf hι, mem_Union] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ principal s, from infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption, by simp only [filter.le_principal_iff] at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := let ⟨i, hi⟩ := ne in calc map m (⨅i (h : p i), f i) = map m (⨅i:subtype p, f i.val) : by simp only [infi_subtype, eq_self_iff_true] ... = (⨅i:subtype p, map m (f i.val)) : map_infi_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨅i (h : p i), map m (f i)) : by simp only [infi_subtype, eq_self_iff_true] lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm (le_inf (map_mono inf_le_left) (map_mono inf_le_right)) (assume s hs, _), simp only [map, mem_inf_sets, exists_prop, mem_map, mem_preimage_eq, mem_inf_sets] at hs ⊢, rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩, refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩, { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { rw [image_inter_on], { refine image_subset_iff.2 _, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _, h x y) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀s∈ f, m '' s ∈ g) : g ≤ f.map m := assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _ section applicative @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := by simp only [iff_self, pure_def, mem_principal_sets, singleton_subset_iff] lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) := by simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff] @[simp] lemma pure_neq_bot {α : Type u} {a : α} : pure a ≠ (⊥ : filter α) := by simp only [pure, has_pure.pure, ne.def, not_false_iff, singleton_ne_empty, principal_eq_bot_iff] lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.refl _ lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀x∈u, ∀y∈t, m x y ∈ s) := iff.intro (assume ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, assume a, hts _⟩) (assume ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, assume f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g): s.seq t ∈ f.seq g := ⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀t ∈ f, ∀u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $ assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq_sets _ hs, simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff] }, { rw mem_pure_sets at hs, refine sets_of_superset (map g f) (image_mem_map ht) _, rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := le_antisymm (le_principal_iff.2 $ sets_of_superset (map f (pure a)) (image_mem_map singleton_mem_pure_sets) $ by simp only [image_singleton, mem_singleton, singleton_subset_iff]) (le_map $ assume s, begin simp only [mem_image, pure_def, mem_principal_sets, singleton_subset_iff], exact assume has, ⟨a, has, rfl⟩ end) @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq_sets hs (by simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff]) }, { rw mem_pure_sets at ht, refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)), rw ← set.seq_seq, exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) }, { rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht), rw set.seq_seq, exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw ← set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu }, { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := assume α f, map_id, comp_map := assume α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := assume α β, pure_seq_eq_map, map_pure := assume α β, map_pure, seq_pure := assume α β, seq_pure, seq_assoc := assume α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨assume α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /- bind equations -/ section bind @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : by simp only [bind, mem_map, iff_self, mem_join_sets, mem_set_of_eq] ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.refl _ lemma bind_mono {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f) : bind f g ≤ bind f h := assume x h₂, show (_ ∈ f), by filter_upwards [h₁, h₂] assume s gh' h', gh' h' lemma bind_sup {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma bind_mono2 {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) : bind f h ≤ bind g h := assume s h', h₁ h' lemma principal_bind {s : set α} {f : α → filter β} : (bind (principal s) f) = (⨆x ∈ s, f x) := show join (map f (principal s)) = (⨆x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind lemma infi_neq_bot_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≥) f) (hb : ∀i, f i ≠ ⊥) : (infi f) ≠ ⊥ := let ⟨x⟩ := hn in assume h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)), classical.by_cases (assume : nonempty ι, have ∃i, ∅ ∈ f i, by rw [mem_infi hd this] at he; simp only [mem_Union] at he; assumption, let ⟨i, hi⟩ := this in hb i $ bot_unique $ assume s _, (f i).sets_of_superset hi $ empty_subset _) (assume : ¬ nonempty ι, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ this ⟨i⟩) end, this $ mem_univ x) lemma infi_neq_bot_iff_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≥) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) := ⟨assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _, infi_neq_bot_of_directed hn hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [mem_infi_finite] at hs, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { assume s hs, rwa [mem_top_sets.1 hs] }, { rintros ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_sets] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, exact upw hs (ins hs₁ (ih hs₂)) } end /- tendsto -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : {x | f₁ x = f₂ x} ∈ l₁) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := by rwa [tendsto, ←map_cong hl] theorem tendsto.congr'r {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := iff_of_eq (by congr'; exact funext h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto.congr'r h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hf : tendsto f x y) (hg : tendsto g y z) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto_le_left {f : α → β} {x y : filter α} {z : filter β} (h : y ≤ x) : tendsto f x z → tendsto f y z := le_trans (map_mono h) lemma tendsto_le_right {f : α → β} {x : filter α} {y z : filter β} (h₁ : y ≤ z) (h₂ : tendsto f x y) : tendsto f x z := le_trans h₂ h₁ lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by rw [tendsto, map_map]; refl lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, h.comp tendsto_comap, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by rw [tendsto, ← map_compose]; simp only [(∘), map_comap h, tendsto] lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ), rw [comap_comap_comp, eq, comap_id], exact le_refl _ end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_refl _ end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, lattice.le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp only [tendsto, iff_self, lattice.le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) : tendsto f (x i) y → tendsto f (⨅i, x i) y := tendsto_le_left (infi_le _ _) lemma tendsto_principal {f : α → β} {a : filter α} {s : set β} : tendsto f a (principal s) ↔ {a | f a ∈ s} ∈ a := by simp only [tendsto, le_principal_iff, mem_map, iff_self] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (principal s) (principal t) ↔ ∀a∈s, f a ∈ t := by simp only [tendsto, image_subset_iff, le_principal_iff, map_principal, mem_principal_sets]; refl lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := show filter.map f (pure a) ≤ pure (f a), by rw [filter.map_pure]; exact le_refl _ lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λa, b) a (pure b) := by simp [tendsto]; exact univ_mem_sets lemma tendsto_if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [decidable_pred p] (h₀ : tendsto f (l₁ ⊓ principal p) l₂) (h₁ : tendsto g (l₁ ⊓ principal { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin revert h₀ h₁, simp only [tendsto_def, mem_inf_principal], intros h₀ h₁ s hs, apply mem_sets_of_superset (inter_mem_sets (h₀ s hs) (h₁ s hs)), rintros x ⟨hp₀, hp₁⟩, dsimp, by_cases h : p x, { rw if_pos h, exact hp₀ h }, rw if_neg h, exact hp₁ h end section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x <- seq, y <- top, return (x, y)} hence: s ∈ F <-> ∃n, [n..∞] × univ ⊆ s G := do {y <- top, x <- seq, return (x, y)} hence: s ∈ G <-> ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ filter.prod f g := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ filter.prod f g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩, ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩, exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩, ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩ end lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (filter.prod f g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod f g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (filter.prod g h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma prod_infi_left {f : ι → filter α} {g : filter β} (i : ι) : filter.prod (⨅i, f i) g = (⨅i, filter.prod (f i) g) := by rw [filter.prod, comap_infi, infi_inf i]; simp only [filter.prod, eq_self_iff_true] lemma prod_infi_right {f : filter α} {g : ι → filter β} (i : ι) : filter.prod f (⨅i, g i) = (⨅i, filter.prod f (g i)) := by rw [filter.prod, comap_infi, inf_infi i]; simp only [filter.prod, eq_self_iff_true] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : filter.prod (comap m₁ f₁) (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := by simp only [filter.prod, comap_comap_comp, eq_self_iff_true, comap_inf] lemma prod_comm' : filter.prod f g = comap (prod.swap) (filter.prod g f) := by simp only [filter.prod, comap_comap_comp, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) := by rw [prod_comm', ← map_swap_eq_comap_swap]; refl lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := le_antisymm (assume s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto_fst.comp (le_refl _)).prod_mk (tendsto_snd.comp (le_refl _))) lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f.prod g) = (f.map (λa b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], assume s, split, exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f.prod g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, lattice.inf_left_comm] @[simp] lemma prod_bot {f : filter α} : filter.prod f (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : filter.prod (⊥ : filter α) g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : filter.prod (principal s) (principal t) = principal (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma prod_pure_pure {a : α} {b : β} : filter.prod (pure a) (pure b) = pure (a, b) := by simp lemma prod_eq_bot {f : filter α} {g : filter β} : filter.prod f g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { assume h, rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) }, { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } }, { rintros (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_neq_bot {f : filter α} {g : filter β} : filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) := by rw [(≠), prod_eq_bot, not_or_distrib] lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (filter.prod x y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod /- at_top and at_bot -/ /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b} /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a} lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_sets a $ subset.refl _ @[simp] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : (at_top : filter α) ≠ ⊥ := infi_neq_bot_of_directed (by apply_instance) (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of, mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩) (assume a, by simp only [principal_eq_bot_iff, ne.def, principal_eq_bot_iff]; exact ne_empty_of_mem (le_refl a)) @[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := let ⟨a⟩ := ‹nonempty α› in iff.intro (assume h, infi_sets_induct h ⟨a, by simp only [forall_const, mem_univ, forall_true_iff]⟩ (assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b, assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩) (assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩)) (assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x) lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, principal $ f '' {a' | a ≤ a'}) := calc map f (⨅a, principal {a' | a ≤ a'}) = (⨅a, map f $ principal {a' | a ≤ a'}) : map_infi_eq (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of, mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩) (by apply_instance) ... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by simp only [map_principal, eq_self_iff_true] lemma tendsto_at_top [preorder β] (m : α → β) (f : filter α) : tendsto m f at_top ↔ (∀b, {a | b ≤ m a} ∈ f) := by simp only [at_top, tendsto_infi, tendsto_principal]; refl lemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (principal s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl /-- A function `f` grows to infinity independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_embedding {α β γ : Type*} [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin rw [tendsto_at_top, tendsto_at_top], split, { assume hc b, filter_upwards [hc (e b)] assume a, (hm b (f a)).1 }, { assume hb c, rcases hu c with ⟨b, hc⟩, filter_upwards [hb b] assume a ha, le_trans hc ((hm b (f a)).2 ha) } end lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) : tendsto (λs:finset γ, s.image j) at_top at_top := tendsto_infi.2 $ assume s, tendsto_infi' (s.image i) $ tendsto_principal_principal.2 $ assume t (ht : s.image i ⊆ t), calc s = (s.image i).image j : by simp only [finset.image_image, (∘), h]; exact finset.image_id.symm ... ⊆ t.image j : finset.image_subset_image ht lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂] [semilattice_sup β₁] [semilattice_sup β₂] : filter.prod (@at_top β₁ _) (@at_top β₂ _) = @at_top (β₁ × β₂) _ := by simp [at_top, prod_infi_left (default β₁), prod_infi_right (default β₂), infi_prod]; exact infi_comm lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂] [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : filter.prod (map u₁ at_top) (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β)(hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin rw [@map_at_top_eq α _ ⟨g b'⟩], refine le_antisymm (le_infi $ assume b, infi_le_of_le (g (b ⊔ b')) $ principal_mono.2 $ image_subset_iff.2 _) (le_infi $ assume a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 _), { assume a ha, exact (le_trans le_sup_left $ le_trans (hgi _ le_sup_right) $ hf ha) }, { assume b hb, have hb' : b' ≤ b := le_trans le_sup_right hb, exact ⟨g b, (gc _ _ hb').1 (le_trans le_sup_left hb), le_antisymm ((gc _ _ hb').2 (le_refl _)) (hgi _ hb')⟩ } end lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendso_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendso_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : k > 0) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /- ultrafilter -/ section ultrafilter open zorn variables {f g : filter α} /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ def is_ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g lemma ultrafilter_unique (hg : is_ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g := le_antisymm h (hg.right _ hf h) lemma le_of_ultrafilter {g : filter α} (hf : is_ultrafilter f) (h : f ⊓ g ≠ ⊥) : f ≤ g := le_of_inf_eq $ ultrafilter_unique hf h inf_le_left /-- Equivalent characterization of ultrafilters: A filter f is an ultrafilter if and only if for each set s, -s belongs to f if and only if s does not belong to f. -/ lemma ultrafilter_iff_compl_mem_iff_not_mem : is_ultrafilter f ↔ (∀ s, -s ∈ f ↔ s ∉ f) := ⟨assume hf s, ⟨assume hns hs, hf.1 $ empty_in_sets_eq_bot.mp $ by convert f.inter_sets hs hns; rw [inter_compl_self], assume hs, have f ≤ principal (-s), from le_of_ultrafilter hf $ assume h, hs $ mem_sets_of_neq_bot $ by simp only [h, eq_self_iff_true, lattice.neg_neg], by simp only [le_principal_iff] at this; assumption⟩, assume hf, ⟨mt empty_in_sets_eq_bot.mpr ((hf ∅).mp (by convert f.univ_sets; rw [compl_empty])), assume g hg g_le s hs, classical.by_contradiction $ mt (hf s).mpr $ assume : - s ∈ f, have s ∩ -s ∈ g, from inter_mem_sets hs (g_le this), by simp only [empty_in_sets_eq_bot, hg, inter_compl_self] at this; contradiction⟩⟩ lemma mem_or_compl_mem_of_ultrafilter (hf : is_ultrafilter f) (s : set α) : s ∈ f ∨ - s ∈ f := classical.or_iff_not_imp_left.2 (ultrafilter_iff_compl_mem_iff_not_mem.mp hf s).mpr lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : is_ultrafilter f) (h : s ∪ t ∈ f) : s ∈ f ∨ t ∈ f := (mem_or_compl_mem_of_ultrafilter hf s).imp_right (assume : -s ∈ f, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx) lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : is_ultrafilter f) (hs : finite s) : ⋃₀ s ∈ f → ∃t∈s, t ∈ f := finite.induction_on hs (by simp only [empty_in_sets_eq_bot, hf.left, mem_empty_eq, sUnion_empty, forall_prop_of_false, exists_false, not_false_iff, exists_prop_of_false]) $ λ t s' ht' hs' ih, by simp only [exists_prop, mem_insert_iff, set.sUnion_insert]; exact assume h, (mem_or_mem_of_ultrafilter hf h).elim (assume : t ∈ f, ⟨t, or.inl rfl, this⟩) (assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, or.inr hts', ht⟩) lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α} (hf : is_ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f) : ∃i∈is, s i ∈ f := have his : finite (image s is), from finite_image s his, have h : (⋃₀ image s is) ∈ f, from by simp only [sUnion_image, set.sUnion_image]; assumption, let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in ⟨i, hi, h_eq.symm ▸ ht⟩ lemma ultrafilter_map {f : filter α} {m : α → β} (h : is_ultrafilter f) : is_ultrafilter (map m f) := by rw ultrafilter_iff_compl_mem_iff_not_mem at ⊢ h; exact assume s, h (m ⁻¹' s) lemma ultrafilter_pure {a : α} : is_ultrafilter (pure a) := begin rw ultrafilter_iff_compl_mem_iff_not_mem, intro s, rw [mem_pure_sets, mem_pure_sets], exact iff.rfl end lemma ultrafilter_bind {f : filter α} (hf : is_ultrafilter f) {m : α → filter β} (hm : ∀ a, is_ultrafilter (m a)) : is_ultrafilter (f.bind m) := begin simp only [ultrafilter_iff_compl_mem_iff_not_mem] at ⊢ hf hm, intro s, dsimp [bind, join, map], simp only [hm], apply hf end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ is_ultrafilter u := let τ := {f' // f' ≠ ⊥ ∧ f' ≤ f}, r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, ⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets, top : τ := ⟨f, h, le_refl f⟩, sup : Π(c:set τ), chain r c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val, infi_neq_bot_of_directed ⟨a⟩ (directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩ in have ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _), have (∃ (u : τ), ∀ (a : τ), r u a → r a u), from zorn (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), let ⟨uτ, hmin⟩ := this in ⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩ /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def ultrafilter_of (f : filter α) : filter α := if h : f = ⊥ then ⊥ else classical.epsilon (λu, u ≤ f ∧ is_ultrafilter u) lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ is_ultrafilter (ultrafilter_of f) := begin have h' := classical.epsilon_spec (exists_ultrafilter h), simp only [ultrafilter_of, dif_neg, h, dif_neg, not_false_iff], simp only at h', assumption end lemma ultrafilter_of_le : ultrafilter_of f ≤ f := if h : f = ⊥ then by simp only [ultrafilter_of, dif_pos, h, dif_pos, eq_self_iff_true, le_bot_iff]; exact le_refl _ else (ultrafilter_of_spec h).left lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : is_ultrafilter (ultrafilter_of f) := (ultrafilter_of_spec h).right lemma ultrafilter_of_ultrafilter (h : is_ultrafilter f) : ultrafilter_of f = f := ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le /-- A filter equals the intersection of all the ultrafilters which contain it. -/ lemma sup_of_ultrafilters (f : filter α) : f = ⨆ (g) (u : is_ultrafilter g) (H : g ≤ f), g := begin refine le_antisymm _ (supr_le $ λ g, supr_le $ λ u, supr_le $ λ H, H), intros s hs, -- If s ∉ f.sets, we'll apply the ultrafilter lemma to the restriction of f to -s. by_contradiction hs', let j : (-s) → α := subtype.val, have j_inv_s : j ⁻¹' s = ∅, by erw [←preimage_inter_range, subtype.val_range, inter_compl_self, preimage_empty], let f' := comap j f, have : f' ≠ ⊥, { apply mt empty_in_sets_eq_bot.mpr, rintro ⟨t, htf, ht⟩, suffices : t ⊆ s, from absurd (f.sets_of_superset htf this) hs', rw [subset_empty_iff] at ht, have : j '' (j ⁻¹' t) = ∅, by rw [ht, image_empty], erw [image_preimage_eq_inter_range, subtype.val_range, ←subset_compl_iff_disjoint, set.compl_compl] at this, exact this }, rcases exists_ultrafilter this with ⟨g', g'f', u'⟩, simp only [supr_sets_eq, mem_Inter] at hs, have := hs (g'.map subtype.val) (ultrafilter_map u') (map_le_iff_le_comap.mpr g'f'), rw [←le_principal_iff, map_le_iff_le_comap, comap_principal, j_inv_s, principal_empty, le_bot_iff] at this, exact absurd this u'.1 end /-- The `tendsto` relation can be checked on ultrafilters. -/ lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) : tendsto f l₁ l₂ ↔ ∀ g, is_ultrafilter g → g ≤ l₁ → g.map f ≤ l₂ := ⟨assume h g u gx, le_trans (map_mono gx) h, assume h, by rw [sup_of_ultrafilters l₁]; simpa only [tendsto, map_supr, supr_le_iff]⟩ /- The ultrafilter monad. The monad structure on ultrafilters is the restriction of the one on filters. -/ def ultrafilter (α : Type u) : Type u := {f : filter α // is_ultrafilter f} def ultrafilter.map (m : α → β) (u : ultrafilter α) : ultrafilter β := ⟨u.val.map m, ultrafilter_map u.property⟩ def ultrafilter.pure (x : α) : ultrafilter α := ⟨pure x, ultrafilter_pure⟩ def ultrafilter.bind (u : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β := ⟨u.val.bind (λ a, (m a).val), ultrafilter_bind u.property (λ a, (m a).property)⟩ instance ultrafilter.has_pure : has_pure ultrafilter := ⟨@ultrafilter.pure⟩ instance ultrafilter.has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩ instance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map } instance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map } section local attribute [instance] filter.monad filter.is_lawful_monad instance ultrafilter.is_lawful_monad : is_lawful_monad ultrafilter := { id_map := assume α f, subtype.eq (id_map f.val), pure_bind := assume α β a f, subtype.eq (pure_bind a (subtype.val ∘ f)), bind_assoc := assume α β γ f m₁ m₂, subtype.eq (filter_eq rfl), bind_pure_comp_eq_map := assume α β f x, subtype.eq (bind_pure_comp_eq_map _ f x.val) } end lemma ultrafilter.eq_iff_val_le_val {u v : ultrafilter α} : u = v ↔ u.val ≤ v.val := ⟨assume h, by rw h; exact le_refl _, assume h, by rw subtype.ext; apply ultrafilter_unique v.property u.property.1 h⟩ lemma exists_ultrafilter_iff (f : filter α) : (∃ (u : ultrafilter α), u.val ≤ f) ↔ f ≠ ⊥ := ⟨assume ⟨u, uf⟩, lattice.neq_bot_of_le_neq_bot u.property.1 uf, assume h, let ⟨u, uf, hu⟩ := exists_ultrafilter h in ⟨⟨u, hu⟩, uf⟩⟩ end ultrafilter end filter namespace filter variables {α β γ : Type u} {f : β → filter α} {s : γ → set α} open list lemma mem_traverse_sets : ∀(fs : list β) (us : list γ), forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _ | (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs) lemma mem_traverse_sets_iff (fs : list β) (t : set (list α)) : t ∈ traverse f fs ↔ (∃us:list (set α), forall₂ (λb (s : set α), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, pure_def, imp_self, forall₂_nil_left_iff, pure_def, exists_eq_left, mem_principal_sets, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { assume ht, rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } }, { rintros ⟨us, hus, hs⟩, exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs } end lemma sequence_mono : ∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_refl _ | (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) end filter
69e9793a21eefa9270719c9b05d1df92a098f987
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/dynamics/ergodic/conservative.lean
872bd5588886463f707ea963fe74e1c857e0d6f9
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,015
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import dynamics.ergodic.measure_preserving import combinatorics.pigeonhole /-! # Conservative systems In this file we define `f : α → α` to be a *conservative* system w.r.t a measure `μ` if `f` is non-singular (`measure_theory.quasi_measure_preserving`) and for every measurable set `s` of positive measure at least one point `x ∈ s` returns back to `s` after some number of iterations of `f`. There are several properties that look like they are stronger than this one but actually follow from it: * `measure_theory.conservative.frequently_measure_inter_ne_zero`, `measure_theory.conservative.exists_gt_measure_inter_ne_zero`: if `μ s ≠ 0`, then for infinitely many `n`, the measure of `s ∩ (f^[n]) ⁻¹' s` is positive. * `measure_theory.conservative.measure_mem_forall_ge_image_not_mem_eq_zero`, `measure_theory.conservative.ae_mem_imp_frequently_image_mem`: a.e. every point of `s` visits `s` infinitely many times (Poincaré recurrence theorem). We also prove the topological Poincaré recurrence theorem `measure_theory.conservative.ae_frequently_mem_of_mem_nhds`. Let `f : α → α` be a conservative dynamical system on a topological space with second countable topology and measurable open sets. Then almost every point `x : α` is recurrent: it visits every neighborhood `s ∈ 𝓝 x` infinitely many times. ## Tags conservative dynamical system, Poincare recurrence theorem -/ noncomputable theory open classical set filter measure_theory finset function topological_space open_locale classical topological_space variables {ι : Type*} {α : Type*} [measurable_space α] {f : α → α} {s : set α} {μ : measure α} namespace measure_theory open measure /-- We say that a non-singular (`measure_theory.quasi_measure_preserving`) self-map is *conservative* if for any measurable set `s` of positive measure there exists `x ∈ s` such that `x` returns back to `s` under some iteration of `f`. -/ structure conservative (f : α → α) (μ : measure α . volume_tac) extends quasi_measure_preserving f μ μ : Prop := (exists_mem_image_mem : ∀ ⦃s⦄, measurable_set s → μ s ≠ 0 → ∃ (x ∈ s) (m ≠ 0), f^[m] x ∈ s) /-- A self-map preserving a finite measure is conservative. -/ protected lemma measure_preserving.conservative [is_finite_measure μ] (h : measure_preserving f μ μ) : conservative f μ := ⟨h.quasi_measure_preserving, λ s hsm h0, h.exists_mem_image_mem hsm h0⟩ namespace conservative /-- The identity map is conservative w.r.t. any measure. -/ protected lemma id (μ : measure α) : conservative id μ := { to_quasi_measure_preserving := quasi_measure_preserving.id μ, exists_mem_image_mem := λ s hs h0, let ⟨x, hx⟩ := nonempty_of_measure_ne_zero h0 in ⟨x, hx, 1, one_ne_zero, hx⟩ } /-- If `f` is a conservative map and `s` is a measurable set of nonzero measure, then for infinitely many values of `m` a positive measure of points `x ∈ s` returns back to `s` after `m` iterations of `f`. -/ lemma frequently_measure_inter_ne_zero (hf : conservative f μ) (hs : measurable_set s) (h0 : μ s ≠ 0) : ∃ᶠ m in at_top, μ (s ∩ (f^[m]) ⁻¹' s) ≠ 0 := begin by_contra H, simp only [not_frequently, eventually_at_top, ne.def, not_not] at H, rcases H with ⟨N, hN⟩, induction N with N ihN, { apply h0, simpa using hN 0 le_rfl }, rw [imp_false] at ihN, push_neg at ihN, rcases ihN with ⟨n, hn, hμn⟩, set T := s ∩ ⋃ n ≥ N + 1, (f^[n]) ⁻¹' s, have hT : measurable_set T, from hs.inter (measurable_set.bUnion (countable_encodable _) (λ _ _, hf.measurable.iterate _ hs)), have hμT : μ T = 0, { convert (measure_bUnion_null_iff $ countable_encodable _).2 hN, rw ← set.inter_bUnion, refl }, have : μ ((s ∩ (f^[n]) ⁻¹' s) \ T) ≠ 0, by rwa [measure_diff_null hμT], rcases hf.exists_mem_image_mem ((hs.inter (hf.measurable.iterate n hs)).diff hT) this with ⟨x, ⟨⟨hxs, hxn⟩, hxT⟩, m, hm0, ⟨hxms, hxm⟩, hxx⟩, refine hxT ⟨hxs, mem_bUnion_iff.2 ⟨n + m, _, _⟩⟩, { exact add_le_add hn (nat.one_le_of_lt $ pos_iff_ne_zero.2 hm0) }, { rwa [set.mem_preimage, ← iterate_add_apply] at hxm } end /-- If `f` is a conservative map and `s` is a measurable set of nonzero measure, then for an arbitrarily large `m` a positive measure of points `x ∈ s` returns back to `s` after `m` iterations of `f`. -/ lemma exists_gt_measure_inter_ne_zero (hf : conservative f μ) (hs : measurable_set s) (h0 : μ s ≠ 0) (N : ℕ) : ∃ m > N, μ (s ∩ (f^[m]) ⁻¹' s) ≠ 0 := let ⟨m, hm, hmN⟩ := ((hf.frequently_measure_inter_ne_zero hs h0).and_eventually (eventually_gt_at_top N)).exists in ⟨m, hmN, hm⟩ /-- Poincaré recurrence theorem: given a conservative map `f` and a measurable set `s`, the set of points `x ∈ s` such that `x` does not return to `s` after `≥ n` iterations has measure zero. -/ lemma measure_mem_forall_ge_image_not_mem_eq_zero (hf : conservative f μ) (hs : measurable_set s) (n : ℕ) : μ {x ∈ s | ∀ m ≥ n, f^[m] x ∉ s} = 0 := begin by_contradiction H, have : measurable_set (s ∩ {x | ∀ m ≥ n, f^[m] x ∉ s}), { simp only [set_of_forall, ← compl_set_of], exact hs.inter (measurable_set.bInter (countable_encodable _) (λ m _, hf.measurable.iterate m hs.compl)) }, rcases (hf.exists_gt_measure_inter_ne_zero this H) n with ⟨m, hmn, hm⟩, rcases nonempty_of_measure_ne_zero hm with ⟨x, ⟨hxs, hxn⟩, hxm, -⟩, exact hxn m hmn.lt.le hxm end /-- Poincaré recurrence theorem: given a conservative map `f` and a measurable set `s`, almost every point `x ∈ s` returns back to `s` infinitely many times. -/ lemma ae_mem_imp_frequently_image_mem (hf : conservative f μ) (hs : measurable_set s) : ∀ᵐ x ∂μ, x ∈ s → ∃ᶠ n in at_top, (f^[n] x) ∈ s := begin simp only [frequently_at_top, @forall_swap (_ ∈ s), ae_all_iff], intro n, filter_upwards [measure_zero_iff_ae_nmem.1 (hf.measure_mem_forall_ge_image_not_mem_eq_zero hs n)], simp end lemma inter_frequently_image_mem_ae_eq (hf : conservative f μ) (hs : measurable_set s) : (s ∩ {x | ∃ᶠ n in at_top, f^[n] x ∈ s} : set α) =ᵐ[μ] s := inter_eventually_eq_left.2 $ hf.ae_mem_imp_frequently_image_mem hs lemma measure_inter_frequently_image_mem_eq (hf : conservative f μ) (hs : measurable_set s) : μ (s ∩ {x | ∃ᶠ n in at_top, f^[n] x ∈ s}) = μ s := measure_congr (hf.inter_frequently_image_mem_ae_eq hs) /-- Poincaré recurrence theorem: if `f` is a conservative dynamical system and `s` is a measurable set, then for `μ`-a.e. `x`, if the orbit of `x` visits `s` at least once, then it visits `s` infinitely many times. -/ lemma ae_forall_image_mem_imp_frequently_image_mem (hf : conservative f μ) (hs : measurable_set s) : ∀ᵐ x ∂μ, ∀ k, f^[k] x ∈ s → ∃ᶠ n in at_top, (f^[n] x) ∈ s := begin refine ae_all_iff.2 (λ k, _), refine (hf.ae_mem_imp_frequently_image_mem (hf.measurable.iterate k hs)).mono (λ x hx hk, _), rw [← map_add_at_top_eq_nat k, frequently_map], refine (hx hk).mono (λ n hn, _), rwa [add_comm, iterate_add_apply] end /-- If `f` is a conservative self-map and `s` is a measurable set of positive measure, then `μ.ae`-frequently we have `x ∈ s` and `s` returns to `s` under infinitely many iterations of `f`. -/ lemma frequently_ae_mem_and_frequently_image_mem (hf : conservative f μ) (hs : measurable_set s) (h0 : μ s ≠ 0) : ∃ᵐ x ∂μ, x ∈ s ∧ ∃ᶠ n in at_top, (f^[n] x) ∈ s := ((frequently_ae_mem_iff.2 h0).and_eventually (hf.ae_mem_imp_frequently_image_mem hs)).mono $ λ x hx, ⟨hx.1, hx.2 hx.1⟩ /-- Poincaré recurrence theorem. Let `f : α → α` be a conservative dynamical system on a topological space with second countable topology and measurable open sets. Then almost every point `x : α` is recurrent: it visits every neighborhood `s ∈ 𝓝 x` infinitely many times. -/ lemma ae_frequently_mem_of_mem_nhds [topological_space α] [second_countable_topology α] [opens_measurable_space α] {f : α → α} {μ : measure α} (h : conservative f μ) : ∀ᵐ x ∂μ, ∀ s ∈ 𝓝 x, ∃ᶠ n in at_top, f^[n] x ∈ s := begin have : ∀ s ∈ countable_basis α, ∀ᵐ x ∂μ, x ∈ s → ∃ᶠ n in at_top, (f^[n] x) ∈ s, from λ s hs, h.ae_mem_imp_frequently_image_mem (is_open_of_mem_countable_basis hs).measurable_set, refine ((ae_ball_iff $ countable_countable_basis α).2 this).mono (λ x hx s hs, _), rcases (is_basis_countable_basis α).mem_nhds_iff.1 hs with ⟨o, hoS, hxo, hos⟩, exact (hx o hoS hxo).mono (λ n hn, hos hn) end /-- Iteration of a conservative system is a conservative system. -/ protected lemma iterate (hf : conservative f μ) (n : ℕ) : conservative (f^[n]) μ := begin cases n, { exact conservative.id μ }, -- Discharge the trivial case `n = 0` refine ⟨hf.1.iterate _, λ s hs hs0, _⟩, rcases (hf.frequently_ae_mem_and_frequently_image_mem hs hs0).exists with ⟨x, hxs, hx⟩, /- We take a point `x ∈ s` such that `f^[k] x ∈ s` for infinitely many values of `k`, then we choose two of these values `k < l` such that `k ≡ l [MOD (n + 1)]`. Then `f^[k] x ∈ s` and `(f^[n + 1])^[(l - k) / (n + 1)] (f^[k] x) = f^[l] x ∈ s`. -/ rw nat.frequently_at_top_iff_infinite at hx, rcases nat.exists_lt_modeq_of_infinite hx n.succ_pos with ⟨k, hk, l, hl, hkl, hn⟩, set m := (l - k) / (n + 1), have : (n + 1) * m = l - k, { apply nat.mul_div_cancel', exact (nat.modeq_iff_dvd' hkl.le).1 hn }, refine ⟨f^[k] x, hk, m, _, _⟩, { intro hm, rw [hm, mul_zero, eq_comm, nat.sub_eq_zero_iff_le] at this, exact this.not_lt hkl }, { rwa [← iterate_mul, this, ← iterate_add_apply, nat.sub_add_cancel], exact hkl.le } end end conservative end measure_theory
9d5808c9791e1116c8b4a84ae79dc9ec5d97c94f
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/normed_space/affine_isometry.lean
c3e5a9e350546633e1c0db24ee5a449979fd8f4b
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
24,699
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.normed_space.linear_isometry import analysis.normed.group.add_torsor import analysis.normed_space.basic import linear_algebra.affine_space.restrict import algebra.char_p.invertible /-! # Affine isometries In this file we define `affine_isometry 𝕜 P P₂` to be an affine isometric embedding of normed add-torsors `P` into `P₂` over normed `𝕜`-spaces and `affine_isometry_equiv` to be an affine isometric equivalence between `P` and `P₂`. We also prove basic lemmas and provide convenience constructors. The choice of these lemmas and constructors is closely modelled on those for the `linear_isometry` and `affine_map` theories. Since many elementary properties don't require `‖x‖ = 0 → x = 0` we initially set up the theory for `seminormed_add_comm_group` and specialize to `normed_add_comm_group` only when needed. ## Notation We introduce the notation `P →ᵃⁱ[𝕜] P₂` for `affine_isometry 𝕜 P P₂`, and `P ≃ᵃⁱ[𝕜] P₂` for `affine_isometry_equiv 𝕜 P P₂`. In contrast with the notation `→ₗᵢ` for linear isometries, `≃ᵢ` for isometric equivalences, etc., the "i" here is a superscript. This is for aesthetic reasons to match the superscript "a" (note that in mathlib `→ᵃ` is an affine map, since `→ₐ` has been taken by algebra-homomorphisms.) -/ open function set variables (𝕜 : Type*) {V V₁ V₂ V₃ V₄ : Type*} {P₁ : Type*} (P P₂ : Type*) {P₃ P₄ : Type*} [normed_field 𝕜] [seminormed_add_comm_group V] [seminormed_add_comm_group V₁] [seminormed_add_comm_group V₂] [seminormed_add_comm_group V₃] [seminormed_add_comm_group V₄] [normed_space 𝕜 V] [normed_space 𝕜 V₁] [normed_space 𝕜 V₂] [normed_space 𝕜 V₃] [normed_space 𝕜 V₄] [pseudo_metric_space P] [metric_space P₁] [pseudo_metric_space P₂] [pseudo_metric_space P₃] [pseudo_metric_space P₄] [normed_add_torsor V P] [normed_add_torsor V₁ P₁] [normed_add_torsor V₂ P₂] [normed_add_torsor V₃ P₃] [normed_add_torsor V₄ P₄] include V V₂ /-- An `𝕜`-affine isometric embedding of one normed add-torsor over a normed `𝕜`-space into another. -/ structure affine_isometry extends P →ᵃ[𝕜] P₂ := (norm_map : ∀ x : V, ‖linear x‖ = ‖x‖) omit V V₂ variables {𝕜 P P₂} -- `→ᵃᵢ` would be more consistent with the linear isometry notation, but it is uglier notation P ` →ᵃⁱ[`:25 𝕜:25 `] `:0 P₂:0 := affine_isometry 𝕜 P P₂ namespace affine_isometry variables (f : P →ᵃⁱ[𝕜] P₂) /-- The underlying linear map of an affine isometry is in fact a linear isometry. -/ protected def linear_isometry : V →ₗᵢ[𝕜] V₂ := { norm_map' := f.norm_map, .. f.linear } @[simp] lemma linear_eq_linear_isometry : f.linear = f.linear_isometry.to_linear_map := by { ext, refl } include V V₂ instance : has_coe_to_fun (P →ᵃⁱ[𝕜] P₂) (λ _, P → P₂) := ⟨λ f, f.to_fun⟩ omit V V₂ @[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl include V V₂ lemma to_affine_map_injective : injective (to_affine_map : (P →ᵃⁱ[𝕜] P₂) → (P →ᵃ[𝕜] P₂)) | ⟨f, _⟩ ⟨g, _⟩ rfl := rfl lemma coe_fn_injective : @injective (P →ᵃⁱ[𝕜] P₂) (P → P₂) coe_fn := affine_map.coe_fn_injective.comp to_affine_map_injective @[ext] lemma ext {f g : P →ᵃⁱ[𝕜] P₂} (h : ∀ x, f x = g x) : f = g := coe_fn_injective $ funext h omit V V₂ end affine_isometry namespace linear_isometry variables (f : V →ₗᵢ[𝕜] V₂) /-- Reinterpret a linear isometry as an affine isometry. -/ def to_affine_isometry : V →ᵃⁱ[𝕜] V₂ := { norm_map := f.norm_map, .. f.to_linear_map.to_affine_map } @[simp] lemma coe_to_affine_isometry : ⇑(f.to_affine_isometry : V →ᵃⁱ[𝕜] V₂) = f := rfl @[simp] lemma to_affine_isometry_linear_isometry : f.to_affine_isometry.linear_isometry = f := by { ext, refl } -- somewhat arbitrary choice of simp direction @[simp] lemma to_affine_isometry_to_affine_map : f.to_affine_isometry.to_affine_map = f.to_linear_map.to_affine_map := rfl end linear_isometry namespace affine_isometry /-- We use `f₁` when we need the domain to be a `normed_space`. -/ variables (f : P →ᵃⁱ[𝕜] P₂) (f₁ : P₁ →ᵃⁱ[𝕜] P₂) @[simp] lemma map_vadd (p : P) (v : V) : f (v +ᵥ p) = f.linear_isometry v +ᵥ f p := f.to_affine_map.map_vadd p v @[simp] lemma map_vsub (p1 p2 : P) : f.linear_isometry (p1 -ᵥ p2) = f p1 -ᵥ f p2 := f.to_affine_map.linear_map_vsub p1 p2 @[simp] lemma dist_map (x y : P) : dist (f x) (f y) = dist x y := by rw [dist_eq_norm_vsub V₂, dist_eq_norm_vsub V, ← map_vsub, f.linear_isometry.norm_map] @[simp] lemma nndist_map (x y : P) : nndist (f x) (f y) = nndist x y := by simp [nndist_dist] @[simp] lemma edist_map (x y : P) : edist (f x) (f y) = edist x y := by simp [edist_dist] protected lemma isometry : isometry f := f.edist_map protected lemma injective : injective f₁ := f₁.isometry.injective @[simp] lemma map_eq_iff {x y : P₁} : f₁ x = f₁ y ↔ x = y := f₁.injective.eq_iff lemma map_ne {x y : P₁} (h : x ≠ y) : f₁ x ≠ f₁ y := f₁.injective.ne h protected lemma lipschitz : lipschitz_with 1 f := f.isometry.lipschitz protected lemma antilipschitz : antilipschitz_with 1 f := f.isometry.antilipschitz @[continuity] protected lemma continuous : continuous f := f.isometry.continuous lemma ediam_image (s : set P) : emetric.diam (f '' s) = emetric.diam s := f.isometry.ediam_image s lemma ediam_range : emetric.diam (range f) = emetric.diam (univ : set P) := f.isometry.ediam_range lemma diam_image (s : set P) : metric.diam (f '' s) = metric.diam s := f.isometry.diam_image s lemma diam_range : metric.diam (range f) = metric.diam (univ : set P) := f.isometry.diam_range @[simp] lemma comp_continuous_iff {α : Type*} [topological_space α] {g : α → P} : continuous (f ∘ g) ↔ continuous g := f.isometry.comp_continuous_iff include V /-- The identity affine isometry. -/ def id : P →ᵃⁱ[𝕜] P := ⟨affine_map.id 𝕜 P, λ x, rfl⟩ @[simp] lemma coe_id : ⇑(id : P →ᵃⁱ[𝕜] P) = _root_.id := rfl @[simp] lemma id_apply (x : P) : (affine_isometry.id : P →ᵃⁱ[𝕜] P) x = x := rfl @[simp] lemma id_to_affine_map : (id.to_affine_map : P →ᵃ[𝕜] P) = affine_map.id 𝕜 P := rfl instance : inhabited (P →ᵃⁱ[𝕜] P) := ⟨id⟩ include V₂ V₃ /-- Composition of affine isometries. -/ def comp (g : P₂ →ᵃⁱ[𝕜] P₃) (f : P →ᵃⁱ[𝕜] P₂) : P →ᵃⁱ[𝕜] P₃ := ⟨g.to_affine_map.comp f.to_affine_map, λ x, (g.norm_map _).trans (f.norm_map _)⟩ @[simp] lemma coe_comp (g : P₂ →ᵃⁱ[𝕜] P₃) (f : P →ᵃⁱ[𝕜] P₂) : ⇑(g.comp f) = g ∘ f := rfl omit V V₂ V₃ @[simp] lemma id_comp : (id : P₂ →ᵃⁱ[𝕜] P₂).comp f = f := ext $ λ x, rfl @[simp] lemma comp_id : f.comp id = f := ext $ λ x, rfl include V V₂ V₃ V₄ lemma comp_assoc (f : P₃ →ᵃⁱ[𝕜] P₄) (g : P₂ →ᵃⁱ[𝕜] P₃) (h : P →ᵃⁱ[𝕜] P₂) : (f.comp g).comp h = f.comp (g.comp h) := rfl omit V₂ V₃ V₄ instance : monoid (P →ᵃⁱ[𝕜] P) := { one := id, mul := comp, mul_assoc := comp_assoc, one_mul := id_comp, mul_one := comp_id } @[simp] lemma coe_one : ⇑(1 : P →ᵃⁱ[𝕜] P) = _root_.id := rfl @[simp] lemma coe_mul (f g : P →ᵃⁱ[𝕜] P) : ⇑(f * g) = f ∘ g := rfl end affine_isometry namespace affine_subspace include V /-- `affine_subspace.subtype` as an `affine_isometry`. -/ def subtypeₐᵢ (s : affine_subspace 𝕜 P) [nonempty s] : s →ᵃⁱ[𝕜] P := { norm_map := s.direction.subtypeₗᵢ.norm_map, .. s.subtype } lemma subtypeₐᵢ_linear (s : affine_subspace 𝕜 P) [nonempty s] : s.subtypeₐᵢ.linear = s.direction.subtype := rfl @[simp] lemma subtypeₐᵢ_linear_isometry (s : affine_subspace 𝕜 P) [nonempty s] : s.subtypeₐᵢ.linear_isometry = s.direction.subtypeₗᵢ := rfl @[simp] lemma coe_subtypeₐᵢ (s : affine_subspace 𝕜 P) [nonempty s] : ⇑s.subtypeₐᵢ = s.subtype := rfl @[simp] lemma subtypeₐᵢ_to_affine_map (s : affine_subspace 𝕜 P) [nonempty s] : s.subtypeₐᵢ.to_affine_map = s.subtype := rfl end affine_subspace variables (𝕜 P P₂) include V V₂ /-- A affine isometric equivalence between two normed vector spaces. -/ structure affine_isometry_equiv extends P ≃ᵃ[𝕜] P₂ := (norm_map : ∀ x, ‖linear x‖ = ‖x‖) variables {𝕜 P P₂} omit V V₂ -- `≃ᵃᵢ` would be more consistent with the linear isometry equiv notation, but it is uglier notation P ` ≃ᵃⁱ[`:25 𝕜:25 `] `:0 P₂:0 := affine_isometry_equiv 𝕜 P P₂ namespace affine_isometry_equiv variables (e : P ≃ᵃⁱ[𝕜] P₂) /-- The underlying linear equiv of an affine isometry equiv is in fact a linear isometry equiv. -/ protected def linear_isometry_equiv : V ≃ₗᵢ[𝕜] V₂ := { norm_map' := e.norm_map, .. e.linear } @[simp] lemma linear_eq_linear_isometry : e.linear = e.linear_isometry_equiv.to_linear_equiv := by { ext, refl } include V V₂ instance : has_coe_to_fun (P ≃ᵃⁱ[𝕜] P₂) (λ _, P → P₂) := ⟨λ f, f.to_fun⟩ @[simp] lemma coe_mk (e : P ≃ᵃ[𝕜] P₂) (he : ∀ x, ‖e.linear x‖ = ‖x‖) : ⇑(mk e he) = e := rfl @[simp] lemma coe_to_affine_equiv (e : P ≃ᵃⁱ[𝕜] P₂) : ⇑e.to_affine_equiv = e := rfl lemma to_affine_equiv_injective : injective (to_affine_equiv : (P ≃ᵃⁱ[𝕜] P₂) → (P ≃ᵃ[𝕜] P₂)) | ⟨e, _⟩ ⟨_, _⟩ rfl := rfl @[ext] lemma ext {e e' : P ≃ᵃⁱ[𝕜] P₂} (h : ∀ x, e x = e' x) : e = e' := to_affine_equiv_injective $ affine_equiv.ext h omit V V₂ /-- Reinterpret a `affine_isometry_equiv` as a `affine_isometry`. -/ def to_affine_isometry : P →ᵃⁱ[𝕜] P₂ := ⟨e.1.to_affine_map, e.2⟩ @[simp] lemma coe_to_affine_isometry : ⇑e.to_affine_isometry = e := rfl /-- Construct an affine isometry equivalence by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `e : P₁ → P₂`, a linear isometry equivalence `e' : V₁ ≃ᵢₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `e p' = e' (p' -ᵥ p) +ᵥ e p`. -/ def mk' (e : P₁ → P₂) (e' : V₁ ≃ₗᵢ[𝕜] V₂) (p : P₁) (h : ∀ p' : P₁, e p' = e' (p' -ᵥ p) +ᵥ e p) : P₁ ≃ᵃⁱ[𝕜] P₂ := { norm_map := e'.norm_map, .. affine_equiv.mk' e e'.to_linear_equiv p h } @[simp] lemma coe_mk' (e : P₁ → P₂) (e' : V₁ ≃ₗᵢ[𝕜] V₂) (p h) : ⇑(mk' e e' p h) = e := rfl @[simp] lemma linear_isometry_equiv_mk' (e : P₁ → P₂) (e' : V₁ ≃ₗᵢ[𝕜] V₂) (p h) : (mk' e e' p h).linear_isometry_equiv = e' := by { ext, refl } end affine_isometry_equiv namespace linear_isometry_equiv variables (e : V ≃ₗᵢ[𝕜] V₂) /-- Reinterpret a linear isometry equiv as an affine isometry equiv. -/ def to_affine_isometry_equiv : V ≃ᵃⁱ[𝕜] V₂ := { norm_map := e.norm_map, .. e.to_linear_equiv.to_affine_equiv } @[simp] lemma coe_to_affine_isometry_equiv : ⇑(e.to_affine_isometry_equiv : V ≃ᵃⁱ[𝕜] V₂) = e := rfl @[simp] lemma to_affine_isometry_equiv_linear_isometry_equiv : e.to_affine_isometry_equiv.linear_isometry_equiv = e := by { ext, refl } -- somewhat arbitrary choice of simp direction @[simp] lemma to_affine_isometry_equiv_to_affine_equiv : e.to_affine_isometry_equiv.to_affine_equiv = e.to_linear_equiv.to_affine_equiv := rfl -- somewhat arbitrary choice of simp direction @[simp] lemma to_affine_isometry_equiv_to_affine_isometry : e.to_affine_isometry_equiv.to_affine_isometry = e.to_linear_isometry.to_affine_isometry := rfl end linear_isometry_equiv namespace affine_isometry_equiv variables (e : P ≃ᵃⁱ[𝕜] P₂) protected lemma isometry : isometry e := e.to_affine_isometry.isometry /-- Reinterpret a `affine_isometry_equiv` as an `isometry_equiv`. -/ def to_isometry_equiv : P ≃ᵢ P₂ := ⟨e.to_affine_equiv.to_equiv, e.isometry⟩ @[simp] lemma coe_to_isometry_equiv : ⇑e.to_isometry_equiv = e := rfl include V V₂ lemma range_eq_univ (e : P ≃ᵃⁱ[𝕜] P₂) : set.range e = set.univ := by { rw ← coe_to_isometry_equiv, exact isometry_equiv.range_eq_univ _, } omit V V₂ /-- Reinterpret a `affine_isometry_equiv` as an `homeomorph`. -/ def to_homeomorph : P ≃ₜ P₂ := e.to_isometry_equiv.to_homeomorph @[simp] lemma coe_to_homeomorph : ⇑e.to_homeomorph = e := rfl protected lemma continuous : continuous e := e.isometry.continuous protected lemma continuous_at {x} : continuous_at e x := e.continuous.continuous_at protected lemma continuous_on {s} : continuous_on e s := e.continuous.continuous_on protected lemma continuous_within_at {s x} : continuous_within_at e s x := e.continuous.continuous_within_at variables (𝕜 P) include V /-- Identity map as a `affine_isometry_equiv`. -/ def refl : P ≃ᵃⁱ[𝕜] P := ⟨affine_equiv.refl 𝕜 P, λ x, rfl⟩ variables {𝕜 P} instance : inhabited (P ≃ᵃⁱ[𝕜] P) := ⟨refl 𝕜 P⟩ @[simp] lemma coe_refl : ⇑(refl 𝕜 P) = id := rfl @[simp] lemma to_affine_equiv_refl : (refl 𝕜 P).to_affine_equiv = affine_equiv.refl 𝕜 P := rfl @[simp] lemma to_isometry_equiv_refl : (refl 𝕜 P).to_isometry_equiv = isometry_equiv.refl P := rfl @[simp] lemma to_homeomorph_refl : (refl 𝕜 P).to_homeomorph = homeomorph.refl P := rfl omit V /-- The inverse `affine_isometry_equiv`. -/ def symm : P₂ ≃ᵃⁱ[𝕜] P := { norm_map := e.linear_isometry_equiv.symm.norm_map, .. e.to_affine_equiv.symm } @[simp] lemma apply_symm_apply (x : P₂) : e (e.symm x) = x := e.to_affine_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (x : P) : e.symm (e x) = x := e.to_affine_equiv.symm_apply_apply x @[simp] lemma symm_symm : e.symm.symm = e := ext $ λ x, rfl @[simp] lemma to_affine_equiv_symm : e.to_affine_equiv.symm = e.symm.to_affine_equiv := rfl @[simp] lemma to_isometry_equiv_symm : e.to_isometry_equiv.symm = e.symm.to_isometry_equiv := rfl @[simp] lemma to_homeomorph_symm : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl include V₃ /-- Composition of `affine_isometry_equiv`s as a `affine_isometry_equiv`. -/ def trans (e' : P₂ ≃ᵃⁱ[𝕜] P₃) : P ≃ᵃⁱ[𝕜] P₃ := ⟨e.to_affine_equiv.trans e'.to_affine_equiv, λ x, (e'.norm_map _).trans (e.norm_map _)⟩ include V V₂ @[simp] lemma coe_trans (e₁ : P ≃ᵃⁱ[𝕜] P₂) (e₂ : P₂ ≃ᵃⁱ[𝕜] P₃) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl omit V V₂ V₃ @[simp] lemma trans_refl : e.trans (refl 𝕜 P₂) = e := ext $ λ x, rfl @[simp] lemma refl_trans : (refl 𝕜 P).trans e = e := ext $ λ x, rfl @[simp] lemma self_trans_symm : e.trans e.symm = refl 𝕜 P := ext e.symm_apply_apply @[simp] lemma symm_trans_self : e.symm.trans e = refl 𝕜 P₂ := ext e.apply_symm_apply include V V₂ V₃ @[simp] lemma coe_symm_trans (e₁ : P ≃ᵃⁱ[𝕜] P₂) (e₂ : P₂ ≃ᵃⁱ[𝕜] P₃) : ⇑(e₁.trans e₂).symm = e₁.symm ∘ e₂.symm := rfl include V₄ lemma trans_assoc (ePP₂ : P ≃ᵃⁱ[𝕜] P₂) (eP₂G : P₂ ≃ᵃⁱ[𝕜] P₃) (eGG' : P₃ ≃ᵃⁱ[𝕜] P₄) : ePP₂.trans (eP₂G.trans eGG') = (ePP₂.trans eP₂G).trans eGG' := rfl omit V₂ V₃ V₄ /-- The group of affine isometries of a `normed_add_torsor`, `P`. -/ instance : group (P ≃ᵃⁱ[𝕜] P) := { mul := λ e₁ e₂, e₂.trans e₁, one := refl _ _, inv := symm, one_mul := trans_refl, mul_one := refl_trans, mul_assoc := λ _ _ _, trans_assoc _ _ _, mul_left_inv := self_trans_symm } @[simp] lemma coe_one : ⇑(1 : P ≃ᵃⁱ[𝕜] P) = id := rfl @[simp] lemma coe_mul (e e' : P ≃ᵃⁱ[𝕜] P) : ⇑(e * e') = e ∘ e' := rfl @[simp] lemma coe_inv (e : P ≃ᵃⁱ[𝕜] P) : ⇑(e⁻¹) = e.symm := rfl omit V @[simp] lemma map_vadd (p : P) (v : V) : e (v +ᵥ p) = e.linear_isometry_equiv v +ᵥ e p := e.to_affine_isometry.map_vadd p v @[simp] lemma map_vsub (p1 p2 : P) : e.linear_isometry_equiv (p1 -ᵥ p2) = e p1 -ᵥ e p2 := e.to_affine_isometry.map_vsub p1 p2 @[simp] lemma dist_map (x y : P) : dist (e x) (e y) = dist x y := e.to_affine_isometry.dist_map x y @[simp] lemma edist_map (x y : P) : edist (e x) (e y) = edist x y := e.to_affine_isometry.edist_map x y protected lemma bijective : bijective e := e.1.bijective protected lemma injective : injective e := e.1.injective protected lemma surjective : surjective e := e.1.surjective @[simp] lemma map_eq_iff {x y : P} : e x = e y ↔ x = y := e.injective.eq_iff lemma map_ne {x y : P} (h : x ≠ y) : e x ≠ e y := e.injective.ne h protected lemma lipschitz : lipschitz_with 1 e := e.isometry.lipschitz protected lemma antilipschitz : antilipschitz_with 1 e := e.isometry.antilipschitz @[simp] lemma ediam_image (s : set P) : emetric.diam (e '' s) = emetric.diam s := e.isometry.ediam_image s @[simp] lemma diam_image (s : set P) : metric.diam (e '' s) = metric.diam s := e.isometry.diam_image s variables {α : Type*} [topological_space α] @[simp] lemma comp_continuous_on_iff {f : α → P} {s : set α} : continuous_on (e ∘ f) s ↔ continuous_on f s := e.isometry.comp_continuous_on_iff @[simp] lemma comp_continuous_iff {f : α → P} : continuous (e ∘ f) ↔ continuous f := e.isometry.comp_continuous_iff section constructions variables (𝕜) /-- The map `v ↦ v +ᵥ p` as an affine isometric equivalence between `V` and `P`. -/ def vadd_const (p : P) : V ≃ᵃⁱ[𝕜] P := { norm_map := λ x, rfl, .. affine_equiv.vadd_const 𝕜 p } variables {𝕜} include V @[simp] lemma coe_vadd_const (p : P) : ⇑(vadd_const 𝕜 p) = λ v, v +ᵥ p := rfl @[simp] lemma coe_vadd_const_symm (p : P) : ⇑(vadd_const 𝕜 p).symm = λ p', p' -ᵥ p := rfl @[simp] lemma vadd_const_to_affine_equiv (p : P) : (vadd_const 𝕜 p).to_affine_equiv = affine_equiv.vadd_const 𝕜 p := rfl omit V variables (𝕜) /-- `p' ↦ p -ᵥ p'` as an affine isometric equivalence. -/ def const_vsub (p : P) : P ≃ᵃⁱ[𝕜] V := { norm_map := norm_neg, .. affine_equiv.const_vsub 𝕜 p } variables {𝕜} include V @[simp] lemma coe_const_vsub (p : P) : ⇑(const_vsub 𝕜 p) = (-ᵥ) p := rfl @[simp] lemma symm_const_vsub (p : P) : (const_vsub 𝕜 p).symm = (linear_isometry_equiv.neg 𝕜).to_affine_isometry_equiv.trans (vadd_const 𝕜 p) := by { ext, refl } omit V variables (𝕜 P) /-- Translation by `v` (that is, the map `p ↦ v +ᵥ p`) as an affine isometric automorphism of `P`. -/ def const_vadd (v : V) : P ≃ᵃⁱ[𝕜] P := { norm_map := λ x, rfl, .. affine_equiv.const_vadd 𝕜 P v } variables {𝕜 P} @[simp] lemma coe_const_vadd (v : V) : ⇑(const_vadd 𝕜 P v : P ≃ᵃⁱ[𝕜] P) = (+ᵥ) v := rfl @[simp] lemma const_vadd_zero : const_vadd 𝕜 P (0:V) = refl 𝕜 P := ext $ zero_vadd V include 𝕜 V /-- The map `g` from `V` to `V₂` corresponding to a map `f` from `P` to `P₂`, at a base point `p`, is an isometry if `f` is one. -/ lemma vadd_vsub {f : P → P₂} (hf : isometry f) {p : P} {g : V → V₂} (hg : ∀ v, g v = f (v +ᵥ p) -ᵥ f p) : isometry g := begin convert (vadd_const 𝕜 (f p)).symm.isometry.comp (hf.comp (vadd_const 𝕜 p).isometry), exact funext hg end omit 𝕜 variables (𝕜) /-- Point reflection in `x` as an affine isometric automorphism. -/ def point_reflection (x : P) : P ≃ᵃⁱ[𝕜] P := (const_vsub 𝕜 x).trans (vadd_const 𝕜 x) variables {𝕜} lemma point_reflection_apply (x y : P) : (point_reflection 𝕜 x) y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_to_affine_equiv (x : P) : (point_reflection 𝕜 x).to_affine_equiv = affine_equiv.point_reflection 𝕜 x := rfl @[simp] lemma point_reflection_self (x : P) : point_reflection 𝕜 x x = x := affine_equiv.point_reflection_self 𝕜 x lemma point_reflection_involutive (x : P) : function.involutive (point_reflection 𝕜 x) := equiv.point_reflection_involutive x @[simp] lemma point_reflection_symm (x : P) : (point_reflection 𝕜 x).symm = point_reflection 𝕜 x := to_affine_equiv_injective $ affine_equiv.point_reflection_symm 𝕜 x @[simp] lemma dist_point_reflection_fixed (x y : P) : dist (point_reflection 𝕜 x y) x = dist y x := by rw [← (point_reflection 𝕜 x).dist_map y x, point_reflection_self] lemma dist_point_reflection_self' (x y : P) : dist (point_reflection 𝕜 x y) y = ‖bit0 (x -ᵥ y)‖ := by rw [point_reflection_apply, dist_eq_norm_vsub V, vadd_vsub_assoc, bit0] lemma dist_point_reflection_self (x y : P) : dist (point_reflection 𝕜 x y) y = ‖(2:𝕜)‖ * dist x y := by rw [dist_point_reflection_self', ← two_smul' 𝕜 (x -ᵥ y), norm_smul, ← dist_eq_norm_vsub V] lemma point_reflection_fixed_iff [invertible (2:𝕜)] {x y : P} : point_reflection 𝕜 x y = y ↔ y = x := affine_equiv.point_reflection_fixed_iff_of_module 𝕜 variables [normed_space ℝ V] lemma dist_point_reflection_self_real (x y : P) : dist (point_reflection ℝ x y) y = 2 * dist x y := by { rw [dist_point_reflection_self, real.norm_two] } @[simp] lemma point_reflection_midpoint_left (x y : P) : point_reflection ℝ (midpoint ℝ x y) x = y := affine_equiv.point_reflection_midpoint_left x y @[simp] lemma point_reflection_midpoint_right (x y : P) : point_reflection ℝ (midpoint ℝ x y) y = x := affine_equiv.point_reflection_midpoint_right x y end constructions end affine_isometry_equiv include V V₂ /-- If `f` is an affine map, then its linear part is continuous iff `f` is continuous. -/ lemma affine_map.continuous_linear_iff {f : P →ᵃ[𝕜] P₂} : continuous f.linear ↔ continuous f := begin inhabit P, have : (f.linear : V → V₂) = (affine_isometry_equiv.vadd_const 𝕜 $ f default).to_homeomorph.symm ∘ f ∘ (affine_isometry_equiv.vadd_const 𝕜 default).to_homeomorph, { ext v, simp }, rw this, simp only [homeomorph.comp_continuous_iff, homeomorph.comp_continuous_iff'], end /-- If `f` is an affine map, then its linear part is an open map iff `f` is an open map. -/ lemma affine_map.is_open_map_linear_iff {f : P →ᵃ[𝕜] P₂} : is_open_map f.linear ↔ is_open_map f := begin inhabit P, have : (f.linear : V → V₂) = (affine_isometry_equiv.vadd_const 𝕜 $ f default).to_homeomorph.symm ∘ f ∘ (affine_isometry_equiv.vadd_const 𝕜 default).to_homeomorph, { ext v, simp }, rw this, simp only [homeomorph.comp_is_open_map_iff, homeomorph.comp_is_open_map_iff'], end local attribute [instance, nolint fails_quickly] affine_subspace.nonempty_map include V₁ omit V namespace affine_subspace /-- An affine subspace is isomorphic to its image under an injective affine map. This is the affine version of `submodule.equiv_map_of_injective`. -/ @[simps] noncomputable def equiv_map_of_injective (E: affine_subspace 𝕜 P₁) [nonempty E] (φ : P₁ →ᵃ[𝕜] P₂) (hφ : function.injective φ) : E ≃ᵃ[𝕜] E.map φ := { linear := (E.direction.equiv_map_of_injective φ.linear (φ.linear_injective_iff.mpr hφ)).trans (linear_equiv.of_eq _ _ (affine_subspace.map_direction _ _).symm), map_vadd' := λ p v, subtype.ext $ φ.map_vadd p v, .. equiv.set.image _ (E : set P₁) hφ } /-- Restricts an affine isometry to an affine isometry equivalence between a nonempty affine subspace `E` and its image. This is an isometry version of `affine_subspace.equiv_map`, having a stronger premise and a stronger conclusion. -/ noncomputable def isometry_equiv_map (φ : P₁ →ᵃⁱ[𝕜] P₂) (E : affine_subspace 𝕜 P₁) [nonempty E] : E ≃ᵃⁱ[𝕜] E.map φ.to_affine_map := ⟨E.equiv_map_of_injective φ.to_affine_map φ.injective, (λ _, φ.norm_map _)⟩ @[simp] lemma isometry_equiv_map.apply_symm_apply {E : affine_subspace 𝕜 P₁} [nonempty E] {φ : P₁ →ᵃⁱ[𝕜] P₂} (x : E.map φ.to_affine_map) : φ ((E.isometry_equiv_map φ).symm x) = x := congr_arg coe $ (E.isometry_equiv_map φ).apply_symm_apply _ @[simp] lemma isometry_equiv_map.coe_apply (φ : P₁ →ᵃⁱ[𝕜] P₂) (E : affine_subspace 𝕜 P₁) [nonempty E] (g: E) : ↑(E.isometry_equiv_map φ g) = φ g := rfl @[simp] lemma isometry_equiv_map.to_affine_map_eq (φ : P₁ →ᵃⁱ[𝕜] P₂) (E : affine_subspace 𝕜 P₁) [nonempty E] : (E.isometry_equiv_map φ).to_affine_map = E.equiv_map_of_injective φ.to_affine_map φ.injective := rfl end affine_subspace
847ff359057f994837c9b9f124ab29731434314f
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/run/assoc_flat.lean
4d4a472dbaef0cafc923d7685775a58804b88713
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,303
lean
open tactic expr meta definition is_op_app (op : expr) (e : expr) : option (expr × expr) := match e with | (app (app fn a1) a2) := if op = fn then some (a1, a2) else none | e := none end meta definition flat_with : expr → expr → expr → expr → tactic (expr × expr) | op assoc e rhs := match (is_op_app op e) with | (some (a1, a2)) := do -- H₁ is a proof for a2 + rhs = rhs₁ (rhs₁, H₁) ← flat_with op assoc a2 rhs, -- H₂ is a proof for a1 + rhs₁ = rhs₂ (new_app, H₂) ← flat_with op assoc a1 rhs₁, -- We need to generate a proof that (a1 + a2) + rhs = a1 + (a2 + rhs) -- H₃ is a proof for (a1 + a2) + rhs = a1 + (a2 + rhs) H₃ : expr ← return (app (app (app assoc a1) a2) rhs), -- H₃ is a proof for a1 + (a2 + rhs) = a1 + rhs1 H₄ : expr ← mk_app `congr_arg [app op a1, H₁], H₅ ← mk_app `eq.trans [H₃, H₄], H ← mk_app `eq.trans [H₅, H₂], return (new_app, H) | none := do new_app ← return $ app (app op e) rhs, H ← mk_app `eq.refl [new_app], return (new_app, H) end meta definition flat : expr → expr → expr → tactic (expr × expr) | op assoc e := match (is_op_app op e) with | (some (a1, a2)) := do -- H₁ is a proof that a2 = new_a2 (new_a2, H₁) ← flat op assoc a2, -- H₂ is a proof that a1 + new_a2 = new_app (new_app, H₂) ← flat_with op assoc a1 new_a2, -- We need a proof that (a1 + a2) = new_app -- H₃ is a proof for a1 + a2 = a1 + new_a2 H₃ : expr ← mk_app `congr_arg [app op a1, H₁], H ← mk_app `eq.trans [H₃, H₂], return (new_app, H) | none := do pr ← mk_app `eq.refl [e], return (e, pr) end local infix `+` := nat.add set_option trace.app_builder true set_option pp.all true example (a b c d e f g : nat) : ((a + b) + c) + ((d + e) + (f + g)) = a + (b + (c + (d + (e + (f + g))))) := by do assoc : expr ← mk_const $ `nat.add_assoc, op : expr ← mk_const $ `nat.add, tgt ← target, match (is_eq tgt) with | (some (lhs, rhs)) := do r ← flat op assoc lhs, trace (prod.snd r), exact (prod.snd r) | none := failed end
c77c6a763cbe1462b1c4f6edc6ae0c01a74c9b77
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/data/int/default.lean
a6abbc610bf5d36c3dd94c67fa76c9a401b40a82
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
199
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.data.int.basic
53f65945829f56f37bcff21e71a0e6b52a0300f9
618003631150032a5676f229d13a079ac875ff77
/src/data/list/rotate.lean
6e3be3dced13a2021072caf1a800a1c62eda23bf
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
4,582
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.list.basic universes u variables {α : Type u} open nat namespace list lemma rotate_mod (l : list α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n := by simp [rotate] @[simp] lemma rotate_nil (n : ℕ) : ([] : list α).rotate n = [] := by cases n; refl @[simp] lemma rotate_zero (l : list α) : l.rotate 0 = l := by simp [rotate] @[simp] lemma rotate'_nil (n : ℕ) : ([] : list α).rotate' n = [] := by cases n; refl @[simp] lemma rotate'_zero (l : list α) : l.rotate' 0 = l := by cases l; refl lemma rotate'_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate'] @[simp] lemma length_rotate' : ∀ (l : list α) (n : ℕ), (l.rotate' n).length = l.length | [] n := rfl | (a::l) 0 := rfl | (a::l) (n+1) := by rw [list.rotate', length_rotate' (l ++ [a]) n]; simp lemma rotate'_eq_take_append_drop : ∀ {l : list α} {n : ℕ}, n ≤ l.length → l.rotate' n = l.drop n ++ l.take n | [] n h := by simp [drop_append_of_le_length h] | l 0 h := by simp [take_append_of_le_length h] | (a::l) (n+1) h := have hnl : n ≤ l.length, from le_of_succ_le_succ h, have hnl' : n ≤ (l ++ [a]).length, by rw [length_append, length_cons, list.length, zero_add]; exact (le_of_succ_le h), by rw [rotate'_cons_succ, rotate'_eq_take_append_drop hnl', drop, take, drop_append_of_le_length hnl, take_append_of_le_length hnl]; simp lemma rotate'_rotate' : ∀ (l : list α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m) | (a::l) 0 m := by simp | [] n m := by simp | (a::l) (n+1) m := by rw [rotate'_cons_succ, rotate'_rotate', add_right_comm, rotate'_cons_succ] @[simp] lemma rotate'_length (l : list α) : rotate' l l.length = l := by rw rotate'_eq_take_append_drop (le_refl _); simp @[simp] lemma rotate'_length_mul (l : list α) : ∀ n : ℕ, l.rotate' (l.length * n) = l | 0 := by simp | (n+1) := calc l.rotate' (l.length * (n + 1)) = (l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length : by simp [-rotate'_length, nat.mul_succ, rotate'_rotate'] ... = l : by rw [rotate'_length, rotate'_length_mul] lemma rotate'_mod (l : list α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n := calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate' ((l.rotate' (n % l.length)).length * (n / l.length)) : by rw rotate'_length_mul ... = l.rotate' n : by rw [rotate'_rotate', length_rotate', nat.mod_add_div] lemma rotate_eq_rotate' (l : list α) (n : ℕ) : l.rotate n = l.rotate' n := if h : l.length = 0 then by simp [length_eq_zero, *] at * else by rw [← rotate'_mod, rotate'_eq_take_append_drop (le_of_lt (nat.mod_lt _ (nat.pos_of_ne_zero h)))]; simp [rotate] lemma rotate_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate n.succ = (l ++ [a]).rotate n := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ] @[simp] lemma mem_rotate : ∀ {l : list α} {a : α} {n : ℕ}, a ∈ l.rotate n ↔ a ∈ l | [] _ n := by simp | (a::l) _ 0 := by simp | (a::l) _ (n+1) := by simp [rotate_cons_succ, mem_rotate, or.comm] @[simp] lemma length_rotate (l : list α) (n : ℕ) : (l.rotate n).length = l.length := by rw [rotate_eq_rotate', length_rotate'] lemma rotate_eq_take_append_drop {l : list α} {n : ℕ} : n ≤ l.length → l.rotate n = l.drop n ++ l.take n := by rw rotate_eq_rotate'; exact rotate'_eq_take_append_drop lemma rotate_rotate (l : list α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate'] @[simp] lemma rotate_length (l : list α) : rotate l l.length = l := by rw [rotate_eq_rotate', rotate'_length] @[simp] lemma rotate_length_mul (l : list α) (n : ℕ) : l.rotate (l.length * n) = l := by rw [rotate_eq_rotate', rotate'_length_mul] lemma prod_rotate_eq_one_of_prod_eq_one [group α] : ∀ {l : list α} (hl : l.prod = 1) (n : ℕ), (l.rotate n).prod = 1 | [] _ _ := by simp | (a::l) hl n := have n % list.length (a :: l) ≤ list.length (a :: l), from le_of_lt (nat.mod_lt _ dec_trivial), by rw ← list.take_append_drop (n % list.length (a :: l)) (a :: l) at hl; rw [← rotate_mod, rotate_eq_take_append_drop this, list.prod_append, mul_eq_one_iff_inv_eq, ← one_mul (list.prod _)⁻¹, ← hl, list.prod_append, mul_assoc, mul_inv_self, mul_one] end list
0527a26b0744a91e8fb016a580b116e64c7204d8
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/prod/basic.lean
ca46ef41721bf0f6b53591bf0c9943a256004070
[ "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
10,766
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import tactic.basic import logic.function.basic /-! # Extra facts about `prod` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `prod.swap : α × β → β × α` and proves various simple lemmas about `prod`. -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} @[simp] lemma prod_map (f : α → γ) (g : β → δ) (p : α × β) : prod.map f g p = (f p.1, g p.2) := rfl namespace prod @[simp] theorem «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 «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⟩⟩ theorem forall' {p : α → β → Prop} : (∀ x : α × β, p x.1 x.2) ↔ ∀ a b, p a b := prod.forall theorem exists' {p : α → β → Prop} : (∃ x : α × β, p x.1 x.2) ↔ ∃ a b, p a b := prod.exists @[simp] lemma snd_comp_mk (x : α) : prod.snd ∘ (prod.mk x : β → α × β) = id := rfl @[simp] lemma fst_comp_mk (x : α) : prod.fst ∘ (prod.mk x : β → α × β) = function.const β x := rfl @[simp] lemma map_mk (f : α → γ) (g : β → δ) (a : α) (b : β) : map f g (a, b) = (f a, g b) := rfl lemma map_fst (f : α → γ) (g : β → δ) (p : α × β) : (map f g p).1 = f (p.1) := rfl lemma map_snd (f : α → γ) (g : β → δ) (p : α × β) : (map f g p).2 = g (p.2) := rfl lemma map_fst' (f : α → γ) (g : β → δ) : (prod.fst ∘ map f g) = f ∘ prod.fst := funext $ map_fst f g lemma map_snd' (f : α → γ) (g : β → δ) : (prod.snd ∘ map f g) = g ∘ prod.snd := funext $ map_snd f g /-- Composing a `prod.map` with another `prod.map` is equal to a single `prod.map` of composed functions. -/ lemma map_comp_map {ε ζ : Type*} (f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) : prod.map g g' ∘ prod.map f f' = prod.map (g ∘ f) (g' ∘ f') := rfl /-- Composing a `prod.map` with another `prod.map` is equal to a single `prod.map` of composed functions, fully applied. -/ lemma map_map {ε ζ : Type*} (f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) (x : α × γ) : prod.map g g' (prod.map f f' x) = prod.map (g ∘ f) (g' ∘ f') x := rfl variables {a a₁ a₂ : α} {b b₁ b₂ : β} @[simp] lemma mk.inj_iff : (a₁, b₁) = (a₂, b₂) ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨prod.mk.inj, by cc⟩ lemma mk.inj_left {α β : Type*} (a : α) : function.injective (prod.mk a : β → α × β) := by { intros b₁ b₂ h, simpa only [true_and, prod.mk.inj_iff, eq_self_iff_true] using h } lemma mk.inj_right {α β : Type*} (b : β) : function.injective (λ a, prod.mk a b : α → α × β) := by { intros b₁ b₂ h, by simpa only [and_true, eq_self_iff_true, mk.inj_iff] using h } lemma mk_inj_left : (a, b₁) = (a, b₂) ↔ b₁ = b₂ := (mk.inj_left _).eq_iff lemma mk_inj_right : (a₁, b) = (a₂, b) ↔ a₁ = a₂ := (mk.inj_right _).eq_iff 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] @[ext] 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 lemma map_id : (prod.map (@id α) (@id β)) = id := id_prod lemma fst_surjective [h : nonempty β] : function.surjective (@fst α β) := λ x, h.elim $ λ y, ⟨⟨x, y⟩, rfl⟩ lemma snd_surjective [h : nonempty α] : function.surjective (@snd α β) := λ y, h.elim $ λ x, ⟨⟨x, y⟩, rfl⟩ lemma fst_injective [subsingleton β] : function.injective (@fst α β) := λ x y h, ext h (subsingleton.elim _ _) lemma snd_injective [subsingleton α] : function.injective (@snd α β) := λ x y h, ext (subsingleton.elim _ _) h /-- 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 swap_injective : function.injective (@swap α β) := swap_left_inverse.injective lemma swap_surjective : function.surjective (@swap α β) := swap_left_inverse.surjective lemma swap_bijective : function.bijective (@swap α β) := ⟨swap_injective, swap_surjective⟩ @[simp] lemma swap_inj {p q : α × β} : swap p = swap q ↔ p = q := swap_injective.eq_iff 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 lemma fst_eq_iff : ∀ {p : α × β} {x : α}, p.1 = x ↔ p = (x, p.2) | ⟨a, b⟩ x := by simp lemma snd_eq_iff : ∀ {p : α × β} {x : β}, p.2 = x ↔ p = (p.1, x) | ⟨a, b⟩ x := by simp variables {r : α → α → Prop} {s : β → β → Prop} {x y : α × β} 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⟩ lemma lex_iff : lex r s x y ↔ r x.1 y.1 ∨ x.1 = y.1 ∧ s x.2 y.2 := lex_def _ _ instance lex.decidable [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 @[refl] lemma lex.refl_left (r : α → α → Prop) (s : β → β → Prop) [is_refl α r] : ∀ x, prod.lex r s x x | (x₁, x₂) := lex.left _ _ (refl _) instance is_refl_left {r : α → α → Prop} {s : β → β → Prop} [is_refl α r] : is_refl (α × β) (lex r s) := ⟨lex.refl_left _ _⟩ @[refl] lemma lex.refl_right (r : α → α → Prop) (s : β → β → Prop) [is_refl β s] : ∀ x, prod.lex r s x x | (x₁, x₂) := lex.right _ (refl _) instance is_refl_right {r : α → α → Prop} {s : β → β → Prop} [is_refl β s] : is_refl (α × β) (lex r s) := ⟨lex.refl_right _ _⟩ instance is_irrefl [is_irrefl α r] [is_irrefl β s] : is_irrefl (α × β) (lex r s) := ⟨by rintro ⟨i, a⟩ (⟨_, _, h⟩ | ⟨_, h⟩); exact irrefl _ h⟩ @[trans] lemma lex.trans {r : α → α → Prop} {s : β → β → Prop} [is_trans α r] [is_trans β s] : ∀ {x y z : α × β}, prod.lex r s x y → prod.lex r s y z → prod.lex r s x z | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.left _ _ hxy₁) (lex.left _ _ hyz₁) := lex.left _ _ (trans hxy₁ hyz₁) | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.left _ _ hxy₁) (lex.right _ hyz₂) := lex.left _ _ hxy₁ | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.right _ _) (lex.left _ _ hyz₁) := lex.left _ _ hyz₁ | (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.right _ hxy₂) (lex.right _ hyz₂) := lex.right _ (trans hxy₂ hyz₂) instance {r : α → α → Prop} {s : β → β → Prop} [is_trans α r] [is_trans β s] : is_trans (α × β) (lex r s) := ⟨λ _ _ _, lex.trans⟩ instance {r : α → α → Prop} {s : β → β → Prop} [is_strict_order α r] [is_antisymm β s] : is_antisymm (α × β) (lex r s) := ⟨λ x₁ x₂ h₁₂ h₂₁, match x₁, x₂, h₁₂, h₂₁ with | (a₁, b₁), (a₂, b₂), lex.left _ _ hr₁, lex.left _ _ hr₂ := (irrefl a₁ (trans hr₁ hr₂)).elim | (a₁, b₁), (a₂, b₂), lex.left _ _ hr₁, lex.right _ _ := (irrefl _ hr₁).elim | (a₁, b₁), (a₂, b₂), lex.right _ _, lex.left _ _ hr₂ := (irrefl _ hr₂).elim | (a₁, b₁), (a₂, b₂), lex.right _ hs₁, lex.right _ hs₂ := antisymm hs₁ hs₂ ▸ rfl end⟩ instance is_total_left {r : α → α → Prop} {s : β → β → Prop} [is_total α r] : is_total (α × β) (lex r s) := ⟨λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, (is_total.total a₁ a₂).imp (lex.left _ _) (lex.left _ _)⟩ instance is_total_right {r : α → α → Prop} {s : β → β → Prop} [is_trichotomous α r] [is_total β s] : is_total (α × β) (lex r s) := ⟨λ ⟨i, a⟩ ⟨j, b⟩, begin obtain hij | rfl | hji := trichotomous_of r i j, { exact or.inl (lex.left _ _ hij) }, { exact (total_of (s) a b).imp (lex.right _) (lex.right _), }, { exact or.inr (lex.left _ _ hji) } end⟩ instance is_trichotomous [is_trichotomous α r] [is_trichotomous β s] : is_trichotomous (α × β) (lex r s) := ⟨λ ⟨i, a⟩ ⟨j, b⟩, begin obtain hij | rfl | hji := trichotomous_of r i j, { exact or.inl (lex.left _ _ hij) }, { exact (trichotomous_of s a b).imp3 (lex.right _) (congr_arg _) (lex.right _) }, { exact or.inr (or.inr $ lex.left _ _ hji) } end⟩ end prod open prod namespace function variables {f : α → γ} {g : β → δ} {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α} {g₂ : δ → γ} lemma injective.prod_map (hf : injective f) (hg : injective g) : injective (map f g) := λ x y h, ext (hf (ext_iff.1 h).1) (hg $ (ext_iff.1 h).2) lemma surjective.prod_map (hf : surjective f) (hg : surjective g) : surjective (map f g) := λ p, let ⟨x, hx⟩ := hf p.1 in let ⟨y, hy⟩ := hg p.2 in ⟨(x, y), prod.ext hx hy⟩ lemma bijective.prod_map (hf : bijective f) (hg : bijective g) : bijective (map f g) := ⟨hf.1.prod_map hg.1, hf.2.prod_map hg.2⟩ lemma left_inverse.prod_map (hf : left_inverse f₁ f₂) (hg : left_inverse g₁ g₂) : left_inverse (map f₁ g₁) (map f₂ g₂) := λ a, by rw [prod.map_map, hf.comp_eq_id, hg.comp_eq_id, map_id, id] lemma right_inverse.prod_map : right_inverse f₁ f₂ → right_inverse g₁ g₂ → right_inverse (map f₁ g₁) (map f₂ g₂) := left_inverse.prod_map lemma involutive.prod_map {f : α → α} {g : β → β} : involutive f → involutive g → involutive (map f g) := left_inverse.prod_map end function
ffa63c0e6285fc07647af09ae33af0196b361c42
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/struct_inst_exprs2.lean
f2d61502e99103b4d2148edda5fb5d5e322192a7
[ "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
564
lean
import data.nat.basic open nat structure s1 (A : Type) := (x : A) (y : A) (h : x = y) structure s2 (A : Type) := (mul : A → A → A) (one : A) structure s3 (A : Type) extends s1 A, s2 A := (mul_one : ∀ a : A, mul a one = a) definition v1 : s1 nat := {| s1, x := 10, y := 10, h := rfl |} definition v2 : s2 nat := {| s2, mul := nat.add, one := zero |} definition v3 : s3 nat := {| s3, mul_one := nat.add_zero, v1, v2 |} example : s3.x v3 = 10 := rfl example : s3.y v3 = 10 := rfl example : s3.mul v3 = nat.add := rfl example : s3.one v3 = nat.zero := rfl
a756f86ed3d59cac01b9482c363f3bdd0298d7a3
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/solutions/wednesday/afternoon/topological_spaces.lean
00b15144399493a63d4b063da0756c8e3b9240ad
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
19,394
lean
import tactic import data.set.finite import data.real.basic -- for metrics /- # (Re)-Building topological spaces in Lean Mathlib has a large library of results on topological spaces, including various constructions, separation axioms, Tychonoff's theorem, sheaves, Stone-Čech compactification, Heine-Cantor, to name but a few. See https://leanprover-community.github.io/theories/topology.html which for a (subset) of what's in library. But today we will ignore all that, and build our own version of topological spaces from scratch! (On Friday morning Patrick Massot will lead a session exploring the existing mathlib library in more detail) To get this file run either `leanproject get lftcm2020`, if you didn't already or cd to that folder and run `git pull; leanproject get-mathlib-cache`, this is `src/exercise_sources/wednesday/afternoon/topological_spaces.lean`. The exercises are spread throughout, you needn't do them in order! They are marked as short, medium and long, so I suggest you try some short ones first. First a little setup, we will be making definitions involving the real numbers, the theory of which is not computable, and we'll use sets. -/ noncomputable theory open set /-! ## What is a topological space: There are many definitions: one from Wikipedia: A topological space is an ordered pair (X, τ), where X is a set and τ is a collection of subsets of X, satisfying the following axioms: - The empty set and X itself belong to τ. - Any arbitrary (finite or infinite) union of members of τ still belongs to τ. - The intersection of any finite number of members of τ still belongs to τ. We can formalize this as follows: -/ class topological_space_wiki := (X : Type) -- the underlying Type that the topology will be on (τ : set (set X)) -- the set of open subsets of X (empty_mem : ∅ ∈ τ) -- empty set is open (univ_mem : univ ∈ τ) -- whole space is open (union : ∀ B ⊆ τ, ⋃₀ B ∈ τ) -- arbitrary unions (sUnions) of members of τ are open (inter : ∀ (B ⊆ τ) (h : finite B), ⋂₀ B ∈ τ) -- finite intersections of -- members of τ are open /- Before we go on we should be sure we want to use this as our definition. -/ -- omit /- (Changing your definitions later can be less of a hassle in formalized mathematics than pen and paper maths as the proof assistant will tell you exactly which steps in which proofs you broke, it can also be more of a hassle as you actually have to fix things, so its still best to get it right the first time!) -/ -- omit @[ext] class topological_space (X : Type) := (is_open : set X → Prop) -- why set X → Prop not set (set X)? former plays -- nicer with typeclasses later (empty_mem : is_open ∅) (univ_mem : is_open univ) (union : ∀ (B : set (set X)) (h : ∀ b ∈ B, is_open b), is_open (⋃₀ B)) (inter : ∀ (A B : set X) (hA : is_open A) (hB : is_open B), is_open (A ∩ B)) namespace topological_space /- We can now work with topological spaces like this. -/ example (X : Type) [topological_space X] (U V W : set X) (hU : is_open U) (hV : is_open V) (hW : is_open W) : is_open (U ∩ V ∩ W) := begin apply inter _ _ _ hW, exact inter _ _ hU hV, end /- ## Exercise 0 [short]: One of the axioms of a topological space we have here is unnecessary, it follows from the others. If we remove it we'll have less work to do each time we want to create a new topological space so: 1. Identify and remove the unneeded axiom, make sure to remove it throughout the file. 2. Add the axiom back as a lemma with the same name and prove it based on the others, so that the _interface_ is the same. -/ -- omit lemma empty_mem' (X : Type) [topological_space X] : is_open (∅ : set X) := begin convert union (∅ : set (set X)) _; simp, end -- omit /- Defining a basic topology now works like so: -/ def discrete (X : Type) : topological_space X := { is_open := λ U, true, -- everything is open empty_mem := trivial, univ_mem := trivial, union := begin intros B h, trivial, end, inter := begin intros A hA B hB, trivial, end } /- ## Exercise 1 [medium]: One way me might want to create topological spaces in practice is to take the coarsest possible topological space containing a given set of is_open. To define this we might say we want to define what `is_open` is given the set of generators. So we want to define the predicate `is_open` by declaring that each generator will be open, the intersection of two opens will be open, and each union of a set of opens will be open, and finally the empty and whole space (`univ`) must be open. The cleanest way to do this is as an inductive definition. The exercise is to make this definition of the topological space generated by a given set in Lean. ### Hint: As a hint for this exercise take a look at the following definition of a constructible set of a topological space, defined by saying that an intersection of an open and a closed set is constructible and that the union of any pair of constructible sets is constructible. (Bonus exercise: mathlib doesn't have any theory of constructible sets, make one and PR it! [arbitrarily long!], or just prove that open and closed sets are constructible for now) -/ inductive is_constructible {X : Type} (T : topological_space X) : set X → Prop /- Given two open sets in `T`, the intersection of one with the complement of the other open is locally closed, hence constructible: -/ | locally_closed : ∀ (A B : set X), is_open A → is_open B → is_constructible (A ∩ Bᶜ) -- Given two constructible sets their union is constructible: | union : ∀ A B, is_constructible A → is_constructible B → is_constructible (A ∪ B) -- For example we can now use this definition to prove the empty set is constructible example {X : Type} (T : topological_space X) : is_constructible T ∅ := begin -- The intersection of the whole space (open) with the empty set (closed) is -- locally closed, hence constructible have := is_constructible.locally_closed univ univ T.univ_mem T.univ_mem, -- but simp knows that's just the empty set (`simp` uses `this` automatically) simpa, end /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generated_open (X : Type) (g : set (set X)) : set X → Prop -- The exercise: Add a definition here defining which sets are generated by `g` like the -- `is_constructible` definition above. -- omit | basic : ∀ s ∈ g, generated_open s | univ : generated_open univ | inter : ∀s t, generated_open s → generated_open t → generated_open (s ∩ t) | sUnion : ∀k, (∀ s ∈ k, generated_open s) → generated_open (⋃₀ k) lemma generated_open.empty (X : Type) (g : set (set X)) : generated_open X g ∅ := begin have := generated_open.sUnion (∅ : set (set X)), simpa, end -- omit /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (X : Type) (g : set (set X)) : topological_space X := { is_open := generated_open X g, empty_mem := /- inline sorry -/generated_open.empty X g/- inline sorry -/, univ_mem := /- inline sorry -/generated_open.univ/- inline sorry -/, inter := /- inline sorry -/generated_open.inter/- inline sorry -/, union := /- inline sorry -/generated_open.sUnion/- inline sorry -/ } /- ## Exercise 2 [short]: Define the indiscrete topology on any type using this. (To do it without this it is surprisingly fiddly to prove that the set `{∅, univ}` actually forms a topology) -/ def indiscrete (X : Type) : topological_space X := /- inline sorry -/ generate_from X ∅ /- inline sorry -/ end topological_space open topological_space /- Now it is quite easy to give a topology on the product of a pair of topological spaces. -/ instance prod.topological_space (X Y : Type) [topological_space X] [topological_space Y] : topological_space (X × Y) := topological_space.generate_from (X × Y) {U | ∃ (Ux : set X) (Uy : set Y) (hx : is_open Ux) (hy : is_open Uy), U = set.prod Ux Uy} -- the proof of this is bit long so I've left it out for the purpose of this file! lemma is_open_prod_iff (X Y : Type) [topological_space X] [topological_space Y] {s : set (X × Y)} : 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) := sorry /- # Metric spaces -/ open_locale big_operators class metric_space_basic (X : Type) := (dist : X → X → ℝ) (dist_eq_zero_iff : ∀ x y, dist x y = 0 ↔ x = y) (dist_symm : ∀ x y, dist x y = dist y x) (triangle : ∀ x y z, dist x z ≤ dist x y + dist y z) namespace metric_space_basic open topological_space /- ## Exercise 3 [short]: We have defined a metric space with a metric landing in ℝ, and made no mention of nonnegativity, (this is in line with the philosophy of using the easiest axioms for our definitions as possible, to make it easier to define individual metrics). Show that we really did define the usual notion of metric space. -/ lemma dist_nonneg {X : Type} [metric_space_basic X] (x y : X) : 0 ≤ dist x y := -- sorry begin have := calc 0 = dist x x : by rw (dist_eq_zero_iff x x).mpr rfl ... ≤ dist x y + dist y x : triangle x y x ... = dist x y + dist x y : by rw dist_symm ... = 2 * dist x y : by rw two_mul (dist x y), linarith, end -- sorry /- From a metric space we get an induced topological space structure like so: -/ instance {X : Type} [metric_space_basic X] : topological_space X := generate_from X { B | ∃ (x : X) r, B = {y | dist x y < r} } end metric_space_basic open metric_space_basic /- So far so good, now lets define the product of two metric spaces: ## Exercise 4 [medium]: Fill in the proofs here. Hint: the computer can do boring casework you would never dream of in real life. `max` is defined as `if x < y then y else x` and the `split_ifs` tactic will break apart if statements. -/ instance prod.metric_space_basic (X Y : Type) [metric_space_basic X] [metric_space_basic Y] : metric_space_basic (X × Y) := { dist := λ u v, max (dist u.fst v.fst) (dist u.snd v.snd), dist_eq_zero_iff := -- sorry begin intros u v, split; intro h, { have hf := dist_nonneg u.fst v.fst, have hs := dist_nonneg u.snd v.snd, have := max_le_iff.mp (le_of_eq h), ext; rw ← dist_eq_zero_iff; linarith, }, { rw [h, (dist_eq_zero_iff _ _).mpr, (dist_eq_zero_iff _ _).mpr, max_self]; refl, }, end -- sorry , dist_symm := /- inline sorry -/ begin intros u v, simp [metric_space_basic.dist_symm], end /- inline sorry -/, triangle := -- sorry begin intros x y z, have hf := triangle x.fst y.fst z.fst, have hs := triangle x.snd y.snd z.snd, simp only [max], split_ifs; linarith, end -- sorry } /- ☡ Let's try to prove a simple lemma involving the product topology: ☡ -/ -- omit set_option pp.all false set_option trace.class_instances false set_option trace.type_context.is_def_eq_detail false -- omit set_option trace.type_context.is_def_eq false example (X : Type) [metric_space_basic X] : is_open {xy : X × X | dist xy.fst xy.snd < 100 } := begin rw is_open_prod_iff X X, -- this fails, why? Because we have two subtly different topologies on the product -- they are equal but the proof that they are equal is nontrivial and the -- typeclass mechanism can't see that they automatically to apply. We need to change -- our set-up. sorry, end /- Note that lemma works fine when there is only one topology involved. -/ lemma diag_closed (X : Type) [topological_space X] : is_open {xy : X × X | xy.fst ≠ xy.snd } := begin rw is_open_prod_iff X X, sorry, -- Don't try and fill this in: see below! end /- ## Exercise 5 [short]: The previous lemma isn't true! It requires a separation axiom. Define a `class` that posits that the topology on a type `X` satisfies this axiom. Mathlib uses `T_i` naming scheme for these axioms. -/ class t2_space (X : Type) [topological_space X] := (t2 : /- inline sorry -/ ∀ x y : X, ∃ (Ux Uy : set X) (hUx : is_open Ux) (hUy : is_open Uy) (hx : x ∈ Ux) (hy : y ∈ Uy), Ux ∩ Uy = ∅ /- inline sorry -/) /- (Bonus exercises [medium], the world is your oyster: prove the correct version of the above lemma `diag_closed`, prove that the discrete topology is t2, or that any metric topology is t2, ). -/ -- omit example (X : Type) [topological_space X] [t2_space X] : is_open {xy : X × X | xy.fst ≠ xy.snd } := begin rw is_open_prod_iff X X, intros x y h, obtain ⟨Ux, Uy, hUx, hUy, hx, hy, hxy⟩ := t2_space.t2 x y, use [Ux, Uy, hUx, hUy, hx, hy], rintros ⟨tx, ty⟩ ⟨ht1, ht2⟩, dsimp, intro txy, rw txy at *, have : ty ∈ Ux ∩ Uy := ⟨ht1, ht2⟩, rw hxy at this, exact this, -- exact not_mem_empty ty this, end -- omit /- Let's fix the broken example from earlier, by redefining the topology on a metric space. We have unfortunately created two topologies on `X × Y`, one via `prod.topology` that we defined earlier as the product of the two topologies coming from the respective metric space structures. And one coming from the metric on the product. These are equal, i.e. the same topology (otherwise mathematically the product would not be a good definition). However they are not definitionally equal, there is as nontrivial proof to show they are the same. The typeclass system (which finds the relevant topological space instance when we use lemmas involving topological spaces) isn't able to check that topological space structures which are equal for some nontrivial reason are equal on the fly so it gets stuck. We can use `extends` to say that a metric space is an extra structure on top of being a topological space so we are making a choice of topology for each metric space. This may not be *definitionally* equal to the induced topology, but we should add the axiom that the metric and the topology are equal to stop us from creating a metric inducing a different topology to the topological structure we chose. -/ class metric_space (X : Type) extends topological_space X, metric_space_basic X := (compatible : ∀ U, is_open U ↔ generated_open X { B | ∃ (x : X) r, B = {y | dist x y < r}} U) namespace metric_space open topological_space /- This might seem a bit inconvenient to have to define a topological space each time we want a metric space. We would still like a way of making a `metric_space` just given a metric and some properties it satisfies, i.e. a `metric_space_basic`, so we should setup a metric space constructor from a `metric_space_basic` by setting the topology to be the induced one. -/ def of_basic {X : Type} (m : metric_space_basic X) : metric_space X := { compatible := begin intros, refl, /- this should when the above parts are complete -/ end, ..m, ..@metric_space_basic.topological_space X m } /- Now lets define the product of two metric spaces properly -/ instance {X Y : Type} [metric_space X] [metric_space Y] : metric_space (X × Y) := { compatible := begin -- Let's not fill this in for the demo, let me know if you do it! -- sorry rintros U, rw is_open_prod_iff, split; intro h, sorry, sorry, -- sorry end, ..prod.topological_space X Y, ..prod.metric_space_basic X Y, } /- Now this will work, there is only one topological space on the product, we can rewrite like we tried to before a lemma about topologies our result on metric spaces, as there is only one topology here. ## Exercise 6 [long?]: Complete the proof of the example (you can generalise the 100 too if it makes it feel less silly). -/ example (X : Type) [metric_space X] : is_open {xy : X × X | dist xy.fst xy.snd < 100 } := begin rw is_open_prod_iff X X, -- sorry intros x y h, use [{t | dist x t < 50 - dist x y / 2}, {t | dist y t < 50 - dist x y / 2}], split, { rw compatible, apply generated_open.basic, use [x, 50 - dist x y / 2], }, split, { rw compatible, apply generated_open.basic, use [y, 50 - dist x y / 2], }, split, { dsimp, rw (metric_space_basic.dist_eq_zero_iff x x).mpr rfl, change dist x y < 100 at h, linarith, }, split, { dsimp, rw (metric_space_basic.dist_eq_zero_iff y y).mpr rfl, change dist x y < 100 at h, linarith, }, rintros ⟨tx, ty⟩ ⟨htx, hty⟩, dsimp at *, calc dist tx ty ≤ dist tx x + dist x ty : triangle tx x ty ... ≤ dist tx x + dist x y + dist y ty : by linarith [triangle x y ty] ... = dist x tx + dist x y + dist y ty : by rw dist_symm ... < 100 : by linarith, -- sorry end end metric_space namespace topological_space /- As mentioned, there are many definitions of a topological space, for instance one can define them via specifying a set of closed sets satisfying various axioms, this is equivalent and sometimes more convenient. We _could_ create two distinct Types defined by different data and provide an equivalence between theses types, e.g. `topological_space_via_open_sets` and `topological_space_via_closed_sets`, but this would quickly get unwieldy. What's better is to make an alternative _constructor_ for our original topological space. This is a function takes a set of subsets satisfying the axioms to be the closed sets of a topological space and creates the topological space defined by the corresponding set of open sets. ## Exercise 7 [medium]: Complete the following constructor of a topological space from a set of subsets of a given type `X` satisfying the axioms for the closed sets of a topology. Hint: there are many useful lemmas about complements in mathlib, with names involving `compl`, like `compl_empty`, `compl_univ`, `compl_compl`, `compl_sUnion`, `mem_compl_image`, `compl_inter`, `compl_compl'`, `you can #check them to see what they say. -/ def mk_closed_sets (X : Type) (σ : set (set X)) (empty_mem : ∅ ∈ σ) (univ_mem : univ ∈ σ) (inter : ∀ B ⊆ σ, ⋂₀ B ∈ σ) (union : ∀ (A ∈ σ) (B ∈ σ), A ∪ B ∈ σ) : topological_space X := { is_open := λ U, U ∈ compl '' σ, -- the corresponding `is_open` empty_mem := -- sorry begin use univ, split, assumption, exact compl_univ, end -- sorry , univ_mem := -- sorry begin use ∅, split, assumption, exact compl_empty, end -- sorry , union := -- sorry begin intros B hB, use (⋃₀ B)ᶜ, split, { rw compl_sUnion, apply inter, intros b hb, have := hB bᶜ ((mem_compl_image b B).mp hb), rw mem_compl_image at this, simpa, }, exact compl_compl', end -- sorry , inter := -- sorry begin rintros A B ⟨Ac, hA, rfl⟩ ⟨Bc, hB, rfl⟩, rw [mem_compl_image, compl_inter, compl_compl, compl_compl], exact union _ hA _ hB, end -- sorry } /- Here are some more exercises: ## Exercise 8 [medium/long]: Define the cofinite topology on any type (PR it to mathlib?). ## Exercise 9 [medium/long]: Define a normed space? ## Exercise 10 [medium/long]: Define more separation axioms? -/ end topological_space
2f8f2f31ce20875a4ca9e04e9a2b275a4db0e02d
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/implicit.lean
e0c2a6d90832f8be556b3a25ef888205c7f483a2
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
206
lean
definition f {A : Type} {B : Type} (f : A → B → Prop) ⦃C : Type⦄ {R : C → C → Prop} {c : C} (H : R c c) : R c c := H constant g : Prop → Prop → Prop constant H : true ∧ true check f g H
f4c48c49edc6b3019b5d3ec48ad6b431eb5989cf
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/combinatorics/colex.lean
8e98a64abddb066145fc2d054b3c9e6bb520f160
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,100
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Alena Gusakov -/ import data.finset import data.fintype.basic import algebra.geom_sum /-! # Colex We define the colex ordering for finite sets, and give a couple of important lemmas and properties relating to it. The colex ordering likes to avoid large values - it can be thought of on `finset ℕ` as the "binary" ordering. That is, order A based on `∑_{i ∈ A} 2^i`. It's defined here in a slightly more general way, requiring only `has_lt α` in the definition of colex on `finset α`. In the context of the Kruskal-Katona theorem, we are interested in particular on how colex behaves for sets of a fixed size. If the size is 3, colex on ℕ starts 123, 124, 134, 234, 125, 135, 235, 145, 245, 345, ... ## Main statements * `colex.hom_lt_iff`: strictly monotone functions preserve colex * Colex order properties - linearity, decidability and so on. * `forall_lt_of_colex_lt_of_forall_lt`: if A < B in colex, and everything in B is < t, then everything in A is < t. This confirms the idea that an enumeration under colex will exhaust all sets using elements < t before allowing t to be included. * `sum_two_pow_le_iff_lt`: colex for α = ℕ is the same as binary (this also proves binary expansions are unique) ## Notation We define `<` and `≤` to denote colex ordering, useful in particular when multiple orderings are available in context. ## Tags colex, colexicographic, binary ## References * https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf -/ variable {α : Type*} open finset open_locale big_operators /-- We define this type synonym to refer to the colexicographic ordering on finsets rather than the natural subset ordering. -/ @[derive inhabited] def finset.colex (α) := finset α /-- A convenience constructor to turn a `finset α` into a `finset.colex α`, useful in order to use the colex ordering rather than the subset ordering. -/ def finset.to_colex {α} (s : finset α) : finset.colex α := s @[simp] lemma colex.eq_iff (A B : finset α) : A.to_colex = B.to_colex ↔ A = B := iff.rfl /-- `A` is less than `B` in the colex ordering if the largest thing that's not in both sets is in B. In other words, max (A Δ B) ∈ B (if the maximum exists). -/ instance [has_lt α] : has_lt (finset.colex α) := ⟨λ (A B : finset α), ∃ (k : α), (∀ {x}, k < x → (x ∈ A ↔ x ∈ B)) ∧ k ∉ A ∧ k ∈ B⟩ /-- We can define (≤) in the obvious way. -/ instance [has_lt α] : has_le (finset.colex α) := ⟨λ A B, A < B ∨ A = B⟩ lemma colex.lt_def [has_lt α] (A B : finset α) : A.to_colex < B.to_colex ↔ ∃ k, (∀ {x}, k < x → (x ∈ A ↔ x ∈ B)) ∧ k ∉ A ∧ k ∈ B := iff.rfl lemma colex.le_def [has_lt α] (A B : finset α) : A.to_colex ≤ B.to_colex ↔ A.to_colex < B.to_colex ∨ A = B := iff.rfl /-- If everything in `A` is less than `k`, we can bound the sum of powers. -/ lemma nat.sum_two_pow_lt {k : ℕ} {A : finset ℕ} (h₁ : ∀ {x}, x ∈ A → x < k) : A.sum (pow 2) < 2^k := begin apply lt_of_le_of_lt (sum_le_sum_of_subset (λ t, mem_range.2 ∘ h₁)), have z := geom_sum_mul_add 1 k, rw [geom_sum, mul_one, one_add_one_eq_two] at z, rw ← z, apply nat.lt_succ_self, end namespace colex /-- Strictly monotone functions preserve the colex ordering. -/ lemma hom_lt_iff {β : Type*} [linear_order α] [decidable_eq β] [preorder β] {f : α → β} (h₁ : strict_mono f) (A B : finset α) : (A.image f).to_colex < (B.image f).to_colex ↔ A.to_colex < B.to_colex := begin simp only [colex.lt_def, not_exists, mem_image, exists_prop, not_and], split, { rintro ⟨k, z, q, k', _, rfl⟩, exact ⟨k', λ x hx, by simpa [h₁.injective.eq_iff] using z (h₁ hx), λ t, q _ t rfl, ‹k' ∈ B›⟩ }, rintro ⟨k, z, ka, _⟩, refine ⟨f k, λ x hx, _, _, k, ‹k ∈ B›, rfl⟩, { split, any_goals { rintro ⟨x', hx', rfl⟩, refine ⟨x', _, rfl⟩, rwa ← z _ <|> rwa z _, rwa strict_mono.lt_iff_lt h₁ at hx } }, { simp only [h₁.injective, function.injective.eq_iff], exact λ x hx, ne_of_mem_of_not_mem hx ka } end /-- A special case of `colex.hom_lt_iff` which is sometimes useful. -/ @[simp] lemma hom_fin_lt_iff {n : ℕ} (A B : finset (fin n)) : (A.image (λ i : fin n, (i : ℕ))).to_colex < (B.image (λ i : fin n, (i : ℕ))).to_colex ↔ A.to_colex < B.to_colex := colex.hom_lt_iff (λ x y k, k) _ _ instance [has_lt α] : is_irrefl (finset.colex α) (<) := ⟨λ A h, exists.elim h (λ _ ⟨_,a,b⟩, a b)⟩ @[trans] lemma lt_trans [linear_order α] {a b c : finset.colex α} : a < b → b < c → a < c := begin rintros ⟨k₁, k₁z, notinA, inB⟩ ⟨k₂, k₂z, notinB, inC⟩, cases lt_or_gt_of_ne (ne_of_mem_of_not_mem inB notinB), { refine ⟨k₂, _, by rwa k₁z h, inC⟩, intros x hx, rw ← k₂z hx, apply k₁z (trans h hx) }, { refine ⟨k₁, _, notinA, by rwa ← k₂z h⟩, intros x hx, rw k₁z hx, apply k₂z (trans h hx) } end @[trans] lemma le_trans [linear_order α] (a b c : finset.colex α) : a ≤ b → b ≤ c → a ≤ c := λ AB BC, AB.elim (λ k, BC.elim (λ t, or.inl (lt_trans k t)) (λ t, t ▸ AB)) (λ k, k.symm ▸ BC) instance [linear_order α] : is_trans (finset.colex α) (<) := ⟨λ _ _ _, colex.lt_trans⟩ lemma lt_trichotomy [linear_order α] (A B : finset.colex α) : A < B ∨ A = B ∨ B < A := begin by_cases h₁ : (A = B), { tauto }, rcases (exists_max_image (A \ B ∪ B \ A) id _) with ⟨k, hk, z⟩, { simp only [mem_union, mem_sdiff] at hk, cases hk, { right, right, refine ⟨k, λ t th, _, hk.2, hk.1⟩, specialize z t, by_contra h₂, simp only [mem_union, mem_sdiff, id.def] at z, rw [not_iff, iff_iff_and_or_not_and_not, not_not, and_comm] at h₂, apply not_le_of_lt th (z h₂) }, { left, refine ⟨k, λ t th, _, hk.2, hk.1⟩, specialize z t, by_contra h₃, simp only [mem_union, mem_sdiff, id.def] at z, rw [not_iff, iff_iff_and_or_not_and_not, not_not, and_comm, or_comm] at h₃, apply not_le_of_lt th (z h₃) }, }, rw nonempty_iff_ne_empty, intro a, simp only [union_eq_empty_iff, sdiff_eq_empty_iff_subset] at a, apply h₁ (subset.antisymm a.1 a.2) end instance [linear_order α] : is_trichotomous (finset.colex α) (<) := ⟨lt_trichotomy⟩ instance decidable_lt [linear_order α] : ∀ {A B : finset.colex α}, decidable (A < B) := show ∀ A B : finset α, decidable (A.to_colex < B.to_colex), from λ A B, decidable_of_iff' (∃ (k ∈ B), (∀ x ∈ A ∪ B, k < x → (x ∈ A ↔ x ∈ B)) ∧ k ∉ A) begin rw colex.lt_def, apply exists_congr, simp only [mem_union, exists_prop, or_imp_distrib, and_comm (_ ∈ B), and_assoc], intro k, refine and_congr_left' (forall_congr _), tauto, end instance [linear_order α] : linear_order (finset.colex α) := { le_refl := λ A, or.inr rfl, le_trans := le_trans, le_antisymm := λ A B AB BA, AB.elim (λ k, BA.elim (λ t, (asymm k t).elim) (λ t, t.symm)) id, le_total := λ A B, (lt_trichotomy A B).elim3 (or.inl ∘ or.inl) (or.inl ∘ or.inr) (or.inr ∘ or.inl), decidable_le := λ A B, by apply_instance, decidable_lt := λ A B, by apply_instance, decidable_eq := λ A B, by apply_instance, lt_iff_le_not_le := λ A B, begin split, { intro t, refine ⟨or.inl t, _⟩, rintro (i | rfl), { apply asymm_of _ t i }, { apply irrefl _ t } }, rintro ⟨h₁ | rfl, h₂⟩, { apply h₁ }, apply h₂.elim (or.inr rfl), end, ..finset.colex.has_lt, ..finset.colex.has_le } /-- The instances set up let us infer that `colex.lt` is a strict total order. -/ example [linear_order α] : is_strict_total_order (finset.colex α) (<) := infer_instance /-- Strictly monotone functions preserve the colex ordering. -/ lemma hom_le_iff {β : Type*} [linear_order α] [linear_order β] {f : α → β} (h₁ : strict_mono f) (A B : finset α) : (A.image f).to_colex ≤ (B.image f).to_colex ↔ A.to_colex ≤ B.to_colex := by rw [le_iff_le_iff_lt_iff_lt, hom_lt_iff h₁] /-- A special case of `colex_hom` which is sometimes useful. -/ @[simp] lemma hom_fin_le_iff {n : ℕ} (A B : finset (fin n)) : (A.image (λ i : fin n, (i : ℕ))).to_colex ≤ (B.image (λ i : fin n, (i : ℕ))).to_colex ↔ A.to_colex ≤ B.to_colex := colex.hom_le_iff (λ x y k, k) _ _ /-- If `A` is before `B` in colex, and everything in `B` is small, then everything in `A` is small. -/ lemma forall_lt_of_colex_lt_of_forall_lt [linear_order α] {A B : finset α} (t : α) (h₁ : A.to_colex < B.to_colex) (h₂ : ∀ x ∈ B, x < t) : ∀ x ∈ A, x < t := begin rw colex.lt_def at h₁, rcases h₁ with ⟨k, z, _, _⟩, intros x hx, apply lt_of_not_ge, intro a, refine not_lt_of_ge a (h₂ x _), rwa ← z, apply lt_of_lt_of_le (h₂ k ‹_›) a, end /-- `s.to_colex < {r}.to_colex` iff all elements of `s` are less than `r`. -/ lemma lt_singleton_iff_mem_lt [linear_order α] {r : α} {s : finset α} : s.to_colex < ({r} : finset α).to_colex ↔ ∀ x ∈ s, x < r := begin simp only [lt_def, mem_singleton, ←and_assoc, exists_eq_right], split, { intros t x hx, rw ←not_le, intro h, rcases lt_or_eq_of_le h with h₁ | rfl, { exact ne_of_irrefl h₁ ((t.1 h₁).1 hx).symm }, { exact t.2 hx } }, { exact λ h, ⟨λ z hz, ⟨λ i, (asymm hz (h _ i)).elim, λ i, (hz.ne' i).elim⟩, by simpa using h r⟩ } end /-- If {r} is less than or equal to s in the colexicographical sense, then s contains an element greater than or equal to r. -/ lemma mem_le_of_singleton_le [linear_order α] {r : α} {s : finset α}: ({r} : finset α).to_colex ≤ s.to_colex ↔ ∃ x ∈ s, r ≤ x := by { rw ←not_lt, simp [lt_singleton_iff_mem_lt] } /-- Colex is an extension of the base ordering on α. -/ lemma singleton_lt_iff_lt [linear_order α] {r s : α} : ({r} : finset α).to_colex < ({s} : finset α).to_colex ↔ r < s := by simp [lt_singleton_iff_mem_lt] /-- Colex is an extension of the base ordering on α. -/ lemma singleton_le_iff_le [linear_order α] {r s : α} : ({r} : finset α).to_colex ≤ ({s} : finset α).to_colex ↔ r ≤ s := by rw [le_iff_le_iff_lt_iff_lt, singleton_lt_iff_lt] /-- Colex doesn't care if you remove the other set -/ @[simp] lemma sdiff_lt_sdiff_iff_lt [has_lt α] [decidable_eq α] (A B : finset α) : (A \ B).to_colex < (B \ A).to_colex ↔ A.to_colex < B.to_colex := begin rw [colex.lt_def, colex.lt_def], apply exists_congr, intro k, simp only [mem_sdiff, not_and, not_not], split, { rintro ⟨z, kAB, kB, kA⟩, refine ⟨_, kA, kB⟩, { intros x hx, specialize z hx, tauto } }, { rintro ⟨z, kA, kB⟩, refine ⟨_, λ _, kB, kB, kA⟩, intros x hx, rw z hx }, end /-- Colex doesn't care if you remove the other set -/ @[simp] lemma sdiff_le_sdiff_iff_le [linear_order α] (A B : finset α) : (A \ B).to_colex ≤ (B \ A).to_colex ↔ A.to_colex ≤ B.to_colex := by rw [le_iff_le_iff_lt_iff_lt, sdiff_lt_sdiff_iff_lt] lemma empty_to_colex_lt [linear_order α] {A : finset α} (hA : A.nonempty) : (∅ : finset α).to_colex < A.to_colex := begin rw [colex.lt_def], refine ⟨max' _ hA, _, by simp, max'_mem _ _⟩, simp only [false_iff, not_mem_empty], intros x hx t, apply not_le_of_lt hx (le_max' _ _ t), end /-- If `A ⊂ B`, then `A` is less than `B` in the colex order. Note the converse does not hold, as `⊆` is not a linear order. -/ lemma colex_lt_of_ssubset [linear_order α] {A B : finset α} (h : A ⊂ B) : A.to_colex < B.to_colex := begin rw [←sdiff_lt_sdiff_iff_lt, sdiff_eq_empty_iff_subset.2 h.1], exact empty_to_colex_lt (by simpa [finset.nonempty] using exists_of_ssubset h), end @[simp] lemma empty_to_colex_le [linear_order α] {A : finset α} : (∅ : finset α).to_colex ≤ A.to_colex := begin rcases A.eq_empty_or_nonempty with rfl | hA, { simp }, { apply (empty_to_colex_lt hA).le }, end /-- If `A ⊆ B`, then `A ≤ B` in the colex order. Note the converse does not hold, as `⊆` is not a linear order. -/ lemma colex_le_of_subset [linear_order α] {A B : finset α} (h : A ⊆ B) : A.to_colex ≤ B.to_colex := begin rw [←sdiff_le_sdiff_iff_le, sdiff_eq_empty_iff_subset.2 h], apply empty_to_colex_le end /-- The function from finsets to finsets with the colex order is a relation homomorphism. -/ @[simps] def to_colex_rel_hom [linear_order α] : ((⊆) : finset α → finset α → Prop) →r ((≤) : finset.colex α → finset.colex α → Prop) := { to_fun := finset.to_colex, map_rel' := λ A B, colex_le_of_subset } instance [linear_order α] : order_bot (finset.colex α) := { bot := (∅ : finset α).to_colex, bot_le := λ x, empty_to_colex_le } instance [linear_order α] [fintype α] : order_top (finset.colex α) := { top := finset.univ.to_colex, le_top := λ x, colex_le_of_subset (subset_univ _) } instance [linear_order α] : semilattice_inf_bot (finset.colex α) := { ..finset.colex.order_bot, ..(by apply_instance : semilattice_inf (finset.colex α)) } instance [linear_order α] : semilattice_sup_bot (finset.colex α) := { ..finset.colex.order_bot, ..(by apply_instance : semilattice_sup (finset.colex α)) } instance [linear_order α] [fintype α] : bounded_lattice (finset.colex α) := { ..(by apply_instance : order_top (finset.colex α)), ..(by apply_instance : semilattice_sup (finset.colex α)), ..(by apply_instance : semilattice_inf_bot (finset.colex α)) } /-- For subsets of ℕ, we can show that colex is equivalent to binary. -/ lemma sum_two_pow_lt_iff_lt (A B : finset ℕ) : ∑ i in A, 2^i < ∑ i in B, 2^i ↔ A.to_colex < B.to_colex := begin have z : ∀ (A B : finset ℕ), A.to_colex < B.to_colex → ∑ i in A, 2^i < ∑ i in B, 2^i, { intros A B, rw [← sdiff_lt_sdiff_iff_lt, colex.lt_def], rintro ⟨k, z, kA, kB⟩, rw ← sdiff_union_inter A B, conv_rhs { rw ← sdiff_union_inter B A }, rw [sum_union (disjoint_sdiff_inter _ _), sum_union (disjoint_sdiff_inter _ _), inter_comm, add_lt_add_iff_right], apply lt_of_lt_of_le (@nat.sum_two_pow_lt k (A \ B) _), { apply single_le_sum (λ _ _, nat.zero_le _) kB }, intros x hx, apply lt_of_le_of_ne (le_of_not_lt (λ kx, _)), { apply (ne_of_mem_of_not_mem hx kA) }, have := (z kx).1 hx, rw mem_sdiff at this hx, exact hx.2 this.1 }, refine ⟨λ h, (lt_trichotomy A B).resolve_right (λ h₁, h₁.elim _ (not_lt_of_gt h ∘ z _ _)), z A B⟩, rintro rfl, apply irrefl _ h end /-- For subsets of ℕ, we can show that colex is equivalent to binary. -/ lemma sum_two_pow_le_iff_lt (A B : finset ℕ) : ∑ i in A, 2^i ≤ ∑ i in B, 2^i ↔ A.to_colex ≤ B.to_colex := by rw [le_iff_le_iff_lt_iff_lt, sum_two_pow_lt_iff_lt] end colex
fb6a86ec5b2eeee20fae5cda56bcfee3fa2a3de6
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/tests/lean/run/rewriter7.lean
8a9787e4326d094488227966bf0d75bc7928e589
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
262
lean
import data.int open int constant f : int → int definition double (x : int) := x + x theorem tst1 (x y : int) (H1 : double x = 0) (H2 : double y = 0) (H3 : f (double y) = 0) (H4 : y > 0) : f (x + x) = 0 := by rewrite ⟨↑double at H1, H1, H2 at H3, H3⟩
af24bbfc832b960d1a24327cfc96a0786ced4347
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/order/bounds.lean
5c9aedc4daa128ff1c3b43e8358faede2926cdf7
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
5,652
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 (Least / Greatest) upper / lower bounds -/ import order.complete_lattice open set lattice universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a a₁ a₂ : α} {b b₁ b₂ : β} {s t : set α} section preorder variables [preorder α] [preorder β] {f : α → β} def upper_bounds (s : set α) : set α := { x | ∀a ∈ s, a ≤ x } def lower_bounds (s : set α) : set α := { x | ∀a ∈ s, x ≤ a } def is_least (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ lower_bounds s def is_greatest (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ upper_bounds s def is_lub (s : set α) : α → Prop := is_least (upper_bounds s) def is_glb (s : set α) : α → Prop := is_greatest (lower_bounds s) lemma mem_upper_bounds_image (Hf : monotone f) (Ha : a ∈ upper_bounds s) : f a ∈ upper_bounds (f '' s) := ball_image_of_ball (assume x H, Hf (Ha _ ‹x ∈ s›)) lemma mem_lower_bounds_image (Hf : monotone f) (Ha : a ∈ lower_bounds s) : f a ∈ lower_bounds (f '' s) := ball_image_of_ball (assume x H, Hf (Ha _ ‹x ∈ s›)) lemma is_lub_singleton {a : α} : is_lub {a} a := by simp [is_lub, is_least, upper_bounds, lower_bounds] {contextual := tt} lemma is_glb_singleton {a : α} : is_glb {a} a := by simp [is_glb, is_greatest, upper_bounds, lower_bounds] {contextual := tt} end preorder section partial_order variables [partial_order α] lemma eq_of_is_least_of_is_least (Ha : is_least s a₁) (Hb : is_least s a₂) : a₁ = a₂ := le_antisymm (Ha.right _ Hb.left) (Hb.right _ Ha.left) lemma is_least_iff_eq_of_is_least (Ha : is_least s a₁) : is_least s a₂ ↔ a₁ = a₂ := iff.intro (eq_of_is_least_of_is_least Ha) (assume h, h ▸ Ha) lemma eq_of_is_greatest_of_is_greatest (Ha : is_greatest s a₁) (Hb : is_greatest s a₂) : a₁ = a₂ := le_antisymm (Hb.right _ Ha.left) (Ha.right _ Hb.left) lemma is_greatest_iff_eq_of_is_greatest (Ha : is_greatest s a₁) : is_greatest s a₂ ↔ a₁ = a₂ := iff.intro (eq_of_is_greatest_of_is_greatest Ha) (assume h, h ▸ Ha) lemma eq_of_is_lub_of_is_lub : is_lub s a₁ → is_lub s a₂ → a₁ = a₂ := eq_of_is_least_of_is_least lemma is_lub_iff_eq_of_is_lub : is_lub s a₁ → (is_lub s a₂ ↔ a₁ = a₂) := is_least_iff_eq_of_is_least lemma eq_of_is_glb_of_is_glb : is_glb s a₁ → is_glb s a₂ → a₁ = a₂ := eq_of_is_greatest_of_is_greatest lemma is_glb_iff_eq_of_is_glb : is_glb s a₁ → (is_glb s a₂ ↔ a₁ = a₂) := is_greatest_iff_eq_of_is_greatest lemma ne_empty_of_is_lub [no_bot_order α] (hs : is_lub s a) : s ≠ ∅ := let ⟨a', ha'⟩ := no_bot a in assume h, have a ≤ a', from hs.right _ (by simp [upper_bounds, h]), lt_irrefl a $ lt_of_le_of_lt this ha' lemma ne_empty_of_is_glb [no_top_order α] (hs : is_glb s a) : s ≠ ∅ := let ⟨a', ha'⟩ := no_top a in assume h, have a' ≤ a, from hs.right _ (by simp [lower_bounds, h]), lt_irrefl a $ lt_of_lt_of_le ha' this end partial_order section lattice lemma is_glb_empty [order_top α] : is_glb ∅ (⊤:α) := by simp [is_glb, is_greatest, lower_bounds, upper_bounds] lemma is_lub_empty [order_bot α] : is_lub ∅ (⊥:α) := by simp [is_lub, is_least, lower_bounds, upper_bounds] lemma is_lub_union_sup [semilattice_sup α] (hs : is_lub s a₁) (ht : is_lub t a₂) : is_lub (s ∪ t) (a₁ ⊔ a₂) := ⟨assume c h, h.cases_on (le_sup_left_of_le ∘ hs.left c) (le_sup_right_of_le ∘ ht.left c), assume c hc, sup_le (hs.right _ $ assume d hd, hc _ $ or.inl hd) (ht.right _ $ assume d hd, hc _ $ or.inr hd)⟩ lemma is_glb_union_inf [semilattice_inf α] (hs : is_glb s a₁) (ht : is_glb t a₂) : is_glb (s ∪ t) (a₁ ⊓ a₂) := ⟨assume c h, h.cases_on (inf_le_left_of_le ∘ hs.left c) (inf_le_right_of_le ∘ ht.left c), assume c hc, le_inf (hs.right _ $ assume d hd, hc _ $ or.inl hd) (ht.right _ $ assume d hd, hc _ $ or.inr hd)⟩ lemma is_lub_insert_sup [semilattice_sup α] (h : is_lub s a₁) : is_lub (insert a₂ s) (a₂ ⊔ a₁) := by rw [insert_eq]; exact is_lub_union_sup is_lub_singleton h lemma is_lub_iff_sup_eq [semilattice_sup α] : is_lub {a₁, a₂} a ↔ a₂ ⊔ a₁ = a := is_lub_iff_eq_of_is_lub $ is_lub_insert_sup $ is_lub_singleton lemma is_glb_insert_inf [semilattice_inf α] (h : is_glb s a₁) : is_glb (insert a₂ s) (a₂ ⊓ a₁) := by rw [insert_eq]; exact is_glb_union_inf is_glb_singleton h lemma is_glb_iff_inf_eq [semilattice_inf α] : is_glb {a₁, a₂} a ↔ a₂ ⊓ a₁ = a := is_glb_iff_eq_of_is_glb $ is_glb_insert_inf $ is_glb_singleton end lattice section complete_lattice variables [complete_lattice α] {f : ι → α} lemma is_lub_Sup : is_lub s (Sup s) := and.intro (assume x, le_Sup) (assume x, Sup_le) lemma is_lub_supr : is_lub (range f) (⨆j, f j) := have is_lub (range f) (Sup (range f)), from is_lub_Sup, by rwa [Sup_range] at this lemma is_lub_iff_supr_eq : is_lub (range f) a ↔ (⨆j, f j) = a := is_lub_iff_eq_of_is_lub is_lub_supr lemma is_lub_iff_Sup_eq : is_lub s a ↔ Sup s = a := is_lub_iff_eq_of_is_lub is_lub_Sup lemma is_glb_Inf : is_glb s (Inf s) := and.intro (assume a, Inf_le) (assume a, le_Inf) lemma is_glb_infi : is_glb (range f) (⨅j, f j) := have is_glb (range f) (Inf (range f)), from is_glb_Inf, by rwa [Inf_range] at this lemma is_glb_iff_infi_eq : is_glb (range f) a ↔ (⨅j, f j) = a := is_glb_iff_eq_of_is_glb is_glb_infi lemma is_glb_iff_Inf_eq : is_glb s a ↔ Inf s = a := is_glb_iff_eq_of_is_glb is_glb_Inf end complete_lattice
daeb332c56e301a9259b9bde8df63e6e91e8ad41
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/compiler/phashmap3.lean
6ad98d6f56f1368c78d6bd3fa7d5786c76e392f3
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,758
lean
import Init.Data.PersistentHashMap import Init.Lean.Data.Format open Lean PersistentHashMap abbrev Map := PersistentHashMap Nat Nat partial def formatMap : Node Nat Nat → Format | Node.collision keys vals _ => Format.sbracket $ keys.size.fold (fun i fmt => let k := keys.get! i; let v := vals.get! i; let p := if i > 0 then fmt ++ format "," ++ Format.line else fmt; p ++ "c@" ++ Format.paren (format k ++ " => " ++ format v)) Format.nil | Node.entries entries => Format.sbracket $ entries.size.fold (fun i fmt => let entry := entries.get! i; let p := if i > 0 then fmt ++ format "," ++ Format.line else fmt; p ++ match entry with | Entry.null => "<null>" | Entry.ref node => formatMap node | Entry.entry k v => Format.paren (format k ++ " => " ++ format v)) Format.nil def main : IO Unit := do let m : Map := PersistentHashMap.empty; let m := m.insert 1 1; let m := m.insert (32^5 + 1) 2; let max := PersistentHashMap.maxDepth.toNat; let m := m.insert (32^max + 1) 3; let m := m.insert (32^(max+1) + 1) 4; let m := m.insert (32^(max+2) + 1) 5; unless (m.stats.maxDepth == PersistentHashMap.maxDepth.toNat) (IO.println "unexpected max depth"); unless (m.stats.numCollisions == 3) (IO.println "unexpected number of collisions"); IO.println m.stats; let m := m.erase (32^(max+1) + 1); let m := m.erase (32^(max+2) + 1); let m := m.erase (32^max + 1); unless (m.stats.maxDepth == PersistentHashMap.maxDepth.toNat - 1) (IO.println "unexpected max depth"); let m := m.erase (32^5 + 1); unless (m.stats.maxDepth == 1) (IO.println "unexpected max depth"); unless (m.stats.numCollisions == 0) (IO.println "unexpected number of collisions"); IO.println m.stats
a05e2882c2fc9a77b1887bbd209f748e25911bac
e9dbaaae490bc072444e3021634bf73664003760
/src/Background/Nat.lean
7b6347d27a6b8b5422168e455aecdcecd54955e5
[ "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
255
lean
namespace Nat def fact : Nat -> Nat | 0 => 1 | 1 => 1 | n+1 => (n+1) * fact n def choose (n : Nat) (k : Fin n) : Nat := n.fact / (k.val.fact * (n-k.val).fact) partial def gcd : Nat → Nat → Nat | a, b => if b == 0 then a else gcd b (a % b) end Nat
fa828eb8e5fb819a50b5f1616743329750c50605
56762daf61566a2baf390b5d77988c29c75187e3
/src/lie_group.lean
a029e44b82458fd9c74029835a45621d15a37f5b
[]
no_license
Nicknamen/lie_group
de173ce5f1ffccb945ba05dca23ff27daef0e3b4
e0d5c4f859654e3dea092702f1320c3c72a49983
refs/heads/master
1,674,937,428,196
1,607,213,423,000
1,607,213,423,000
275,196,635
0
0
null
null
null
null
UTF-8
Lean
false
false
8,095
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import .prod_manifold import .diffeomorph noncomputable theory /-! # Lie groups We define Lie groups. ## Main definitions and statements * `Lie_add_group I G` : a Lie additive group where `G` is a manifold on the model with corners `I`. * `Lie_group I G` : a Lie multiplicative group where `G` is a manifold on the model with corners `I`. ## Implementation notes Note that this definition is temporary, as manifolds are not yet true manifolds, but really charted spaces. Moreover a priori, a Lie group here is a manifold with corner. The fact that it is infact corerless should be a theorem. -/ class smooth_manifold {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E E) (G : Type*) [topological_space G] [charted_space E G] extends smooth_manifold_with_corners I G, model_with_corners.boundaryless I, t2_space G, topological_space.second_countable_topology G : Prop section Lie_group universes u v /-- A Lie (additive) group is a group and a smooth manifold at the same time in which the addition and negation operations are smooth. -/ class Lie_add_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E E) (G : Type*) [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [add_group G] extends topological_add_group G : Prop := (smooth_add : smooth_in_charts (I.prod I) I (λ p : G×G, p.1 + p.2)) (smooth_neg : smooth_in_charts I I (λ a:G, -a)) /-- A Lie group is a group and a smooth manifold at the same time in which the multiplication and inverse operations are smooth. -/ @[to_additive Lie_add_group] class Lie_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E E) (G : Type*) [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] extends topological_group G : Prop := (smooth_mul : smooth_in_charts (I.prod I) I (λ p : G×G, p.1 * p.2)) (smooth_inv : smooth_in_charts I I (λ a:G, a⁻¹)) /- Why cannot I be made implicit? -/ section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E E} {F : Type*} [normed_group F] [normed_space 𝕜 F] {J : model_with_corners 𝕜 F F} {G : Type*} [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] [Lie_group I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M : Type*} [topological_space M] [charted_space H' M] [smooth_manifold_with_corners I' M] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M' : Type*} [topological_space M'] [charted_space H'' M'] [smooth_manifold_with_corners I'' M'] @[to_additive] lemma smooth_in_charts_mul : smooth_in_charts (I.prod I) I (λ p : G×G, p.1 * p.2) := Lie_group.smooth_mul @[to_additive] lemma smooth_in_charts.mul {f : M → G} {g : M → G} (hf : smooth_in_charts I' I f) (hg : smooth_in_charts I' I g) : smooth_in_charts I' I (f * g) := smooth_in_charts_mul.comp (hf.prod_mk hg) @[to_additive] lemma smooth_mul_left (a : G) : smooth I I (λ b : G, a * b) := smooth_mul.comp (smooth_const.prod_mk smooth_id) def L : G → G → G := λ g : G, λ x : G, g * x @[to_additive] lemma smooth_mul_right (a : G) : smooth I I (λ b : G, b * a) := smooth_mul.comp (smooth_id.prod_mk smooth_const) def R : G → G → G := λ g : G, λ x : G, x * g /- @[to_additive] lemma smooth_on.mul {f : M → G} {g : M → G} {s : set M} (hf : smooth_on I' I f s) (hg : smooth_on I' I g s) : smooth_on I' I (f * g) s := by sorry -/ lemma smooth_pow : ∀ n : ℕ, smooth I I (λ a : G, a ^ n) | 0 := by simpa using smooth_const | (k+1) := show smooth I I (λ (a : G), a * a ^ k), from smooth_id.mul (smooth_pow _) @[to_additive] lemma smooth_inv : smooth I I (λ x : G, x⁻¹) := Lie_group.smooth_inv @[to_additive] lemma smooth.inv {f : M → G} (hf : smooth I' I f) : smooth I' I (λx, (f x)⁻¹) := smooth_inv.comp hf /- @[to_additive] lemma smooth_on.inv {f : M → G} {s : set M} (hf : smooth_on I' I f s) : smooth_on I' I (λx, (f x)⁻¹) s := smooth_inv.comp_smooth_on hf -/ /- Coercion to topological group instance to_topological_add_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E E} (G : Type*) [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [add_group G] [h : Lie_add_group I G] : topological_add_group G := { continuous_add := h.smooth_add.1, continuous_neg := h.smooth_neg.1, } @[to_additive to_topological_add_group] instance to_topological_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E E} (G : Type*) [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] [h : Lie_group I G] : topological_group G := { continuous_mul := h.smooth_mul.1, continuous_inv := h.smooth_inv.1, }-/ /- Instance of product group -/ /-@[to_additive]-/ instance prod_Lie_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E E} {G : Type*} [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] [h : Lie_group I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] [finite_dimensional 𝕜 E'] {I' : model_with_corners 𝕜 E' E'} {G' : Type*} [topological_space G'] [charted_space E' G'] [smooth_manifold_with_corners I' G'] [group G'] [h' : Lie_group I' G'] : Lie_group (I.prod I') (G×G') := { smooth_mul := ((smooth_fst.comp smooth_fst).mul (smooth_fst.comp smooth_snd)).prod_mk ((smooth_snd.comp smooth_fst).mul (smooth_snd.comp smooth_snd)), smooth_inv := smooth_fst.inv.prod_mk smooth_snd.inv, } structure Lie_add_group_morphism (I : model_with_corners 𝕜 E E) (I' : model_with_corners 𝕜 E' E') (G : Type*) [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [add_group G] [Lie_add_group I G] (G' : Type*) [topological_space G'] [charted_space E' G'] [smooth_manifold_with_corners I' G'] [add_group G'] [Lie_add_group I' G'] extends add_monoid_hom G G' := (smooth_to_fun : smooth I I' to_fun) @[to_additive Lie_add_group_morphism] structure Lie_group_morphism (I : model_with_corners 𝕜 E E) (I' : model_with_corners 𝕜 E' E') (G : Type*) [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] [Lie_group I G] (G' : Type*) [topological_space G'] [charted_space E' G'] [smooth_manifold_with_corners I' G'] [group G'] [Lie_group I' G'] extends monoid_hom G G' := (smooth_to_fun : smooth I I' to_fun) @[to_additive] instance {I : model_with_corners 𝕜 E E} {I' : model_with_corners 𝕜 E' E'} {G : Type*} [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] [h: Lie_group I G] {G' : Type*} [topological_space G'] [charted_space E' G'] [smooth_manifold_with_corners I' G'] [group G'] [h' : Lie_group I' G'] : has_coe_to_fun (Lie_group_morphism I I' G G') := ⟨_, λ a, a.to_fun⟩ @[to_additive] protected def diffeomorph.mul_left (g : G) : diffeomorph I I G G := { smooth_to_fun := smooth_in_charts_const.mul smooth_in_charts_id, smooth_inv_fun := smooth_in_charts_const.mul smooth_in_charts_id, .. homeomorph.mul_left g } @[to_additive] protected def diffeomorph.mul_right (g : G) : diffeomorph I I G G := { smooth_to_fun := smooth_in_charts_id.mul smooth_in_charts_const, smooth_inv_fun := smooth_in_charts_id.mul smooth_in_charts_const, .. homeomorph.mul_right g } end end Lie_group
0dcb93ebfa00c2f69900d7e8873642cb3b0c4c53
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/algebra/category/constructions/default.hlean
c8d65bd74d123823489706db31d03e16df9ee789
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
252
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import .functor .set .opposite .product .comma .sum .discrete .indiscrete .terminal .initial
b4dc1838cb2ba4fd72bbfddef06cbeddfbe72244
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Data/Format.lean
e555b5e30832a945fa69e50412632e1a3301f50e
[ "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
1,744
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 Lean.Data.Options universe u v namespace Std namespace Format open Lean def getWidth (o : Options) : Nat := o.get `format.width defWidth def getIndent (o : Options) : Nat := o.get `format.indent defIndent def getUnicode (o : Options) : Bool := o.get `format.unicode defUnicode register_builtin_option format.width : Nat := { defValue := defWidth descr := "indentation" } register_builtin_option format.unicode : Bool := { defValue := defUnicode descr := "unicode characters" } register_builtin_option format.indent : Nat := { defValue := defIndent descr := "indentation" } def pretty' (f : Format) (o : Options := {}) : String := pretty f (format.width.get o) end Format end Std namespace Lean open Std export Std (Format ToFormat Format.nest Format.nil Format.joinSep Format.line Format.sbracket Format.bracket Format.group Format.tag Format.pretty Format.fill Format.paren Format.join) export Std.ToFormat (format) instance : ToFormat Name where format n := n.toString instance : ToFormat DataValue where format | DataValue.ofString v => format (repr v) | DataValue.ofBool v => format v | DataValue.ofName v => "`" ++ format v | DataValue.ofNat v => format v | DataValue.ofInt v => format v | DataValue.ofSyntax v => format v instance : ToFormat (Name × DataValue) where format | (n, v) => format n ++ " := " ++ format v open Std.Format def formatKVMap (m : KVMap) : Format := sbracket (Format.joinSep m.entries ", ") instance : ToFormat KVMap := ⟨formatKVMap⟩ end Lean
124fd0cb2706163dbfd92b9aae4b9b1516a51dc4
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/alex_playground/structure.lean
99716bfc7c379b5e70ab505ac83f70fe7e8dd886
[]
no_license
skbaek/cvx
e32822ad5943541539966a37dee162b0a5495f55
c50c790c9116f9fac8dfe742903a62bdd7292c15
refs/heads/master
1,623,803,010,339
1,618,058,958,000
1,618,058,958,000
176,293,135
3
2
null
null
null
null
UTF-8
Lean
false
false
202
lean
import data.real.basic structure myspace := (x : ℝ) (y : ℝ) #check (λ s : myspace, s.x + s.y) example : (λ s : myspace, s.x + s.y) ≠ (λ s : myspace, s.x + s.y) := begin unfold myspace, end
abb0b94529ba2333cc46176a4597c1aee5ffd5e3
37da0369b6c03e380e057bf680d81e6c9fdf9219
/hott/types/trunc.hlean
e83e76c86775d4aaac13a7f77972a740017b5ea4
[ "Apache-2.0" ]
permissive
kodyvajjha/lean2
72b120d95c3a1d77f54433fa90c9810e14a931a4
227fcad22ab2bc27bb7471be7911075d101ba3f9
refs/heads/master
1,627,157,512,295
1,501,855,676,000
1,504,809,427,000
109,317,326
0
0
null
1,509,839,253,000
1,509,655,713,000
C++
UTF-8
Lean
false
false
35,820
hlean
/- Copyright (c) 2015 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Properties of trunc_index, is_trunc, trunctype, trunc, and the pointed versions of these -/ -- NOTE: the fact that (is_trunc n A) is a mere proposition is proved in .prop_trunc import .pointed ..function algebra.order types.nat.order types.unit open eq sigma sigma.ops pi function equiv trunctype is_equiv prod pointed nat is_trunc algebra sum unit /- basic computation with ℕ₋₂, its operations and its order -/ namespace trunc_index definition minus_one_le_succ (n : ℕ₋₂) : -1 ≤ n.+1 := succ_le_succ (minus_two_le n) definition zero_le_of_nat (n : ℕ) : 0 ≤ of_nat n := succ_le_succ !minus_one_le_succ open decidable protected definition has_decidable_eq [instance] : Π(n m : ℕ₋₂), decidable (n = m) | has_decidable_eq -2 -2 := inl rfl | has_decidable_eq (n.+1) -2 := inr (by contradiction) | has_decidable_eq -2 (m.+1) := inr (by contradiction) | has_decidable_eq (n.+1) (m.+1) := match has_decidable_eq n m with | inl xeqy := inl (by rewrite xeqy) | inr xney := inr (λ h : succ n = succ m, by injection h with xeqy; exact absurd xeqy xney) end definition not_succ_le_minus_two {n : ℕ₋₂} (H : n .+1 ≤ -2) : empty := by cases H protected definition le_trans {n m k : ℕ₋₂} (H1 : n ≤ m) (H2 : m ≤ k) : n ≤ k := begin induction H2 with k H2 IH, { exact H1}, { exact le.step IH} end definition le_of_succ_le_succ {n m : ℕ₋₂} (H : n.+1 ≤ m.+1) : n ≤ m := begin cases H with m H', { apply le.tr_refl}, { exact trunc_index.le_trans (le.step !le.tr_refl) H'} end theorem not_succ_le_self {n : ℕ₋₂} : ¬n.+1 ≤ n := begin induction n with n IH: intro H, { exact not_succ_le_minus_two H}, { exact IH (le_of_succ_le_succ H)} end protected definition le_antisymm {n m : ℕ₋₂} (H1 : n ≤ m) (H2 : m ≤ n) : n = m := begin induction H2 with n H2 IH, { reflexivity}, { exfalso, apply @not_succ_le_self n, exact trunc_index.le_trans H1 H2} end protected definition le_succ {n m : ℕ₋₂} (H1 : n ≤ m) : n ≤ m.+1 := le.step H1 protected definition self_le_succ (n : ℕ₋₂) : n ≤ n.+1 := le.step (trunc_index.le.tr_refl n) -- the order is total protected theorem le_sum_le (n m : ℕ₋₂) : n ≤ m ⊎ m ≤ n := begin induction m with m IH, { exact inr !minus_two_le}, { cases IH with H H, { exact inl (trunc_index.le_succ H)}, { cases H with n' H, { exact inl !trunc_index.self_le_succ}, { exact inr (succ_le_succ H)}}} end end trunc_index open trunc_index definition linear_weak_order_trunc_index [trans_instance] [reducible] : linear_weak_order trunc_index := linear_weak_order.mk le trunc_index.le.tr_refl @trunc_index.le_trans @trunc_index.le_antisymm trunc_index.le_sum_le namespace trunc_index /- more theorems about truncation indices -/ definition zero_add (n : ℕ₋₂) : (0 : ℕ₋₂) + n = n := begin cases n with n, reflexivity, cases n with n, reflexivity, induction n with n IH, reflexivity, exact ap succ IH end definition add_zero (n : ℕ₋₂) : n + (0 : ℕ₋₂) = n := by reflexivity definition succ_add_nat (n : ℕ₋₂) (m : ℕ) : n.+1 + m = (n + m).+1 := by induction m with m IH; reflexivity; exact ap succ IH definition nat_add_succ (n : ℕ) (m : ℕ₋₂) : n + m.+1 = (n + m).+1 := begin cases m with m, reflexivity, cases m with m, reflexivity, induction m with m IH, reflexivity, exact ap succ IH end definition add_nat_succ (n : ℕ₋₂) (m : ℕ) : n + (nat.succ m) = (n + m).+1 := by reflexivity definition nat_succ_add (n : ℕ) (m : ℕ₋₂) : (nat.succ n) + m = (n + m).+1 := begin cases m with m, reflexivity, cases m with m, reflexivity, induction m with m IH, reflexivity, exact ap succ IH end definition sub_two_add_two (n : ℕ₋₂) : sub_two (add_two n) = n := begin induction n with n IH, { reflexivity}, { exact ap succ IH} end definition add_two_sub_two (n : ℕ) : add_two (sub_two n) = n := begin induction n with n IH, { reflexivity}, { exact ap nat.succ IH} end definition of_nat_add_plus_two_of_nat (n m : ℕ) : n +2+ m = of_nat (n + m + 2) := begin induction m with m IH, { reflexivity}, { exact ap succ IH} end definition of_nat_add_of_nat (n m : ℕ) : of_nat n + of_nat m = of_nat (n + m) := begin induction m with m IH, { reflexivity}, { exact ap succ IH} end definition succ_add_plus_two (n m : ℕ₋₂) : n.+1 +2+ m = (n +2+ m).+1 := begin induction m with m IH, { reflexivity}, { exact ap succ IH} end definition add_plus_two_succ (n m : ℕ₋₂) : n +2+ m.+1 = (n +2+ m).+1 := idp definition add_succ_succ (n m : ℕ₋₂) : n + m.+2 = n +2+ m := idp definition succ_add_succ (n m : ℕ₋₂) : n.+1 + m.+1 = n +2+ m := begin cases m with m IH, { reflexivity}, { apply succ_add_plus_two} end definition succ_succ_add (n m : ℕ₋₂) : n.+2 + m = n +2+ m := begin cases m with m IH, { reflexivity}, { exact !succ_add_succ ⬝ !succ_add_plus_two} end definition succ_sub_two (n : ℕ) : (nat.succ n).-2 = n.-2 .+1 := rfl definition sub_two_succ_succ (n : ℕ) : n.-2.+1.+1 = n := rfl definition succ_sub_two_succ (n : ℕ) : (nat.succ n).-2.+1 = n := rfl definition of_nat_add_two (n : ℕ₋₂) : of_nat (add_two n) = n.+2 := begin induction n with n IH, reflexivity, exact ap succ IH end definition of_nat_le_of_nat {n m : ℕ} (H : n ≤ m) : (of_nat n ≤ of_nat m) := begin induction H with m H IH, { apply le.refl}, { exact trunc_index.le_succ IH} end definition sub_two_le_sub_two {n m : ℕ} (H : n ≤ m) : n.-2 ≤ m.-2 := begin induction H with m H IH, { apply le.refl}, { exact trunc_index.le_succ IH} end definition add_two_le_add_two {n m : ℕ₋₂} (H : n ≤ m) : add_two n ≤ add_two m := begin induction H with m H IH, { reflexivity}, { constructor, exact IH}, end definition le_of_sub_two_le_sub_two {n m : ℕ} (H : n.-2 ≤ m.-2) : n ≤ m := begin rewrite [-add_two_sub_two n, -add_two_sub_two m], exact add_two_le_add_two H, end definition le_of_of_nat_le_of_nat {n m : ℕ} (H : of_nat n ≤ of_nat m) : n ≤ m := begin apply le_of_sub_two_le_sub_two, exact le_of_succ_le_succ (le_of_succ_le_succ H) end protected theorem succ_le_of_not_le {n m : ℕ₋₂} (H : ¬ n ≤ m) : m.+1 ≤ n := begin cases (le.total n m) with H2 H2, { exfalso, exact H H2}, { cases H2 with n' H2', { exfalso, exact H !le.refl}, { exact succ_le_succ H2'}} end definition trunc_index.decidable_le [instance] : Π(n m : ℕ₋₂), decidable (n ≤ m) := begin intro n, induction n with n IH: intro m, { left, apply minus_two_le}, cases m with m, { right, apply not_succ_le_minus_two}, cases IH m with H H, { left, apply succ_le_succ H}, right, intro H2, apply H, exact le_of_succ_le_succ H2 end end trunc_index open trunc_index namespace is_trunc variables {A B : Type} {n : ℕ₋₂} /- closure properties of truncatedness -/ theorem is_trunc_is_embedding_closed (f : A → B) [Hf : is_embedding f] [HB : is_trunc n B] (Hn : -1 ≤ n) : is_trunc n A := begin induction n with n, {exfalso, exact not_succ_le_minus_two Hn}, {apply is_trunc_succ_intro, intro a a', fapply @is_trunc_is_equiv_closed_rev _ _ n (ap f)} end theorem is_trunc_is_retraction_closed (f : A → B) [Hf : is_retraction f] (n : ℕ₋₂) [HA : is_trunc n A] : is_trunc n B := begin revert A B f Hf HA, induction n with n IH, { intro A B f Hf HA, induction Hf with g ε, fapply is_contr.mk, { exact f (center A)}, { intro b, apply concat, { apply (ap f), exact (center_eq (g b))}, { apply ε}}}, { intro A B f Hf HA, induction Hf with g ε, apply is_trunc_succ_intro, intro b b', fapply (IH (g b = g b')), { intro q, exact ((ε b)⁻¹ ⬝ ap f q ⬝ ε b')}, { apply (is_retraction.mk (ap g)), { intro p, induction p, {rewrite [↑ap, con.left_inv]}}}, { apply is_trunc_eq}} end definition is_embedding_to_fun (A B : Type) : is_embedding (@to_fun A B) := λf f', !is_equiv_ap_to_fun /- theorems about trunctype -/ protected definition trunctype.sigma_char.{l} [constructor] (n : ℕ₋₂) : (trunctype.{l} n) ≃ (Σ (A : Type.{l}), is_trunc n A) := begin fapply equiv.MK, { intro A, exact (⟨carrier A, struct A⟩)}, { intro S, exact (trunctype.mk S.1 S.2)}, { intro S, induction S with S1 S2, reflexivity}, { intro A, induction A with A1 A2, reflexivity}, end definition trunctype_eq_equiv [constructor] (n : ℕ₋₂) (A B : n-Type) : (A = B) ≃ (carrier A = carrier B) := calc (A = B) ≃ (to_fun (trunctype.sigma_char n) A = to_fun (trunctype.sigma_char n) B) : eq_equiv_fn_eq_of_equiv ... ≃ ((to_fun (trunctype.sigma_char n) A).1 = (to_fun (trunctype.sigma_char n) B).1) : equiv.symm (!equiv_subtype) ... ≃ (carrier A = carrier B) : equiv.refl theorem is_trunc_trunctype [instance] (n : ℕ₋₂) : is_trunc n.+1 (n-Type) := begin apply is_trunc_succ_intro, intro X Y, fapply is_trunc_equiv_closed_rev, { apply trunctype_eq_equiv}, fapply is_trunc_equiv_closed_rev, { apply eq_equiv_equiv}, induction n, { apply @is_contr_of_inhabited_prop, { apply is_trunc_equiv }, { apply equiv_of_is_contr_of_is_contr}}, { apply is_trunc_equiv } end /- univalence for truncated types -/ definition teq_equiv_equiv {n : ℕ₋₂} {A B : n-Type} : (A = B) ≃ (A ≃ B) := trunctype_eq_equiv n A B ⬝e eq_equiv_equiv A B definition tua {n : ℕ₋₂} {A B : n-Type} (f : A ≃ B) : A = B := (trunctype_eq_equiv n A B)⁻¹ᶠ (ua f) definition tua_refl {n : ℕ₋₂} (A : n-Type) : tua (@erfl A) = idp := begin refine ap (trunctype_eq_equiv n A A)⁻¹ᶠ (ua_refl A) ⬝ _, refine ap (eq_of_fn_eq_fn _) _ ⬝ !eq_of_fn_eq_fn'_idp , apply ap (dpair_eq_dpair idp), apply is_prop.elim end definition tua_trans {n : ℕ₋₂} {A B C : n-Type} (f : A ≃ B) (g : B ≃ C) : tua (f ⬝e g) = tua f ⬝ tua g := begin refine ap (trunctype_eq_equiv n A C)⁻¹ᶠ (ua_trans f g) ⬝ _, refine ap (eq_of_fn_eq_fn _) _ ⬝ !eq_of_fn_eq_fn'_con, refine _ ⬝ !dpair_eq_dpair_con, apply ap (dpair_eq_dpair _), esimp, apply is_prop.elim end definition tua_symm {n : ℕ₋₂} {A B : n-Type} (f : A ≃ B) : tua f⁻¹ᵉ = (tua f)⁻¹ := begin apply eq_inv_of_con_eq_idp', refine !tua_trans⁻¹ ⬝ _, refine ap tua _ ⬝ !tua_refl, apply equiv_eq, exact to_right_inv f end definition tcast [unfold 4] {n : ℕ₋₂} {A B : n-Type} (p : A = B) (a : A) : B := cast (ap trunctype.carrier p) a definition ptcast [constructor] {n : ℕ₋₂} {A B : n-Type*} (p : A = B) : A →* B := pcast (ap ptrunctype.to_pType p) theorem tcast_tua_fn {n : ℕ₋₂} {A B : n-Type} (f : A ≃ B) : tcast (tua f) = to_fun f := begin cases A with A HA, cases B with B HB, esimp at *, induction f using rec_on_ua_idp, esimp, have HA = HB, from !is_prop.elim, cases this, exact ap tcast !tua_refl end /- theorems about decidable equality and axiom K -/ theorem is_set_of_axiom_K {A : Type} (K : Π{a : A} (p : a = a), p = idp) : is_set A := is_set.mk _ (λa b p q, eq.rec K q p) theorem is_set_of_relation.{u} {A : Type.{u}} (R : A → A → Type.{u}) (mere : Π(a b : A), is_prop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) : is_set A := is_set_of_axiom_K (λa p, have H2 : transport (λx, R a x → a = x) p (@imp a a) = @imp a a, from !apdt, have H3 : Π(r : R a a), transport (λx, a = x) p (imp r) = imp (transport (λx, R a x) p r), from to_fun (equiv.symm !heq_pi) H2, have H4 : imp (refl a) ⬝ p = imp (refl a), from calc imp (refl a) ⬝ p = transport (λx, a = x) p (imp (refl a)) : eq_transport_r ... = imp (transport (λx, R a x) p (refl a)) : H3 ... = imp (refl a) : is_prop.elim, cancel_left (imp (refl a)) H4) definition relation_equiv_eq {A : Type} (R : A → A → Type) (mere : Π(a b : A), is_prop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) (a b : A) : R a b ≃ a = b := have is_set A, from is_set_of_relation R mere refl @imp, equiv_of_is_prop imp (λp, p ▸ refl a) local attribute not [reducible] theorem is_set_of_double_neg_elim {A : Type} (H : Π(a b : A), ¬¬a = b → a = b) : is_set A := is_set_of_relation (λa b, ¬¬a = b) _ (λa n, n idp) H section open decidable --this is proven differently in init.hedberg theorem is_set_of_decidable_eq (A : Type) [H : decidable_eq A] : is_set A := is_set_of_double_neg_elim (λa b, by_contradiction) end theorem is_trunc_of_axiom_K_of_le {A : Type} {n : ℕ₋₂} (H : -1 ≤ n) (K : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λa b, is_trunc_of_imp_is_trunc_of_le H (λp, eq.rec_on p !K)) theorem is_trunc_succ_of_is_trunc_loop (Hn : -1 ≤ n) (Hp : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := begin apply is_trunc_succ_intro, intros a a', apply is_trunc_of_imp_is_trunc_of_le Hn, intro p, induction p, apply Hp end theorem is_prop_iff_is_contr {A : Type} (a : A) : is_prop A ↔ is_contr A := iff.intro (λH, is_contr.mk a (is_prop.elim a)) _ theorem is_trunc_succ_iff_is_trunc_loop (A : Type) (Hn : -1 ≤ n) : is_trunc (n.+1) A ↔ Π(a : A), is_trunc n (a = a) := iff.intro _ (is_trunc_succ_of_is_trunc_loop Hn) -- use loopn in name theorem is_trunc_iff_is_contr_loop_succ (n : ℕ) (A : Type) : is_trunc n A ↔ Π(a : A), is_contr (Ω[succ n](pointed.Mk a)) := begin revert A, induction n with n IH, { intro A, esimp [loopn], transitivity _, { apply is_trunc_succ_iff_is_trunc_loop, apply le.refl}, { apply pi_iff_pi, intro a, esimp, apply is_prop_iff_is_contr, reflexivity}}, { intro A, esimp [loopn], transitivity _, { apply @is_trunc_succ_iff_is_trunc_loop @n, esimp, apply minus_one_le_succ}, apply pi_iff_pi, intro a, transitivity _, apply IH, transitivity _, apply pi_iff_pi, intro p, rewrite [loopn_space_loop_irrel n p], apply iff.refl, esimp, apply imp_iff, reflexivity} end -- use loopn in name theorem is_trunc_iff_is_contr_loop (n : ℕ) (A : Type) : is_trunc (n.-2.+1) A ↔ (Π(a : A), is_contr (Ω[n](pointed.Mk a))) := begin induction n with n, { esimp [sub_two,loopn], apply iff.intro, intro H a, exact is_contr_of_inhabited_prop a, intro H, apply is_prop_of_imp_is_contr, exact H}, { apply is_trunc_iff_is_contr_loop_succ}, end -- rename to is_contr_loopn_of_is_trunc theorem is_contr_loop_of_is_trunc (n : ℕ) (A : Type*) [H : is_trunc (n.-2.+1) A] : is_contr (Ω[n] A) := begin induction A, apply iff.mp !is_trunc_iff_is_contr_loop H end -- rename to is_trunc_loopn_of_is_trunc theorem is_trunc_loop_of_is_trunc (n : ℕ₋₂) (k : ℕ) (A : Type*) [H : is_trunc n A] : is_trunc n (Ω[k] A) := begin induction k with k IH, { exact H}, { apply is_trunc_eq} end definition is_trunc_loopn (k : ℕ₋₂) (n : ℕ) (A : Type*) [H : is_trunc (k+n) A] : is_trunc k (Ω[n] A) := begin revert k H, induction n with n IH: intro k H, exact _, apply is_trunc_eq, apply IH, rewrite [succ_add_nat, add_nat_succ at H], exact H end definition is_set_loopn (n : ℕ) (A : Type*) [is_trunc n A] : is_set (Ω[n] A) := have is_trunc (0+[ℕ₋₂]n) A, by rewrite [trunc_index.zero_add]; exact _, is_trunc_loopn 0 n A definition pequiv_punit_of_is_contr [constructor] (A : Type*) (H : is_contr A) : A ≃* punit := pequiv_of_equiv (equiv_unit_of_is_contr A) (@is_prop.elim unit _ _ _) definition pequiv_punit_of_is_contr' [constructor] (A : Type) (H : is_contr A) : pointed.MK A (center A) ≃* punit := pequiv_punit_of_is_contr (pointed.MK A (center A)) H definition is_trunc_is_contr_fiber (n : ℕ₋₂) {A B : Type} (f : A → B) (b : B) [is_trunc n A] [is_trunc n B] : is_trunc n (is_contr (fiber f b)) := begin cases n, { apply is_contr_of_inhabited_prop, apply is_contr_fun_of_is_equiv, apply is_equiv_of_is_contr }, { apply is_trunc_succ_of_is_prop } end end is_trunc open is_trunc namespace trunc universe variable u variables {n : ℕ₋₂} {A : Type.{u}} {B : Type} {a₁ a₂ a₃ a₄ : A} definition trunc_functor2 [unfold 6 7] {n : ℕ₋₂} {A B C : Type} (f : A → B → C) (x : trunc n A) (y : trunc n B) : trunc n C := by induction x with a; induction y with b; exact tr (f a b) definition tconcat [unfold 6 7] (p : trunc n (a₁ = a₂)) (q : trunc n (a₂ = a₃)) : trunc n (a₁ = a₃) := trunc_functor2 concat p q definition tinverse [unfold 5] (p : trunc n (a₁ = a₂)) : trunc n (a₂ = a₁) := trunc_functor _ inverse p definition tidp [reducible] [constructor] : trunc n (a₁ = a₁) := tr idp definition tassoc (p : trunc n (a₁ = a₂)) (q : trunc n (a₂ = a₃)) (r : trunc n (a₃ = a₄)) : tconcat (tconcat p q) r = tconcat p (tconcat q r) := by induction p; induction q; induction r; exact ap tr !con.assoc definition tidp_tcon (p : trunc n (a₁ = a₂)) : tconcat tidp p = p := by induction p; exact ap tr !idp_con definition tcon_tidp (p : trunc n (a₁ = a₂)) : tconcat p tidp = p := by induction p; reflexivity definition left_tinv (p : trunc n (a₁ = a₂)) : tconcat (tinverse p) p = tidp := by induction p; exact ap tr !con.left_inv definition right_tinv (p : trunc n (a₁ = a₂)) : tconcat p (tinverse p) = tidp := by induction p; exact ap tr !con.right_inv definition tap [unfold 7] (f : A → B) (p : trunc n (a₁ = a₂)) : trunc n (f a₁ = f a₂) := trunc_functor _ (ap f) p definition tap_tidp (f : A → B) : tap f (@tidp n A a₁) = tidp := idp definition tap_tcon (f : A → B) (p : trunc n (a₁ = a₂)) (q : trunc n (a₂ = a₃)) : tap f (tconcat p q) = tconcat (tap f p) (tap f q) := by induction p; induction q; exact ap tr !ap_con /- characterization of equality in truncated types -/ protected definition code [unfold 3 4] (n : ℕ₋₂) (aa aa' : trunc n.+1 A) : trunctype.{u} n := by induction aa with a; induction aa' with a'; exact trunctype.mk' n (trunc n (a = a')) protected definition encode [unfold 3 5] {n : ℕ₋₂} {aa aa' : trunc n.+1 A} : aa = aa' → trunc.code n aa aa' := begin intro p, induction p, induction aa with a, esimp, exact (tr idp) end protected definition decode [unfold 3 4 5] {n : ℕ₋₂} (aa aa' : trunc n.+1 A) : trunc.code n aa aa' → aa = aa' := begin induction aa' with a', induction aa with a, esimp [trunc.code, trunc.rec_on], intro x, induction x with p, exact ap tr p, end definition trunc_eq_equiv [constructor] (n : ℕ₋₂) (aa aa' : trunc n.+1 A) : aa = aa' ≃ trunc.code n aa aa' := begin fapply equiv.MK, { apply trunc.encode}, { apply trunc.decode}, { eapply (trunc.rec_on aa'), eapply (trunc.rec_on aa), intro a a' x, esimp [trunc.code, trunc.rec_on] at x, refine (@trunc.rec_on n _ _ x _ _), intro x, apply is_trunc_eq, intro p, induction p, reflexivity}, { intro p, induction p, apply (trunc.rec_on aa), intro a, exact idp}, end definition tr_eq_tr_equiv [constructor] (n : ℕ₋₂) (a a' : A) : (tr a = tr a' :> trunc n.+1 A) ≃ trunc n (a = a') := !trunc_eq_equiv definition trunc_eq {n : ℕ₋₂} {a a' : A} (p : trunc n (a = a')) :tr a = tr a' :> trunc n.+1 A := !tr_eq_tr_equiv⁻¹ᵉ p definition code_mul {n : ℕ₋₂} {aa₁ aa₂ aa₃ : trunc n.+1 A} (g : trunc.code n aa₁ aa₂) (h : trunc.code n aa₂ aa₃) : trunc.code n aa₁ aa₃ := begin induction aa₁ with a₁, induction aa₂ with a₂, induction aa₃ with a₃, esimp at *, apply tconcat g h, end /- encode preserves concatenation -/ definition encode_con' {n : ℕ₋₂} {aa₁ aa₂ aa₃ : trunc n.+1 A} (p : aa₁ = aa₂) (q : aa₂ = aa₃) : trunc.encode (p ⬝ q) = code_mul (trunc.encode p) (trunc.encode q) := begin induction p, induction q, induction aa₁ with a₁, reflexivity end definition encode_con {n : ℕ₋₂} {a₁ a₂ a₃ : A} (p : tr a₁ = tr a₂ :> trunc (n.+1) A) (q : tr a₂ = tr a₃ :> trunc (n.+1) A) : trunc.encode (p ⬝ q) = tconcat (trunc.encode p) (trunc.encode q) := encode_con' p q /- the principle of unique choice -/ definition unique_choice {P : A → Type} [H : Πa, is_prop (P a)] (f : Πa, ∥ P a ∥) (a : A) : P a := !trunc_equiv (f a) /- transport over a truncated family -/ definition trunc_transport {a a' : A} {P : A → Type} (p : a = a') (n : ℕ₋₂) (x : P a) : transport (λa, trunc n (P a)) p (tr x) = tr (p ▸ x) := by induction p; reflexivity /- pathover over a truncated family -/ definition trunc_pathover {A : Type} {B : A → Type} {n : ℕ₋₂} {a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') : @tr n _ b =[p] @tr n _ b' := by induction q; constructor /- truncations preserve truncatedness -/ definition is_trunc_trunc_of_is_trunc [instance] [priority 500] (A : Type) (n m : ℕ₋₂) [H : is_trunc n A] : is_trunc n (trunc m A) := begin revert A m H, eapply (trunc_index.rec_on n), { clear n, intro A m H, apply is_contr_equiv_closed, { apply equiv.symm, apply trunc_equiv, apply (@is_trunc_of_le _ -2), apply minus_two_le} }, { clear n, intro n IH A m H, induction m with m, { apply (@is_trunc_of_le _ -2), apply minus_two_le}, { apply is_trunc_succ_intro, intro aa aa', apply (@trunc.rec_on _ _ _ aa (λy, !is_trunc_succ_of_is_prop)), eapply (@trunc.rec_on _ _ _ aa' (λy, !is_trunc_succ_of_is_prop)), intro a a', apply (is_trunc_equiv_closed_rev), { apply tr_eq_tr_equiv}, { exact (IH _ _ _)}}} end /- equivalences between truncated types (see also hit.trunc) -/ definition trunc_trunc_equiv_left [constructor] (A : Type) {n m : ℕ₋₂} (H : n ≤ m) : trunc n (trunc m A) ≃ trunc n A := begin note H2 := is_trunc_of_le (trunc n A) H, fapply equiv.MK, { intro x, induction x with x, induction x with x, exact tr x}, { intro x, induction x with x, exact tr (tr x)}, { intro x, induction x with x, reflexivity}, { intro x, induction x with x, induction x with x, reflexivity} end definition trunc_trunc_equiv_right [constructor] (A : Type) {n m : ℕ₋₂} (H : n ≤ m) : trunc m (trunc n A) ≃ trunc n A := begin apply trunc_equiv, exact is_trunc_of_le _ H, end definition trunc_equiv_trunc_of_le {n m : ℕ₋₂} {A B : Type} (H : n ≤ m) (f : trunc m A ≃ trunc m B) : trunc n A ≃ trunc n B := (trunc_trunc_equiv_left A H)⁻¹ᵉ ⬝e trunc_equiv_trunc n f ⬝e trunc_trunc_equiv_left B H definition trunc_trunc_equiv_trunc_trunc [constructor] (n m : ℕ₋₂) (A : Type) : trunc n (trunc m A) ≃ trunc m (trunc n A) := begin fapply equiv.MK: intro x; induction x with x; induction x with x, { exact tr (tr x)}, { exact tr (tr x)}, { reflexivity}, { reflexivity} end theorem is_trunc_trunc_of_le (A : Type) (n : ℕ₋₂) {m k : ℕ₋₂} (H : m ≤ k) [is_trunc n (trunc k A)] : is_trunc n (trunc m A) := begin apply is_trunc_equiv_closed, { apply trunc_trunc_equiv_left, exact H}, end definition trunc_functor_homotopy [unfold 7] {X Y : Type} (n : ℕ₋₂) {f g : X → Y} (p : f ~ g) (x : trunc n X) : trunc_functor n f x = trunc_functor n g x := begin induction x with x, esimp, exact ap tr (p x) end definition trunc_functor_homotopy_of_le {n k : ℕ₋₂} {A B : Type} (f : A → B) (H : n ≤ k) : to_fun (trunc_trunc_equiv_left B H) ∘ trunc_functor n (trunc_functor k f) ∘ to_fun (trunc_trunc_equiv_left A H)⁻¹ᵉ ~ trunc_functor n f := begin intro x, induction x with x, reflexivity end definition is_equiv_trunc_functor_of_le {n k : ℕ₋₂} {A B : Type} (f : A → B) (H : n ≤ k) [is_equiv (trunc_functor k f)] : is_equiv (trunc_functor n f) := is_equiv_of_equiv_of_homotopy (trunc_equiv_trunc_of_le H (equiv.mk (trunc_functor k f) _)) (trunc_functor_homotopy_of_le f H) /- trunc_functor preserves surjectivity -/ definition is_surjective_trunc_functor {A B : Type} (n : ℕ₋₂) (f : A → B) [H : is_surjective f] : is_surjective (trunc_functor n f) := begin cases n with n: intro b, { exact tr (fiber.mk !center !is_prop.elim)}, { refine @trunc.rec _ _ _ _ _ b, {intro x, exact is_trunc_of_le _ !minus_one_le_succ}, clear b, intro b, induction H b with a p, exact tr (fiber.mk (tr a) (ap tr p))} end /- truncation of pointed types -/ definition ptrunc [constructor] (n : ℕ₋₂) (X : Type*) : n-Type* := ptrunctype.mk (trunc n X) _ (tr pt) /- pointed maps involving ptrunc -/ definition ptrunc_functor [constructor] {X Y : Type*} (n : ℕ₋₂) (f : X →* Y) : ptrunc n X →* ptrunc n Y := pmap.mk (trunc_functor n f) (ap tr (respect_pt f)) definition ptr [constructor] (n : ℕ₋₂) (A : Type*) : A →* ptrunc n A := pmap.mk tr idp definition puntrunc [constructor] (n : ℕ₋₂) (A : Type*) [is_trunc n A] : ptrunc n A →* A := pmap.mk untrunc_of_is_trunc idp definition ptrunc.elim [constructor] (n : ℕ₋₂) {X Y : Type*} [is_trunc n Y] (f : X →* Y) : ptrunc n X →* Y := pmap.mk (trunc.elim f) (respect_pt f) /- pointed equivalences involving ptrunc -/ definition ptrunc_pequiv_ptrunc [constructor] (n : ℕ₋₂) {X Y : Type*} (H : X ≃* Y) : ptrunc n X ≃* ptrunc n Y := pequiv_of_equiv (trunc_equiv_trunc n H) (ap tr (respect_pt H)) definition ptrunc_pequiv [constructor] (n : ℕ₋₂) (X : Type*) [H : is_trunc n X] : ptrunc n X ≃* X := pequiv_of_equiv (trunc_equiv n X) idp definition ptrunc_ptrunc_pequiv_left [constructor] (A : Type*) {n m : ℕ₋₂} (H : n ≤ m) : ptrunc n (ptrunc m A) ≃* ptrunc n A := pequiv_of_equiv (trunc_trunc_equiv_left A H) idp definition ptrunc_ptrunc_pequiv_right [constructor] (A : Type*) {n m : ℕ₋₂} (H : n ≤ m) : ptrunc m (ptrunc n A) ≃* ptrunc n A := pequiv_of_equiv (trunc_trunc_equiv_right A H) idp definition ptrunc_pequiv_ptrunc_of_le {n m : ℕ₋₂} {A B : Type*} (H : n ≤ m) (f : ptrunc m A ≃* ptrunc m B) : ptrunc n A ≃* ptrunc n B := (ptrunc_ptrunc_pequiv_left A H)⁻¹ᵉ* ⬝e* ptrunc_pequiv_ptrunc n f ⬝e* ptrunc_ptrunc_pequiv_left B H definition ptrunc_ptrunc_pequiv_ptrunc_ptrunc [constructor] (n m : ℕ₋₂) (A : Type*) : ptrunc n (ptrunc m A) ≃* ptrunc m (ptrunc n A) := pequiv_of_equiv (trunc_trunc_equiv_trunc_trunc n m A) idp definition loop_ptrunc_pequiv [constructor] (n : ℕ₋₂) (A : Type*) : Ω (ptrunc (n+1) A) ≃* ptrunc n (Ω A) := pequiv_of_equiv !tr_eq_tr_equiv idp definition loop_ptrunc_pequiv_con {n : ℕ₋₂} {A : Type*} (p q : Ω (ptrunc (n+1) A)) : loop_ptrunc_pequiv n A (p ⬝ q) = tconcat (loop_ptrunc_pequiv n A p) (loop_ptrunc_pequiv n A q) := encode_con p q definition loopn_ptrunc_pequiv (n : ℕ₋₂) (k : ℕ) (A : Type*) : Ω[k] (ptrunc (n+k) A) ≃* ptrunc n (Ω[k] A) := begin revert n, induction k with k IH: intro n, { reflexivity}, { refine _ ⬝e* loop_ptrunc_pequiv n (Ω[k] A), change Ω (Ω[k] (ptrunc (n + succ k) A)) ≃* Ω (ptrunc (n + 1) (Ω[k] A)), apply loop_pequiv_loop, refine _ ⬝e* IH (n.+1), exact loopn_pequiv_loopn k (pequiv_of_eq (ap (λn, ptrunc n A) !succ_add_nat⁻¹)) } end definition loopn_ptrunc_pequiv_con {n : ℕ₋₂} {k : ℕ} {A : Type*} (p q : Ω[succ k] (ptrunc (n+succ k) A)) : loopn_ptrunc_pequiv n (succ k) A (p ⬝ q) = tconcat (loopn_ptrunc_pequiv n (succ k) A p) (loopn_ptrunc_pequiv n (succ k) A q) := begin refine _ ⬝ loop_ptrunc_pequiv_con _ _, exact ap !loop_ptrunc_pequiv !loop_pequiv_loop_con end definition loopn_ptrunc_pequiv_inv_con {n : ℕ₋₂} {k : ℕ} {A : Type*} (p q : ptrunc n (Ω[succ k] A)) : (loopn_ptrunc_pequiv n (succ k) A)⁻¹ᵉ* (tconcat p q) = (loopn_ptrunc_pequiv n (succ k) A)⁻¹ᵉ* p ⬝ (loopn_ptrunc_pequiv n (succ k) A)⁻¹ᵉ* q := equiv.inv_preserve_binary (loopn_ptrunc_pequiv n (succ k) A) concat tconcat (@loopn_ptrunc_pequiv_con n k A) p q /- pointed homotopies involving ptrunc -/ definition ptrunc_functor_pcompose [constructor] {X Y Z : Type*} (n : ℕ₋₂) (g : Y →* Z) (f : X →* Y) : ptrunc_functor n (g ∘* f) ~* ptrunc_functor n g ∘* ptrunc_functor n f := begin fapply phomotopy.mk, { apply trunc_functor_compose}, { esimp, refine !idp_con ⬝ _, refine whisker_right _ !ap_compose'⁻¹ᵖ ⬝ _, esimp, refine whisker_right _ (ap_compose' tr g _) ⬝ _, exact !ap_con⁻¹}, end definition ptrunc_functor_pid [constructor] (X : Type*) (n : ℕ₋₂) : ptrunc_functor n (pid X) ~* pid (ptrunc n X) := begin fapply phomotopy.mk, { apply trunc_functor_id}, { reflexivity}, end definition ptrunc_functor_pcast [constructor] {X Y : Type*} (n : ℕ₋₂) (p : X = Y) : ptrunc_functor n (pcast p) ~* pcast (ap (ptrunc n) p) := begin fapply phomotopy.mk, { intro x, esimp, refine !trunc_functor_cast ⬝ _, refine ap010 cast _ x, refine !ap_compose'⁻¹ ⬝ !ap_compose'}, { induction p, reflexivity}, end definition ptrunc_functor_phomotopy [constructor] {X Y : Type*} (n : ℕ₋₂) {f g : X →* Y} (p : f ~* g) : ptrunc_functor n f ~* ptrunc_functor n g := begin fapply phomotopy.mk, { exact trunc_functor_homotopy n p}, { esimp, refine !ap_con⁻¹ ⬝ _, exact ap02 tr !to_homotopy_pt}, end definition pcast_ptrunc [constructor] (n : ℕ₋₂) {A B : Type*} (p : A = B) : pcast (ap (ptrunc n) p) ~* ptrunc_functor n (pcast p) := begin fapply phomotopy.mk, { intro a, induction p, esimp, exact !trunc_functor_id⁻¹}, { induction p, reflexivity} end definition ptrunc_elim_ptr [constructor] (n : ℕ₋₂) {X Y : Type*} [is_trunc n Y] (f : X →* Y) : ptrunc.elim n f ∘* ptr n X ~* f := begin fapply phomotopy.mk, { reflexivity }, { reflexivity } end definition ptrunc_elim_phomotopy (n : ℕ₋₂) {X Y : Type*} [is_trunc n Y] {f g : X →* Y} (H : f ~* g) : ptrunc.elim n f ~* ptrunc.elim n g := begin fapply phomotopy.mk, { intro x, induction x with x, exact H x }, { exact to_homotopy_pt H } end definition ap1_ptrunc_functor (n : ℕ₋₂) {A B : Type*} (f : A →* B) : Ω→ (ptrunc_functor (n.+1) f) ∘* (loop_ptrunc_pequiv n A)⁻¹ᵉ* ~* (loop_ptrunc_pequiv n B)⁻¹ᵉ* ∘* ptrunc_functor n (Ω→ f) := begin fapply phomotopy.mk, { intro p, induction p with p, refine (!ap_inv⁻¹ ◾ !ap_compose⁻¹ ◾ idp) ⬝ _ ⬝ !ap_con⁻¹, apply whisker_right, refine _ ⬝ !ap_con⁻¹, exact whisker_left _ !ap_compose }, { induction B with B b, induction f with f p, esimp at f, esimp at p, induction p, reflexivity } end definition ap1_ptrunc_elim (n : ℕ₋₂) {A B : Type*} (f : A →* B) [is_trunc (n.+1) B] : Ω→ (ptrunc.elim (n.+1) f) ∘* (loop_ptrunc_pequiv n A)⁻¹ᵉ* ~* ptrunc.elim n (Ω→ f) := begin fapply phomotopy.mk, { intro p, induction p with p, exact idp ◾ !ap_compose⁻¹ ◾ idp }, { reflexivity } end definition ap1_ptr (n : ℕ₋₂) (A : Type*) : Ω→ (ptr (n.+1) A) ~* (loop_ptrunc_pequiv n A)⁻¹ᵉ* ∘* ptr n (Ω A) := begin fapply phomotopy.mk, { intro p, apply idp_con }, { reflexivity } end definition ptrunc_elim_ptrunc_functor (n : ℕ₋₂) {A B C : Type*} (g : B →* C) (f : A →* B) [is_trunc n C] : ptrunc.elim n g ∘* ptrunc_functor n f ~* ptrunc.elim n (g ∘* f) := begin fapply phomotopy.mk, { intro x, induction x with a, reflexivity }, { esimp, exact !idp_con ⬝ whisker_right _ !ap_compose }, end end trunc open trunc /- The truncated encode-decode method -/ namespace eq definition truncated_encode {k : ℕ₋₂} {A : Type} {a₀ a : A} {code : A → Type} [Πa, is_trunc k (code a)] (c₀ : code a₀) (p : trunc k (a₀ = a)) : code a := begin induction p with p, exact transport code p c₀ end definition truncated_encode_decode_method {k : ℕ₋₂} {A : Type} (a₀ a : A) (code : A → Type) [Πa, is_trunc k (code a)] (c₀ : code a₀) (decode : Π(a : A) (c : code a), trunc k (a₀ = a)) (encode_decode : Π(a : A) (c : code a), truncated_encode c₀ (decode a c) = c) (decode_encode : decode a₀ c₀ = tr idp) : trunc k (a₀ = a) ≃ code a := begin fapply equiv.MK, { exact truncated_encode c₀}, { apply decode}, { intro c, apply encode_decode}, { intro p, induction p with p, induction p, exact decode_encode}, end end eq /- some consequences for properties about functions (surjectivity etc.) -/ namespace function variables {A B : Type} definition is_surjective_of_is_equiv [instance] (f : A → B) [H : is_equiv f] : is_surjective f := λb, begin esimp, apply center, apply is_trunc_trunc_of_is_trunc end definition is_equiv_equiv_is_embedding_times_is_surjective [constructor] (f : A → B) : is_equiv f ≃ (is_embedding f × is_surjective f) := equiv_of_is_prop (λH, (_, _)) (λP, prod.rec_on P (λH₁ H₂, !is_equiv_of_is_surjective_of_is_embedding)) /- Theorem 8.8.1: A function is an equivalence if it's an embedding and it's action on sets is an surjection -/ definition is_equiv_of_is_surjective_trunc_of_is_embedding {A B : Type} (f : A → B) [H : is_embedding f] [H' : is_surjective (trunc_functor 0 f)] : is_equiv f := have is_surjective f, begin intro b, induction H' (tr b) with a p, induction a with a, esimp at p, induction (tr_eq_tr_equiv _ _ _ p) with q, exact image.mk a q end, is_equiv_of_is_surjective_of_is_embedding f /- Corollary 8.8.2: A function f is an equivalence if Ωf and trunc_functor 0 f are equivalences -/ definition is_equiv_of_is_equiv_ap1_of_is_equiv_trunc {A B : Type} (f : A → B) [H : Πa, is_equiv (ap1 (pmap_of_map f a))] [H' : is_equiv (trunc_functor 0 f)] : is_equiv f := have is_embedding f, begin intro a a', apply is_equiv_of_imp_is_equiv, intro p, note q := ap (@tr 0 _) p, note r := @(eq_of_fn_eq_fn' (trunc_functor 0 f)) _ (tr a) (tr a') q, induction (tr_eq_tr_equiv _ _ _ r) with s, induction s, apply is_equiv.homotopy_closed (ap1 (pmap_of_map f a)), intro p, apply idp_con end, is_equiv_of_is_surjective_trunc_of_is_embedding f -- Whitehead's principle itself is in homotopy.homotopy_group, since it needs the definition of -- a homotopy group. end function
dd2da52c2c1770dc2994ac64172a9c2b1d4a761b
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/tutorial/2.lean
e4b529b5154403ae047dcdf05c3e8030d2c388ca
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
85
lean
lemma example2 (x y z : mynat) (h : y = x + 7) : 2 * y = 2 * (x + 7) := rwa h, end
7f17fda18f4ff075f89b2dd4d5600a4a7b440203
05b503addd423dd68145d68b8cde5cd595d74365
/src/data/zmod/basic.lean
ea24dfca9fcac5c7ce22f8346c836dac444a87a8
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,619
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.int.modeq data.int.gcd data.fintype.basic data.pnat.basic tactic.ring /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. There are two types defined, `zmod n`, which is for integers modulo a positive nat `n : ℕ+`. `zmodp` is the type of integers modulo a prime number, for which a field structure is defined. ## Definitions * `val` is inherited from `fin` and returns the least natural number in the equivalence class * `val_min_abs` returns the integer closest to zero in the equivalence class. * A coercion `cast` is defined from `zmod n` into any semiring. This is a semiring hom if the ring has characteristic dividing `n` ## Implentation notes `zmod` and `zmodp` are implemented as different types so that the field instance for `zmodp` can be synthesized. This leads to a lot of code duplication and most of the functions and theorems for `zmod` are restated for `zmodp` -/ open nat nat.modeq int def zmod (n : ℕ+) := fin n namespace zmod instance (n : ℕ+) : has_neg (zmod n) := ⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n, have h : (n : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.2 n.pos, have h₁ : ((n : ℕ) : ℤ) = abs n := (abs_of_nonneg (int.coe_nat_nonneg n)).symm, by rw [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h), h₁]; exact int.mod_lt _ h⟩⟩ instance (n : ℕ+) : add_comm_semigroup (zmod n) := { add_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (show ((a + b) % n + c) ≡ (a + (b + c) % n) [MOD n], from calc ((a + b) % n + c) ≡ a + b + c [MOD n] : modeq_add (nat.mod_mod _ _) rfl ... ≡ a + (b + c) [MOD n] : by rw add_assoc ... ≡ (a + (b + c) % n) [MOD n] : modeq_add rfl (nat.mod_mod _ _).symm), add_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a + b) % n = (b + a) % n, by rw add_comm), ..fin.has_add } instance (n : ℕ+) : comm_semigroup (zmod n) := { mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc ((a * b) % n * c) ≡ a * b * c [MOD n] : modeq_mul (nat.mod_mod _ _) rfl ... ≡ a * (b * c) [MOD n] : by rw mul_assoc ... ≡ a * (b * c % n) [MOD n] : modeq_mul rfl (nat.mod_mod _ _).symm), mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % n = (b * a) % n, by rw mul_comm), ..fin.has_mul } instance (n : ℕ+) : has_one (zmod n) := ⟨⟨(1 % n), nat.mod_lt _ n.pos⟩⟩ instance (n : ℕ+) : has_zero (zmod n) := ⟨⟨0, n.pos⟩⟩ instance (n : ℕ+) : inhabited (zmod n) := ⟨0⟩ instance zmod_one.subsingleton : subsingleton (zmod 1) := ⟨λ a b, fin.eq_of_veq (by rw [eq_zero_of_le_zero (le_of_lt_succ a.2), eq_zero_of_le_zero (le_of_lt_succ b.2)])⟩ lemma add_val {n : ℕ+} : ∀ a b : zmod n, (a + b).val = (a.val + b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma mul_val {n : ℕ+} : ∀ a b : zmod n, (a * b).val = (a.val * b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma one_val {n : ℕ+} : (1 : zmod n).val = 1 % n := rfl @[simp] lemma zero_val (n : ℕ+) : (0 : zmod n).val = 0 := rfl private lemma one_mul_aux (n : ℕ+) (a : zmod n) : (1 : zmod n) * a = a := begin cases n with n hn, cases n with n, { exact (lt_irrefl _ hn).elim }, { cases n with n, { exact @subsingleton.elim (zmod 1) _ _ _ }, { have h₁ : a.1 % n.succ.succ = a.1 := nat.mod_eq_of_lt a.2, have h₂ : 1 % n.succ.succ = 1 := nat.mod_eq_of_lt dec_trivial, refine fin.eq_of_veq _, simp [mul_val, one_val, h₁, h₂] } } end private lemma left_distrib_aux (n : ℕ+) : ∀ a b c : zmod n, a * (b + c) = a * b + a * c := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc a * ((b + c) % n) ≡ a * (b + c) [MOD n] : modeq_mul rfl (nat.mod_mod _ _) ... ≡ a * b + a * c [MOD n] : by rw mul_add ... ≡ (a * b) % n + (a * c) % n [MOD n] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm) instance (n : ℕ+) : comm_ring (zmod n) := { zero_add := λ ⟨a, ha⟩, fin.eq_of_veq (show (0 + a) % n = a, by rw zero_add; exact nat.mod_eq_of_lt ha), add_zero := λ ⟨a, ha⟩, fin.eq_of_veq (nat.mod_eq_of_lt ha), add_left_neg := λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % n).to_nat + a) % n = 0, from int.coe_nat_inj begin have hn : (n : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 n.pos)).symm, rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm], simp, end), one_mul := one_mul_aux n, mul_one := λ a, by rw mul_comm; exact one_mul_aux n a, left_distrib := left_distrib_aux n, right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl, ..zmod.has_zero n, ..zmod.has_one n, ..zmod.has_neg n, ..zmod.add_comm_semigroup n, ..zmod.comm_semigroup n } lemma val_cast_nat {n : ℕ+} (a : ℕ) : (a : zmod n).val = a % n := begin induction a with a ih, { rw [nat.zero_mod]; refl }, { rw [succ_eq_add_one, nat.cast_add, add_val, ih], show (a % n + ((0 + (1 % n)) % n)) % n = (a + 1) % n, rw [zero_add, nat.mod_mod], exact nat.modeq.modeq_add (nat.mod_mod a n) (nat.mod_mod 1 n) } end lemma neg_val' {m : pnat} (n : zmod m) : (-n).val = (m - n.val) % m := have ((-n).val + n.val) % m = (m - n.val + n.val) % m, by { rw [←add_val, add_left_neg, nat.sub_add_cancel (le_of_lt n.is_lt), nat.mod_self], refl }, (nat.mod_eq_of_lt (fin.is_lt _)).symm.trans (nat.modeq.modeq_add_cancel_right rfl this) lemma neg_val {m : pnat} (n : zmod m) : (-n).val = if n = 0 then 0 else m - n.val := begin rw neg_val', by_cases h : n = 0; simp [h], cases n with n nlt; cases n; dsimp, { contradiction }, rw nat.mod_eq_of_lt, apply nat.sub_lt m.2 (nat.succ_pos _), end lemma mk_eq_cast {n : ℕ+} {a : ℕ} (h : a < n) : (⟨a, h⟩ : zmod n) = (a : zmod n) := fin.eq_of_veq (by rw [val_cast_nat, nat.mod_eq_of_lt h]) @[simp] lemma cast_self_eq_zero {n : ℕ+} : ((n : ℕ) : zmod n) = 0 := fin.eq_of_veq (show (n : zmod n).val = 0, by simp [val_cast_nat]) lemma val_cast_of_lt {n : ℕ+} {a : ℕ} (h : a < n) : (a : zmod n).val = a := by rw [val_cast_nat, nat.mod_eq_of_lt h] @[simp] lemma cast_mod_nat (n : ℕ+) (a : ℕ) : ((a % n : ℕ) : zmod n) = a := by conv {to_rhs, rw ← nat.mod_add_div a n}; simp @[simp, priority 980] lemma cast_mod_nat' {n : ℕ} (hn : 0 < n) (a : ℕ) : ((a % n : ℕ) : zmod ⟨n, hn⟩) = a := cast_mod_nat _ _ @[simp] lemma cast_val {n : ℕ+} (a : zmod n) : (a.val : zmod n) = a := by cases a; simp [mk_eq_cast] @[simp] lemma cast_mod_int (n : ℕ+) (a : ℤ) : ((a % (n : ℕ) : ℤ) : zmod n) = a := by conv {to_rhs, rw ← int.mod_add_div a n}; simp @[simp, priority 980] lemma cast_mod_int' {n : ℕ} (hn : 0 < n) (a : ℤ) : ((a % (n : ℕ) : ℤ) : zmod ⟨n, hn⟩) = a := cast_mod_int _ _ lemma val_cast_int {n : ℕ+} (a : ℤ) : (a : zmod n).val = (a % (n : ℕ)).nat_abs := have h : nat_abs (a % (n : ℕ)) < n := int.coe_nat_lt.1 begin rw [nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))], conv {to_rhs, rw ← abs_of_nonneg (int.coe_nat_nonneg n)}, exact int.mod_lt _ (int.coe_nat_ne_zero_iff_pos.2 n.pos) end, int.coe_nat_inj $ by conv {to_lhs, rw [← cast_mod_int n a, ← nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)), int.cast_coe_nat, val_cast_of_lt h] } lemma coe_val_cast_int {n : ℕ+} (a : ℤ) : ((a : zmod n).val : ℤ) = a % (n : ℕ) := by rw [val_cast_int, int.nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))] lemma eq_iff_modeq_nat {n : ℕ+} {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] := ⟨λ h, by have := fin.veq_of_eq h; rwa [val_cast_nat, val_cast_nat] at this, λ h, fin.eq_of_veq $ by rwa [val_cast_nat, val_cast_nat]⟩ lemma eq_iff_modeq_nat' {n : ℕ} (hn : 0 < n) {a b : ℕ} : (a : zmod ⟨n, hn⟩) = b ↔ a ≡ b [MOD n] := eq_iff_modeq_nat lemma eq_iff_modeq_int {n : ℕ+} {a b : ℤ} : (a : zmod n) = b ↔ a ≡ b [ZMOD (n : ℕ)] := ⟨λ h, by have := fin.veq_of_eq h; rwa [val_cast_int, val_cast_int, ← int.coe_nat_eq_coe_nat_iff, nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)), nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))] at this, λ h : a % (n : ℕ) = b % (n : ℕ), by rw [← cast_mod_int n a, ← cast_mod_int n b, h]⟩ lemma eq_iff_modeq_int' {n : ℕ} (hn : 0 < n) {a b : ℤ} : (a : zmod ⟨n, hn⟩) = b ↔ a ≡ b [ZMOD (n : ℕ)] := eq_iff_modeq_int lemma eq_zero_iff_dvd_nat {n : ℕ+} {a : ℕ} : (a : zmod n) = 0 ↔ (n : ℕ) ∣ a := by rw [← @nat.cast_zero (zmod n), eq_iff_modeq_nat, nat.modeq.modeq_zero_iff] lemma eq_zero_iff_dvd_int {n : ℕ+} {a : ℤ} : (a : zmod n) = 0 ↔ ((n : ℕ) : ℤ) ∣ a := by rw [← @int.cast_zero (zmod n), eq_iff_modeq_int, int.modeq.modeq_zero_iff] instance (n : ℕ+) : fintype (zmod n) := fin.fintype _ instance decidable_eq (n : ℕ+) : decidable_eq (zmod n) := fin.decidable_eq _ instance (n : ℕ+) : has_repr (zmod n) := fin.has_repr _ lemma card_zmod (n : ℕ+) : fintype.card (zmod n) = n := fintype.card_fin n instance : subsingleton (units (zmod 2)) := ⟨λ x y, begin cases x with x xi, cases y with y yi, revert x y xi yi, exact dec_trivial end⟩ lemma le_div_two_iff_lt_neg {n : ℕ+} (hn : (n : ℕ) % 2 = 1) {x : zmod n} (hx0 : x ≠ 0) : x.1 ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).1 := have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left n.pos).2 dec_trivial), have hn2' : (n : ℕ) - n / 2 = n / 2 + 1, by conv {to_lhs, congr, rw [← succ_sub_one n, succ_sub n.pos]}; rw [← two_mul_odd_div_two hn, two_mul, ← succ_add, nat.add_sub_cancel], have hxn : (n : ℕ) - x.val < n, begin rw [nat.sub_lt_iff (le_of_lt x.2) (le_refl _), nat.sub_self], rw ← zmod.cast_val x at hx0, exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) end, by conv {to_rhs, rw [← nat.succ_le_iff, succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.cast_self_eq_zero, ← sub_eq_add_neg, ← zmod.cast_val x, ← nat.cast_sub (le_of_lt x.2), zmod.val_cast_nat, mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.2)] } lemma ne_neg_self {n : ℕ+} (hn1 : (n : ℕ) % 2 = 1) {a : zmod n} (ha : a ≠ 0) : a ≠ -a := λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg hn1 ha, by rwa [← h, ← not_lt, not_iff_self] at this @[simp] lemma cast_mul_right_val_cast {n m : ℕ+} (a : ℕ) : ((a : zmod (m * n)).val : zmod m) = (a : zmod m) := zmod.eq_iff_modeq_nat.2 (by rw zmod.val_cast_nat; exact nat.modeq.modeq_of_modeq_mul_right _ (nat.mod_mod _ _)) @[simp] lemma cast_mul_left_val_cast {n m : ℕ+} (a : ℕ) : ((a : zmod (n * m)).val : zmod m) = (a : zmod m) := zmod.eq_iff_modeq_nat.2 (by rw zmod.val_cast_nat; exact nat.modeq.modeq_of_modeq_mul_left _ (nat.mod_mod _ _)) lemma cast_val_cast_of_dvd {n m : ℕ+} (h : (m : ℕ) ∣ n) (a : ℕ) : ((a : zmod n).val : zmod m) = (a : zmod m) := let ⟨k , hk⟩ := h in zmod.eq_iff_modeq_nat.2 (nat.modeq.modeq_of_modeq_mul_right k (by rw [← hk, zmod.val_cast_nat]; exact nat.mod_mod _ _)) /-- `unit_of_coprime` makes an element of `units (zmod n)` given a natural number `x` and a proof that `x` is coprime to `n` -/ def unit_of_coprime {n : ℕ+} (x : ℕ) (h : nat.coprime x n) : units (zmod n) := have (x * gcd_a x ↑n : zmod n) = 1, by rw [← int.cast_coe_nat, ← int.cast_one, ← int.cast_mul, zmod.eq_iff_modeq_int, ← int.coe_nat_one, ← (show nat.gcd _ _ = _, from h)]; simpa using int.modeq.gcd_a_modeq x n, ⟨x, gcd_a x n, this, by simpa [mul_comm] using this⟩ @[simp] lemma cast_unit_of_coprime {n : ℕ+} (x : ℕ) (h : nat.coprime x n) : (unit_of_coprime x h : zmod n) = x := rfl def units_equiv_coprime {n : ℕ+} : units (zmod n) ≃ {x : zmod n // nat.coprime x.1 n} := { to_fun := λ x, ⟨x, nat.modeq.coprime_of_mul_modeq_one (x⁻¹).1.1 begin have := units.ext_iff.1 (mul_right_inv x), rwa [← zmod.cast_val ((1 : units (zmod n)) : zmod n), units.coe_one, zmod.one_val, ← zmod.cast_val ((x * x⁻¹ : units (zmod n)) : zmod n), units.coe_mul, zmod.mul_val, zmod.cast_mod_nat, zmod.cast_mod_nat, zmod.eq_iff_modeq_nat] at this end⟩, inv_fun := λ x, unit_of_coprime x.1.1 x.2, left_inv := λ ⟨_, _, _, _⟩, units.ext (by simp), right_inv := λ ⟨_, _⟩, by simp } /-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`, The result will be in the interval `(-n/2, n/2]` -/ def val_min_abs {n : ℕ+} (x : zmod n) : ℤ := if x.val ≤ n / 2 then x.val else x.val - n @[simp] lemma coe_val_min_abs {n : ℕ+} (x : zmod n) : (x.val_min_abs : zmod n) = x := by simp [zmod.val_min_abs]; split_ifs; simp [sub_eq_add_neg] lemma nat_abs_val_min_abs_le {n : ℕ+} (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 := have (x.val - n : ℤ) ≤ 0, from sub_nonpos.2 $ int.coe_nat_le.2 $ le_of_lt x.2, begin rw zmod.val_min_abs, split_ifs with h, { exact h }, { rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub], conv_lhs { congr, rw [coe_coe, ← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul, int.coe_nat_bit0, int.coe_nat_one] }, rw ← sub_nonneg, suffices : (0 : ℤ) ≤ x.val - ((n % 2 : ℕ) + (n / 2 : ℕ)), { exact le_trans this (le_of_eq $ by ring) }, exact sub_nonneg.2 (by rw [← int.coe_nat_add, int.coe_nat_le]; exact calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 : add_le_add (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) (le_refl _) ... ≤ x.val : by rw add_comm; exact nat.succ_le_of_lt (lt_of_not_ge h)) } end @[simp] lemma val_min_abs_zero {n : ℕ+} : (0 : zmod n).val_min_abs = 0 := by simp [zmod.val_min_abs] @[simp] lemma val_min_abs_eq_zero {n : ℕ+} (x : zmod n) : x.val_min_abs = 0 ↔ x = 0 := ⟨λ h, begin dsimp [zmod.val_min_abs] at h, split_ifs at h, { exact fin.eq_of_veq (by simp * at *) }, { exact absurd h (mt sub_eq_zero.1 (ne_of_lt $ int.coe_nat_lt.2 x.2)) } end, λ hx0, hx0.symm ▸ zmod.val_min_abs_zero⟩ lemma cast_nat_abs_val_min_abs {n : ℕ+} (a : zmod n) : (a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a := have (a.val : ℤ) + -n ≤ 0, by erw [sub_nonpos, int.coe_nat_le]; exact le_of_lt a.2, begin dsimp [zmod.val_min_abs], split_ifs, { simp }, { erw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this], simp } end @[simp] lemma nat_abs_val_min_abs_neg {n : ℕ+} (a : zmod n) : (-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs := if haa : -a = a then by rw [haa] else have hpa : (n : ℕ) - a.val ≤ n / 2 ↔ (n : ℕ) / 2 < a.val, from suffices (((n : ℕ) % 2) + 2 * (n / 2)) - a.val ≤ (n : ℕ) / 2 ↔ (n : ℕ) / 2 < a.val, by rwa [nat.mod_add_div] at this, begin rw [nat.sub_le_iff, two_mul, ← add_assoc, nat.add_sub_cancel], cases (n : ℕ).mod_two_eq_zero_or_one with hn0 hn1, { split, { exact λ h, lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h) begin assume hna, rw [← zmod.cast_val a, ← hna, neg_eq_iff_add_eq_zero, ← nat.cast_add, zmod.eq_zero_iff_dvd_nat, ← two_mul, ← zero_add (2 * _), ← hn0, nat.mod_add_div] at haa, exact haa (dvd_refl _) end }, { rw [hn0, zero_add], exact le_of_lt } }, { rw [hn1, add_comm, nat.succ_le_iff] } end, have ha0 : ¬ a = 0, from λ ha0, by simp * at *, begin dsimp [zmod.val_min_abs], rw [← not_le] at hpa, simp only [if_neg ha0, zmod.neg_val, hpa, int.coe_nat_sub (le_of_lt a.2)], split_ifs, { simp [sub_eq_add_neg] }, { rw [← int.nat_abs_neg], simp } end lemma val_eq_ite_val_min_abs {n : ℕ+} (a : zmod n) : (a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n := by simp [zmod.val_min_abs]; split_ifs; simp lemma neg_eq_self_mod_two : ∀ (a : zmod 2), -a = a := dec_trivial @[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a := by cases a; simp [zmod.neg_eq_self_mod_two] section variables {α : Type*} [has_zero α] [has_one α] [has_add α] {n : ℕ+} def cast : zmod n → α := nat.cast ∘ fin.val end end zmod def zmodp (p : ℕ) (hp : prime p) : Type := zmod ⟨p, hp.pos⟩ namespace zmodp variables {p : ℕ} (hp : prime p) instance : comm_ring (zmodp p hp) := zmod.comm_ring ⟨p, hp.pos⟩ instance : inhabited (zmodp p hp) := ⟨0⟩ instance {p : ℕ} (hp : prime p) : has_inv (zmodp p hp) := ⟨λ a, gcd_a a.1 p⟩ lemma add_val : ∀ a b : zmodp p hp, (a + b).val = (a.val + b.val) % p | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma mul_val : ∀ a b : zmodp p hp, (a * b).val = (a.val * b.val) % p | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] lemma one_val : (1 : zmodp p hp).val = 1 := nat.mod_eq_of_lt hp.one_lt @[simp] lemma zero_val : (0 : zmodp p hp).val = 0 := rfl lemma val_cast_nat (a : ℕ) : (a : zmodp p hp).val = a % p := @zmod.val_cast_nat ⟨p, hp.pos⟩ _ lemma mk_eq_cast {a : ℕ} (h : a < p) : (⟨a, h⟩ : zmodp p hp) = (a : zmodp p hp) := @zmod.mk_eq_cast ⟨p, hp.pos⟩ _ _ @[simp] lemma cast_self_eq_zero: (p : zmodp p hp) = 0 := fin.eq_of_veq $ by simp [val_cast_nat] lemma val_cast_of_lt {a : ℕ} (h : a < p) : (a : zmodp p hp).val = a := @zmod.val_cast_of_lt ⟨p, hp.pos⟩ _ h @[simp] lemma cast_mod_nat (a : ℕ) : ((a % p : ℕ) : zmodp p hp) = a := @zmod.cast_mod_nat ⟨p, hp.pos⟩ _ @[simp] lemma cast_val (a : zmodp p hp) : (a.val : zmodp p hp) = a := @zmod.cast_val ⟨p, hp.pos⟩ _ @[simp] lemma cast_mod_int (a : ℤ) : ((a % p : ℤ) : zmodp p hp) = a := @zmod.cast_mod_int ⟨p, hp.pos⟩ _ lemma val_cast_int (a : ℤ) : (a : zmodp p hp).val = (a % p).nat_abs := @zmod.val_cast_int ⟨p, hp.pos⟩ _ lemma coe_val_cast_int (a : ℤ) : ((a : zmodp p hp).val : ℤ) = a % (p : ℕ) := @zmod.coe_val_cast_int ⟨p, hp.pos⟩ _ lemma eq_iff_modeq_nat {a b : ℕ} : (a : zmodp p hp) = b ↔ a ≡ b [MOD p] := @zmod.eq_iff_modeq_nat ⟨p, hp.pos⟩ _ _ lemma eq_iff_modeq_int {a b : ℤ} : (a : zmodp p hp) = b ↔ a ≡ b [ZMOD p] := @zmod.eq_iff_modeq_int ⟨p, hp.pos⟩ _ _ lemma eq_zero_iff_dvd_nat (a : ℕ) : (a : zmodp p hp) = 0 ↔ p ∣ a := @zmod.eq_zero_iff_dvd_nat ⟨p, hp.pos⟩ _ lemma eq_zero_iff_dvd_int (a : ℤ) : (a : zmodp p hp) = 0 ↔ (p : ℤ) ∣ a := @zmod.eq_zero_iff_dvd_int ⟨p, hp.pos⟩ _ instance : fintype (zmodp p hp) := @zmod.fintype ⟨p, hp.pos⟩ instance decidable_eq : decidable_eq (zmodp p hp) := fin.decidable_eq _ instance X (h : prime 2) : subsingleton (units (zmodp 2 h)) := zmod.subsingleton instance : has_repr (zmodp p hp) := fin.has_repr _ @[simp] lemma card_zmodp : fintype.card (zmodp p hp) = p := @zmod.card_zmod ⟨p, hp.pos⟩ lemma le_div_two_iff_lt_neg {p : ℕ} (hp : prime p) (hp1 : p % 2 = 1) {x : zmodp p hp} (hx0 : x ≠ 0) : x.1 ≤ (p / 2 : ℕ) ↔ (p / 2 : ℕ) < (-x).1 := @zmod.le_div_two_iff_lt_neg ⟨p, hp.pos⟩ hp1 _ hx0 lemma ne_neg_self (hp1 : p % 2 = 1) {a : zmodp p hp} (ha : a ≠ 0) : a ≠ -a := @zmod.ne_neg_self ⟨p, hp.pos⟩ hp1 _ ha variable {hp} /-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`, The result will be in the interval `(-n/2, n/2]` -/ def val_min_abs (x : zmodp p hp) : ℤ := zmod.val_min_abs x @[simp] lemma coe_val_min_abs (x : zmodp p hp) : (x.val_min_abs : zmodp p hp) = x := zmod.coe_val_min_abs x lemma nat_abs_val_min_abs_le (x : zmodp p hp) : x.val_min_abs.nat_abs ≤ p / 2 := zmod.nat_abs_val_min_abs_le x @[simp] lemma val_min_abs_zero : (0 : zmodp p hp).val_min_abs = 0 := zmod.val_min_abs_zero @[simp] lemma val_min_abs_eq_zero (x : zmodp p hp) : x.val_min_abs = 0 ↔ x = 0 := zmod.val_min_abs_eq_zero x lemma cast_nat_abs_val_min_abs (a : zmodp p hp) : (a.val_min_abs.nat_abs : zmodp p hp) = if a.val ≤ p / 2 then a else -a := zmod.cast_nat_abs_val_min_abs a @[simp] lemma nat_abs_val_min_abs_neg (a : zmodp p hp) : (-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs := zmod.nat_abs_val_min_abs_neg _ lemma val_eq_ite_val_min_abs (a : zmodp p hp) : (a.val : ℤ) = a.val_min_abs + if a.val ≤ p / 2 then 0 else p := zmod.val_eq_ite_val_min_abs _ variable (hp) lemma prime_ne_zero {q : ℕ} (hq : prime q) (hpq : p ≠ q) : (q : zmodp p hp) ≠ 0 := by rwa [← nat.cast_zero, ne.def, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_zero_iff, ← hp.coprime_iff_not_dvd, coprime_primes hp hq] lemma mul_inv_eq_gcd (a : ℕ) : (a : zmodp p hp) * a⁻¹ = nat.gcd a p := by rw [← int.cast_coe_nat (nat.gcd _ _), nat.gcd_comm, nat.gcd_rec, ← (eq_iff_modeq_int _).2 (int.modeq.gcd_a_modeq _ _)]; simp [has_inv.inv, val_cast_nat] private lemma mul_inv_cancel_aux : ∀ a : zmodp p hp, a ≠ 0 → a * a⁻¹ = 1 := λ ⟨a, hap⟩ ha0, begin rw [mk_eq_cast, ne.def, ← @nat.cast_zero (zmodp p hp), eq_iff_modeq_nat, modeq_zero_iff] at ha0, have : nat.gcd p a = 1 := (prime.coprime_iff_not_dvd hp).2 ha0, rw [mk_eq_cast _ hap, mul_inv_eq_gcd, nat.gcd_comm], simpa [nat.gcd_comm, this] end instance : field (zmodp p hp) := { zero_ne_one := fin.ne_of_vne $ show 0 ≠ 1 % p, by rw nat.mod_eq_of_lt hp.one_lt; exact zero_ne_one, mul_inv_cancel := mul_inv_cancel_aux hp, inv_zero := show (gcd_a 0 p : zmodp p hp) = 0, by unfold gcd_a xgcd xgcd_aux; refl, ..zmodp.comm_ring hp, ..zmodp.has_inv hp } end zmodp
fac6de7e98761da9a0a3025cce0bac64d0edd7d2
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_simp2.lean
adbd26971329f1b15ea466a30139017e4ff45e66
[ "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
83
lean
definition tst1 (a b : Prop) : a ∧ b ∧ true → b ∧ a := by simp print tst1
4628eb1193accd0a39620ef3cab4465eb9f738d9
a721fe7446524f18ba361625fc01033d9c8b7a78
/src/principia/experimental/oldint/basic.lean
e51e74827d482c9806ae380284e696b48c084754
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
6,127
lean
-- vim: ts=2 sw=0 sts=-1 et ai tw=70 import principia.logic import principia.mynat.basic import principia.mynat.le import principia.mynat.nat_sub namespace hidden -- Basic definitions for integers -- TODO: -- - Prove basic theorems about arithmetic again -- - Define some quotient/remainder things inductive oldint: Type | of_nat : mynat → oldint | neg_succ_of_nat: mynat → oldint -- "has coercion" I think. Seems to introduce the notation -- ↑n (\u n) for "coerce n" instance: has_coe mynat oldint := ⟨oldint.of_nat⟩ -- lets you write -[1+ n] for negative numbers. Note the spacing is -- unforgiving. notation `-[1+ ` n `]` := oldint.neg_succ_of_nat n namespace oldint open oldint open mynat instance: has_zero oldint := ⟨of_nat 0⟩ instance: has_one oldint := ⟨of_nat 1⟩ def neg_of_nat: mynat → oldint | 0 := 0 | (succ m) := -[1+ m] def sub_nat_nat (m n: mynat): oldint := match m - n with | 0 := neg_of_nat (n - m) | d := d end def neg: oldint → oldint | (of_nat n) := neg_of_nat n | -[1+ n] := succ n instance: has_neg oldint := ⟨neg⟩ def abs : oldint → mynat | (of_nat m) := m | -[1+ m] := succ m def sign : oldint → oldint | (of_nat a) := match a with | zero := 0 | (succ _) := 1 end | -[1+ _] := -1 variables {m n k: oldint} variables {a b c: mynat} -- Basic lemma of_nat_zero : of_nat 0 = 0 := rfl lemma of_nat_one : of_nat 1 = 1 := rfl theorem zero_nat: (↑(0: mynat): oldint) = 0 := rfl theorem one_nat: (↑(1:mynat):oldint) = 1 := rfl theorem neg_one: -(1:oldint) = -[1+ 0] := rfl theorem of_nat_ne_neg_succ: of_nat a ≠ -[1+ b] := by apply oldint.no_confusion theorem zero_ne_neg_succ (a : mynat): 0 ≠ -[1+ a] := by apply of_nat_ne_neg_succ @[simp] theorem of_nat_cancel: (↑a: oldint) = ↑b ↔ a = b := begin split; assume h, cases h, refl, rw h, end @[simp] theorem neg_succ_of_nat_cancel: -[1+ a] = -[1+ b] ↔ a = b := begin split; assume h, cases h, refl, congr, assumption, end -- Coercion @[simp] theorem coe_nat_eq (n: mynat): ↑n = of_nat n := rfl -- Neg of nat @[simp] theorem neg_of_nat_zero: neg_of_nat 0 = 0 := rfl @[simp] theorem neg_succ: neg_of_nat (succ a) = -[1+ a] := rfl -- Massive cash bash, for very basic theorem @[simp] theorem neg_of_nat_cancel: ∀ {a b}, neg_of_nat a = neg_of_nat b ↔ a = b := begin assume a b, split; assume h, cases a, cases b, refl, rw zz, rw [zz, neg_of_nat_zero, neg_succ] at h, exfalso, from zero_ne_neg_succ b h, cases b, rw [zz, neg_succ, neg_of_nat_zero] at h, exfalso, from zero_ne_neg_succ a h.symm, congr, rw [neg_succ, neg_succ] at h, rw ←neg_succ_of_nat_cancel, assumption, congr, assumption, end -- Sub nat nat @[simp] theorem zero_sub_neg: sub_nat_nat 0 a = neg_of_nat a := begin cases a, refl, refl, end @[simp] theorem nat_sub_zero: sub_nat_nat a 0 = ↑a := begin cases a, refl, refl, end -- Extremely useful @[simp] theorem sub_succ_succ: sub_nat_nat (succ a) (succ b) = sub_nat_nat a b := begin unfold sub_nat_nat, rw sub_succ_succ, cases (a - b), refl, refl, end @[simp] theorem sub_self: ∀ a, sub_nat_nat a a = 0 | zero := rfl | (succ a) := by rw [sub_succ_succ, sub_self] -- Neg lemma neg_eq_minus: neg m = -m := rfl theorem neg_coe_eq_neg_of_nat: -(↑a) = neg_of_nat a := rfl private theorem neg_neg_of_nat: ∀ {a}, -neg_of_nat a = ↑a | zero := rfl | (succ a) := rfl @[simp] theorem neg_zero: -(0:oldint) = 0 := rfl theorem neg_neg_succ: -(-[1+ a]) = ↑(succ a) := by rw ←neg_eq_minus; refl theorem neg_coe_succ: -(↑(succ a)) = -[1+ a] := rfl @[simp] theorem neg_neg: ∀ {m : oldint}, -(-m) = m | (of_nat a) := by rw [←coe_nat_eq, neg_coe_eq_neg_of_nat]; from neg_neg_of_nat | -[1+ a] := by rw neg_neg_succ; refl theorem neg_switch: -m = n → m = -n := begin assume h, -- To "do the same to both sides" have h₁ := congr_arg (λ m, -m) h, simp at h₁, -- To simp lambdas assumption, end @[simp] theorem neg_cancel: -m = -n ↔ m = n := begin repeat {rw ←neg_eq_minus}, split; assume h, repeat {rw neg_eq_minus at h}, have h₁ := congr_arg (λ m, -m) h, simp at h₁, repeat {rw neg_neg at h₁}, assumption, congr, assumption, end theorem sub_nat_nat_switch: ∀ {a b : mynat}, -(sub_nat_nat a b) = sub_nat_nat b a | zero zero := rfl | zero (succ b) := rfl | (succ a) zero := rfl | (succ a) (succ b) := by rw [sub_succ_succ, sub_succ_succ, sub_nat_nat_switch] -- Abs theorem abs_of_nat: abs ↑a = a := rfl theorem abs_neg_succ: abs -[1+ a] = succ a := rfl theorem abs_neg: ∀ {m}, abs (-m) = abs m | (of_nat a) := begin rw ←coe_nat_eq, cases a, { rw [zz, zero_nat, neg_zero], }, { rw [←neg_neg_succ, neg_neg, neg_neg_succ, abs_of_nat, abs_neg_succ], }, end | -[1+ a] := by rw [neg_neg_succ, abs_neg_succ, abs_of_nat] -- Sign theorem sign_zero: sign 0 = 0 := rfl theorem sign_neg_succ: sign -[1+ a] = -1 := rfl theorem sign_succ: sign ↑(succ a) = 1 := rfl theorem zero_iff_sign_zero: m = 0 ↔ sign m = 0 := begin split; assume h, { subst h, refl, }, { cases m, { cases m, { rw [zz, ←coe_nat_eq, zero_nat], }, { exfalso, rw [←coe_nat_eq, sign_succ, ←zero_nat, ←one_nat, of_nat_cancel] at h, from mynat.no_confusion h, }, }, { exfalso, rw [sign_neg_succ] at h, from oldint.no_confusion h, }, }, end theorem nzero_iff_sign_nzero: m ≠ 0 ↔ sign m ≠ 0 := iff_to_contrapositive zero_iff_sign_zero -- Decidability instance: decidable_eq oldint | (of_nat a) (of_nat b) := by rw [←coe_nat_eq, ←coe_nat_eq, of_nat_cancel]; apply_instance | (of_nat a) -[1+ b] := is_false of_nat_ne_neg_succ | -[1+ a] (of_nat b) := is_false of_nat_ne_neg_succ.symm | -[1+ a] -[1+ b] := by rw [neg_succ_of_nat_cancel]; apply_instance theorem zero_ne_one : (0 : oldint) ≠ 1 := begin rw [←one_nat, ←zero_nat], assume h, rw of_nat_cancel at h, from zero_ne_one h, end end oldint end hidden
5e2104432fd1453ba0a881beaf8069b27e9c5b84
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/category/Mon/colimits.lean
544165071772d273f1cf4b072d24f50cb29c99bb
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
7,526
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Mon.basic import category_theory.limits.limits import category_theory.limits.concrete_category /-! # The category of monoids has all colimits. We do this construction knowing nothing about monoids. In particular, I want to claim that this file could be produced by a python script that just looks at the output of `#print monoid`: -- structure monoid : Type u → Type u -- fields: -- monoid.mul : Π {α : Type u} [c : monoid α], α → α → α -- monoid.mul_assoc : ∀ {α : Type u} [c : monoid α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) -- monoid.one : Π (α : Type u) [c : monoid α], α -- monoid.one_mul : ∀ {α : Type u} [c : monoid α] (a : α), 1 * a = a -- monoid.mul_one : ∀ {α : Type u} [c : monoid α] (a : α), a * 1 = a and if we'd fed it the output of `#print comm_ring`, this file would instead build colimits of commutative rings. A slightly bolder claim is that we could do this with tactics, as well. -/ universes v open category_theory open category_theory.limits namespace Mon.colimits /-! We build the colimit of a diagram in `Mon` by constructing the free monoid on the disjoint union of all the monoids in the diagram, then taking the quotient by the monoid laws within each monoid, and the identifications given by the morphisms in the diagram. -/ variables {J : Type v} [small_category J] (F : J ⥤ Mon.{v}) /-- An inductive type representing all monoid expressions (without relations) on a collection of types indexed by the objects of `J`. -/ inductive prequotient -- There's always `of` | of : Π (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | one : prequotient | mul : prequotient → prequotient → prequotient instance : inhabited (prequotient F) := ⟨prequotient.one⟩ open prequotient /-- The relation on `prequotient` saying when two expressions are equal because of the monoid laws, or because one element is mapped to another by a morphism in the diagram. -/ inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' ((F.map f) x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | mul : Π (j) (x y : F.obj j), relation (of j (x * y)) (mul (of j x) (of j y)) | one : Π (j), relation (of j 1) one -- Then one relation per argument of each operation | mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y) | mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y') -- And one relation per axiom | mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z)) | one_mul : Π (x), relation (mul one x) x | mul_one : Π (x), relation (mul x one) x /-- The setoid corresponding to monoid expressions modulo monoid relations and identifications. -/ def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid /-- The underlying type of the colimit of a diagram in `Mon`. -/ @[derive inhabited] def colimit_type : Type v := quotient (colimit_setoid F) instance monoid_colimit_type : monoid (colimit_type F) := { mul := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (mul x y) }, { intros y y' r, apply quot.sound, exact relation.mul_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.mul_1 _ _ _ r }, { refl } }, end, one := begin exact quot.mk _ one end, mul_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.mul_assoc, refl, refl, refl, end, one_mul := λ x, begin induction x, dsimp, apply quot.sound, apply relation.one_mul, refl, end, mul_one := λ x, begin induction x, dsimp, apply quot.sound, apply relation.mul_one, refl, end } @[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl @[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl /-- The bundled monoid giving the colimit of a diagram. -/ def colimit : Mon := ⟨colimit_type F, by apply_instance⟩ /-- The function from a given monoid in the diagram to the colimit monoid. -/ def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) /-- The monoid homomorphism from a given monoid in the diagram to the colimit monoid. -/ def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_one' := quot.sound (relation.one _), map_mul' := λ x y, quot.sound (relation.mul _ _ _) } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } /-- The cocone over the proposed colimit monoid. -/ def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F, } }. /-- The function from the free monoid on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | one := 1 | (mul x y) := desc_fun_lift x * desc_fun_lift y /-- The function from the colimit monoid to the cone point of any other cocone. -/ def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { simp, }, -- mul { simp, }, -- one { simp, }, -- mul_1 { rw r_ih, }, -- mul_2 { rw r_ih, }, -- mul_assoc { rw mul_assoc, }, -- one_mul { rw one_mul, }, -- mul_one { rw mul_one, } } end /-- The monoid homomorphism from the colimit monoid to the cone point of any other cocone. -/ @[simps] def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_one' := rfl, map_mul' := λ x y, by { induction x; induction y; refl }, } /-- Evidence that the proposed colimit is the colimit. -/ def colimit_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp *, }, { simp *, }, refl end }. instance has_colimits_Mon : has_colimits Mon := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI { cocone := colimit_cocone F, is_colimit := colimit_is_colimit F } } } end Mon.colimits
5ce764f4002df5084bfef4feefafce82f9190486
7b66d83f3b69dae0a3dfb684d7ebe5e9e3f3c913
/src/hints/thursday/afternoon/category_theory/exercise1/hint1.lean
238f414c01aae21b744fe850fa9d050f95f67b5c
[]
permissive
dpochekutov/lftcm2020
58a09e10f0e638075b97884d3c2612eb90296adb
cdfbf1ac089f21058e523db73f2476c9c98ed16a
refs/heads/master
1,669,226,265,076
1,594,629,725,000
1,594,629,725,000
279,213,346
1
0
MIT
1,594,622,757,000
1,594,615,843,000
null
UTF-8
Lean
false
false
437
lean
import algebra.category.CommRing import category_theory.yoneda noncomputable theory open category_theory open opposite /-! We need to provide a commutative ring, and then an isomorphism between two functors. -/ def CommRing_forget_representable : Σ (R : CommRing), (forget CommRing) ≅ coyoneda.obj (op R) := ⟨CommRing.of (polynomial ℤ), { hom := sorry, inv := sorry, hom_inv_id' := sorry, inv_hom_id' := sorry, }⟩
d5d8d7c81876f7217b89f7b2d71e23a5dd3501a9
ea97c777e51529c97caac532f9a6bbea417eca7a
/01_programming.lean
904340fcecdcf6d811aa74284cd81bcc3f3f7e13
[]
no_license
gebner/avm2017_tutorial
0fcd023fbcefd6e46384ca4919b90a0f6118368e
3954983cdc8aef0e58e1a5809c0b3e217057ac4c
refs/heads/master
1,624,860,271,990
1,505,717,496,000
1,505,717,496,000
103,569,052
2
0
null
null
null
null
UTF-8
Lean
false
false
3,543
lean
/- Definitions -/ def square (m : nat) : nat := m * m -- We can write the same function as a lambda def square' : ℕ → ℕ := λ (m : ℕ), m * m -- ... or using pattern matching def square'' : ℕ → ℕ | 0 := 0 | (m+1) := (m+1) * (m+1) /- Interactive commands -/ #print square' #eval square' 12 #check square #check λ x, square (string.length x) example (x : string) := square (string.length x) /- Polymorphic definitions -/ -- types are first-class values #check ℕ #check Type #check Type 1 #check Type 2 universes u #check Type u -- polymorphic functions take the type as an extra argument def squared_length (α : Type u) (xs : list α) : ℕ := square (list.length xs) #eval squared_length ℕ [1, 2, 3] #eval squared_length ℕ (1 :: 2 :: 3 :: []) #eval squared_length Type [ℕ, ℤ, string → bool] -- using curly braces, Lean will fill in the type automatically ("implicit argument") def squared_length' {α : Type u} (xs : list α) : ℕ := square (list.length xs) #eval squared_length' [1, 2, 3] #eval @squared_length' ℕ [1, 2, 3] /- Higher-order functions -/ def twice {α : Type u} (f : α → α) (a : α) : α := f (f a) def twice' {α : Type u} (f : α → α) : α → α := f ∘ f /- Recursion -/ def reverse {α : Type u} : list α → list α -- pattern matching only applies to the arguments after the colon | [] := [] | (x::xs) := reverse xs ++ [x] def nested_list (α : Type u) : ℕ → Type u | 0 := α -- recursive calls only have arguments from after the colon | (n+1) := list (nested_list n) #reduce nested_list ℕ 5 -- Why does this work? example (n : ℕ) (xs : nested_list string (n+1)) := reverse xs -- xs needs to be a (list _) here, but it's a nested_list! -- (nested_list _ (n+1)) reduces to a (list _): #reduce λ n, nested_list string (n+1) -- This is called "definitional equality". -- We can of course write functions that return nested_list def n_singleton {α : Type u} : ∀ n, α → nested_list α n -- in the base case, the return type is (nested_list α 0) =def= α | 0 a := a -- in the step case, the return type is (list (nested_list α n)) | (n+1) a := [n_singleton n a] /- Inductive types -/ inductive tree (α : Type u) | leaf (value : α) : tree | node (left : tree) (right : tree) : tree #check tree.node (tree.leaf 1) (tree.leaf 3) /- Inductive families -/ inductive vector (α : Type u) : ℕ → Type u | nil : vector 0 | cons {n : ℕ} (head : α) (tail : vector n) : vector (n+1) def vector.head {α} : ∀ {n}, vector α (n+1) → α | _ (vector.cons hd tl) := hd #check vector.cons 3 (vector.cons 4 (vector.nil ℕ)) #eval vector.head $ vector.cons 3 (vector.cons 4 (vector.nil ℕ)) /- Structures -/ structure point (α : Type u) := (x : α) (y : α) def pt : point ℕ := { y := 1, x := 2 } #eval pt.y #eval point.y pt example : point ℕ := point.mk 1 2 example : point ℕ := ⟨1, 2⟩ example := { point . x := 1, y := 2 } example : point ℕ := { x := 1, y := 2 } example := { pt with x := 5 } structure point3 (α : Type u) extends point α := (z : α) example : point3 ℕ := { pt with z := 3 } /- Type classes -/ -- using square brackets, Lean will fill in the argument using type-class inference def tree.sum {α : Type u} [has_add α] : tree α → α | (tree.leaf v) := v | (tree.node t s) := tree.sum t + tree.sum s instance (α : Type u) : has_append (tree α) := { append := tree.node } -- type classes are just structures example (t : tree ℕ) (s : tree ℕ) := t ++ s
26a73663ada6984f885541bb7e454e3bae79f6c2
9a0b1b3a653ea926b03d1495fef64da1d14b3174
/tidy/command/rfl_lemma.lean
211a6a1f42621429f3a7bd9eaf0e99dba2de3655
[ "Apache-2.0" ]
permissive
khoek/mathlib-tidy
8623b27b4e04e7d598164e7eaf248610d58f768b
866afa6ab597c47f1b72e8fe2b82b97fff5b980f
refs/heads/master
1,585,598,975,772
1,538,659,544,000
1,538,659,544,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,938
lean
import tidy.lib.pretty_print import tidy.lib.name import tidy.lib.expr import tidy.lib.parser open lean.parser open interactive open exceptional open declaration namespace tidy.command namespace rfl_lemma structure config := (attrs : list string := ["simp"]) (priv : bool := ff) (trace : bool := ff) open tactic meta def handle_defn (lemma_name : string) (conf : config) (e : environment) (fn_name : name) (fn_us : list name) (fn_type : expr) (fn_val : expr) (field : name) : tactic string := do (obj_name, obj_name_levels, fn_type_app_vars) ← app.chop $ prod.snd fn_type.unroll_pi_binders, (fn_val_params, fn_val_core) ← pure fn_val.unroll_lam_binders, let proj_name := obj_name ++ field, let proj_prime_name := obj_name ++ field.append_suffix "'", pi ← e.is_projection proj_prime_name <|> e.is_projection proj_name <|> fail format!"There are no projections: {proj_prime_name}', nor {proj_prime_name}", (field_params, field_val) ← expr.unroll_lam_binders <$> structure_instance.extract_field fn_val_core pi, field_proj ← mk_const proj_name >>= infer_type <|> fail format!"There is no identifier: {proj_name}", let field_proj_params := (prod.fst field_proj.unroll_pi_binders).drop (pi.nparams + 1), let field_params := field_params.zip_with binder.set_binder_info (field_proj_params.map binder.binder_info), let lemma_params := fn_val_params ++ field_params, args ← binder.list_to_args lemma_params, st_value ← pretty_print (binder.instantiate field_val lemma_params) ff tt, attrs ← if ¬(conf.attrs.length = 0) then pp format!"@[{string.lconcat (conf.attrs.intersperse \", \")}] " else return "", let mods := if conf.priv then "private " else "", code ← pp format!"{attrs}{mods}lemma {lemma_name} {args} : ({fn_name} {binder.list_to_invocation fn_val_params}).{field} {binder.list_to_invocation field_params} = {st_value} := rfl", if conf.trace then tactic.trace code else skip, return code.to_string meta def assert_not_declared (n : string) : tactic unit := do ret ← try_core $ resolve_constant $ mk_simple_name n, match ret with | some _ := tactic.fail format!"There is already an identifier \"{n}\" in the environment!" | none := return () end meta def handle (conf : config) (obj_def : name) (field : name) : tactic string := do e ← tactic.get_env, obj_def ← tactic.resolve_constant obj_def <|> interaction_monad.fail format!"Could not resolve the identifier \"{obj_def}\"", match e.get obj_def with | exception _ f := do interaction_monad.fail format!"Could not retrieve the declaration associated with \"{obj_def}\" from the environment!" | success decl := match decl with | defn n us type val _ _ := do n ← n.get_suffix, lemma_name ← to_string <$> pp format!"{n}_{field}", assert_not_declared lemma_name, handle_defn lemma_name conf e n us type val field | _ := interaction_monad.fail format!"\"{obj_def}\" must be a definition, not a lemma, theorem, or axiom!" end end end rfl_lemma meta def rfl_lemma_core (conf : rfl_lemma.config) : lean.parser unit := do obj_def ← ident, field ← ident, lean.parser.of_tactic_safe (rfl_lemma.handle conf obj_def field) >>= emit_code_here @[user_command] meta def rfl_lemma_cmd (d : decl_meta_info) (_ : parse $ tk "rfl_lemma") : lean.parser unit := rfl_lemma_core {} @[user_command] meta def rfl_lemma_private_cmd (d : decl_meta_info) (_ : parse $ tk "private rfl_lemma") : lean.parser unit := rfl_lemma_core {priv := tt} @[user_command] meta def rfl_lemma_question_cmd (d : decl_meta_info) (_ : parse $ tk "rfl_lemma?") : lean.parser unit := rfl_lemma_core {trace := tt} @[user_command] meta def rfl_lemma_question_private_cmd (d : decl_meta_info) (_ : parse $ tk "private rfl_lemma?") : lean.parser unit := rfl_lemma_core {trace := tt, priv := tt} end tidy.command
9c2ef456285815e92719c4a20c16359e1c785afa
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/logic/cast.lean
dc06984f99450cf4cfd9d4af415055f58e88e7e3
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,547
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: cast.lean Author: Leonardo de Moura Casts and heterogeneous equality. See also init.datatypes and init.logic. -/ import logic.eq logic.quantifiers open eq.ops section universe variable u variables {A B : Type.{u}} definition cast (H : A = B) (a : A) : B := eq.rec a H theorem cast_refl (a : A) : cast (eq.refl A) a = a := rfl theorem cast_proof_irrel (H₁ H₂ : A = B) (a : A) : cast H₁ a = cast H₂ a := rfl theorem cast_eq (H : A = A) (a : A) : cast H a = a := rfl end namespace heq universe variable u variables {A B C : Type.{u}} {a a' : A} {b b' : B} {c : C} definition type_eq (H : a == b) : A = B := heq.rec_on H (eq.refl A) theorem drec_on {C : Π {B : Type} (b : B), a == b → Type} (H₁ : a == b) (H₂ : C a (refl a)) : C b H₁ := heq.rec (λ H₁ : a == a, show C a H₁, from H₂) H₁ H₁ theorem to_cast_eq (H : a == b) : cast (type_eq H) a = b := drec_on H !cast_eq end heq theorem eq_rec_heq {A : Type} {P : A → Type} {a a' : A} (H : a = a') (p : P a) : eq.rec_on H p == p := eq.drec_on H !heq.refl section universe variables u v variables {A A' B C : Type.{u}} {P P' : A → Type.{v}} {a a' : A} {b : B} theorem hcongr_fun {f : Π x, P x} {f' : Π x, P' x} (a : A) (H₁ : f == f') (H₂ : P = P') : f a == f' a := have aux : ∀ (f : Π x, P x) (f' : Π x, P x), f == f' → f a == f' a, from take f f' H, heq.to_eq H ▸ heq.refl (f a), (H₂ ▸ aux) f f' H₁ theorem hcongr {P' : A' → Type} {f : Π a, P a} {f' : Π a', P' a'} {a : A} {a' : A'} (Hf : f == f') (HP : P == P') (Ha : a == a') : f a == f' a' := have H1 : ∀ (B P' : A → Type) (f : Π x, P x) (f' : Π x, P' x), f == f' → (λx, P x) == (λx, P' x) → f a == f' a, from take P P' f f' Hf HB, hcongr_fun a Hf (heq.to_eq HB), have H2 : ∀ (B : A → Type) (P' : A' → Type) (f : Π x, P x) (f' : Π x, P' x), f == f' → (λx, P x) == (λx, P' x) → f a == f' a', from heq.subst Ha H1, H2 P P' f f' Hf HP theorem hcongr_arg (f : Πx, P x) {a b : A} (H : a = b) : f a == f b := H ▸ (heq.refl (f a)) end section variables {A : Type} {B : A → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} variables {a a' : A} {b : B a} {b' : B a'} {c : C a b} {c' : C a' b'} theorem hcongr_arg2 (f : Πa b, C a b) (Ha : a = a') (Hb : b == b') : f a b == f a' b' := hcongr (hcongr_arg f Ha) (hcongr_arg C Ha) Hb theorem hcongr_arg3 (f : Πa b c, D a b c) (Ha : a = a') (Hb : b == b') (Hc : c == c') : f a b c == f a' b' c' := hcongr (hcongr_arg2 f Ha Hb) (hcongr_arg2 D Ha Hb) Hc end section universe variables u v variables {A A' B C : Type.{u}} {P P' : A → Type.{v}} {a a' : A} {b : B} -- should H₁ be explicit (useful in e.g. hproof_irrel) theorem eq_rec_to_heq {H₁ : a = a'} {p : P a} {p' : P a'} (H₂ : eq.rec_on H₁ p = p') : p == p' := calc p == eq.rec_on H₁ p : heq.symm (eq_rec_heq H₁ p) ... = p' : H₂ theorem cast_to_heq {H₁ : A = B} (H₂ : cast H₁ a = b) : a == b := eq_rec_to_heq H₂ theorem hproof_irrel {a b : Prop} (H : a = b) (H₁ : a) (H₂ : b) : H₁ == H₂ := eq_rec_to_heq (proof_irrel (cast H H₁) H₂) --TODO: generalize to eq.rec. This is a special case of rec_on_compose in eq.lean theorem cast_trans (Hab : A = B) (Hbc : B = C) (a : A) : cast Hbc (cast Hab a) = cast (Hab ⬝ Hbc) a := heq.to_eq (calc cast Hbc (cast Hab a) == cast Hab a : eq_rec_heq Hbc (cast Hab a) ... == a : eq_rec_heq Hab a ... == cast (Hab ⬝ Hbc) a : heq.symm (eq_rec_heq (Hab ⬝ Hbc) a)) theorem pi_eq (H : P = P') : (Π x, P x) = (Π x, P' x) := H ▸ (eq.refl (Π x, P x)) theorem rec_on_app (H : P = P') (f : Π x, P x) (a : A) : eq.rec_on H f a == f a := have aux : ∀ H : P = P, eq.rec_on H f a == f a, from take H : P = P, heq.refl (eq.rec_on H f a), (H ▸ aux) H theorem rec_on_pull (H : P = P') (f : Π x, P x) (a : A) : eq.rec_on H f a = eq.rec_on (congr_fun H a) (f a) := heq.to_eq (calc eq.rec_on H f a == f a : rec_on_app H f a ... == eq.rec_on (congr_fun H a) (f a) : heq.symm (eq_rec_heq (congr_fun H a) (f a))) theorem cast_app (H : P = P') (f : Π x, P x) (a : A) : cast (pi_eq H) f a == f a := have H₁ : ∀ (H : (Π x, P x) = (Π x, P x)), cast H f a == f a, from assume H, heq.of_eq (congr_fun (cast_eq H f) a), have H₂ : ∀ (H : (Π x, P x) = (Π x, P' x)), cast H f a == f a, from H ▸ H₁, H₂ (pi_eq H) end section variables {A : Type} {B : A → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {E : Πa b c, D a b c → Type} {F : Type} variables {a a' : A} {b : B a} {b' : B a'} {c : C a b} {c' : C a' b'} {d : D a b c} {d' : D a' b' c'} theorem hcongr_arg4 (f : Πa b c d, E a b c d) (Ha : a = a') (Hb : b == b') (Hc : c == c') (Hd : d == d') : f a b c d == f a' b' c' d' := hcongr (hcongr_arg3 f Ha Hb Hc) (hcongr_arg3 E Ha Hb Hc) Hd theorem dcongr_arg2 (f : Πa, B a → F) (Ha : a = a') (Hb : eq.rec_on Ha b = b') : f a b = f a' b' := heq.to_eq (hcongr_arg2 f Ha (eq_rec_to_heq Hb)) theorem dcongr_arg3 (f : Πa b, C a b → F) (Ha : a = a') (Hb : eq.rec_on Ha b = b') (Hc : cast (dcongr_arg2 C Ha Hb) c = c') : f a b c = f a' b' c' := heq.to_eq (hcongr_arg3 f Ha (eq_rec_to_heq Hb) (eq_rec_to_heq Hc)) theorem dcongr_arg4 (f : Πa b c, D a b c → F) (Ha : a = a') (Hb : eq.rec_on Ha b = b') (Hc : cast (dcongr_arg2 C Ha Hb) c = c') (Hd : cast (dcongr_arg3 D Ha Hb Hc) d = d') : f a b c d = f a' b' c' d' := heq.to_eq (hcongr_arg4 f Ha (eq_rec_to_heq Hb) (eq_rec_to_heq Hc) (eq_rec_to_heq Hd)) -- mixed versions (we want them for example if C a' b' is a subsingleton, like a proposition. -- Then proving eq is easier than proving heq) theorem hdcongr_arg3 (f : Πa b, C a b → F) (Ha : a = a') (Hb : b == b') (Hc : cast (heq.to_eq (hcongr_arg2 C Ha Hb)) c = c') : f a b c = f a' b' c' := heq.to_eq (hcongr_arg3 f Ha Hb (eq_rec_to_heq Hc)) theorem hhdcongr_arg4 (f : Πa b c, D a b c → F) (Ha : a = a') (Hb : b == b') (Hc : c == c') (Hd : cast (dcongr_arg3 D Ha (!eq.rec_on_irrel_arg ⬝ heq.to_cast_eq Hb) (!eq.rec_on_irrel_arg ⬝ heq.to_cast_eq Hc)) d = d') : f a b c d = f a' b' c' d' := heq.to_eq (hcongr_arg4 f Ha Hb Hc (eq_rec_to_heq Hd)) theorem hddcongr_arg4 (f : Πa b c, D a b c → F) (Ha : a = a') (Hb : b == b') (Hc : cast (heq.to_eq (hcongr_arg2 C Ha Hb)) c = c') (Hd : cast (hdcongr_arg3 D Ha Hb Hc) d = d') : f a b c d = f a' b' c' d' := heq.to_eq (hcongr_arg4 f Ha Hb (eq_rec_to_heq Hc) (eq_rec_to_heq Hd)) --Is a reasonable version of "hcongr2" provable without pi_ext and funext? --It looks like you need some ugly extra conditions -- theorem hcongr2' {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type} {C' : Πa, B' a → Type} -- {f : Π a b, C a b} {f' : Π a' b', C' a' b'} {a : A} {a' : A'} {b : B a} {b' : B' a'} -- (HBB' : B == B') (HCC' : C == C') -- (Hff' : f == f') (Haa' : a == a') (Hbb' : b == b') : f a b == f' a' b' := -- hcongr (hcongr Hff' (sorry) Haa') (hcongr HCC' (sorry) Haa') Hbb' end
68debf9b06689537da1973a2c280baafc24b0ed1
bdb33f8b7ea65f7705fc342a178508e2722eb851
/algebra/field.lean
d199a77b8be467dfe1b12a35b8e62b3d4f6efb25
[ "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
6,769
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 algebra.ring logic.basic open set universe u variables {α : Type u} namespace units variables [division_ring α] {a b : α} /-- Embed an element of a division ring into the unit group. By combining this function with the operations on units, or the `/ₚ` operation, it is possible to write a division as a partial function with three arguments. -/ def mk0 (a : α) (ha : a ≠ 0) : units α := ⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩ @[simp] theorem ne_zero (u : units α) : (u : α) ≠ 0 | h := by simpa [h] using inv_mul u @[simp] theorem inv_eq_inv (u : units α) : (↑u⁻¹ : α) = u⁻¹ := (mul_left_inj u).1 $ by simp @[simp] theorem mk0_val (ha : a ≠ 0) : (mk0 a ha : α) = a := rfl @[simp] theorem mk0_inv (ha : a ≠ 0) : ((mk0 a ha)⁻¹ : α) = a⁻¹ := rfl end units section division_ring variables [s : division_ring α] {a b c : α} include s instance division_ring.to_domain : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, classical.by_contradiction $ λ hn, division_ring.mul_ne_zero (mt or.inl hn) (mt or.inr hn) h ..s } lemma div_eq_mul_inv : a / b = a * b⁻¹ := rfl attribute [simp] div_one zero_div div_self theorem divp_eq_div (a : α) (u : units α) : a /ₚ u = a / u := by simp [divp, (/), algebra.div] @[simp] theorem divp_mk0 (a : α) {b : α} (hb : b ≠ 0) : a /ₚ units.mk0 b hb = a / b := divp_eq_div _ _ lemma inv_div (ha : a ≠ 0) (hb : b ≠ 0) : (a / b)⁻¹ = b / a := by rw [division_def, mul_inv_eq (inv_ne_zero hb) ha, division_ring.inv_inv hb, division_def] lemma inv_div_left (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ / b = (b * a)⁻¹ := by rw [mul_inv_eq ha hb]; refl lemma neg_inv (h : a ≠ 0) : - a⁻¹ = (- a)⁻¹ := by rwa [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma division_ring.inv_comm_of_comm (h : a ≠ 0) (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ := begin have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ := congr_arg (λ x:α, a⁻¹ * x * a⁻¹) H.symm, rwa [mul_assoc, mul_assoc, mul_inv_cancel, mul_one, ← mul_assoc, inv_mul_cancel, one_mul] at this; exact h end lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 := division_ring.mul_ne_zero ha (inv_ne_zero hb) lemma div_ne_zero_iff (hb : b ≠ 0) : a / b ≠ 0 ↔ a ≠ 0 := ⟨mt (λ h, by simp [h]), λ ha, div_ne_zero ha hb⟩ lemma div_eq_zero_iff (hb : b ≠ 0) : a / b = 0 ↔ a = 0 := by haveI := classical.prop_decidable; exact not_iff_not.1 (div_ne_zero_iff hb) lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma div_right_inj (hc : c ≠ 0) : a / c = b / c ↔ a = b := by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_right_inj] lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma division_ring.inv_inj (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b⁻¹ ↔ a = b := ⟨λ h, by simpa [division_ring.inv_inv, ha, hb] using congr_arg (λx,x⁻¹) h, congr_arg (λx,x⁻¹)⟩ lemma division_ring.inv_eq_iff (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b ↔ b⁻¹ = a := by rw [← division_ring.inv_inj (inv_ne_zero ha) hb, eq_comm, division_ring.inv_inv ha] lemma div_neg (a : α) (hb : b ≠ 0) : a / -b = -(a / b) := by rw [← division_ring.neg_div_neg_eq _ (neg_ne_zero.2 hb), neg_neg, neg_div] lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a := ⟨λ h, by rw [← h, div_mul_cancel _ hb], λ h, by rw [← h, mul_div_cancel _ hb]⟩ end division_ring instance field.to_integral_domain [F : field α] : integral_domain α := { ..F, ..division_ring.to_domain } section variables [field α] {a b c d : α} lemma div_eq_inv_mul : a / b = b⁻¹ * a := mul_comm _ _ lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] lemma mul_div_right_comm (a b c : α) : (a * b) / c = (a / c) * b := (div_mul_eq_mul_div _ _ _).symm lemma mul_comm_div (a b c : α) : (a / b) * c = a * (c / b) := by rw [← mul_div_assoc, mul_div_right_comm] lemma div_mul_comm (a b c : α) : (a / b) * c = (c / b) * a := by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm] lemma mul_div_comm (a b c : α) : a * (b / c) = b * (a / c) := by rw [← mul_div_assoc, mul_comm, mul_div_assoc] lemma field.div_right_comm (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / b) / c = (a / c) / b := by rw [field.div_div_eq_div_mul _ hb hc, field.div_div_eq_div_mul _ hc hb, mul_comm] lemma field.div_div_div_cancel_right (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) / (b / c) = a / b := by rw [field.div_div_eq_mul_div _ hb hc, div_mul_cancel _ hc] lemma field.div_mul_div_cancel (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) * (c / b) = a / b := by rw [← mul_div_assoc, div_mul_cancel _ hc] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := (domain.mul_right_inj (mul_ne_zero' hb hd)).symm.trans $ by rw [← mul_assoc, div_mul_cancel _ hb, ← mul_assoc, mul_right_comm, div_mul_cancel _ hd] lemma field.div_div_cancel (ha : a ≠ 0) (hb : b ≠ 0) : a / (a / b) = b := by rw [div_eq_mul_inv, inv_div ha hb, mul_div_cancel' _ ha] end section variables [discrete_field α] {a b c : α} attribute [simp] inv_zero div_zero lemma inv_sub_inv_eq (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := have a * b ≠ 0, by simp [mul_eq_zero_iff_eq_zero_or_eq_zero, ha, hb], calc (a⁻¹ - b⁻¹) = ((a⁻¹ - b⁻¹) * (a * b)) / (a * b) : by rwa [mul_div_cancel] ... = _ : begin simp [mul_add, add_mul, hb, mul_assoc, mul_comm, mul_left_comm], rw [mul_comm a, mul_assoc, mul_comm a⁻¹, mul_inv_cancel ha], simp end lemma div_right_comm (a b c : α) : (a / b) / c = (a / c) / b := if b0 : b = 0 then by simp [b0] else if c0 : c = 0 then by simp [c0] else field.div_right_comm _ b0 c0 lemma div_div_div_cancel_right (a b : α) (hc : c ≠ 0) : (a / c) / (b / c) = a / b := if b0 : b = 0 then by simp [b0] else field.div_div_div_cancel_right _ b0 hc lemma div_mul_div_cancel (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) * (c / b) = a / b := if b0 : b = 0 then by simp [b0] else field.div_mul_div_cancel _ b0 hc lemma div_div_cancel (ha : a ≠ 0) : a / (a / b) = b := if b0 : b = 0 then by simp [b0] else field.div_div_cancel ha b0 end
87e4884e53ff8981c87b184b3e1e16cae2fe4f8a
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/yoneda.lean
4417bb9de949103cdfbc33c2a00777eb39b10883
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
2,371
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .natural_transformation import .opposites import .equivalence import .examples.types.types open tqft.categories open tqft.categories.functor open tqft.categories.natural_transformation open tqft.categories.equivalence open tqft.categories.examples.types namespace tqft.categories.yoneda local attribute [pointwise] funext definition {u v} Yoneda ( C : Category.{u v} ) : Functor C (FunctorCategory (Opposite C) CategoryOfTypes.{v}) := { onObjects := λ X, { onObjects := λ Y, C.Hom Y X, onMorphisms := λ Y Y' f, λ g, C.compose f g, identities := ♯, functoriality := ♯ }, onMorphisms := λ X X' f, { components := λ Y, λ g, C.compose g f, naturality := ♯ }, identities := ♮, functoriality := ♯ } theorem {u v} YonedaEmbedding ( C : Category.{u v} ) : Embedding (Yoneda C) := begin -- This almost works very quickly with blast, but too much gets deferred. -- blast, -- rewrite id_locked_eq, -- FIXME why doesn't blast do this? -- all_goals { try { -- pose p := congr_arg (λ T, NaturalTransformation.components T) a, -- simp at p, -- pose p' := congr_fun p X, -- simp at p', -- pose p'' := congr_fun p' (C.identity X), -- simp at p'', -- exact p'' -- } }, unfold Embedding, unfold Yoneda, split, -- First we show it is full. begin unfold Full, intros, unfold Surjective, fapply subtype.mk, -- we ned to build a preimage, which is expressed as a subtype. -- Now we have to construct the preimage begin intros, exact (a.components X) (C.identity X), -- <-- this is a critical step for surjectivity end, -- then verify that it really is a preimage begin blast end, end, -- Second we show it is faithful. begin unfold Faithful, intros, unfold Injective, apply plift.up, intros X Y f g, simp, intros a, pose p := congr_arg (λ T, NaturalTransformation.components T) a, simp at p, pose p' := congr_fun p X, simp at p', pose p'' := congr_fun p' (C.identity X), simp at p'', exact p'' end end end tqft.categories.yoneda
2ce9c354cf371f2fbe612dfca24cae4c46f54281
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/indimp.lean
652ed04aedf6b27aacab6ebe30e3b479c37203cc
[ "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
500
lean
prelude definition Prop := Type.{0} inductive nat := zero : nat, succ : nat → nat inductive list (A : Type) := nil {} : list A, cons : A → list A → list A inductive list2 (A : Type) : Type := nil2 {} : list2 A, cons2 : A → list2 A → list2 A inductive and (A B : Prop) : Prop := and_intro : A → B → and A B inductive cls {T1 : Type} (R1 : T1 → T1 → Prop) {T2 : Type} (R2 : T2 → T2 → Prop) (f : T1 → T2) := mk : (∀x y : T1, R1 x y → R2 (f x) (f y)) → cls R1 R2 f
a538a283c8c8d302141491f635dd581db316ac9a
cc5bb0a18c45fa529fc8bf0365b1fbf48464c5a8
/tests/lean/run/check_constants.lean
846a49085bb12a2eb56c62e949a604e7d4de50e5
[ "Apache-2.0" ]
permissive
mk12/lean
6bb58b9f3cfe312236b41779478d345399f00918
092fc89333160661c4c5a6295f3054cafff4341e
refs/heads/master
1,609,531,450,083
1,501,275,267,000
1,501,278,025,000
98,760,144
0
0
null
1,501,364,485,000
1,501,364,485,000
null
UTF-8
Lean
false
false
15,016
lean
-- DO NOT EDIT, automatically generated file, generator scripts/gen_constants_cpp.py import smt system.io open tactic meta def script_check_id (n : name) : tactic unit := do env ← get_env, (env^.get n >> return ()) <|> (guard $ env^.is_namespace n) <|> (attribute.get_instances n >> return ()) <|> fail ("identifier '" ++ to_string n ++ "' is not a constant, namespace nor attribute") run_cmd script_check_id `abs run_cmd script_check_id `absurd run_cmd script_check_id `acc.cases_on run_cmd script_check_id `acc.rec run_cmd script_check_id `add_comm_group run_cmd script_check_id `add_comm_semigroup run_cmd script_check_id `add_group run_cmd script_check_id `add_monoid run_cmd script_check_id `and run_cmd script_check_id `and.elim_left run_cmd script_check_id `and.elim_right run_cmd script_check_id `and.intro run_cmd script_check_id `and.rec run_cmd script_check_id `and.cases_on run_cmd script_check_id `auto_param run_cmd script_check_id `bit0 run_cmd script_check_id `bit1 run_cmd script_check_id `bin_tree.empty run_cmd script_check_id `bin_tree.leaf run_cmd script_check_id `bin_tree.node run_cmd script_check_id `bool run_cmd script_check_id `bool.ff run_cmd script_check_id `bool.tt run_cmd script_check_id `combinator.K run_cmd script_check_id `caching_user_attribute run_cmd script_check_id `cast run_cmd script_check_id `cast_heq run_cmd script_check_id `char run_cmd script_check_id `char.of_nat run_cmd script_check_id `char.of_nat_ne_of_ne run_cmd script_check_id `classical.prop_decidable run_cmd script_check_id `classical.type_decidable_eq run_cmd script_check_id `coe run_cmd script_check_id `coe_fn run_cmd script_check_id `coe_sort run_cmd script_check_id `coe_to_lift run_cmd script_check_id `congr run_cmd script_check_id `congr_arg run_cmd script_check_id `congr_fun run_cmd script_check_id `decidable run_cmd script_check_id `decidable.to_bool run_cmd script_check_id `distrib run_cmd script_check_id `dite run_cmd script_check_id `id run_cmd script_check_id `empty run_cmd script_check_id `Exists run_cmd script_check_id `eq run_cmd script_check_id `eq.cases_on run_cmd script_check_id `eq.drec run_cmd script_check_id `eq.mp run_cmd script_check_id `eq.mpr run_cmd script_check_id `eq.rec run_cmd script_check_id `eq.refl run_cmd script_check_id `eq.subst run_cmd script_check_id `eq.symm run_cmd script_check_id `eq.trans run_cmd script_check_id `eq_of_heq run_cmd script_check_id `eq_rec_heq run_cmd script_check_id `eq_true_intro run_cmd script_check_id `eq_false_intro run_cmd script_check_id `eq_self_iff_true run_cmd script_check_id `expr run_cmd script_check_id `expr.subst run_cmd script_check_id `format run_cmd script_check_id `false run_cmd script_check_id `false_of_true_iff_false run_cmd script_check_id `false_of_true_eq_false run_cmd script_check_id `true_eq_false_of_false run_cmd script_check_id `false.rec run_cmd script_check_id `field run_cmd script_check_id `fin.mk run_cmd script_check_id `fin.ne_of_vne run_cmd script_check_id `forall_congr run_cmd script_check_id `forall_congr_eq run_cmd script_check_id `forall_not_of_not_exists run_cmd script_check_id `funext run_cmd script_check_id `ge run_cmd script_check_id `gt run_cmd script_check_id `has_add run_cmd script_check_id `has_add.add run_cmd script_check_id `andthen run_cmd script_check_id `has_bind.and_then run_cmd script_check_id `has_bind.bind run_cmd script_check_id `has_bind.seq run_cmd script_check_id `has_div run_cmd script_check_id `has_div.div run_cmd script_check_id `has_emptyc.emptyc run_cmd script_check_id `has_mod.mod run_cmd script_check_id `has_mul run_cmd script_check_id `has_mul.mul run_cmd script_check_id `has_insert.insert run_cmd script_check_id `has_inv run_cmd script_check_id `has_inv.inv run_cmd script_check_id `has_le run_cmd script_check_id `has_le.le run_cmd script_check_id `has_lt run_cmd script_check_id `has_lt.lt run_cmd script_check_id `has_neg run_cmd script_check_id `has_neg.neg run_cmd script_check_id `has_one run_cmd script_check_id `has_one.one run_cmd script_check_id `has_orelse.orelse run_cmd script_check_id `has_sep.sep run_cmd script_check_id `has_sizeof run_cmd script_check_id `has_sizeof.mk run_cmd script_check_id `has_sub run_cmd script_check_id `has_sub.sub run_cmd script_check_id `has_to_format run_cmd script_check_id `has_repr run_cmd script_check_id `has_well_founded run_cmd script_check_id `has_well_founded.r run_cmd script_check_id `has_well_founded.wf run_cmd script_check_id `has_zero run_cmd script_check_id `has_zero.zero run_cmd script_check_id `has_coe_t run_cmd script_check_id `heq run_cmd script_check_id `heq.refl run_cmd script_check_id `heq.symm run_cmd script_check_id `heq.trans run_cmd script_check_id `heq_of_eq run_cmd script_check_id `hole_command run_cmd script_check_id `id_locked run_cmd script_check_id `id_rhs run_cmd script_check_id `if_neg run_cmd script_check_id `if_pos run_cmd script_check_id `iff run_cmd script_check_id `iff_false_intro run_cmd script_check_id `iff.intro run_cmd script_check_id `iff.mp run_cmd script_check_id `iff.mpr run_cmd script_check_id `iff.refl run_cmd script_check_id `iff.symm run_cmd script_check_id `iff.trans run_cmd script_check_id `iff_true_intro run_cmd script_check_id `imp_congr run_cmd script_check_id `imp_congr_eq run_cmd script_check_id `imp_congr_ctx run_cmd script_check_id `imp_congr_ctx_eq run_cmd script_check_id `implies run_cmd script_check_id `implies_of_if_neg run_cmd script_check_id `implies_of_if_pos run_cmd script_check_id `int run_cmd script_check_id `int.has_add run_cmd script_check_id `int.has_mul run_cmd script_check_id `int.has_sub run_cmd script_check_id `int.has_div run_cmd script_check_id `int.has_le run_cmd script_check_id `int.has_lt run_cmd script_check_id `int.has_neg run_cmd script_check_id `int.has_mod run_cmd script_check_id `int.bit0_nonneg run_cmd script_check_id `int.bit1_nonneg run_cmd script_check_id `int.one_nonneg run_cmd script_check_id `int.zero_nonneg run_cmd script_check_id `int.bit0_pos run_cmd script_check_id `int.bit1_pos run_cmd script_check_id `int.one_pos run_cmd script_check_id `int.nat_abs_zero run_cmd script_check_id `int.nat_abs_one run_cmd script_check_id `int.nat_abs_bit0_step run_cmd script_check_id `int.nat_abs_bit1_nonneg_step run_cmd script_check_id `int.ne_of_nat_ne_nonneg_case run_cmd script_check_id `int.ne_neg_of_ne run_cmd script_check_id `int.neg_ne_of_pos run_cmd script_check_id `int.ne_neg_of_pos run_cmd script_check_id `int.neg_ne_zero_of_ne run_cmd script_check_id `int.zero_ne_neg_of_ne run_cmd script_check_id `int.decidable_linear_ordered_comm_group run_cmd script_check_id `interactive.param_desc run_cmd script_check_id `interactive.parse run_cmd script_check_id `io run_cmd script_check_id `io.interface run_cmd script_check_id `is_associative run_cmd script_check_id `is_associative.assoc run_cmd script_check_id `is_commutative run_cmd script_check_id `is_commutative.comm run_cmd script_check_id `ite run_cmd script_check_id `lean.parser run_cmd script_check_id `lean.parser.pexpr run_cmd script_check_id `lean.parser.tk run_cmd script_check_id `left_distrib run_cmd script_check_id `left_comm run_cmd script_check_id `le_refl run_cmd script_check_id `linear_ordered_ring run_cmd script_check_id `linear_ordered_semiring run_cmd script_check_id `list run_cmd script_check_id `list.nil run_cmd script_check_id `list.cons run_cmd script_check_id `match_failed run_cmd script_check_id `monad run_cmd script_check_id `monad_fail run_cmd script_check_id `monoid run_cmd script_check_id `mul_one run_cmd script_check_id `mul_zero run_cmd script_check_id `mul_zero_class run_cmd script_check_id `name.anonymous run_cmd script_check_id `name.mk_numeral run_cmd script_check_id `name.mk_string run_cmd script_check_id `nat run_cmd script_check_id `nat.succ run_cmd script_check_id `nat.zero run_cmd script_check_id `nat.has_zero run_cmd script_check_id `nat.has_one run_cmd script_check_id `nat.has_add run_cmd script_check_id `nat.add run_cmd script_check_id `nat.cases_on run_cmd script_check_id `nat.bit0_ne run_cmd script_check_id `nat.bit0_ne_bit1 run_cmd script_check_id `nat.bit0_ne_zero run_cmd script_check_id `nat.bit0_ne_one run_cmd script_check_id `nat.bit1_ne run_cmd script_check_id `nat.bit1_ne_bit0 run_cmd script_check_id `nat.bit1_ne_zero run_cmd script_check_id `nat.bit1_ne_one run_cmd script_check_id `nat.zero_ne_one run_cmd script_check_id `nat.zero_ne_bit0 run_cmd script_check_id `nat.zero_ne_bit1 run_cmd script_check_id `nat.one_ne_zero run_cmd script_check_id `nat.one_ne_bit0 run_cmd script_check_id `nat.one_ne_bit1 run_cmd script_check_id `nat.bit0_lt run_cmd script_check_id `nat.bit1_lt run_cmd script_check_id `nat.bit0_lt_bit1 run_cmd script_check_id `nat.bit1_lt_bit0 run_cmd script_check_id `nat.zero_lt_one run_cmd script_check_id `nat.zero_lt_bit1 run_cmd script_check_id `nat.zero_lt_bit0 run_cmd script_check_id `nat.one_lt_bit0 run_cmd script_check_id `nat.one_lt_bit1 run_cmd script_check_id `nat.le_of_lt run_cmd script_check_id `nat.le_refl run_cmd script_check_id `ne run_cmd script_check_id `neq_of_not_iff run_cmd script_check_id `norm_num.add1 run_cmd script_check_id `norm_num.add1_bit0 run_cmd script_check_id `norm_num.add1_bit1_helper run_cmd script_check_id `norm_num.add1_one run_cmd script_check_id `norm_num.add1_zero run_cmd script_check_id `norm_num.add_div_helper run_cmd script_check_id `norm_num.bin_add_zero run_cmd script_check_id `norm_num.bin_zero_add run_cmd script_check_id `norm_num.bit0_add_bit0_helper run_cmd script_check_id `norm_num.bit0_add_bit1_helper run_cmd script_check_id `norm_num.bit0_add_one run_cmd script_check_id `norm_num.bit1_add_bit0_helper run_cmd script_check_id `norm_num.bit1_add_bit1_helper run_cmd script_check_id `norm_num.bit1_add_one_helper run_cmd script_check_id `norm_num.div_add_helper run_cmd script_check_id `norm_num.div_eq_div_helper run_cmd script_check_id `norm_num.div_helper run_cmd script_check_id `norm_num.div_mul_helper run_cmd script_check_id `norm_num.mk_cong run_cmd script_check_id `norm_num.mul_bit0_helper run_cmd script_check_id `norm_num.mul_bit1_helper run_cmd script_check_id `norm_num.mul_div_helper run_cmd script_check_id `norm_num.neg_add_neg_helper run_cmd script_check_id `norm_num.neg_add_pos_helper1 run_cmd script_check_id `norm_num.neg_add_pos_helper2 run_cmd script_check_id `norm_num.neg_mul_neg_helper run_cmd script_check_id `norm_num.neg_mul_pos_helper run_cmd script_check_id `norm_num.neg_neg_helper run_cmd script_check_id `norm_num.neg_zero_helper run_cmd script_check_id `norm_num.nonneg_bit0_helper run_cmd script_check_id `norm_num.nonneg_bit1_helper run_cmd script_check_id `norm_num.nonzero_of_div_helper run_cmd script_check_id `norm_num.nonzero_of_neg_helper run_cmd script_check_id `norm_num.nonzero_of_pos_helper run_cmd script_check_id `norm_num.one_add_bit0 run_cmd script_check_id `norm_num.one_add_bit1_helper run_cmd script_check_id `norm_num.one_add_one run_cmd script_check_id `norm_num.pos_add_neg_helper run_cmd script_check_id `norm_num.pos_bit0_helper run_cmd script_check_id `norm_num.pos_bit1_helper run_cmd script_check_id `norm_num.pos_mul_neg_helper run_cmd script_check_id `norm_num.sub_nat_zero_helper run_cmd script_check_id `norm_num.sub_nat_pos_helper run_cmd script_check_id `norm_num.subst_into_div run_cmd script_check_id `norm_num.subst_into_prod run_cmd script_check_id `norm_num.subst_into_subtr run_cmd script_check_id `norm_num.subst_into_sum run_cmd script_check_id `not run_cmd script_check_id `not_of_iff_false run_cmd script_check_id `not_of_eq_false run_cmd script_check_id `of_eq_true run_cmd script_check_id `of_iff_true run_cmd script_check_id `opt_param run_cmd script_check_id `or run_cmd script_check_id `inout_param run_cmd script_check_id `punit run_cmd script_check_id `punit.star run_cmd script_check_id `prod.mk run_cmd script_check_id `pprod run_cmd script_check_id `pprod.mk run_cmd script_check_id `pprod.fst run_cmd script_check_id `pprod.snd run_cmd script_check_id `propext run_cmd script_check_id `to_pexpr run_cmd script_check_id `quot.mk run_cmd script_check_id `quot.lift run_cmd script_check_id `real run_cmd script_check_id `real.of_int run_cmd script_check_id `real.to_int run_cmd script_check_id `real.is_int run_cmd script_check_id `real.has_neg run_cmd script_check_id `real.has_div run_cmd script_check_id `real.has_add run_cmd script_check_id `real.has_mul run_cmd script_check_id `real.has_sub run_cmd script_check_id `real.has_lt run_cmd script_check_id `real.has_le run_cmd script_check_id `reflected run_cmd script_check_id `reflected.subst run_cmd script_check_id `repr run_cmd script_check_id `rfl run_cmd script_check_id `right_distrib run_cmd script_check_id `ring run_cmd script_check_id `scope_trace run_cmd script_check_id `set_of run_cmd script_check_id `semiring run_cmd script_check_id `psigma run_cmd script_check_id `psigma.cases_on run_cmd script_check_id `psigma.mk run_cmd script_check_id `psigma.fst run_cmd script_check_id `psigma.snd run_cmd script_check_id `singleton run_cmd script_check_id `sizeof run_cmd script_check_id `smt.array run_cmd script_check_id `smt.select run_cmd script_check_id `smt.store run_cmd script_check_id `smt.prove run_cmd script_check_id `string run_cmd script_check_id `string.empty run_cmd script_check_id `string.str run_cmd script_check_id `string.empty_ne_str run_cmd script_check_id `string.str_ne_empty run_cmd script_check_id `string.str_ne_str_left run_cmd script_check_id `string.str_ne_str_right run_cmd script_check_id `subsingleton run_cmd script_check_id `subsingleton.elim run_cmd script_check_id `subsingleton.helim run_cmd script_check_id `subtype run_cmd script_check_id `subtype.mk run_cmd script_check_id `subtype.val run_cmd script_check_id `subtype.rec run_cmd script_check_id `psum run_cmd script_check_id `psum.cases_on run_cmd script_check_id `psum.inl run_cmd script_check_id `psum.inr run_cmd script_check_id `tactic run_cmd script_check_id `tactic.try run_cmd script_check_id `tactic.triv run_cmd script_check_id `thunk run_cmd script_check_id `to_fmt run_cmd script_check_id `trans_rel_left run_cmd script_check_id `trans_rel_right run_cmd script_check_id `true run_cmd script_check_id `true.intro run_cmd script_check_id `unification_hint run_cmd script_check_id `unification_hint.mk run_cmd script_check_id `unit run_cmd script_check_id `unit.cases_on run_cmd script_check_id `unit.star run_cmd script_check_id `unsafe_monad_from_pure_bind run_cmd script_check_id `user_attribute run_cmd script_check_id `vm_monitor run_cmd script_check_id `weak_order run_cmd script_check_id `well_founded.fix run_cmd script_check_id `well_founded.fix_eq run_cmd script_check_id `well_founded_tactics run_cmd script_check_id `well_founded_tactics.default run_cmd script_check_id `well_founded_tactics.rel_tac run_cmd script_check_id `well_founded_tactics.dec_tac run_cmd script_check_id `xor run_cmd script_check_id `zero_le_one run_cmd script_check_id `zero_lt_one run_cmd script_check_id `zero_mul
f5ce0eb55d554e8a1811a7c4bbac808831d9d0aa
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Inductive.lean
25ba641af1e14c69f12bcf82b854d9cd112cecfa
[ "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
770
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic /-! # Helper methods for inductive datatypes -/ namespace Lean.Meta /-- Return true if the types of the given constructors are compatible. -/ def compatibleCtors (ctorName₁ ctorName₂ : Name) : MetaM Bool := do let ctorInfo₁ ← getConstInfoCtor ctorName₁ let ctorInfo₂ ← getConstInfoCtor ctorName₂ if ctorInfo₁.induct != ctorInfo₂.induct then return false else let (_, _, ctorType₁) ← forallMetaTelescope ctorInfo₁.type let (_, _, ctorType₂) ← forallMetaTelescope ctorInfo₂.type isDefEq ctorType₁ ctorType₂ end Lean.Meta
fa9008c0c260eb7166e428fe811fbd824a32b5ce
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/algebra/group/basic.lean
d07655a08c6627d1eddc39373bc63e822327cba7
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
16,280
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.defs import logic.function.basic universe u section associative variables {α : Type u} (f : α → α → α) [is_associative α f] (x y : α) /-- Composing two associative operations of `f : α → α → α` on the left is equal to an associative operation on the left. -/ lemma comp_assoc_left : (f x) ∘ (f y) = (f (f x y)) := by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] } /-- Composing two associative operations of `f : α → α → α` on the right is equal to an associative operation on the right. -/ lemma comp_assoc_right : (λ z, f z x) ∘ (λ z, f z y) = (λ z, f z (f y x)) := by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] } end associative section semigroup variables {α : Type*} /-- Composing two multiplications on the left by `y` then `x` is equal to a multiplication on the left by `x * y`. -/ @[simp, to_additive "Composing two additions on the left by `y` then `x` is equal to a addition on the left by `x + y`."] lemma comp_mul_left [semigroup α] (x y : α) : ((*) x) ∘ ((*) y) = ((*) (x * y)) := comp_assoc_left _ _ _ /-- Composing two multiplications on the right by `y` and `x` is equal to a multiplication on the right by `y * x`. -/ @[simp, to_additive "Composing two additions on the right by `y` and `x` is equal to a addition on the right by `y + x`."] lemma comp_mul_right [semigroup α] (x y : α) : (* x) ∘ (* y) = (* (y * x)) := comp_assoc_right _ _ _ end semigroup section monoid variables {M : Type u} [monoid M] @[to_additive] lemma ite_mul_one {P : Prop} [decidable P] {a b : M} : ite P (a * b) 1 = ite P a 1 * ite P b 1 := by { by_cases h : P; simp [h], } @[to_additive] lemma eq_one_iff_eq_one_of_mul_eq_one {a b : M} (h : a * b = 1) : a = 1 ↔ b = 1 := by split; { rintro rfl, simpa using h } end monoid section comm_semigroup variables {G : Type u} [comm_semigroup G] @[no_rsimp, to_additive] lemma mul_left_comm : ∀ a b c : G, a * (b * c) = b * (a * c) := left_comm has_mul.mul mul_comm mul_assoc attribute [no_rsimp] add_left_comm @[to_additive] lemma mul_right_comm : ∀ a b c : G, a * b * c = a * c * b := right_comm has_mul.mul mul_comm mul_assoc @[to_additive] theorem mul_mul_mul_comm (a b c d : G) : (a * b) * (c * d) = (a * c) * (b * d) := by simp only [mul_left_comm, mul_assoc] end comm_semigroup local attribute [simp] mul_assoc sub_eq_add_neg section add_monoid variables {M : Type u} [add_monoid M] {a b c : M} @[simp] lemma bit0_zero : bit0 (0 : M) = 0 := add_zero _ @[simp] lemma bit1_zero [has_one M] : bit1 (0 : M) = 1 := by rw [bit1, bit0_zero, zero_add] end add_monoid section comm_monoid variables {M : Type u} [comm_monoid M] {x y z : M} @[to_additive] lemma inv_unique (hy : x * y = 1) (hz : x * z = 1) : y = z := left_inv_eq_right_inv (trans (mul_comm _ _) hy) hz end comm_monoid section left_cancel_monoid variables {M : Type u} [left_cancel_monoid M] {a b : M} @[simp, to_additive] lemma mul_eq_left_iff : a * b = a ↔ b = 1 := calc a * b = a ↔ a * b = a * 1 : by rw mul_one ... ↔ b = 1 : mul_left_cancel_iff @[simp, to_additive] lemma left_eq_mul_iff : a = a * b ↔ b = 1 := eq_comm.trans mul_eq_left_iff end left_cancel_monoid section right_cancel_monoid variables {M : Type u} [right_cancel_monoid M] {a b : M} @[simp, to_additive] lemma mul_eq_right_iff : a * b = b ↔ a = 1 := calc a * b = b ↔ a * b = 1 * b : by rw one_mul ... ↔ a = 1 : mul_right_cancel_iff @[simp, to_additive] lemma right_eq_mul_iff : b = a * b ↔ a = 1 := eq_comm.trans mul_eq_right_iff end right_cancel_monoid section div_inv_monoid variables {G : Type u} [div_inv_monoid G] @[to_additive] lemma inv_eq_one_div (x : G) : x⁻¹ = 1 / x := by rw [div_eq_mul_inv, one_mul] @[to_additive] lemma mul_one_div (x y : G) : x * (1 / y) = x / y := by rw [div_eq_mul_inv, one_mul, div_eq_mul_inv] lemma mul_div_assoc {a b c : G} : a * b / c = a * (b / c) := by rw [div_eq_mul_inv, div_eq_mul_inv, mul_assoc _ _ _] lemma mul_div_assoc' (a b c : G) : a * (b / c) = (a * b) / c := mul_div_assoc.symm @[simp, to_additive] lemma one_div (a : G) : 1 / a = a⁻¹ := (inv_eq_one_div a).symm end div_inv_monoid section group variables {G : Type u} [group G] {a b c : G} @[simp, to_additive] lemma inv_mul_cancel_right (a b : G) : a * b⁻¹ * b = a := by simp [mul_assoc] @[simp, to_additive neg_zero] lemma one_inv : 1⁻¹ = (1 : G) := inv_eq_of_mul_eq_one (one_mul 1) @[to_additive] theorem left_inverse_inv (G) [group G] : function.left_inverse (λ a : G, a⁻¹) (λ a, a⁻¹) := inv_inv @[simp, to_additive] lemma inv_involutive : function.involutive (has_inv.inv : G → G) := inv_inv @[to_additive] lemma inv_injective : function.injective (has_inv.inv : G → G) := inv_involutive.injective @[simp, to_additive] theorem inv_inj : a⁻¹ = b⁻¹ ↔ a = b := inv_injective.eq_iff @[simp, to_additive] lemma mul_inv_cancel_left (a b : G) : a * (a⁻¹ * b) = b := by rw [← mul_assoc, mul_right_inv, one_mul] @[to_additive] theorem mul_left_surjective (a : G) : function.surjective ((*) a) := λ x, ⟨a⁻¹ * x, mul_inv_cancel_left a x⟩ @[to_additive] theorem mul_right_surjective (a : G) : function.surjective (λ x, x * a) := λ x, ⟨x * a⁻¹, inv_mul_cancel_right x a⟩ @[simp, to_additive neg_add_rev] lemma mul_inv_rev (a b : G) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := inv_eq_of_mul_eq_one $ by simp @[to_additive] lemma eq_inv_of_eq_inv (h : a = b⁻¹) : b = a⁻¹ := by simp [h] @[to_additive] lemma eq_inv_of_mul_eq_one (h : a * b = 1) : a = b⁻¹ := have a⁻¹ = b, from inv_eq_of_mul_eq_one h, by simp [this.symm] @[to_additive] lemma eq_mul_inv_of_mul_eq (h : a * c = b) : a = b * c⁻¹ := by simp [h.symm] @[to_additive] lemma eq_inv_mul_of_mul_eq (h : b * a = c) : a = b⁻¹ * c := by simp [h.symm] @[to_additive] lemma inv_mul_eq_of_eq_mul (h : b = a * c) : a⁻¹ * b = c := by simp [h] @[to_additive] lemma mul_inv_eq_of_eq_mul (h : a = c * b) : a * b⁻¹ = c := by simp [h] @[to_additive] lemma eq_mul_of_mul_inv_eq (h : a * c⁻¹ = b) : a = b * c := by simp [h.symm] @[to_additive] lemma eq_mul_of_inv_mul_eq (h : b⁻¹ * a = c) : a = b * c := by simp [h.symm, mul_inv_cancel_left] @[to_additive] lemma mul_eq_of_eq_inv_mul (h : b = a⁻¹ * c) : a * b = c := by rw [h, mul_inv_cancel_left] @[to_additive] lemma mul_eq_of_eq_mul_inv (h : a = c * b⁻¹) : a * b = c := by simp [h] @[to_additive] theorem mul_self_iff_eq_one : a * a = a ↔ a = 1 := by have := @mul_right_inj _ _ a a 1; rwa mul_one at this @[simp, to_additive] theorem inv_eq_one : a⁻¹ = 1 ↔ a = 1 := by rw [← @inv_inj _ _ a 1, one_inv] @[simp, to_additive] theorem one_eq_inv : 1 = a⁻¹ ↔ a = 1 := by rw [eq_comm, inv_eq_one] @[to_additive] theorem inv_ne_one : a⁻¹ ≠ 1 ↔ a ≠ 1 := not_congr inv_eq_one @[to_additive] theorem eq_inv_iff_eq_inv : a = b⁻¹ ↔ b = a⁻¹ := ⟨eq_inv_of_eq_inv, eq_inv_of_eq_inv⟩ @[to_additive] theorem inv_eq_iff_inv_eq : a⁻¹ = b ↔ b⁻¹ = a := eq_comm.trans $ eq_inv_iff_eq_inv.trans eq_comm @[to_additive] theorem mul_eq_one_iff_eq_inv : a * b = 1 ↔ a = b⁻¹ := by simpa [mul_left_inv, -mul_left_inj] using @mul_left_inj _ _ b a (b⁻¹) @[to_additive] theorem mul_eq_one_iff_inv_eq : a * b = 1 ↔ a⁻¹ = b := by rw [mul_eq_one_iff_eq_inv, eq_inv_iff_eq_inv, eq_comm] @[to_additive] theorem eq_inv_iff_mul_eq_one : a = b⁻¹ ↔ a * b = 1 := mul_eq_one_iff_eq_inv.symm @[to_additive] theorem inv_eq_iff_mul_eq_one : a⁻¹ = b ↔ a * b = 1 := mul_eq_one_iff_inv_eq.symm @[to_additive] theorem eq_mul_inv_iff_mul_eq : a = b * c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq : a = b⁻¹ * c ↔ b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul : a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul : a * b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ @[to_additive] theorem mul_inv_eq_one : a * b⁻¹ = 1 ↔ a = b := by rw [mul_eq_one_iff_eq_inv, inv_inv] @[to_additive] theorem inv_mul_eq_one : a⁻¹ * b = 1 ↔ a = b := by rw [mul_eq_one_iff_eq_inv, inv_inj] @[simp, to_additive] lemma mul_left_eq_self : a * b = b ↔ a = 1 := ⟨λ h, @mul_right_cancel _ _ a b 1 (by simp [h]), λ h, by simp [h]⟩ @[simp, to_additive] lemma mul_right_eq_self : a * b = a ↔ b = 1 := ⟨λ h, @mul_left_cancel _ _ a b 1 (by simp [h]), λ h, by simp [h]⟩ @[to_additive] lemma div_left_injective : function.injective (λ a, a / b) := by simpa only [div_eq_mul_inv] using λ a a' h, mul_left_injective (b⁻¹) h @[to_additive] lemma div_right_injective : function.injective (λ a, b / a) := by simpa only [div_eq_mul_inv] using λ a a' h, inv_injective (mul_right_injective b h) end group section add_group variables {G : Type u} [add_group G] {a b c d : G} @[simp] lemma sub_self (a : G) : a - a = 0 := by rw [sub_eq_add_neg, add_right_neg a] @[simp] lemma sub_add_cancel (a b : G) : a - b + b = a := by rw [sub_eq_add_neg, neg_add_cancel_right a b] @[simp] lemma add_sub_cancel (a b : G) : a + b - b = a := by rw [sub_eq_add_neg, add_neg_cancel_right a b] lemma add_sub_assoc (a b c : G) : a + b - c = a + (b - c) := by rw [sub_eq_add_neg, add_assoc, ←sub_eq_add_neg] lemma eq_of_sub_eq_zero (h : a - b = 0) : a = b := have 0 + b = b, by rw zero_add, have (a - b) + b = b, by rwa h, by rwa [sub_eq_add_neg, neg_add_cancel_right] at this lemma sub_eq_zero_of_eq (h : a = b) : a - b = 0 := by rw [h, sub_self] lemma sub_eq_zero_iff_eq : a - b = 0 ↔ a = b := ⟨eq_of_sub_eq_zero, sub_eq_zero_of_eq⟩ @[simp] lemma sub_zero (a : G) : a - 0 = a := by rw [sub_eq_add_neg, neg_zero, add_zero] lemma sub_ne_zero_of_ne (h : a ≠ b) : a - b ≠ 0 := begin intro hab, apply h, apply eq_of_sub_eq_zero hab end @[simp] lemma sub_neg_eq_add (a b : G) : a - (-b) = a + b := by rw [sub_eq_add_neg, neg_neg] @[simp] lemma neg_sub (a b : G) : -(a - b) = b - a := neg_eq_of_add_eq_zero (by rw [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, add_right_neg]) local attribute [simp] add_assoc lemma add_sub (a b c : G) : a + (b - c) = a + b - c := by simp lemma sub_add_eq_sub_sub_swap (a b c : G) : a - (b + c) = a - c - b := by simp @[simp] lemma add_sub_add_right_eq_sub (a b c : G) : (a + c) - (b + c) = a - b := by rw [sub_add_eq_sub_sub_swap]; simp lemma eq_sub_of_add_eq (h : a + c = b) : a = b - c := by simp [h.symm] lemma sub_eq_of_eq_add (h : a = c + b) : a - b = c := by simp [h] lemma eq_add_of_sub_eq (h : a - c = b) : a = b + c := by simp [h.symm] lemma add_eq_of_eq_sub (h : a = c - b) : a + b = c := by simp [h] @[simp] lemma sub_right_inj : a - b = a - c ↔ b = c := sub_right_injective.eq_iff @[simp] lemma sub_left_inj : b - a = c - a ↔ b = c := by { rw [sub_eq_add_neg, sub_eq_add_neg], exact add_left_inj _ } lemma sub_add_sub_cancel (a b c : G) : (a - b) + (b - c) = a - c := by rw [← add_sub_assoc, sub_add_cancel] lemma sub_sub_sub_cancel_right (a b c : G) : (a - c) - (b - c) = a - b := by rw [← neg_sub c b, sub_neg_eq_add, sub_add_sub_cancel] theorem sub_sub_assoc_swap : a - (b - c) = a + c - b := by simp theorem sub_eq_zero : a - b = 0 ↔ a = b := ⟨eq_of_sub_eq_zero, λ h, by rw [h, sub_self]⟩ theorem sub_ne_zero : a - b ≠ 0 ↔ a ≠ b := not_congr sub_eq_zero theorem eq_sub_iff_add_eq : a = b - c ↔ a + c = b := by rw [sub_eq_add_neg, eq_add_neg_iff_add_eq] theorem sub_eq_iff_eq_add : a - b = c ↔ a = c + b := by rw [sub_eq_add_neg, add_neg_eq_iff_eq_add] theorem eq_iff_eq_of_sub_eq_sub (H : a - b = c - d) : a = b ↔ c = d := by rw [← sub_eq_zero, H, sub_eq_zero] theorem left_inverse_sub_add_left (c : G) : function.left_inverse (λ x, x - c) (λ x, x + c) := assume x, add_sub_cancel x c theorem left_inverse_add_left_sub (c : G) : function.left_inverse (λ x, x + c) (λ x, x - c) := assume x, sub_add_cancel x c theorem left_inverse_add_right_neg_add (c : G) : function.left_inverse (λ x, c + x) (λ x, - c + x) := assume x, add_neg_cancel_left c x theorem left_inverse_neg_add_add_right (c : G) : function.left_inverse (λ x, - c + x) (λ x, c + x) := assume x, neg_add_cancel_left c x end add_group section comm_group variables {G : Type u} [comm_group G] @[to_additive neg_add] lemma mul_inv (a b : G) : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by rw [mul_inv_rev, mul_comm] end comm_group section add_comm_group variables {G : Type u} [add_comm_group G] {a b c d : G} local attribute [simp] add_assoc add_comm add_left_comm sub_eq_add_neg lemma sub_add_eq_sub_sub (a b c : G) : a - (b + c) = a - b - c := by simp lemma neg_add_eq_sub (a b : G) : -a + b = b - a := by simp lemma sub_add_eq_add_sub (a b c : G) : a - b + c = a + c - b := by simp lemma sub_sub (a b c : G) : a - b - c = a - (b + c) := by simp lemma sub_add (a b c : G) : a - b + c = a - (b - c) := by simp @[simp] lemma add_sub_add_left_eq_sub (a b c : G) : (c + a) - (c + b) = a - b := by simp lemma eq_sub_of_add_eq' (h : c + a = b) : a = b - c := by simp [h.symm] lemma sub_eq_of_eq_add' (h : a = b + c) : a - b = c := begin simp [h], rw [add_left_comm], simp end lemma eq_add_of_sub_eq' (h : a - b = c) : a = b + c := by simp [h.symm] lemma add_eq_of_eq_sub' (h : b = c - a) : a + b = c := begin simp [h], rw [add_comm c, add_neg_cancel_left] end lemma sub_sub_self (a b : G) : a - (a - b) = b := begin simp, rw [add_comm b, add_neg_cancel_left] end lemma add_sub_comm (a b c d : G) : a + b - (c + d) = (a - c) + (b - d) := by simp lemma sub_eq_sub_add_sub (a b c : G) : a - b = c - b + (a - c) := begin simp, rw [add_left_comm c], simp end lemma neg_neg_sub_neg (a b : G) : - (-a - -b) = a - b := by simp @[simp] lemma sub_sub_cancel (a b : G) : a - (a - b) = b := sub_sub_self a b lemma sub_eq_neg_add (a b : G) : a - b = -b + a := by rw [sub_eq_add_neg, add_comm _ _] theorem neg_add' (a b : G) : -(a + b) = -a - b := by rw [sub_eq_add_neg, neg_add a b] @[simp] lemma neg_sub_neg (a b : G) : -a - -b = b - a := by simp [sub_eq_neg_add, add_comm] lemma eq_sub_iff_add_eq' : a = b - c ↔ c + a = b := by rw [eq_sub_iff_add_eq, add_comm] lemma sub_eq_iff_eq_add' : a - b = c ↔ a = b + c := by rw [sub_eq_iff_eq_add, add_comm] @[simp] lemma add_sub_cancel' (a b : G) : a + b - a = b := by rw [sub_eq_neg_add, neg_add_cancel_left] @[simp] lemma add_sub_cancel'_right (a b : G) : a + (b - a) = b := by rw [← add_sub_assoc, add_sub_cancel'] -- This lemma is in the `simp` set under the name `add_neg_cancel_comm_assoc`, -- defined in `algebra/group/commute` lemma add_add_neg_cancel'_right (a b : G) : a + (b + -a) = b := by rw [← sub_eq_add_neg, add_sub_cancel'_right a b] lemma sub_right_comm (a b c : G) : a - b - c = a - c - b := by { repeat { rw sub_eq_add_neg }, exact add_right_comm _ _ _ } @[simp] lemma add_add_sub_cancel (a b c : G) : (a + c) + (b - c) = a + b := by rw [add_assoc, add_sub_cancel'_right] @[simp] lemma sub_add_add_cancel (a b c : G) : (a - c) + (b + c) = a + b := by rw [add_left_comm, sub_add_cancel, add_comm] @[simp] lemma sub_add_sub_cancel' (a b c : G) : (a - b) + (c - a) = c - b := by rw add_comm; apply sub_add_sub_cancel @[simp] lemma add_sub_sub_cancel (a b c : G) : (a + b) - (a - c) = b + c := by rw [← sub_add, add_sub_cancel'] @[simp] lemma sub_sub_sub_cancel_left (a b c : G) : (c - a) - (c - b) = b - a := by rw [← neg_sub b c, sub_neg_eq_add, add_comm, sub_add_sub_cancel] lemma sub_eq_sub_iff_add_eq_add : a - b = c - d ↔ a + d = c + b := begin rw [sub_eq_iff_eq_add, sub_add_eq_add_sub, eq_comm, sub_eq_iff_eq_add'], simp only [add_comm, eq_comm] end lemma sub_eq_sub_iff_sub_eq_sub : a - b = c - d ↔ a - c = b - d := by simp [-sub_eq_add_neg, sub_eq_sub_iff_add_eq_add, add_comm] end add_comm_group
55d3f973b35cfd98636ebb9afae6a6a4c9a91d8c
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/compact_open.lean
e28027ceddac36f0ba29c60d06fa22b7baab3be5
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
4,199
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton Type of continuous maps and the compact-open topology on them. -/ import topology.subset_properties tactic.tidy open set open_locale topological_space universes u v w def continuous_map (α : Type u) (β : Type v) [topological_space α] [topological_space β] : Type (max u v) := subtype (continuous : (α → β) → Prop) local notation `C(` α `, ` β `)` := continuous_map α β namespace continuous_map section compact_open variables {α : Type u} {β : Type v} {γ : Type w} variables [topological_space α] [topological_space β] [topological_space γ] instance : has_coe_to_fun C(α, β) := ⟨λ_, α → β, λf, f.1⟩ instance [inhabited β] : inhabited C(α, β) := ⟨⟨λ _, default _, continuous_const⟩⟩ def compact_open.gen (s : set α) (u : set β) : set C(α,β) := {f | f '' s ⊆ u} -- The compact-open topology on the space of continuous maps α → β. instance compact_open : topological_space C(α, β) := topological_space.generate_from {m | ∃ (s : set α) (hs : compact s) (u : set β) (hu : is_open u), m = compact_open.gen s u} private lemma is_open_gen {s : set α} (hs : compact s) {u : set β} (hu : is_open u) : is_open (compact_open.gen s u) := topological_space.generate_open.basic _ (by dsimp [mem_set_of_eq]; tauto) section functorial variables {g : β → γ} (hg : continuous g) def induced (f : C(α, β)) : C(α, γ) := ⟨g ∘ f, hg.comp f.property⟩ private lemma preimage_gen {s : set α} (hs : compact s) {u : set γ} (hu : is_open u) : continuous_map.induced hg ⁻¹' (compact_open.gen s u) = compact_open.gen s (g ⁻¹' u) := begin ext ⟨f, _⟩, change g ∘ f '' s ⊆ u ↔ f '' s ⊆ g ⁻¹' u, rw [image_comp, image_subset_iff] end /-- C(α, -) is a functor. -/ lemma continuous_induced : continuous (continuous_map.induced hg : C(α, β) → C(α, γ)) := continuous_generated_from $ assume m ⟨s, hs, u, hu, hm⟩, by rw [hm, preimage_gen hg hs hu]; exact is_open_gen hs (hg _ hu) end functorial section ev variables (α β) def ev (p : C(α, β) × α) : β := p.1 p.2 variables {α β} -- The evaluation map C(α, β) × α → β is continuous if α is locally compact. lemma continuous_ev [locally_compact_space α] : continuous (ev α β) := continuous_iff_continuous_at.mpr $ assume ⟨f, x⟩ n hn, let ⟨v, vn, vo, fxv⟩ := mem_nhds_sets_iff.mp hn in have v ∈ 𝓝 (f.val x), from mem_nhds_sets vo fxv, let ⟨s, hs, sv, sc⟩ := locally_compact_space.local_compact_nhds x (f.val ⁻¹' v) (f.property.tendsto x this) in let ⟨u, us, uo, xu⟩ := mem_nhds_sets_iff.mp hs in show (ev α β) ⁻¹' n ∈ 𝓝 (f, x), from let w := set.prod (compact_open.gen s v) u in have w ⊆ ev α β ⁻¹' n, from assume ⟨f', x'⟩ ⟨hf', hx'⟩, calc f'.val x' ∈ f'.val '' s : mem_image_of_mem f'.val (us hx') ... ⊆ v : hf' ... ⊆ n : vn, have is_open w, from is_open_prod (is_open_gen sc vo) uo, have (f, x) ∈ w, from ⟨image_subset_iff.mpr sv, xu⟩, mem_nhds_sets_iff.mpr ⟨w, by assumption, by assumption, by assumption⟩ end ev section coev variables (α β) def coev (b : β) : C(α, β × α) := ⟨λ a, (b, a), continuous.prod_mk continuous_const continuous_id⟩ variables {α β} lemma image_coev {y : β} (s : set α) : (coev α β y).val '' s = set.prod {y} s := by tidy -- The coevaluation map β → C(α, β × α) is continuous (always). lemma continuous_coev : continuous (coev α β) := continuous_generated_from $ begin rintros _ ⟨s, sc, u, uo, rfl⟩, rw is_open_iff_forall_mem_open, intros y hy, change (coev α β y).val '' s ⊆ u at hy, rw image_coev s at hy, rcases generalized_tube_lemma compact_singleton sc uo hy with ⟨v, w, vo, wo, yv, sw, vwu⟩, refine ⟨v, _, vo, singleton_subset_iff.mp yv⟩, intros y' hy', change (coev α β y').val '' s ⊆ u, rw image_coev s, exact subset.trans (prod_mono (singleton_subset_iff.mpr hy') sw) vwu end end coev end compact_open end continuous_map
0d444a536417972e55c91628d8b2459b2f0b0215
7da4b05ff6af3f2cd178a7c188a45934cee1cce5
/test.lean
273175d53572b5a99a124172d4b5b62cad358b91
[]
no_license
KeenS/lean_tutorial
794793c6da95b4c8b7eb6e30e1721da8c86e88de
e4463ddaac14fb321f79d7138b9822238ea10a8f
refs/heads/master
1,587,246,479,934
1,472,389,890,000
1,472,389,890,000
66,768,865
1
0
null
null
null
null
UTF-8
Lean
false
false
732
lean
axiom dne {p: Prop}: ¬¬ p -> p theorem em {p: Prop}: p ∨ ¬ p := have Hdn: ¬ ¬ (p ∨ ¬ p), from (assume Hcontra: ¬ (p ∨ ¬p), have Hnp: ¬ p, from (assume Hp: p, Hcontra (or.inl Hp)), Hcontra (or.inr Hnp)), show p ∨ ¬ p, from dne Hdn open classical example {p: Prop} (H: ¬¬p): p := by_cases (assume H1: p, H1) (assume H1: ¬ p, absurd H1 H) example {p: Prop} (H: ¬¬p): p := by_contradiction (assume H1: ¬ p, show false, from H H1) example {p q: Prop} (H: ¬ (p ∧ q)): ¬ p ∨ ¬ q := or.elim (em p) (assume Hp: p, or.inr (show ¬ q, from assume Hq: q, H (and.intro Hp Hq))) (assume Hnp: ¬p, or.inl Hnp)
3957e1d8392560993cf9794350e70006ea39fdd2
94e33a31faa76775069b071adea97e86e218a8ee
/src/order/partition/finpartition.lean
e2446127518e8f651058ffd9098dc10c9324dbbe
[ "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
18,897
lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import algebra.big_operators.basic import order.atoms import order.locally_finite import order.sup_indep /-! # Finite partitions In this file, we define finite partitions. A finpartition of `a : α` is a finite set of pairwise disjoint parts `parts : finset α` which does not contain `⊥` and whose supremum is `a`. Finpartitions of a finset are at the heart of Szemerédi's regularity lemma. They are also studied purely order theoretically in Sperner theory. ## Constructions We provide many ways to build finpartitions: * `finpartition.of_erase`: Builds a finpartition by erasing `⊥` for you. * `finpartition.of_subset`: Builds a finpartition from a subset of the parts of a previous finpartition. * `finpartition.empty`: The empty finpartition of `⊥`. * `finpartition.indiscrete`: The indiscrete, aka trivial, aka pure, finpartition made of a single part. * `finpartition.discrete`: The discrete finpartition of `s : finset α` made of singletons. * `finpartition.bind`: Puts together the finpartitions of the parts of a finpartition into a new finpartition. * `finpartition.atomise`: Makes a finpartition of `s : finset α` by breaking `s` along all finsets in `F : finset (finset α)`. Two elements of `s` belong to the same part iff they belong to the same elements of `F`. `finpartition.indiscrete` and `finpartition.bind` together form the monadic structure of `finpartition`. ## Implementation notes Forbidding `⊥` as a part follows mathematical tradition and is a pragmatic choice concerning operations on `finpartition`. Not caring about `⊥` being a part or not breaks extensionality (it's not because the parts of `P` and the parts of `Q` have the same elements that `P = Q`). Enforcing `⊥` to be a part makes `finpartition.bind` uglier and doesn't rid us of the need of `finpartition.of_erase`. ## TODO Link `finpartition` and `setoid.is_partition`. The order is the wrong way around to make `finpartition a` a graded order. Is it bad to depart from the literature and turn the order around? -/ open finset function open_locale big_operators variables {α : Type*} /-- A finite partition of `a : α` is a pairwise disjoint finite set of elements whose supremum is `a`. We forbid `⊥` as a part. -/ @[ext, derive decidable_eq] structure finpartition [lattice α] [order_bot α] (a : α) := (parts : finset α) (sup_indep : parts.sup_indep id) (sup_parts : parts.sup id = a) (not_bot_mem : ⊥ ∉ parts) attribute [protected] finpartition.sup_indep namespace finpartition section lattice variables [lattice α] [order_bot α] /-- A `finpartition` constructor which does not insist on `⊥` not being a part. -/ @[simps] def of_erase [decidable_eq α] {a : α} (parts : finset α) (sup_indep : parts.sup_indep id) (sup_parts : parts.sup id = a) : finpartition a := { parts := parts.erase ⊥, sup_indep := sup_indep.subset (erase_subset _ _), sup_parts := (sup_erase_bot _).trans sup_parts, not_bot_mem := not_mem_erase _ _ } /-- A `finpartition` constructor from a bigger existing finpartition. -/ @[simps] def of_subset {a b : α} (P : finpartition a) {parts : finset α} (subset : parts ⊆ P.parts) (sup_parts : parts.sup id = b) : finpartition b := { parts := parts, sup_indep := P.sup_indep.subset subset, sup_parts := sup_parts, not_bot_mem := λ h, P.not_bot_mem (subset h) } /-- Changes the type of a finpartition to an equal one. -/ @[simps] def copy {a b : α} (P : finpartition a) (h : a = b) : finpartition b := { parts := P.parts, sup_indep := P.sup_indep, sup_parts := h ▸ P.sup_parts, not_bot_mem := P.not_bot_mem } variables (α) /-- The empty finpartition. -/ @[simps] protected def empty : finpartition (⊥ : α) := { parts := ∅, sup_indep := sup_indep_empty _, sup_parts := finset.sup_empty, not_bot_mem := not_mem_empty ⊥ } instance : inhabited (finpartition (⊥ : α)) := ⟨finpartition.empty α⟩ @[simp] lemma default_eq_empty : (default : finpartition (⊥ : α)) = finpartition.empty α := rfl variables {α} {a : α} /-- The finpartition in one part, aka indiscrete finpartition. -/ @[simps] def indiscrete (ha : a ≠ ⊥) : finpartition a := { parts := {a}, sup_indep := sup_indep_singleton _ _, sup_parts := finset.sup_singleton, not_bot_mem := λ h, ha (mem_singleton.1 h).symm } variables (P : finpartition a) protected lemma le {b : α} (hb : b ∈ P.parts) : b ≤ a := (le_sup hb).trans P.sup_parts.le lemma ne_bot {b : α} (hb : b ∈ P.parts) : b ≠ ⊥ := λ h, P.not_bot_mem $ h.subst hb protected lemma disjoint : (P.parts : set α).pairwise_disjoint id := P.sup_indep.pairwise_disjoint variables {P} lemma parts_eq_empty_iff : P.parts = ∅ ↔ a = ⊥ := begin simp_rw ←P.sup_parts, refine ⟨λ h, _, λ h, eq_empty_iff_forall_not_mem.2 (λ b hb, P.not_bot_mem _)⟩, { rw h, exact finset.sup_empty }, { rwa ←le_bot_iff.1 ((le_sup hb).trans h.le) } end lemma parts_nonempty_iff : P.parts.nonempty ↔ a ≠ ⊥ := by rw [nonempty_iff_ne_empty, not_iff_not, parts_eq_empty_iff] lemma parts_nonempty (P : finpartition a) (ha : a ≠ ⊥) : P.parts.nonempty := parts_nonempty_iff.2 ha instance : unique (finpartition (⊥ : α)) := { uniq := λ P, by { ext a, exact iff_of_false (λ h, P.ne_bot h $ le_bot_iff.1 $ P.le h) (not_mem_empty a) }, ..finpartition.inhabited α } /-- There's a unique partition of an atom. -/ @[reducible] -- See note [reducible non instances] def _root_.is_atom.unique_finpartition (ha : is_atom a) : unique (finpartition a) := { default := indiscrete ha.1, uniq := λ P, begin have h : ∀ b ∈ P.parts, b = a, { exact λ b hb, (ha.le_iff.mp $ P.le hb).resolve_left (P.ne_bot hb) }, ext b, refine iff.trans ⟨h b, _⟩ mem_singleton.symm, rintro rfl, obtain ⟨c, hc⟩ := P.parts_nonempty ha.1, simp_rw ←h c hc, exact hc, end } instance [fintype α] [decidable_eq α] (a : α) : fintype (finpartition a) := @fintype.of_surjective {p : finset α // p.sup_indep id ∧ p.sup id = a ∧ ⊥ ∉ p} (finpartition a) _ (subtype.fintype _) (λ i, ⟨i.1, i.2.1, i.2.2.1, i.2.2.2⟩) (λ ⟨_, y, z, w⟩, ⟨⟨_, y, z, w⟩, rfl⟩) /-! ### Refinement order -/ section order /-- We say that `P ≤ Q` if `P` refines `Q`: each part of `P` is less than some part of `Q`. -/ instance : has_le (finpartition a) := ⟨λ P Q, ∀ ⦃b⦄, b ∈ P.parts → ∃ c ∈ Q.parts, b ≤ c⟩ instance : partial_order (finpartition a) := { le_refl := λ P b hb, ⟨b, hb, le_rfl⟩, le_trans := λ P Q R hPQ hQR b hb, begin obtain ⟨c, hc, hbc⟩ := hPQ hb, obtain ⟨d, hd, hcd⟩ := hQR hc, exact ⟨d, hd, hbc.trans hcd⟩, end, le_antisymm := λ P Q hPQ hQP, begin ext b, refine ⟨λ hb, _, λ hb, _⟩, { obtain ⟨c, hc, hbc⟩ := hPQ hb, obtain ⟨d, hd, hcd⟩ := hQP hc, rwa hbc.antisymm, rwa P.disjoint.eq_of_le hb hd (P.ne_bot hb) (hbc.trans hcd) }, { obtain ⟨c, hc, hbc⟩ := hQP hb, obtain ⟨d, hd, hcd⟩ := hPQ hc, rwa hbc.antisymm, rwa Q.disjoint.eq_of_le hb hd (Q.ne_bot hb) (hbc.trans hcd) } end, ..finpartition.has_le } instance [decidable (a = ⊥)] : order_top (finpartition a) := { top := if ha : a = ⊥ then (finpartition.empty α).copy ha.symm else indiscrete ha, le_top := λ P, begin split_ifs, { intros x hx, simpa [h, P.ne_bot hx] using P.le hx }, { exact λ b hb, ⟨a, mem_singleton_self _, P.le hb⟩ } end } lemma parts_top_subset (a : α) [decidable (a = ⊥)] : (⊤ : finpartition a).parts ⊆ {a} := begin intros b hb, change b ∈ finpartition.parts (dite _ _ _) at hb, split_ifs at hb, { simp only [copy_parts, empty_parts, not_mem_empty] at hb, exact hb.elim }, { exact hb } end lemma parts_top_subsingleton (a : α) [decidable (a = ⊥)] : ((⊤ : finpartition a).parts : set α).subsingleton := set.subsingleton_of_subset_singleton $ λ b hb, mem_singleton.1 $ parts_top_subset _ hb end order end lattice section distrib_lattice variables [distrib_lattice α] [order_bot α] section inf variables [decidable_eq α] {a b c : α} instance : has_inf (finpartition a) := ⟨λ P Q, of_erase ((P.parts.product Q.parts).image $ λ bc, bc.1 ⊓ bc.2) begin rw sup_indep_iff_disjoint_erase, simp only [mem_image, and_imp, exists_prop, forall_exists_index, id.def, prod.exists, mem_product, finset.disjoint_sup_right, mem_erase, ne.def], rintro _ x₁ y₁ hx₁ hy₁ rfl _ h x₂ y₂ hx₂ hy₂ rfl, rcases eq_or_ne x₁ x₂ with rfl | xdiff, { refine disjoint.mono inf_le_right inf_le_right (Q.disjoint hy₁ hy₂ _), intro t, simpa [t] using h }, exact disjoint.mono inf_le_left inf_le_left (P.disjoint hx₁ hx₂ xdiff), end begin rw [sup_image, comp.left_id, sup_product_left], transitivity P.parts.sup id ⊓ Q.parts.sup id, { simp_rw [finset.sup_inf_distrib_right, finset.sup_inf_distrib_left], refl }, { rw [P.sup_parts, Q.sup_parts, inf_idem] } end⟩ @[simp] lemma parts_inf (P Q : finpartition a) : (P ⊓ Q).parts = ((P.parts.product Q.parts).image $ λ bc : α × α, bc.1 ⊓ bc.2).erase ⊥ := rfl instance : semilattice_inf (finpartition a) := { inf_le_left := λ P Q b hb, begin obtain ⟨c, hc, rfl⟩ := mem_image.1 (mem_of_mem_erase hb), rw mem_product at hc, exact ⟨c.1, hc.1, inf_le_left⟩, end, inf_le_right := λ P Q b hb, begin obtain ⟨c, hc, rfl⟩ := mem_image.1 (mem_of_mem_erase hb), rw mem_product at hc, exact ⟨c.2, hc.2, inf_le_right⟩, end, le_inf := λ P Q R hPQ hPR b hb, begin obtain ⟨c, hc, hbc⟩ := hPQ hb, obtain ⟨d, hd, hbd⟩ := hPR hb, have h := _root_.le_inf hbc hbd, refine ⟨c ⊓ d, mem_erase_of_ne_of_mem (ne_bot_of_le_ne_bot (P.ne_bot hb) h) (mem_image.2 ⟨(c, d), mem_product.2 ⟨hc, hd⟩, rfl⟩), h⟩, end, ..finpartition.partial_order, ..finpartition.has_inf } end inf lemma exists_le_of_le {a b : α} {P Q : finpartition a} (h : P ≤ Q) (hb : b ∈ Q.parts) : ∃ c ∈ P.parts, c ≤ b := begin by_contra' H, refine Q.ne_bot hb (disjoint_self.1 $ disjoint.mono_right (Q.le hb) _), rw [←P.sup_parts, finset.disjoint_sup_right], rintro c hc, obtain ⟨d, hd, hcd⟩ := h hc, refine (Q.disjoint hb hd _).mono_right hcd, rintro rfl, exact H _ hc hcd, end lemma card_mono {a : α} {P Q : finpartition a} (h : P ≤ Q) : Q.parts.card ≤ P.parts.card := begin classical, have : ∀ b ∈ Q.parts, ∃ c ∈ P.parts, c ≤ b := λ b, exists_le_of_le h, choose f hP hf using this, rw ←card_attach, refine card_le_card_of_inj_on (λ b, f _ b.2) (λ b _, hP _ b.2) (λ b hb c hc h, _), exact subtype.coe_injective (Q.disjoint.elim b.2 c.2 $ λ H, P.ne_bot (hP _ b.2) $ disjoint_self.1 $ H.mono (hf _ b.2) $ h.le.trans $ hf _ c.2), end variables [decidable_eq α] {a b c : α} section bind variables {P : finpartition a} {Q : Π i ∈ P.parts, finpartition i} /-- Given a finpartition `P` of `a` and finpartitions of each part of `P`, this yields the finpartition of `a` obtained by juxtaposing all the subpartitions. -/ @[simps] def bind (P : finpartition a) (Q : Π i ∈ P.parts, finpartition i) : finpartition a := { parts := P.parts.attach.bUnion (λ i, (Q i.1 i.2).parts), sup_indep := begin rw sup_indep_iff_pairwise_disjoint, rintro a ha b hb h, rw [finset.mem_coe, finset.mem_bUnion] at ha hb, obtain ⟨⟨A, hA⟩, -, ha⟩ := ha, obtain ⟨⟨B, hB⟩, -, hb⟩ := hb, obtain rfl | hAB := eq_or_ne A B, { exact (Q A hA).disjoint ha hb h }, { exact (P.disjoint hA hB hAB).mono ((Q A hA).le ha) ((Q B hB).le hb) } end, sup_parts := begin simp_rw [sup_bUnion, ←P.sup_parts], rw [eq_comm, ←finset.sup_attach], exact sup_congr rfl (λ b hb, (Q b.1 b.2).sup_parts.symm), end, not_bot_mem := λ h, begin rw finset.mem_bUnion at h, obtain ⟨⟨A, hA⟩, -, h⟩ := h, exact (Q A hA).not_bot_mem h, end } lemma mem_bind : b ∈ (P.bind Q).parts ↔ ∃ A hA, b ∈ (Q A hA).parts := begin rw [bind, mem_bUnion], split, { rintro ⟨⟨A, hA⟩, -, h⟩, exact ⟨A, hA, h⟩ }, { rintro ⟨A, hA, h⟩, exact ⟨⟨A, hA⟩, mem_attach _ ⟨A, hA⟩, h⟩ } end lemma card_bind (Q : Π i ∈ P.parts, finpartition i) : (P.bind Q).parts.card = ∑ A in P.parts.attach, (Q _ A.2).parts.card := begin apply card_bUnion, rintro ⟨b, hb⟩ - ⟨c, hc⟩ - hbc d, rw [inf_eq_inter, mem_inter], rintro ⟨hdb, hdc⟩, rw [ne.def, subtype.mk_eq_mk] at hbc, exact (Q b hb).ne_bot hdb (eq_bot_iff.2 $ (le_inf ((Q b hb).le hdb) $ (Q c hc).le hdc).trans $ P.disjoint hb hc hbc), end end bind /-- Adds `b` to a finpartition of `a` to make a finpartition of `a ⊔ b`. -/ @[simps] def extend (P : finpartition a) (hb : b ≠ ⊥) (hab : disjoint a b) (hc : a ⊔ b = c) : finpartition c := { parts := insert b P.parts, sup_indep := begin rw [sup_indep_iff_pairwise_disjoint, coe_insert], exact P.disjoint.insert (λ d hd hbd, hab.symm.mono_right $ P.le hd), end, sup_parts := by rwa [sup_insert, P.sup_parts, id, _root_.sup_comm], not_bot_mem := λ h, (mem_insert.1 h).elim hb.symm P.not_bot_mem } lemma card_extend (P : finpartition a) (b c : α) {hb : b ≠ ⊥} {hab : disjoint a b} {hc : a ⊔ b = c} : (P.extend hb hab hc).parts.card = P.parts.card + 1 := card_insert_of_not_mem $ λ h, hb $ hab.symm.eq_bot_of_le $ P.le h end distrib_lattice section generalized_boolean_algebra variables [generalized_boolean_algebra α] [decidable_eq α] {a b c : α} (P : finpartition a) /-- Restricts a finpartition to avoid a given element. -/ @[simps] def avoid (b : α) : finpartition (a \ b) := of_erase (P.parts.image (\ b)) (P.disjoint.image_finset_of_le $ λ a, sdiff_le).sup_indep (by rw [sup_image, comp.left_id, finset.sup_sdiff_right, ←id_def, P.sup_parts]) @[simp] lemma mem_avoid : c ∈ (P.avoid b).parts ↔ ∃ d ∈ P.parts, ¬ d ≤ b ∧ d \ b = c := begin simp only [avoid, of_erase_parts, mem_erase, ne.def, mem_image, exists_prop, ←exists_and_distrib_left, @and.left_comm (c ≠ ⊥)], refine exists_congr (λ d, and_congr_right' $ and_congr_left _), rintro rfl, rw sdiff_eq_bot_iff, end end generalized_boolean_algebra end finpartition /-! ### Finite partitions of finsets -/ namespace finpartition variables [decidable_eq α] {s t : finset α} (P : finpartition s) lemma nonempty_of_mem_parts {a : finset α} (ha : a ∈ P.parts) : a.nonempty := nonempty_iff_ne_empty.2 $ P.ne_bot ha lemma exists_mem {a : α} (ha : a ∈ s) : ∃ t ∈ P.parts, a ∈ t := by { simp_rw ←P.sup_parts at ha, exact mem_sup.1 ha } lemma bUnion_parts : P.parts.bUnion id = s := (sup_eq_bUnion _ _).symm.trans P.sup_parts lemma sum_card_parts : ∑ i in P.parts, i.card = s.card := begin convert congr_arg finset.card P.bUnion_parts, rw card_bUnion P.sup_indep.pairwise_disjoint, refl, end /-- `⊥` is the partition in singletons, aka discrete partition. -/ instance (s : finset α) : has_bot (finpartition s) := ⟨{ parts := s.map ⟨singleton, singleton_injective⟩, sup_indep := set.pairwise_disjoint.sup_indep begin rw finset.coe_map, exact finset.pairwise_disjoint_range_singleton.subset (set.image_subset_range _ _), end, sup_parts := by rw [sup_map, comp.left_id, embedding.coe_fn_mk, finset.sup_singleton'], not_bot_mem := by simp }⟩ @[simp] lemma parts_bot (s : finset α) : (⊥ : finpartition s).parts = s.map ⟨singleton, singleton_injective⟩ := rfl lemma card_bot (s : finset α) : (⊥ : finpartition s).parts.card = s.card := finset.card_map _ lemma mem_bot_iff : t ∈ (⊥ : finpartition s).parts ↔ ∃ a ∈ s, {a} = t := mem_map instance (s : finset α) : order_bot (finpartition s) := { bot_le := λ P t ht, begin rw mem_bot_iff at ht, obtain ⟨a, ha, rfl⟩ := ht, obtain ⟨t, ht, hat⟩ := P.exists_mem ha, exact ⟨t, ht, singleton_subset_iff.2 hat⟩, end, ..finpartition.has_bot s } lemma card_parts_le_card (P : finpartition s) : P.parts.card ≤ s.card := by { rw ←card_bot s, exact card_mono bot_le } section atomise /-- Cuts `s` along the finsets in `F`: Two elements of `s` will be in the same part if they are in the same finsets of `F`. -/ def atomise (s : finset α) (F : finset (finset α)) : finpartition s := of_erase (F.powerset.image $ λ Q, s.filter (λ i, ∀ t ∈ F, t ∈ Q ↔ i ∈ t)) (set.pairwise_disjoint.sup_indep $ λ x hx y hy h z hz, h begin rw [mem_coe, mem_image] at hx hy, obtain ⟨Q, hQ, rfl⟩ := hx, obtain ⟨R, hR, rfl⟩ := hy, suffices h : Q = R, { subst h }, rw [id, id, inf_eq_inter, mem_inter, mem_filter, mem_filter] at hz, rw mem_powerset at hQ hR, ext i, refine ⟨λ hi, _, λ hi, _⟩, { rwa [hz.2.2 _ (hQ hi), ←hz.1.2 _ (hQ hi)] }, { rwa [hz.1.2 _ (hR hi), ←hz.2.2 _ (hR hi)] } end) (begin refine (finset.sup_le $ λ t ht, _).antisymm (λ a ha, _), { rw mem_image at ht, obtain ⟨A, hA, rfl⟩ := ht, exact s.filter_subset _ }, { rw [mem_sup], refine ⟨s.filter (λ i, ∀ t, t ∈ F → (t ∈ F.filter (λ u, a ∈ u) ↔ i ∈ t)), mem_image_of_mem _ (mem_powerset.2 $ filter_subset _ _), mem_filter.2 ⟨ha, λ t ht, _⟩⟩, rw mem_filter, exact and_iff_right ht } end) variables {F : finset (finset α)} lemma mem_atomise {t : finset α} : t ∈ (atomise s F).parts ↔ t.nonempty ∧ ∃ (Q ⊆ F), s.filter (λ i, ∀ u ∈ F, u ∈ Q ↔ i ∈ u) = t := by simp only [atomise, of_erase, bot_eq_empty, mem_erase, mem_image, nonempty_iff_ne_empty, mem_singleton, and_comm, mem_powerset, exists_prop] lemma atomise_empty (hs : s.nonempty) : (atomise s ∅).parts = {s} := begin simp only [atomise, powerset_empty, image_singleton, not_mem_empty, is_empty.forall_iff, implies_true_iff, filter_true], exact erase_eq_of_not_mem (not_mem_singleton.2 hs.ne_empty.symm), end lemma card_atomise_le : (atomise s F).parts.card ≤ 2^F.card := (card_le_of_subset $ erase_subset _ _).trans $ finset.card_image_le.trans (card_powerset _).le lemma bUnion_filter_atomise (t : finset α) (ht : t ∈ F) (hts : t ⊆ s) : ((atomise s F).parts.filter $ λ u, u ⊆ t).bUnion id = t := begin ext a, rw mem_bUnion, refine ⟨λ ⟨u, hu, ha⟩, (mem_filter.1 hu).2 ha, λ ha, _⟩, obtain ⟨u, hu, hau⟩ := (atomise s F).exists_mem (hts ha), refine ⟨u, mem_filter.2 ⟨hu, λ b hb, _⟩, hau⟩, obtain ⟨Q, hQ, rfl⟩ := (mem_atomise.1 hu).2, rw mem_filter at hau hb, rwa [←hb.2 _ ht, hau.2 _ ht] end end atomise end finpartition
6d7c4630ad908d16cac0005d390cde61d728ece9
7007bb645068e0b6b859aab9da7cf5c1c79e98be
/library/init/logic.lean
50c744ea0e0ff1bd39e092baf0fdafabc9ea568d
[ "Apache-2.0" ]
permissive
EdAyers/lean
7d3fb852380bc386545ebc119b7d03c128c3ce1c
be72c8dc527a062e243a408480f487a55b06cb0a
refs/heads/master
1,624,443,179,694
1,592,837,958,000
1,592,837,958,000
154,972,348
0
0
Apache-2.0
1,557,768,267,000
1,540,649,772,000
C++
UTF-8
Lean
false
false
38,234
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ prelude import init.core universes u v w @[simp] lemma opt_param_eq (α : Sort u) (default : α) : opt_param α default = α := rfl @[inline] def id {α : Sort u} (a : α) : α := a def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := λ b a, f a b /- implication -/ def implies (a b : Prop) := a → b @[trans] lemma implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := assume hp, h₂ (h₁ hp) def trivial : true := ⟨⟩ /-- We can't have `a` and `¬a`, that would be absurd!-/ @[inline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b := false.rec b (h₂ h₁) lemma not.intro {a : Prop} (h : a → false) : ¬ a := h /-- Modus tollens.-/ lemma mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := assume ha : a, h₂ (h₁ ha) /- not -/ lemma not_false : ¬false := id def non_contradictory (a : Prop) : Prop := ¬¬a lemma non_contradictory_intro {a : Prop} (ha : a) : ¬¬a := assume hna : ¬a, absurd ha hna /- false -/ @[inline] def false.elim {C : Sort u} (h : false) : C := false.rec C h /- eq -/ -- proof irrelevance is built in lemma proof_irrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl @[simp] lemma id.def {α : Sort u} (a : α) : id a = a := rfl @[inline] def eq.mp {α β : Sort u} : (α = β) → α → β := eq.rec_on @[inline] def eq.mpr {α β : Sort u} : (α = β) → β → α := λ h₁ h₂, eq.rec_on (eq.symm h₁) h₂ @[elab_as_eliminator] lemma eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) : p a → p b := eq.subst (eq.symm h₁) lemma congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst h₁ (eq.subst h₂ rfl) lemma congr_fun {α : Sort u} {β : α → Sort v} {f g : Π x, β x} (h : f = g) (a : α) : f a = g a := eq.subst h (eq.refl (f a)) lemma congr_arg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) : a₁ = a₂ → f a₁ = f a₂ := congr rfl lemma trans_rel_left {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ lemma trans_rel_right {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁.symm ▸ h₂ lemma of_eq_true {p : Prop} (h : p = true) : p := h.symm ▸ trivial lemma not_of_eq_false {p : Prop} (h : p = false) : ¬p := assume hp, h ▸ hp @[inline] def cast {α β : Sort u} (h : α = β) (a : α) : β := eq.rec a h lemma cast_proof_irrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl lemma cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl /- ne -/ @[reducible] def ne {α : Sort u} (a b : α) := ¬(a = b) notation a ≠ b := ne a b @[simp] lemma ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl namespace ne variable {α : Sort u} variables {a b : α} lemma intro (h : a = b → false) : a ≠ b := h lemma elim (h : a ≠ b) : a = b → false := h lemma irrefl (h : a ≠ a) : false := h rfl lemma symm (h : a ≠ b) : b ≠ a := assume (h₁ : b = a), h (h₁.symm) end ne lemma false_of_ne {α : Sort u} {a : α} : a ≠ a → false := ne.irrefl section variables {p : Prop} lemma ne_false_of_self : p → p ≠ false := assume (hp : p) (heq : p = false), heq ▸ hp lemma ne_true_of_not : ¬p → p ≠ true := assume (hnp : ¬p) (heq : p = true), (heq ▸ hnp) trivial lemma true_ne_false : ¬true = false := ne_false_of_self trivial end attribute [refl] heq.refl section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} lemma heq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a == b) : p a → p b := eq.rec_on (eq_of_heq h₁) lemma heq.subst {p : ∀ T : Sort u, T → Prop} : a == b → p α a → p β b := heq.rec_on @[symm] lemma heq.symm (h : a == b) : b == a := heq.rec_on h (heq.refl a) lemma heq_of_eq (h : a = a') : a == a' := eq.subst h (heq.refl a) @[trans] lemma heq.trans (h₁ : a == b) (h₂ : b == c) : a == c := heq.subst h₂ h₁ @[trans] lemma heq_of_heq_of_eq (h₁ : a == b) (h₂ : b = b') : a == b' := heq.trans h₁ (heq_of_eq h₂) @[trans] lemma heq_of_eq_of_heq (h₁ : a = a') (h₂ : a' == b) : a == b := heq.trans (heq_of_eq h₁) h₂ def type_eq_of_heq (h : a == b) : α = β := heq.rec_on h (eq.refl α) end lemma eq_rec_heq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (eq.rec_on h p : φ a') == p | a _ rfl p := heq.refl p lemma heq_of_eq_rec_left {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a = a') (h₂ : (eq.rec_on e p₁ : φ a') = p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := eq.rec_on h (heq.refl p₁) lemma heq_of_eq_rec_right {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a' = a) (h₂ : p₁ = eq.rec_on e p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := have p₁ = p₂, from h, this ▸ heq.refl p₁ lemma of_heq_true {a : Prop} (h : a == true) : a := of_eq_true (eq_of_heq h) lemma eq_rec_compose : ∀ {α β φ : Sort u} (p₁ : β = φ) (p₂ : α = β) (a : α), (eq.rec_on p₁ (eq.rec_on p₂ a : β) : φ) = eq.rec_on (eq.trans p₂ p₁) a | α _ _ rfl rfl a := rfl lemma cast_heq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a == a | α _ rfl a := heq.refl a /- and -/ notation a /\ b := and a b notation a ∧ b := and a b variables {a b c d : Prop} lemma and.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c := and.rec h₂ h₁ lemma and.swap : a ∧ b → b ∧ a := assume ⟨ha, hb⟩, ⟨hb, ha⟩ def and.symm := @and.swap /- or -/ notation a \/ b := or a b notation a ∨ b := or a b namespace or lemma elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := or.rec h₂ h₃ h₁ end or lemma non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (or.inl pos_a) not_em, absurd (or.inr neg_a) not_em def not_not_em := non_contradictory_em lemma or.swap : a ∨ b → b ∨ a := or.rec or.inr or.inl def or.symm := @or.swap /- xor -/ def xor (a b : Prop) := (a ∧ ¬ b) ∨ (b ∧ ¬ a) /- iff -/ structure iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) notation a <-> b := iff a b notation a ↔ b := iff a b lemma iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := iff.rec attribute [recursor 5] iff.elim lemma iff.elim_left : (a ↔ b) → a → b := iff.mp lemma iff.elim_right : (a ↔ b) → b → a := iff.mpr lemma iff_iff_implies_and_implies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff.intro (λ h, and.intro h.mp h.mpr) (λ h, iff.intro h.left h.right) @[refl] lemma iff.refl (a : Prop) : a ↔ a := iff.intro (assume h, h) (assume h, h) lemma iff.rfl {a : Prop} : a ↔ a := iff.refl a @[trans] lemma iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := iff.intro (assume ha, iff.mp h₂ (iff.mp h₁ ha)) (assume hc, iff.mpr h₁ (iff.mpr h₂ hc)) @[symm] lemma iff.symm (h : a ↔ b) : b ↔ a := iff.intro (iff.elim_right h) (iff.elim_left h) lemma iff.comm : (a ↔ b) ↔ (b ↔ a) := iff.intro iff.symm iff.symm lemma eq.to_iff {a b : Prop} (h : a = b) : a ↔ b := eq.rec_on h iff.rfl lemma neq_of_not_iff {a b : Prop} : ¬(a ↔ b) → a ≠ b := λ h₁ h₂, have a ↔ b, from eq.subst h₂ (iff.refl a), absurd this h₁ lemma not_iff_not_of_iff (h₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (hna : ¬ a) (hb : b), hna (iff.elim_right h₁ hb)) (assume (hnb : ¬ b) (ha : a), hnb (iff.elim_left h₁ ha)) lemma of_iff_true (h : a ↔ true) : a := iff.mp (iff.symm h) trivial lemma not_of_iff_false : (a ↔ false) → ¬a := iff.mp lemma iff_true_intro (h : a) : a ↔ true := iff.intro (λ hl, trivial) (λ hr, h) lemma iff_false_intro (h : ¬a) : a ↔ false := iff.intro h (false.rec a) lemma not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := iff.intro (λ (hl : ¬¬¬a) (ha : a), hl (non_contradictory_intro ha)) absurd def not_not_not_iff := not_non_contradictory_iff_absurd lemma imp_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, iff.mp h₂ (hab (iff.mpr h₁ hc))) (λ hcd ha, iff.mpr h₂ (hcd (iff.mp h₁ ha))) lemma imp_congr_ctx (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, have ha : a, from iff.mpr h₁ hc, have hb : b, from hab ha, iff.mp (h₂ hc) hb) (λ hcd ha, have hc : c, from iff.mp h₁ ha, have hd : d, from hcd hc, iff.mpr (h₂ hc) hd) lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := iff.intro (assume hab ha, iff.elim_left (h ha) (hab ha)) (assume hab ha, iff.elim_right (h ha) (hab ha)) lemma not_not_intro (ha : a) : ¬¬a := assume hna : ¬a, hna ha lemma not_of_not_not_not (h : ¬¬¬a) : ¬a := λ ha, absurd (not_not_intro ha) h @[simp] lemma not_true : (¬ true) ↔ false := iff_false_intro (not_not_intro trivial) def not_true_iff := not_true @[simp] lemma not_false_iff : (¬ false) ↔ true := iff_true_intro not_false @[congr] lemma not_congr (h : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ h₁ h₂, h₁ (iff.mpr h h₂)) (λ h₁ h₂, h₁ (iff.mp h h₂)) @[simp] lemma ne_self_iff_false {α : Sort u} (a : α) : (not (a = a)) ↔ false := iff.intro false_of_ne false.elim @[simp] lemma eq_self_iff_true {α : Sort u} (a : α) : (a = a) ↔ true := iff_true_intro rfl @[simp] lemma heq_self_iff_true {α : Sort u} (a : α) : (a == a) ↔ true := iff_true_intro (heq.refl a) @[simp] lemma iff_not_self (a : Prop) : (a ↔ ¬a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mp h ha) ha), h' (iff.mpr h h')) @[simp] lemma not_iff_self (a : Prop) : (¬a ↔ a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mpr h ha) ha), h' (iff.mp h h')) @[simp] lemma true_iff_false : (true ↔ false) ↔ false := iff_false_intro (λ h, iff.mp h trivial) @[simp] lemma false_iff_true : (false ↔ true) ↔ false := iff_false_intro (λ h, iff.mpr h trivial) lemma false_of_true_iff_false : (true ↔ false) → false := assume h, iff.mp h trivial lemma false_of_true_eq_false : (true = false) → false := assume h, h ▸ trivial lemma true_eq_false_of_false : false → (true = false) := false.elim lemma eq_comm {α : Sort u} {a b : α} : a = b ↔ b = a := ⟨eq.symm, eq.symm⟩ /- and simp rules -/ lemma and.imp (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := assume ⟨ha, hb⟩, ⟨hac ha, hbd hb⟩ def and_implies := @and.imp @[congr] lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := iff.intro (and.imp (iff.mp h₁) (iff.mp h₂)) (and.imp (iff.mpr h₁) (iff.mpr h₂)) lemma and_congr_right (h : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) := iff.intro (assume ⟨ha, hb⟩, ⟨ha, iff.elim_left (h ha) hb⟩) (assume ⟨ha, hc⟩, ⟨ha, iff.elim_right (h ha) hc⟩) lemma and.comm : a ∧ b ↔ b ∧ a := iff.intro and.swap and.swap lemma and_comm (a b : Prop) : a ∧ b ↔ b ∧ a := and.comm lemma and.assoc : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := iff.intro (assume ⟨⟨ha, hb⟩, hc⟩, ⟨ha, ⟨hb, hc⟩⟩) (assume ⟨ha, ⟨hb, hc⟩⟩, ⟨⟨ha, hb⟩, hc⟩) lemma and_assoc (a b : Prop) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := and.assoc lemma and.left_comm : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := iff.trans (iff.symm and.assoc) (iff.trans (and_congr and.comm (iff.refl c)) and.assoc) lemma and_iff_left {a b : Prop} (hb : b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, hb⟩) lemma and_iff_right {a b : Prop} (ha : a) : (a ∧ b) ↔ b := iff.intro and.right (and.intro ha) @[simp] lemma and_true (a : Prop) : a ∧ true ↔ a := and_iff_left trivial @[simp] lemma true_and (a : Prop) : true ∧ a ↔ a := and_iff_right trivial @[simp] lemma and_false (a : Prop) : a ∧ false ↔ false := iff_false_intro and.right @[simp] lemma false_and (a : Prop) : false ∧ a ↔ false := iff_false_intro and.left @[simp] lemma not_and_self (a : Prop) : (¬a ∧ a) ↔ false := iff_false_intro (λ h, and.elim h (λ h₁ h₂, absurd h₂ h₁)) @[simp] lemma and_not_self (a : Prop) : (a ∧ ¬a) ↔ false := iff_false_intro (assume ⟨h₁, h₂⟩, absurd h₁ h₂) @[simp] lemma and_self (a : Prop) : a ∧ a ↔ a := iff.intro and.left (assume h, ⟨h, h⟩) /- or simp rules -/ lemma or.imp (h₂ : a → c) (h₃ : b → d) : a ∨ b → c ∨ d := or.rec (λ h, or.inl (h₂ h)) (λ h, or.inr (h₃ h)) lemma or.imp_left (h : a → b) : a ∨ c → b ∨ c := or.imp h id lemma or.imp_right (h : a → b) : c ∨ a → c ∨ b := or.imp id h @[congr] lemma or_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp h₁) (iff.mp h₂)) (or.imp (iff.mpr h₁) (iff.mpr h₂)) lemma or.comm : a ∨ b ↔ b ∨ a := iff.intro or.swap or.swap lemma or_comm (a b : Prop) : a ∨ b ↔ b ∨ a := or.comm lemma or.assoc : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := iff.intro (or.rec (or.imp_right or.inl) (λ h, or.inr (or.inr h))) (or.rec (λ h, or.inl (or.inl h)) (or.imp_left or.inr)) lemma or_assoc (a b : Prop) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := or.assoc lemma or.left_comm : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := iff.trans (iff.symm or.assoc) (iff.trans (or_congr or.comm (iff.refl c)) or.assoc) theorem or_iff_right_of_imp (ha : a → b) : (a ∨ b) ↔ b := iff.intro (or.rec ha id) or.inr theorem or_iff_left_of_imp (hb : b → a) : (a ∨ b) ↔ a := iff.intro (or.rec id hb) or.inl @[simp] lemma or_true (a : Prop) : a ∨ true ↔ true := iff_true_intro (or.inr trivial) @[simp] lemma true_or (a : Prop) : true ∨ a ↔ true := iff_true_intro (or.inl trivial) @[simp] lemma or_false (a : Prop) : a ∨ false ↔ a := iff.intro (or.rec id false.elim) or.inl @[simp] lemma false_or (a : Prop) : false ∨ a ↔ a := iff.trans or.comm (or_false a) @[simp] lemma or_self (a : Prop) : a ∨ a ↔ a := iff.intro (or.rec id id) or.inl lemma not_or {a b : Prop} : ¬ a → ¬ b → ¬ (a ∨ b) | hna hnb (or.inl ha) := absurd ha hna | hna hnb (or.inr hb) := absurd hb hnb /- or resolution rulse -/ def or.resolve_left {a b : Prop} (h : a ∨ b) (na : ¬ a) : b := or.elim h (λ ha, absurd ha na) id def or.neg_resolve_left {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b := or.elim h (λ na, absurd ha na) id def or.resolve_right {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a := or.elim h id (λ hb, absurd hb nb) def or.neg_resolve_right {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a := or.elim h id (λ nb, absurd hb nb) /- iff simp rules -/ @[simp] lemma iff_true (a : Prop) : (a ↔ true) ↔ a := iff.intro (assume h, iff.mpr h trivial) iff_true_intro @[simp] lemma true_iff (a : Prop) : (true ↔ a) ↔ a := iff.trans iff.comm (iff_true a) @[simp] lemma iff_false (a : Prop) : (a ↔ false) ↔ ¬ a := iff.intro iff.mp iff_false_intro @[simp] lemma false_iff (a : Prop) : (false ↔ a) ↔ ¬ a := iff.trans iff.comm (iff_false a) @[simp] lemma iff_self (a : Prop) : (a ↔ a) ↔ true := iff_true_intro iff.rfl @[congr] lemma iff_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := (iff_iff_implies_and_implies a b).trans ((and_congr (imp_congr h₁ h₂) (imp_congr h₂ h₁)).trans (iff_iff_implies_and_implies c d).symm) /- implies simp rule -/ @[simp] lemma implies_true_iff (α : Sort u) : (α → true) ↔ true := iff.intro (λ h, trivial) (λ ha h, trivial) @[simp] lemma false_implies_iff (a : Prop) : (false → a) ↔ true := iff.intro (λ h, trivial) (λ ha h, false.elim h) @[simp] theorem true_implies_iff (α : Prop) : (true → α) ↔ α := iff.intro (λ h, h trivial) (λ h h', h) /- exists -/ inductive Exists {α : Sort u} (p : α → Prop) : Prop | intro (w : α) (h : p w) : Exists attribute [intro] Exists.intro @[pattern] def exists.intro := @Exists.intro notation `exists` binders `, ` r:(scoped P, Exists P) := r notation `∃` binders `, ` r:(scoped P, Exists P) := r lemma exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : ∃ x, p x) (h₂ : ∀ (a : α), p a → b) : b := Exists.rec h₂ h₁ /- exists unique -/ def exists_unique {α : Sort u} (p : α → Prop) := ∃ x, p x ∧ ∀ y, p y → y = x notation `∃!` binders `, ` r:(scoped P, exists_unique P) := r @[intro] lemma exists_unique.intro {α : Sort u} {p : α → Prop} (w : α) (h₁ : p w) (h₂ : ∀ y, p y → y = w) : ∃! x, p x := exists.intro w ⟨h₁, h₂⟩ attribute [recursor 4] lemma exists_unique.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₂ : ∃! x, p x) (h₁ : ∀ x, p x → (∀ y, p y → y = x) → b) : b := exists.elim h₂ (λ w hw, h₁ w (and.left hw) (and.right hw)) lemma exists_unique_of_exists_of_unique {α : Type u} {p : α → Prop} (hex : ∃ x, p x) (hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x := exists.elim hex (λ x px, exists_unique.intro x px (assume y, assume : p y, hunique y x this px)) lemma exists_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) lemma unique_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := exists_unique.elim h (assume x, assume : p x, assume unique : ∀ y, p y → y = x, show y₁ = y₂, from eq.trans (unique _ py₁) (eq.symm (unique _ py₂))) /- exists, forall, exists unique congruences -/ @[congr] lemma forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (∀ a, p a) ↔ ∀ a, q a := iff.intro (λ p a, iff.mp (h a) (p a)) (λ q a, iff.mpr (h a) (q a)) lemma exists_imp_exists {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists.elim p (λ a hp, ⟨a, h a hp⟩) @[congr] lemma exists_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (Exists p) ↔ ∃ a, q a := iff.intro (exists_imp_exists (λ a, iff.mp (h a))) (exists_imp_exists (λ a, iff.mpr (h a))) @[congr] lemma exists_unique_congr {α : Sort u} {p₁ p₂ : α → Prop} (h : ∀ x, p₁ x ↔ p₂ x) : (exists_unique p₁) ↔ (∃! x, p₂ x) := -- exists_congr (λ x, and_congr (h x) (forall_congr (λ y, imp_congr (h y) iff.rfl))) lemma forall_not_of_not_exists {α : Sort u} {p : α → Prop} : ¬(∃ x, p x) → (∀ x, ¬p x) := λ hne x hp, hne ⟨x, hp⟩ /- decidable -/ def decidable.to_bool (p : Prop) [h : decidable p] : bool := decidable.cases_on h (λ h₁, bool.ff) (λ h₂, bool.tt) export decidable (is_true is_false to_bool) @[simp] lemma to_bool_true_eq_tt (h : decidable true) : @to_bool true h = tt := decidable.cases_on h (λ h, false.elim (iff.mp not_true h)) (λ _, rfl) @[simp] lemma to_bool_false_eq_ff (h : decidable false) : @to_bool false h = ff := decidable.cases_on h (λ h, rfl) (λ h, false.elim h) instance decidable.true : decidable true := is_true trivial instance decidable.false : decidable false := is_false not_false -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[inline] def dite (c : Prop) [h : decidable c] {α : Sort u} : (c → α) → (¬ c → α) → α := λ t e, decidable.rec_on h e t /- if-then-else -/ @[inline] def ite (c : Prop) [h : decidable c] {α : Sort u} (t e : α) : α := decidable.rec_on h (λ hnc, e) (λ hc, t) namespace decidable variables {p q : Prop} def rec_on_true [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, false.rec _ (h h₃)) (λ h, h₄) def rec_on_false [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, h₄) (λ h, false.rec _ (h₃ h)) def by_cases {q : Sort u} [φ : decidable p] : (p → q) → (¬p → q) → q := dite _ /-- Law of Excluded Middle. -/ lemma em (p : Prop) [decidable p] : p ∨ ¬p := by_cases or.inl or.inr lemma by_contradiction [decidable p] (h : ¬p → false) : p := if h₁ : p then h₁ else false.rec _ (h h₁) lemma of_not_not [decidable p] : ¬ ¬ p → p := λ hnn, by_contradiction (λ hn, absurd hn hnn) lemma not_not_iff (p) [decidable p] : (¬ ¬ p) ↔ p := iff.intro of_not_not not_not_intro lemma not_and_iff_or_not (p q : Prop) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := match d₂ with | is_true h₂ := absurd (and.intro h₁ h₂) h | is_false h₂ := or.inr h₂ end | is_false h₁ := or.inl h₁ end) (λ h ⟨hp, hq⟩, or.elim h (λ h, h hp) (λ h, h hq)) lemma not_or_iff_and_not (p q) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := false.elim $ h (or.inl h₁) | is_false h₁ := match d₂ with | is_true h₂ := false.elim $ h (or.inr h₂) | is_false h₂ := ⟨h₁, h₂⟩ end end) (λ ⟨np, nq⟩ h, or.elim h np nq) end decidable section variables {p q : Prop} def decidable_of_decidable_of_iff (hp : decidable p) (h : p ↔ q) : decidable q := if hp : p then is_true (iff.mp h hp) else is_false (iff.mp (not_iff_not_of_iff h) hp) def decidable_of_decidable_of_eq (hp : decidable p) (h : p = q) : decidable q := decidable_of_decidable_of_iff hp h.to_iff protected def or.by_cases [decidable p] [decidable q] {α : Sort u} (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := if hp : p then h₁ hp else if hq : q then h₂ hq else false.rec _ (or.elim h hp hq) end section variables {p q : Prop} instance [decidable p] [decidable q] : decidable (p ∧ q) := if hp : p then if hq : q then is_true ⟨hp, hq⟩ else is_false (assume h : p ∧ q, hq (and.right h)) else is_false (assume h : p ∧ q, hp (and.left h)) instance [decidable p] [decidable q] : decidable (p ∨ q) := if hp : p then is_true (or.inl hp) else if hq : q then is_true (or.inr hq) else is_false (or.rec hp hq) instance [decidable p] : decidable (¬p) := if hp : p then is_false (absurd hp) else is_true hp instance implies.decidable [decidable p] [decidable q] : decidable (p → q) := if hp : p then if hq : q then is_true (assume h, hq) else is_false (assume h : p → q, absurd (h hp) hq) else is_true (assume h, absurd h hp) instance [decidable p] [decidable q] : decidable (p ↔ q) := if hp : p then if hq : q then is_true ⟨λ_, hq, λ_, hp⟩ else is_false $ λh, hq (h.1 hp) else if hq : q then is_false $ λh, hp (h.2 hq) else is_true $ ⟨λh, absurd h hp, λh, absurd h hq⟩ instance [decidable p] [decidable q] : decidable (xor p q) := if hp : p then if hq : q then is_false (or.rec (λ ⟨_, h⟩, h hq : ¬(p ∧ ¬ q)) (λ ⟨_, h⟩, h hp : ¬(q ∧ ¬ p))) else is_true $ or.inl ⟨hp, hq⟩ else if hq : q then is_true $ or.inr ⟨hq, hp⟩ else is_false (or.rec (λ ⟨h, _⟩, hp h : ¬(p ∧ ¬ q)) (λ ⟨h, _⟩, hq h : ¬(q ∧ ¬ p))) instance exists_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∃ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2, ⟨h, h2⟩, λ⟨h', h2⟩, h2⟩ else is_false (mt (λ⟨h, _⟩, h) h) instance forall_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∀ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2 _, h2, λal, al h⟩ else is_true (λ h2, absurd h2 h) end instance {α : Sort u} [decidable_eq α] (a b : α) : decidable (a ≠ b) := implies.decidable lemma bool.ff_ne_tt : ff = tt → false . def is_dec_eq {α : Sort u} (p : α → α → bool) : Prop := ∀ ⦃x y : α⦄, p x y = tt → x = y def is_dec_refl {α : Sort u} (p : α → α → bool) : Prop := ∀ x, p x x = tt open decidable instance : decidable_eq bool | ff ff := is_true rfl | ff tt := is_false bool.ff_ne_tt | tt ff := is_false (ne.symm bool.ff_ne_tt) | tt tt := is_true rfl def decidable_eq_of_bool_pred {α : Sort u} {p : α → α → bool} (h₁ : is_dec_eq p) (h₂ : is_dec_refl p) : decidable_eq α := assume x y : α, if hp : p x y = tt then is_true (h₁ hp) else is_false (assume hxy : x = y, absurd (h₂ y) (@eq.rec_on _ _ (λ z, ¬p z y = tt) _ hxy hp)) lemma decidable_eq_inl_refl {α : Sort u} [h : decidable_eq α] (a : α) : h a a = is_true (eq.refl a) := match (h a a) with | (is_true e) := rfl | (is_false n) := absurd rfl n end lemma decidable_eq_inr_neg {α : Sort u} [h : decidable_eq α] {a b : α} : Π n : a ≠ b, h a b = is_false n := assume n, match (h a b) with | (is_true e) := absurd e n | (is_false n₁) := proof_irrel n n₁ ▸ eq.refl (is_false n) end /- inhabited -/ class inhabited (α : Sort u) := (default [] : α) export inhabited (default) @[inline, irreducible] def arbitrary (α : Sort u) [inhabited α] : α := default α instance prop.inhabited : inhabited Prop := ⟨true⟩ instance pi.inhabited (α : Sort u) {β : α → Sort v} [Π x, inhabited (β x)] : inhabited (Π x, β x) := ⟨λ a, default (β a)⟩ instance : inhabited bool := ⟨ff⟩ instance : inhabited true := ⟨trivial⟩ class inductive nonempty (α : Sort u) : Prop | intro (val : α) : nonempty protected def nonempty.elim {α : Sort u} {p : Prop} (h₁ : nonempty α) (h₂ : α → p) : p := nonempty.rec h₂ h₁ instance nonempty_of_inhabited {α : Sort u} [inhabited α] : nonempty α := ⟨default α⟩ lemma nonempty_of_exists {α : Sort u} {p : α → Prop} : (∃ x, p x) → nonempty α | ⟨w, h⟩ := ⟨w⟩ /- subsingleton -/ class inductive subsingleton (α : Sort u) : Prop | intro (h : ∀ a b : α, a = b) : subsingleton protected def subsingleton.elim {α : Sort u} [h : subsingleton α] : ∀ (a b : α), a = b := subsingleton.rec (λ p, p) h protected def subsingleton.helim {α β : Sort u} [h : subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a == b := eq.rec_on h (λ a b : α, heq_of_eq (subsingleton.elim a b)) instance subsingleton_prop (p : Prop) : subsingleton p := ⟨λ a b, proof_irrel a b⟩ instance (p : Prop) : subsingleton (decidable p) := subsingleton.intro (λ d₁, match d₁ with | (is_true t₁) := (λ d₂, match d₂ with | (is_true t₂) := eq.rec_on (proof_irrel t₁ t₂) rfl | (is_false f₂) := absurd t₁ f₂ end) | (is_false f₁) := (λ d₂, match d₂ with | (is_true t₂) := absurd t₂ f₁ | (is_false f₂) := eq.rec_on (proof_irrel f₁ f₂) rfl end) end) protected lemma rec_subsingleton {p : Prop} [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : Π (h : p), subsingleton (h₁ h)] [h₄ : Π (h : ¬p), subsingleton (h₂ h)] : subsingleton (decidable.rec_on h h₂ h₁) := match h with | (is_true h) := h₃ h | (is_false h) := h₄ h end lemma if_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end lemma if_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end @[simp] lemma if_t_t (c : Prop) [h : decidable c] {α : Sort u} (t : α) : (ite c t t) = t := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end lemma implies_of_if_pos {c t e : Prop} [decidable c] (h : ite c t e) : c → t := assume hc, eq.rec_on (if_pos hc : ite c t e = t) h lemma implies_of_if_neg {c t e : Prop} [decidable c] (h : ite c t e) : ¬c → e := assume hnc, eq.rec_on (if_neg hnc : ite c t e = e) h lemma if_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr α b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) @[simp] lemma if_true {α : Sort u} {h : decidable true} (t e : α) : (@ite true h α t e) = t := if_pos trivial @[simp] lemma if_false {α : Sort u} {h : decidable false} (t e : α) : (@ite false h α t e) = e := if_neg not_false lemma if_ctx_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) lemma if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e @[congr] lemma if_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) @[simp] lemma dif_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = t hc := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end @[simp] lemma dif_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = e hnc := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end lemma dif_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c dec_c α u v) := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end lemma dif_ctx_simp_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c (decidable_of_decidable_of_iff dec_b h_c) α u v) := @dif_ctx_congr α b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e -- Remark: dite and ite are "defally equal" when we ignore the proofs. lemma dif_eq_if (c : Prop) [h : decidable c] {α : Sort u} (t : α) (e : α) : dite c (λ h, t) (λ h, e) = ite c t e := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end instance {c t e : Prop} [d_c : decidable c] [d_t : decidable t] [d_e : decidable e] : decidable (if c then t else e) := match d_c with | (is_true hc) := d_t | (is_false hc) := d_e end instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [d_c : decidable c] [d_t : ∀ h, decidable (t h)] [d_e : ∀ h, decidable (e h)] : decidable (if h : c then t h else e h) := match d_c with | (is_true hc) := d_t hc | (is_false hc) := d_e hc end def as_true (c : Prop) [decidable c] : Prop := if c then true else false def as_false (c : Prop) [decidable c] : Prop := if c then false else true def of_as_true {c : Prop} [h₁ : decidable c] (h₂ : as_true c) : c := match h₁, h₂ with | (is_true h_c), h₂ := h_c | (is_false h_c), h₂ := false.elim h₂ end /-- Universe lifting operation -/ structure {r s} ulift (α : Type s) : Type (max s r) := up :: (down : α) namespace ulift /- Bijection between α and ulift.{v} α -/ lemma up_down {α : Type u} : ∀ (b : ulift.{v} α), up (down b) = b | (up a) := rfl lemma down_up {α : Type u} (a : α) : down (up.{v} a) = a := rfl end ulift /-- Universe lifting operation from Sort to Type -/ structure plift (α : Sort u) : Type u := up :: (down : α) namespace plift /- Bijection between α and plift α -/ lemma up_down {α : Sort u} : ∀ (b : plift α), up (down b) = b | (up a) := rfl lemma down_up {α : Sort u} (a : α) : down (up a) = a := rfl end plift /- Equalities for rewriting let-expressions -/ lemma let_value_eq {α : Sort u} {β : Sort v} {a₁ a₂ : α} (b : α → β) : a₁ = a₂ → (let x : α := a₁ in b x) = (let x : α := a₂ in b x) := λ h, eq.rec_on h rfl lemma let_value_heq {α : Sort v} {β : α → Sort u} {a₁ a₂ : α} (b : Π x : α, β x) : a₁ = a₂ → (let x : α := a₁ in b x) == (let x : α := a₂ in b x) := λ h, eq.rec_on h (heq.refl (b a₁)) lemma let_body_eq {α : Sort v} {β : α → Sort u} (a : α) {b₁ b₂ : Π x : α, β x} : (∀ x, b₁ x = b₂ x) → (let x : α := a in b₁ x) = (let x : α := a in b₂ x) := λ h, h a lemma let_eq {α : Sort v} {β : Sort u} {a₁ a₂ : α} {b₁ b₂ : α → β} : a₁ = a₂ → (∀ x, b₁ x = b₂ x) → (let x : α := a₁ in b₁ x) = (let x : α := a₂ in b₂ x) := λ h₁ h₂, eq.rec_on h₁ (h₂ a₁) section relation variables {α : Sort u} {β : Sort v} (r : β → β → Prop) local infix `≺`:50 := r def reflexive := ∀ x, x ≺ x def symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x def transitive := ∀ ⦃x y z⦄, x ≺ y → y ≺ z → x ≺ z def equivalence := reflexive r ∧ symmetric r ∧ transitive r def total := ∀ x y, x ≺ y ∨ y ≺ x def mk_equivalence (rfl : reflexive r) (symm : symmetric r) (trans : transitive r) : equivalence r := ⟨rfl, symm, trans⟩ def irreflexive := ∀ x, ¬ x ≺ x def anti_symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y def empty_relation := λ a₁ a₂ : α, false def subrelation (q r : β → β → Prop) := ∀ ⦃x y⦄, q x y → r x y def inv_image (f : α → β) : α → α → Prop := λ a₁ a₂, f a₁ ≺ f a₂ lemma inv_image.trans (f : α → β) (h : transitive r) : transitive (inv_image r f) := λ (a₁ a₂ a₃ : α) (h₁ : inv_image r f a₁ a₂) (h₂ : inv_image r f a₂ a₃), h h₁ h₂ lemma inv_image.irreflexive (f : α → β) (h : irreflexive r) : irreflexive (inv_image r f) := λ (a : α) (h₁ : inv_image r f a a), h (f a) h₁ inductive tc {α : Sort u} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → tc a b | trans : ∀ a b c, tc a b → tc b c → tc a c end relation section binary variables {α : Type u} {β : Type v} variable f : α → α → α variable inv : α → α variable one : α local notation a * b := f a b local notation a ⁻¹ := inv a variable g : α → α → α local notation a + b := g a b def commutative := ∀ a b, a * b = b * a def associative := ∀ a b c, (a * b) * c = a * (b * c) def left_identity := ∀ a, one * a = a def right_identity := ∀ a, a * one = a def right_inverse := ∀ a, a * a⁻¹ = one def left_cancelative := ∀ a b c, a * b = a * c → b = c def right_cancelative := ∀ a b c, a * b = c * b → a = c def left_distributive := ∀ a b c, a * (b + c) = a * b + a * c def right_distributive := ∀ a b c, (a + b) * c = a * c + b * c def right_commutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁ def left_commutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b) lemma left_comm : commutative f → associative f → left_commutative f := assume hcomm hassoc, assume a b c, calc a*(b*c) = (a*b)*c : eq.symm (hassoc a b c) ... = (b*a)*c : hcomm a b ▸ rfl ... = b*(a*c) : hassoc b a c lemma right_comm : commutative f → associative f → right_commutative f := assume hcomm hassoc, assume a b c, calc (a*b)*c = a*(b*c) : hassoc a b c ... = a*(c*b) : hcomm b c ▸ rfl ... = (a*c)*b : eq.symm (hassoc a c b) end binary
233837340ecb6feb7b9205aba458ecd1395ae556
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/integrally_closed.lean
c22a25825616229e8fc8a689d1b128834ea2eca9
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,735
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.integral_closure import ring_theory.localization.integral /-! # Integrally closed rings An integrally closed domain `R` contains all the elements of `Frac(R)` that are integral over `R`. A special case of integrally closed domains are the Dedekind domains. ## Main definitions * `is_integrally_closed R` states `R` contains all integral elements of `Frac(R)` ## Main results * `is_integrally_closed_iff K`, where `K` is a fraction field of `R`, states `R` is integrally closed iff it is the integral closure of `R` in `K` -/ open_locale non_zero_divisors /-- `R` is integrally closed if all integral elements of `Frac(R)` are also elements of `R`. This definition uses `fraction_ring R` to denote `Frac(R)`. See `is_integrally_closed_iff` if you want to choose another field of fractions for `R`. -/ class is_integrally_closed (R : Type*) [comm_ring R] [is_domain R] : Prop := (algebra_map_eq_of_integral : ∀ {x : fraction_ring R}, is_integral R x → ∃ y, algebra_map R (fraction_ring R) y = x) section iff variables {R : Type*} [comm_ring R] [is_domain R] variables (K : Type*) [field K] [algebra R K] [is_fraction_ring R K] /-- `R` is integrally closed iff all integral elements of its fraction field `K` are also elements of `R`. -/ theorem is_integrally_closed_iff : is_integrally_closed R ↔ ∀ {x : K}, is_integral R x → ∃ y, algebra_map R K y = x := begin let e : K ≃ₐ[R] fraction_ring R := is_localization.alg_equiv R⁰_ _, split, { rintros ⟨cl⟩, refine λ x hx, _, obtain ⟨y, hy⟩ := cl ((is_integral_alg_equiv e).mpr hx), exact ⟨y, e.algebra_map_eq_apply.mp hy⟩ }, { rintros cl, refine ⟨λ x hx, _⟩, obtain ⟨y, hy⟩ := cl ((is_integral_alg_equiv e.symm).mpr hx), exact ⟨y, e.symm.algebra_map_eq_apply.mp hy⟩ }, end /-- `R` is integrally closed iff it is the integral closure of itself in its field of fractions. -/ theorem is_integrally_closed_iff_is_integral_closure : is_integrally_closed R ↔ is_integral_closure R R K := (is_integrally_closed_iff K).trans $ begin let e : K ≃ₐ[R] fraction_ring R := is_localization.alg_equiv R⁰_ _, split, { intros cl, refine ⟨is_fraction_ring.injective _ _, λ x, ⟨cl, _⟩⟩, rintros ⟨y, y_eq⟩, rw ← y_eq, exact is_integral_algebra_map }, { rintros ⟨-, cl⟩ x hx, exact cl.mp hx } end end iff namespace is_integrally_closed variables {R : Type*} [comm_ring R] [id : is_domain R] [iic : is_integrally_closed R] variables {K : Type*} [field K] [algebra R K] [ifr : is_fraction_ring R K] include iic ifr instance : is_integral_closure R R K := (is_integrally_closed_iff_is_integral_closure K).mp iic lemma is_integral_iff {x : K} : is_integral R x ↔ ∃ y : R, algebra_map R K y = x := is_integral_closure.is_integral_iff lemma exists_algebra_map_eq_of_is_integral_pow {x : K} {n : ℕ} (hn : 0 < n) (hx : is_integral R $ x ^ n) : ∃ y : R, algebra_map R K y = x := is_integral_iff.mp $ is_integral_of_pow hn hx omit iic ifr lemma exists_algebra_map_eq_of_pow_mem_subalgebra {K : Type*} [field K] [algebra R K] {S : subalgebra R K} [is_integrally_closed S] [is_fraction_ring S K] {x : K} {n : ℕ} (hn : 0 < n) (hx : x ^ n ∈ S) : ∃ y : S, algebra_map S K y = x := exists_algebra_map_eq_of_is_integral_pow hn $ is_integral_iff.mpr ⟨⟨x ^ n, hx⟩, rfl⟩ include id ifr variables {R} (K) lemma integral_closure_eq_bot_iff : integral_closure R K = ⊥ ↔ is_integrally_closed R := begin refine eq_bot_iff.trans _, split, { rw is_integrally_closed_iff K, intros h x hx, exact set.mem_range.mp (algebra.mem_bot.mp (h hx)), assumption }, { intros h x hx, rw [algebra.mem_bot, set.mem_range], exactI is_integral_iff.mp hx }, end include iic variables (R K) @[simp] lemma integral_closure_eq_bot : integral_closure R K = ⊥ := (integral_closure_eq_bot_iff K).mpr ‹_› end is_integrally_closed namespace integral_closure open is_integrally_closed variables {R : Type*} [comm_ring R] [is_domain R] variables (K : Type*) [field K] [algebra R K] [is_fraction_ring R K] variables {L : Type*} [field L] [algebra K L] [algebra R L] [is_scalar_tower R K L] -- Can't be an instance because you need to supply `K`. lemma is_integrally_closed_of_finite_extension [finite_dimensional K L] : is_integrally_closed (integral_closure R L) := begin letI : is_fraction_ring (integral_closure R L) L := is_fraction_ring_of_finite_extension K L, exact (integral_closure_eq_bot_iff L).mp integral_closure_idem end end integral_closure
c1b09533e85a1a0595de5e015b446e9113f0a8ce
7cef822f3b952965621309e88eadf618da0c8ae9
/src/topology/algebra/monoid.lean
042192c8e9fb3db3176b7f36f0cb8ce14270a1cb
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
5,250
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Theory of topological monoids. TODO: generalize `topological_monoid` and `topological_add_monoid` to semigroups, or add a type class `topological_operator α (*)`. -/ import topology.constructions topology.continuous_on import algebra.pi_instances open classical set lattice filter topological_space open_locale classical topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section topological_monoid /-- A topological monoid is a monoid in which the multiplication is continuous as a function `α × α → α`. -/ class topological_monoid (α : Type u) [topological_space α] [monoid α] : Prop := (continuous_mul : continuous (λp:α×α, p.1 * p.2)) /-- A topological (additive) monoid is a monoid in which the addition is continuous as a function `α × α → α`. -/ class topological_add_monoid (α : Type u) [topological_space α] [add_monoid α] : Prop := (continuous_add : continuous (λp:α×α, p.1 + p.2)) attribute [to_additive topological_add_monoid] topological_monoid section variables [topological_space α] [monoid α] [topological_monoid α] @[to_additive] lemma continuous_mul : continuous (λp:α×α, p.1 * p.2) := topological_monoid.continuous_mul α @[to_additive] lemma continuous.mul [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := continuous_mul.comp (hf.prod_mk hg) @[to_additive] lemma continuous_mul_left (a : α) : continuous (λ b:α, a * b) := continuous_const.mul continuous_id @[to_additive] lemma continuous_mul_right (a : α) : continuous (λ b:α, b * a) := continuous_id.mul continuous_const @[to_additive] lemma continuous_on.mul [topological_space β] {f : β → α} {g : β → α} {s : set β} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x * g x) s := (continuous_mul.comp_continuous_on (hf.prod hg) : _) -- @[to_additive continuous_smul] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : α, a ^ n) | 0 := by simpa using continuous_const | (k+1) := show continuous (λ (a : α), a * a ^ k), from continuous_id.mul (continuous_pow _) @[to_additive] lemma tendsto_mul {a b : α} : tendsto (λp:α×α, p.fst * p.snd) (𝓝 (a, b)) (𝓝 (a * b)) := continuous_iff_continuous_at.mp (topological_monoid.continuous_mul α) (a, b) @[to_additive] lemma filter.tendsto.mul {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x * g x) x (𝓝 (a * b)) := tendsto.comp (by rw [←nhds_prod_eq]; exact tendsto_mul) (hf.prod_mk hg) @[to_additive] lemma tendsto_list_prod {f : γ → β → α} {x : filter β} {a : γ → α} : ∀l:list γ, (∀c∈l, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, (l.map (λc, f c b)).prod) x (𝓝 ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp, exact (h f (list.mem_cons_self _ _)).mul (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive] lemma continuous_list_prod [topological_space β] {f : γ → β → α} (l : list γ) (h : ∀c∈l, continuous (f c)) : continuous (λa, (l.map (λc, f c a)).prod) := continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_continuous_at.1 (h c hc) x @[to_additive topological_add_monoid] instance [topological_space β] [monoid β] [topological_monoid β] : topological_monoid (α × β) := ⟨((continuous_fst.comp continuous_fst).mul (continuous_fst.comp continuous_snd)).prod_mk ((continuous_snd.comp continuous_fst).mul (continuous_snd.comp continuous_snd))⟩ attribute [instance] prod.topological_add_monoid end section variables [topological_space α] [comm_monoid α] @[to_additive] lemma is_submonoid.mem_nhds_one (β : set α) [is_submonoid β] (oβ : is_open β) : β ∈ 𝓝 (1 : α) := mem_nhds_sets_iff.2 ⟨β, (by refl), oβ, is_submonoid.one_mem _⟩ variable [topological_monoid α] @[to_additive] lemma tendsto_multiset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : multiset γ) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) := by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l } @[to_additive] lemma tendsto_finset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : finset γ) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, s.prod (λc, f c b)) x (𝓝 (s.prod a)) := tendsto_multiset_prod _ @[to_additive] lemma continuous_multiset_prod [topological_space β] {f : γ → β → α} (s : multiset γ) : (∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) := by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l } @[to_additive] lemma continuous_finset_prod [topological_space β] {f : γ → β → α} (s : finset γ) : (∀c∈s, continuous (f c)) → continuous (λa, s.prod (λc, f c a)) := continuous_multiset_prod _ end end topological_monoid
eb449bfbf7e0dd0f49bb216123531475ec8ecef1
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/monoidal_categories/lemmas/pentagon_in_terms_of_natural_transformations_definitions.lean
abc5c6150c33109f8260a0a4537b0eee4f5502ee
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
2,385
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import ..monoidal_category open tqft.categories open tqft.categories.functor open tqft.categories.products open tqft.categories.natural_transformation namespace tqft.categories.monoidal_category universe variables u v @[reducible] definition pentagon_3step_1 { C : Category.{u v} } ( m : MonoidalStructure C ) := let α := m.associator_transformation in whisker_on_right (α.morphism × IdentityNaturalTransformation (IdentityFunctor C)) m.tensor @[reducible] definition pentagon_3step_2 { C : Category.{u v} } ( m : MonoidalStructure C ) := let α := m.associator_transformation in whisker_on_left (FunctorComposition (ProductCategoryAssociator C C C × IdentityFunctor C) ((IdentityFunctor C × m.tensor) × IdentityFunctor C)) α.morphism @[reducible] definition pentagon_3step_3 { C : Category.{u v} } ( m : MonoidalStructure C ) := let α := m.associator_transformation in whisker_on_left (FunctorComposition (ProductCategoryAssociator C C C × IdentityFunctor C) (ProductCategoryAssociator C (C × C) C)) (whisker_on_right (IdentityNaturalTransformation (IdentityFunctor C) × α.morphism) m.tensor) @[reducible] definition pentagon_3step { C : Category.{u v} } ( m : MonoidalStructure C ) := vertical_composition_of_NaturalTransformations (vertical_composition_of_NaturalTransformations (pentagon_3step_1 m) (pentagon_3step_2 m)) (pentagon_3step_3 m) @[reducible] definition pentagon_2step_1 { C : Category.{u v} } ( m : MonoidalStructure C ) := let α := m.associator_transformation in whisker_on_left ((m.tensor × IdentityFunctor C) × IdentityFunctor C) α.morphism @[reducible] definition pentagon_2step_2 { C : Category.{u v} } ( m : MonoidalStructure C ) := let α := m.associator_transformation in whisker_on_left (FunctorComposition (ProductCategoryAssociator (C × C) C C) (IdentityFunctor (C × C) × m.tensor)) α.morphism @[reducible] definition pentagon_2step { C : Category.{u v} } ( m : MonoidalStructure C ) := vertical_composition_of_NaturalTransformations (pentagon_2step_1 m) (pentagon_2step_2 m) end tqft.categories.monoidal_category
a2d652ba9ddf7d8409387c8b11448ef5b3e32f24
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/536.lean
c67b8f980ea2d81eb248346d43a5a20e5db6dda9
[ "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
96
lean
variable (C : Type) [Inhabited C] example : C := default variable {C} example : C := default